sqlite3-binding.c 6.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357
  1. #ifndef USE_LIBSQLITE3
  2. /******************************************************************************
  3. ** This file is an amalgamation of many separate C source files from SQLite
  4. ** version 3.21.0. By combining all the individual C code files into this
  5. ** single large file, the entire code can be compiled as a single translation
  6. ** unit. This allows many compilers to do optimizations that would not be
  7. ** possible if the files were compiled separately. Performance improvements
  8. ** of 5% or more are commonly seen when SQLite is compiled as a single
  9. ** translation unit.
  10. **
  11. ** This file is all you need to compile SQLite. To use SQLite in other
  12. ** programs, you need this file and the "sqlite3.h" header file that defines
  13. ** the programming interface to the SQLite library. (If you do not have
  14. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  15. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  16. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  17. ** if you want a wrapper to interface SQLite with your choice of programming
  18. ** language. The code for the "sqlite3" command-line shell is also in a
  19. ** separate file. This file contains only code for the core SQLite library.
  20. */
  21. #define SQLITE_CORE 1
  22. #define SQLITE_AMALGAMATION 1
  23. #ifndef SQLITE_PRIVATE
  24. # define SQLITE_PRIVATE static
  25. #endif
  26. /************** Begin file ctime.c *******************************************/
  27. /*
  28. ** 2010 February 23
  29. **
  30. ** The author disclaims copyright to this source code. In place of
  31. ** a legal notice, here is a blessing:
  32. **
  33. ** May you do good and not evil.
  34. ** May you find forgiveness for yourself and forgive others.
  35. ** May you share freely, never taking more than you give.
  36. **
  37. *************************************************************************
  38. **
  39. ** This file implements routines used to report what compile-time options
  40. ** SQLite was built with.
  41. */
  42. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  43. /*
  44. ** Include the configuration header output by 'configure' if we're using the
  45. ** autoconf-based build
  46. */
  47. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  48. #include "config.h"
  49. #define SQLITECONFIG_H 1
  50. #endif
  51. /* These macros are provided to "stringify" the value of the define
  52. ** for those options in which the value is meaningful. */
  53. #define CTIMEOPT_VAL_(opt) #opt
  54. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  55. /*
  56. ** An array of names of all compile-time options. This array should
  57. ** be sorted A-Z.
  58. **
  59. ** This array looks large, but in a typical installation actually uses
  60. ** only a handful of compile-time options, so most times this array is usually
  61. ** rather short and uses little memory space.
  62. */
  63. static const char * const sqlite3azCompileOpt[] = {
  64. /*
  65. ** BEGIN CODE GENERATED BY tool/mkctime.tcl
  66. */
  67. #if SQLITE_32BIT_ROWID
  68. "32BIT_ROWID",
  69. #endif
  70. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  71. "4_BYTE_ALIGNED_MALLOC",
  72. #endif
  73. #if SQLITE_64BIT_STATS
  74. "64BIT_STATS",
  75. #endif
  76. #if SQLITE_ALLOW_COVERING_INDEX_SCAN
  77. "ALLOW_COVERING_INDEX_SCAN",
  78. #endif
  79. #if SQLITE_ALLOW_URI_AUTHORITY
  80. "ALLOW_URI_AUTHORITY",
  81. #endif
  82. #ifdef SQLITE_BITMASK_TYPE
  83. "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
  84. #endif
  85. #if SQLITE_BUG_COMPATIBLE_20160819
  86. "BUG_COMPATIBLE_20160819",
  87. #endif
  88. #if SQLITE_CASE_SENSITIVE_LIKE
  89. "CASE_SENSITIVE_LIKE",
  90. #endif
  91. #if SQLITE_CHECK_PAGES
  92. "CHECK_PAGES",
  93. #endif
  94. #if defined(__clang__) && defined(__clang_major__)
  95. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  96. CTIMEOPT_VAL(__clang_minor__) "."
  97. CTIMEOPT_VAL(__clang_patchlevel__),
  98. #elif defined(_MSC_VER)
  99. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  100. #elif defined(__GNUC__) && defined(__VERSION__)
  101. "COMPILER=gcc-" __VERSION__,
  102. #endif
  103. #if SQLITE_COVERAGE_TEST
  104. "COVERAGE_TEST",
  105. #endif
  106. #if SQLITE_DEBUG
  107. "DEBUG",
  108. #endif
  109. #if SQLITE_DEFAULT_AUTOMATIC_INDEX
  110. "DEFAULT_AUTOMATIC_INDEX",
  111. #endif
  112. #if SQLITE_DEFAULT_AUTOVACUUM
  113. "DEFAULT_AUTOVACUUM",
  114. #endif
  115. #ifdef SQLITE_DEFAULT_CACHE_SIZE
  116. "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
  117. #endif
  118. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  119. "DEFAULT_CKPTFULLFSYNC",
  120. #endif
  121. #ifdef SQLITE_DEFAULT_FILE_FORMAT
  122. "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
  123. #endif
  124. #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
  125. "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
  126. #endif
  127. #if SQLITE_DEFAULT_FOREIGN_KEYS
  128. "DEFAULT_FOREIGN_KEYS",
  129. #endif
  130. #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  131. "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
  132. #endif
  133. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  134. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  135. #endif
  136. #ifdef SQLITE_DEFAULT_LOOKASIDE
  137. "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE),
  138. #endif
  139. #if SQLITE_DEFAULT_MEMSTATUS
  140. "DEFAULT_MEMSTATUS",
  141. #endif
  142. #ifdef SQLITE_DEFAULT_MMAP_SIZE
  143. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  144. #endif
  145. #ifdef SQLITE_DEFAULT_PAGE_SIZE
  146. "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
  147. #endif
  148. #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
  149. "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
  150. #endif
  151. #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  152. "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
  153. #endif
  154. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  155. "DEFAULT_RECURSIVE_TRIGGERS",
  156. #endif
  157. #ifdef SQLITE_DEFAULT_ROWEST
  158. "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
  159. #endif
  160. #ifdef SQLITE_DEFAULT_SECTOR_SIZE
  161. "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
  162. #endif
  163. #ifdef SQLITE_DEFAULT_SYNCHRONOUS
  164. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  165. #endif
  166. #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  167. "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
  168. #endif
  169. #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  170. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  171. #endif
  172. #ifdef SQLITE_DEFAULT_WORKER_THREADS
  173. "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
  174. #endif
  175. #if SQLITE_DIRECT_OVERFLOW_READ
  176. "DIRECT_OVERFLOW_READ",
  177. #endif
  178. #if SQLITE_DISABLE_DIRSYNC
  179. "DISABLE_DIRSYNC",
  180. #endif
  181. #if SQLITE_DISABLE_FTS3_UNICODE
  182. "DISABLE_FTS3_UNICODE",
  183. #endif
  184. #if SQLITE_DISABLE_FTS4_DEFERRED
  185. "DISABLE_FTS4_DEFERRED",
  186. #endif
  187. #if SQLITE_DISABLE_INTRINSIC
  188. "DISABLE_INTRINSIC",
  189. #endif
  190. #if SQLITE_DISABLE_LFS
  191. "DISABLE_LFS",
  192. #endif
  193. #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  194. "DISABLE_PAGECACHE_OVERFLOW_STATS",
  195. #endif
  196. #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  197. "DISABLE_SKIPAHEAD_DISTINCT",
  198. #endif
  199. #ifdef SQLITE_ENABLE_8_3_NAMES
  200. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  201. #endif
  202. #if SQLITE_ENABLE_API_ARMOR
  203. "ENABLE_API_ARMOR",
  204. #endif
  205. #if SQLITE_ENABLE_ATOMIC_WRITE
  206. "ENABLE_ATOMIC_WRITE",
  207. #endif
  208. #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  209. "ENABLE_BATCH_ATOMIC_WRITE",
  210. #endif
  211. #if SQLITE_ENABLE_CEROD
  212. "ENABLE_CEROD",
  213. #endif
  214. #if SQLITE_ENABLE_COLUMN_METADATA
  215. "ENABLE_COLUMN_METADATA",
  216. #endif
  217. #if SQLITE_ENABLE_COLUMN_USED_MASK
  218. "ENABLE_COLUMN_USED_MASK",
  219. #endif
  220. #if SQLITE_ENABLE_COSTMULT
  221. "ENABLE_COSTMULT",
  222. #endif
  223. #if SQLITE_ENABLE_CURSOR_HINTS
  224. "ENABLE_CURSOR_HINTS",
  225. #endif
  226. #if SQLITE_ENABLE_DBSTAT_VTAB
  227. "ENABLE_DBSTAT_VTAB",
  228. #endif
  229. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  230. "ENABLE_EXPENSIVE_ASSERT",
  231. #endif
  232. #if SQLITE_ENABLE_FTS1
  233. "ENABLE_FTS1",
  234. #endif
  235. #if SQLITE_ENABLE_FTS2
  236. "ENABLE_FTS2",
  237. #endif
  238. #if SQLITE_ENABLE_FTS3
  239. "ENABLE_FTS3",
  240. #endif
  241. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  242. "ENABLE_FTS3_PARENTHESIS",
  243. #endif
  244. #if SQLITE_ENABLE_FTS3_TOKENIZER
  245. "ENABLE_FTS3_TOKENIZER",
  246. #endif
  247. #if SQLITE_ENABLE_FTS4
  248. "ENABLE_FTS4",
  249. #endif
  250. #if SQLITE_ENABLE_FTS5
  251. "ENABLE_FTS5",
  252. #endif
  253. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  254. "ENABLE_HIDDEN_COLUMNS",
  255. #endif
  256. #if SQLITE_ENABLE_ICU
  257. "ENABLE_ICU",
  258. #endif
  259. #if SQLITE_ENABLE_IOTRACE
  260. "ENABLE_IOTRACE",
  261. #endif
  262. #if SQLITE_ENABLE_JSON1
  263. "ENABLE_JSON1",
  264. #endif
  265. #if SQLITE_ENABLE_LOAD_EXTENSION
  266. "ENABLE_LOAD_EXTENSION",
  267. #endif
  268. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  269. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  270. #endif
  271. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  272. "ENABLE_MEMORY_MANAGEMENT",
  273. #endif
  274. #if SQLITE_ENABLE_MEMSYS3
  275. "ENABLE_MEMSYS3",
  276. #endif
  277. #if SQLITE_ENABLE_MEMSYS5
  278. "ENABLE_MEMSYS5",
  279. #endif
  280. #if SQLITE_ENABLE_MULTIPLEX
  281. "ENABLE_MULTIPLEX",
  282. #endif
  283. #if SQLITE_ENABLE_NULL_TRIM
  284. "ENABLE_NULL_TRIM",
  285. #endif
  286. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  287. "ENABLE_OVERSIZE_CELL_CHECK",
  288. #endif
  289. #if SQLITE_ENABLE_PREUPDATE_HOOK
  290. "ENABLE_PREUPDATE_HOOK",
  291. #endif
  292. #if SQLITE_ENABLE_QPSG
  293. "ENABLE_QPSG",
  294. #endif
  295. #if SQLITE_ENABLE_RBU
  296. "ENABLE_RBU",
  297. #endif
  298. #if SQLITE_ENABLE_RTREE
  299. "ENABLE_RTREE",
  300. #endif
  301. #if SQLITE_ENABLE_SELECTTRACE
  302. "ENABLE_SELECTTRACE",
  303. #endif
  304. #if SQLITE_ENABLE_SESSION
  305. "ENABLE_SESSION",
  306. #endif
  307. #if SQLITE_ENABLE_SNAPSHOT
  308. "ENABLE_SNAPSHOT",
  309. #endif
  310. #if SQLITE_ENABLE_SQLLOG
  311. "ENABLE_SQLLOG",
  312. #endif
  313. #if defined(SQLITE_ENABLE_STAT4)
  314. "ENABLE_STAT4",
  315. #elif defined(SQLITE_ENABLE_STAT3)
  316. "ENABLE_STAT3",
  317. #endif
  318. #if SQLITE_ENABLE_STMTVTAB
  319. "ENABLE_STMTVTAB",
  320. #endif
  321. #if SQLITE_ENABLE_STMT_SCANSTATUS
  322. "ENABLE_STMT_SCANSTATUS",
  323. #endif
  324. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  325. "ENABLE_UNKNOWN_SQL_FUNCTION",
  326. #endif
  327. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  328. "ENABLE_UNLOCK_NOTIFY",
  329. #endif
  330. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  331. "ENABLE_UPDATE_DELETE_LIMIT",
  332. #endif
  333. #if SQLITE_ENABLE_URI_00_ERROR
  334. "ENABLE_URI_00_ERROR",
  335. #endif
  336. #if SQLITE_ENABLE_VFSTRACE
  337. "ENABLE_VFSTRACE",
  338. #endif
  339. #if SQLITE_ENABLE_WHERETRACE
  340. "ENABLE_WHERETRACE",
  341. #endif
  342. #if SQLITE_ENABLE_ZIPVFS
  343. "ENABLE_ZIPVFS",
  344. #endif
  345. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  346. "EXPLAIN_ESTIMATED_ROWS",
  347. #endif
  348. #if SQLITE_EXTRA_IFNULLROW
  349. "EXTRA_IFNULLROW",
  350. #endif
  351. #ifdef SQLITE_EXTRA_INIT
  352. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  353. #endif
  354. #ifdef SQLITE_EXTRA_SHUTDOWN
  355. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  356. #endif
  357. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  358. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  359. #endif
  360. #if SQLITE_FTS5_ENABLE_TEST_MI
  361. "FTS5_ENABLE_TEST_MI",
  362. #endif
  363. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  364. "FTS5_NO_WITHOUT_ROWID",
  365. #endif
  366. #if SQLITE_HAS_CODEC
  367. "HAS_CODEC",
  368. #endif
  369. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  370. "HAVE_ISNAN",
  371. #endif
  372. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  373. "HOMEGROWN_RECURSIVE_MUTEX",
  374. #endif
  375. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  376. "IGNORE_AFP_LOCK_ERRORS",
  377. #endif
  378. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  379. "IGNORE_FLOCK_LOCK_ERRORS",
  380. #endif
  381. #if SQLITE_INLINE_MEMCPY
  382. "INLINE_MEMCPY",
  383. #endif
  384. #if SQLITE_INT64_TYPE
  385. "INT64_TYPE",
  386. #endif
  387. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  388. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  389. #endif
  390. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  391. "LIKE_DOESNT_MATCH_BLOBS",
  392. #endif
  393. #if SQLITE_LOCK_TRACE
  394. "LOCK_TRACE",
  395. #endif
  396. #if SQLITE_LOG_CACHE_SPILL
  397. "LOG_CACHE_SPILL",
  398. #endif
  399. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  400. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  401. #endif
  402. #ifdef SQLITE_MAX_ATTACHED
  403. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  404. #endif
  405. #ifdef SQLITE_MAX_COLUMN
  406. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  407. #endif
  408. #ifdef SQLITE_MAX_COMPOUND_SELECT
  409. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  410. #endif
  411. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  412. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  413. #endif
  414. #ifdef SQLITE_MAX_EXPR_DEPTH
  415. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  416. #endif
  417. #ifdef SQLITE_MAX_FUNCTION_ARG
  418. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  419. #endif
  420. #ifdef SQLITE_MAX_LENGTH
  421. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  422. #endif
  423. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  424. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  425. #endif
  426. #ifdef SQLITE_MAX_MEMORY
  427. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  428. #endif
  429. #ifdef SQLITE_MAX_MMAP_SIZE
  430. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  431. #endif
  432. #ifdef SQLITE_MAX_MMAP_SIZE_
  433. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  434. #endif
  435. #ifdef SQLITE_MAX_PAGE_COUNT
  436. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  437. #endif
  438. #ifdef SQLITE_MAX_PAGE_SIZE
  439. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  440. #endif
  441. #ifdef SQLITE_MAX_SCHEMA_RETRY
  442. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  443. #endif
  444. #ifdef SQLITE_MAX_SQL_LENGTH
  445. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  446. #endif
  447. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  448. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  449. #endif
  450. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  451. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  452. #endif
  453. #ifdef SQLITE_MAX_VDBE_OP
  454. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  455. #endif
  456. #ifdef SQLITE_MAX_WORKER_THREADS
  457. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  458. #endif
  459. #if SQLITE_MEMDEBUG
  460. "MEMDEBUG",
  461. #endif
  462. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  463. "MIXED_ENDIAN_64BIT_FLOAT",
  464. #endif
  465. #if SQLITE_MMAP_READWRITE
  466. "MMAP_READWRITE",
  467. #endif
  468. #if SQLITE_MUTEX_NOOP
  469. "MUTEX_NOOP",
  470. #endif
  471. #if SQLITE_MUTEX_NREF
  472. "MUTEX_NREF",
  473. #endif
  474. #if SQLITE_MUTEX_OMIT
  475. "MUTEX_OMIT",
  476. #endif
  477. #if SQLITE_MUTEX_PTHREADS
  478. "MUTEX_PTHREADS",
  479. #endif
  480. #if SQLITE_MUTEX_W32
  481. "MUTEX_W32",
  482. #endif
  483. #if SQLITE_NEED_ERR_NAME
  484. "NEED_ERR_NAME",
  485. #endif
  486. #if SQLITE_NOINLINE
  487. "NOINLINE",
  488. #endif
  489. #if SQLITE_NO_SYNC
  490. "NO_SYNC",
  491. #endif
  492. #if SQLITE_OMIT_ALTERTABLE
  493. "OMIT_ALTERTABLE",
  494. #endif
  495. #if SQLITE_OMIT_ANALYZE
  496. "OMIT_ANALYZE",
  497. #endif
  498. #if SQLITE_OMIT_ATTACH
  499. "OMIT_ATTACH",
  500. #endif
  501. #if SQLITE_OMIT_AUTHORIZATION
  502. "OMIT_AUTHORIZATION",
  503. #endif
  504. #if SQLITE_OMIT_AUTOINCREMENT
  505. "OMIT_AUTOINCREMENT",
  506. #endif
  507. #if SQLITE_OMIT_AUTOINIT
  508. "OMIT_AUTOINIT",
  509. #endif
  510. #if SQLITE_OMIT_AUTOMATIC_INDEX
  511. "OMIT_AUTOMATIC_INDEX",
  512. #endif
  513. #if SQLITE_OMIT_AUTORESET
  514. "OMIT_AUTORESET",
  515. #endif
  516. #if SQLITE_OMIT_AUTOVACUUM
  517. "OMIT_AUTOVACUUM",
  518. #endif
  519. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  520. "OMIT_BETWEEN_OPTIMIZATION",
  521. #endif
  522. #if SQLITE_OMIT_BLOB_LITERAL
  523. "OMIT_BLOB_LITERAL",
  524. #endif
  525. #if SQLITE_OMIT_BTREECOUNT
  526. "OMIT_BTREECOUNT",
  527. #endif
  528. #if SQLITE_OMIT_CAST
  529. "OMIT_CAST",
  530. #endif
  531. #if SQLITE_OMIT_CHECK
  532. "OMIT_CHECK",
  533. #endif
  534. #if SQLITE_OMIT_COMPLETE
  535. "OMIT_COMPLETE",
  536. #endif
  537. #if SQLITE_OMIT_COMPOUND_SELECT
  538. "OMIT_COMPOUND_SELECT",
  539. #endif
  540. #if SQLITE_OMIT_CONFLICT_CLAUSE
  541. "OMIT_CONFLICT_CLAUSE",
  542. #endif
  543. #if SQLITE_OMIT_CTE
  544. "OMIT_CTE",
  545. #endif
  546. #if SQLITE_OMIT_DATETIME_FUNCS
  547. "OMIT_DATETIME_FUNCS",
  548. #endif
  549. #if SQLITE_OMIT_DECLTYPE
  550. "OMIT_DECLTYPE",
  551. #endif
  552. #if SQLITE_OMIT_DEPRECATED
  553. "OMIT_DEPRECATED",
  554. #endif
  555. #if SQLITE_OMIT_DISKIO
  556. "OMIT_DISKIO",
  557. #endif
  558. #if SQLITE_OMIT_EXPLAIN
  559. "OMIT_EXPLAIN",
  560. #endif
  561. #if SQLITE_OMIT_FLAG_PRAGMAS
  562. "OMIT_FLAG_PRAGMAS",
  563. #endif
  564. #if SQLITE_OMIT_FLOATING_POINT
  565. "OMIT_FLOATING_POINT",
  566. #endif
  567. #if SQLITE_OMIT_FOREIGN_KEY
  568. "OMIT_FOREIGN_KEY",
  569. #endif
  570. #if SQLITE_OMIT_GET_TABLE
  571. "OMIT_GET_TABLE",
  572. #endif
  573. #if SQLITE_OMIT_HEX_INTEGER
  574. "OMIT_HEX_INTEGER",
  575. #endif
  576. #if SQLITE_OMIT_INCRBLOB
  577. "OMIT_INCRBLOB",
  578. #endif
  579. #if SQLITE_OMIT_INTEGRITY_CHECK
  580. "OMIT_INTEGRITY_CHECK",
  581. #endif
  582. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  583. "OMIT_LIKE_OPTIMIZATION",
  584. #endif
  585. #if SQLITE_OMIT_LOAD_EXTENSION
  586. "OMIT_LOAD_EXTENSION",
  587. #endif
  588. #if SQLITE_OMIT_LOCALTIME
  589. "OMIT_LOCALTIME",
  590. #endif
  591. #if SQLITE_OMIT_LOOKASIDE
  592. "OMIT_LOOKASIDE",
  593. #endif
  594. #if SQLITE_OMIT_MEMORYDB
  595. "OMIT_MEMORYDB",
  596. #endif
  597. #if SQLITE_OMIT_OR_OPTIMIZATION
  598. "OMIT_OR_OPTIMIZATION",
  599. #endif
  600. #if SQLITE_OMIT_PAGER_PRAGMAS
  601. "OMIT_PAGER_PRAGMAS",
  602. #endif
  603. #if SQLITE_OMIT_PARSER_TRACE
  604. "OMIT_PARSER_TRACE",
  605. #endif
  606. #if SQLITE_OMIT_POPEN
  607. "OMIT_POPEN",
  608. #endif
  609. #if SQLITE_OMIT_PRAGMA
  610. "OMIT_PRAGMA",
  611. #endif
  612. #if SQLITE_OMIT_PROGRESS_CALLBACK
  613. "OMIT_PROGRESS_CALLBACK",
  614. #endif
  615. #if SQLITE_OMIT_QUICKBALANCE
  616. "OMIT_QUICKBALANCE",
  617. #endif
  618. #if SQLITE_OMIT_REINDEX
  619. "OMIT_REINDEX",
  620. #endif
  621. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  622. "OMIT_SCHEMA_PRAGMAS",
  623. #endif
  624. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  625. "OMIT_SCHEMA_VERSION_PRAGMAS",
  626. #endif
  627. #if SQLITE_OMIT_SHARED_CACHE
  628. "OMIT_SHARED_CACHE",
  629. #endif
  630. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  631. "OMIT_SHUTDOWN_DIRECTORIES",
  632. #endif
  633. #if SQLITE_OMIT_SUBQUERY
  634. "OMIT_SUBQUERY",
  635. #endif
  636. #if SQLITE_OMIT_TCL_VARIABLE
  637. "OMIT_TCL_VARIABLE",
  638. #endif
  639. #if SQLITE_OMIT_TEMPDB
  640. "OMIT_TEMPDB",
  641. #endif
  642. #if SQLITE_OMIT_TEST_CONTROL
  643. "OMIT_TEST_CONTROL",
  644. #endif
  645. #if SQLITE_OMIT_TRACE
  646. "OMIT_TRACE",
  647. #endif
  648. #if SQLITE_OMIT_TRIGGER
  649. "OMIT_TRIGGER",
  650. #endif
  651. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  652. "OMIT_TRUNCATE_OPTIMIZATION",
  653. #endif
  654. #if SQLITE_OMIT_UTF16
  655. "OMIT_UTF16",
  656. #endif
  657. #if SQLITE_OMIT_VACUUM
  658. "OMIT_VACUUM",
  659. #endif
  660. #if SQLITE_OMIT_VIEW
  661. "OMIT_VIEW",
  662. #endif
  663. #if SQLITE_OMIT_VIRTUALTABLE
  664. "OMIT_VIRTUALTABLE",
  665. #endif
  666. #if SQLITE_OMIT_WAL
  667. "OMIT_WAL",
  668. #endif
  669. #if SQLITE_OMIT_WSD
  670. "OMIT_WSD",
  671. #endif
  672. #if SQLITE_OMIT_XFER_OPT
  673. "OMIT_XFER_OPT",
  674. #endif
  675. #if SQLITE_PCACHE_SEPARATE_HEADER
  676. "PCACHE_SEPARATE_HEADER",
  677. #endif
  678. #if SQLITE_PERFORMANCE_TRACE
  679. "PERFORMANCE_TRACE",
  680. #endif
  681. #if SQLITE_POWERSAFE_OVERWRITE
  682. "POWERSAFE_OVERWRITE",
  683. #endif
  684. #if SQLITE_PREFER_PROXY_LOCKING
  685. "PREFER_PROXY_LOCKING",
  686. #endif
  687. #if SQLITE_PROXY_DEBUG
  688. "PROXY_DEBUG",
  689. #endif
  690. #if SQLITE_REVERSE_UNORDERED_SELECTS
  691. "REVERSE_UNORDERED_SELECTS",
  692. #endif
  693. #if SQLITE_RTREE_INT_ONLY
  694. "RTREE_INT_ONLY",
  695. #endif
  696. #if SQLITE_SECURE_DELETE
  697. "SECURE_DELETE",
  698. #endif
  699. #if SQLITE_SMALL_STACK
  700. "SMALL_STACK",
  701. #endif
  702. #ifdef SQLITE_SORTER_PMASZ
  703. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  704. #endif
  705. #if SQLITE_SOUNDEX
  706. "SOUNDEX",
  707. #endif
  708. #ifdef SQLITE_STAT4_SAMPLES
  709. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  710. #endif
  711. #ifdef SQLITE_STMTJRNL_SPILL
  712. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  713. #endif
  714. #if SQLITE_SUBSTR_COMPATIBILITY
  715. "SUBSTR_COMPATIBILITY",
  716. #endif
  717. #if SQLITE_SYSTEM_MALLOC
  718. "SYSTEM_MALLOC",
  719. #endif
  720. #if SQLITE_TCL
  721. "TCL",
  722. #endif
  723. #ifdef SQLITE_TEMP_STORE
  724. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  725. #endif
  726. #if SQLITE_TEST
  727. "TEST",
  728. #endif
  729. #if defined(SQLITE_THREADSAFE)
  730. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  731. #elif defined(THREADSAFE)
  732. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  733. #else
  734. "THREADSAFE=1",
  735. #endif
  736. #if SQLITE_UNLINK_AFTER_CLOSE
  737. "UNLINK_AFTER_CLOSE",
  738. #endif
  739. #if SQLITE_UNTESTABLE
  740. "UNTESTABLE",
  741. #endif
  742. #if SQLITE_USER_AUTHENTICATION
  743. "USER_AUTHENTICATION",
  744. #endif
  745. #if SQLITE_USE_ALLOCA
  746. "USE_ALLOCA",
  747. #endif
  748. #if SQLITE_USE_FCNTL_TRACE
  749. "USE_FCNTL_TRACE",
  750. #endif
  751. #if SQLITE_USE_URI
  752. "USE_URI",
  753. #endif
  754. #if SQLITE_VDBE_COVERAGE
  755. "VDBE_COVERAGE",
  756. #endif
  757. #if SQLITE_WIN32_MALLOC
  758. "WIN32_MALLOC",
  759. #endif
  760. #if SQLITE_ZERO_MALLOC
  761. "ZERO_MALLOC",
  762. #endif
  763. /*
  764. ** END CODE GENERATED BY tool/mkctime.tcl
  765. */
  766. };
  767. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  768. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  769. return (const char**)sqlite3azCompileOpt;
  770. }
  771. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  772. /************** End of ctime.c ***********************************************/
  773. /************** Begin file sqliteInt.h ***************************************/
  774. /*
  775. ** 2001 September 15
  776. **
  777. ** The author disclaims copyright to this source code. In place of
  778. ** a legal notice, here is a blessing:
  779. **
  780. ** May you do good and not evil.
  781. ** May you find forgiveness for yourself and forgive others.
  782. ** May you share freely, never taking more than you give.
  783. **
  784. *************************************************************************
  785. ** Internal interface definitions for SQLite.
  786. **
  787. */
  788. #ifndef SQLITEINT_H
  789. #define SQLITEINT_H
  790. /* Special Comments:
  791. **
  792. ** Some comments have special meaning to the tools that measure test
  793. ** coverage:
  794. **
  795. ** NO_TEST - The branches on this line are not
  796. ** measured by branch coverage. This is
  797. ** used on lines of code that actually
  798. ** implement parts of coverage testing.
  799. **
  800. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  801. ** and the correct answer is still obtained,
  802. ** though perhaps more slowly.
  803. **
  804. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  805. ** and the correct answer is still obtained,
  806. ** though perhaps more slowly.
  807. **
  808. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  809. ** that would be harmless and undetectable
  810. ** if it did occur.
  811. **
  812. ** In all cases, the special comment must be enclosed in the usual
  813. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  814. ** asterisks and the comment text.
  815. */
  816. /*
  817. ** Make sure the Tcl calling convention macro is defined. This macro is
  818. ** only used by test code and Tcl integration code.
  819. */
  820. #ifndef SQLITE_TCLAPI
  821. # define SQLITE_TCLAPI
  822. #endif
  823. /*
  824. ** Include the header file used to customize the compiler options for MSVC.
  825. ** This should be done first so that it can successfully prevent spurious
  826. ** compiler warnings due to subsequent content in this file and other files
  827. ** that are included by this file.
  828. */
  829. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  830. /************** Begin file msvc.h ********************************************/
  831. /*
  832. ** 2015 January 12
  833. **
  834. ** The author disclaims copyright to this source code. In place of
  835. ** a legal notice, here is a blessing:
  836. **
  837. ** May you do good and not evil.
  838. ** May you find forgiveness for yourself and forgive others.
  839. ** May you share freely, never taking more than you give.
  840. **
  841. ******************************************************************************
  842. **
  843. ** This file contains code that is specific to MSVC.
  844. */
  845. #ifndef SQLITE_MSVC_H
  846. #define SQLITE_MSVC_H
  847. #if defined(_MSC_VER)
  848. #pragma warning(disable : 4054)
  849. #pragma warning(disable : 4055)
  850. #pragma warning(disable : 4100)
  851. #pragma warning(disable : 4127)
  852. #pragma warning(disable : 4130)
  853. #pragma warning(disable : 4152)
  854. #pragma warning(disable : 4189)
  855. #pragma warning(disable : 4206)
  856. #pragma warning(disable : 4210)
  857. #pragma warning(disable : 4232)
  858. #pragma warning(disable : 4244)
  859. #pragma warning(disable : 4305)
  860. #pragma warning(disable : 4306)
  861. #pragma warning(disable : 4702)
  862. #pragma warning(disable : 4706)
  863. #endif /* defined(_MSC_VER) */
  864. #endif /* SQLITE_MSVC_H */
  865. /************** End of msvc.h ************************************************/
  866. /************** Continuing where we left off in sqliteInt.h ******************/
  867. /*
  868. ** Special setup for VxWorks
  869. */
  870. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  871. /************** Begin file vxworks.h *****************************************/
  872. /*
  873. ** 2015-03-02
  874. **
  875. ** The author disclaims copyright to this source code. In place of
  876. ** a legal notice, here is a blessing:
  877. **
  878. ** May you do good and not evil.
  879. ** May you find forgiveness for yourself and forgive others.
  880. ** May you share freely, never taking more than you give.
  881. **
  882. ******************************************************************************
  883. **
  884. ** This file contains code that is specific to Wind River's VxWorks
  885. */
  886. #if defined(__RTP__) || defined(_WRS_KERNEL)
  887. /* This is VxWorks. Set up things specially for that OS
  888. */
  889. #include <vxWorks.h>
  890. #include <pthread.h> /* amalgamator: dontcache */
  891. #define OS_VXWORKS 1
  892. #define SQLITE_OS_OTHER 0
  893. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  894. #define SQLITE_OMIT_LOAD_EXTENSION 1
  895. #define SQLITE_ENABLE_LOCKING_STYLE 0
  896. #define HAVE_UTIME 1
  897. #else
  898. /* This is not VxWorks. */
  899. #define OS_VXWORKS 0
  900. #define HAVE_FCHOWN 1
  901. #define HAVE_READLINK 1
  902. #define HAVE_LSTAT 1
  903. #endif /* defined(_WRS_KERNEL) */
  904. /************** End of vxworks.h *********************************************/
  905. /************** Continuing where we left off in sqliteInt.h ******************/
  906. /*
  907. ** These #defines should enable >2GB file support on POSIX if the
  908. ** underlying operating system supports it. If the OS lacks
  909. ** large file support, or if the OS is windows, these should be no-ops.
  910. **
  911. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  912. ** system #includes. Hence, this block of code must be the very first
  913. ** code in all source files.
  914. **
  915. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  916. ** on the compiler command line. This is necessary if you are compiling
  917. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  918. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  919. ** without this option, LFS is enable. But LFS does not exist in the kernel
  920. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  921. ** portability you should omit LFS.
  922. **
  923. ** The previous paragraph was written in 2005. (This paragraph is written
  924. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  925. ** you should probably leave LFS enabled. But some embedded platforms might
  926. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  927. **
  928. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  929. */
  930. #ifndef SQLITE_DISABLE_LFS
  931. # define _LARGE_FILE 1
  932. # ifndef _FILE_OFFSET_BITS
  933. # define _FILE_OFFSET_BITS 64
  934. # endif
  935. # define _LARGEFILE_SOURCE 1
  936. #endif
  937. /* The GCC_VERSION and MSVC_VERSION macros are used to
  938. ** conditionally include optimizations for each of these compilers. A
  939. ** value of 0 means that compiler is not being used. The
  940. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  941. ** optimizations, and hence set all compiler macros to 0
  942. **
  943. ** There was once also a CLANG_VERSION macro. However, we learn that the
  944. ** version numbers in clang are for "marketing" only and are inconsistent
  945. ** and unreliable. Fortunately, all versions of clang also recognize the
  946. ** gcc version numbers and have reasonable settings for gcc version numbers,
  947. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  948. ** when compiling with clang.
  949. */
  950. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  951. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  952. #else
  953. # define GCC_VERSION 0
  954. #endif
  955. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  956. # define MSVC_VERSION _MSC_VER
  957. #else
  958. # define MSVC_VERSION 0
  959. #endif
  960. /* Needed for various definitions... */
  961. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  962. # define _GNU_SOURCE
  963. #endif
  964. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  965. # define _BSD_SOURCE
  966. #endif
  967. /*
  968. ** For MinGW, check to see if we can include the header file containing its
  969. ** version information, among other things. Normally, this internal MinGW
  970. ** header file would [only] be included automatically by other MinGW header
  971. ** files; however, the contained version information is now required by this
  972. ** header file to work around binary compatibility issues (see below) and
  973. ** this is the only known way to reliably obtain it. This entire #if block
  974. ** would be completely unnecessary if there was any other way of detecting
  975. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  976. ** some MinGW-specific macros). When compiling for MinGW, either the
  977. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  978. ** defined; otherwise, detection of conditions specific to MinGW will be
  979. ** disabled.
  980. */
  981. #if defined(_HAVE_MINGW_H)
  982. # include "mingw.h"
  983. #elif defined(_HAVE__MINGW_H)
  984. # include "_mingw.h"
  985. #endif
  986. /*
  987. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  988. ** define is required to maintain binary compatibility with the MSVC runtime
  989. ** library in use (e.g. for Windows XP).
  990. */
  991. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  992. defined(_WIN32) && !defined(_WIN64) && \
  993. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  994. defined(__MSVCRT__)
  995. # define _USE_32BIT_TIME_T
  996. #endif
  997. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  998. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  999. ** MinGW.
  1000. */
  1001. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1002. /************** Begin file sqlite3.h *****************************************/
  1003. /*
  1004. ** 2001-09-15
  1005. **
  1006. ** The author disclaims copyright to this source code. In place of
  1007. ** a legal notice, here is a blessing:
  1008. **
  1009. ** May you do good and not evil.
  1010. ** May you find forgiveness for yourself and forgive others.
  1011. ** May you share freely, never taking more than you give.
  1012. **
  1013. *************************************************************************
  1014. ** This header file defines the interface that the SQLite library
  1015. ** presents to client programs. If a C-function, structure, datatype,
  1016. ** or constant definition does not appear in this file, then it is
  1017. ** not a published API of SQLite, is subject to change without
  1018. ** notice, and should not be referenced by programs that use SQLite.
  1019. **
  1020. ** Some of the definitions that are in this file are marked as
  1021. ** "experimental". Experimental interfaces are normally new
  1022. ** features recently added to SQLite. We do not anticipate changes
  1023. ** to experimental interfaces but reserve the right to make minor changes
  1024. ** if experience from use "in the wild" suggest such changes are prudent.
  1025. **
  1026. ** The official C-language API documentation for SQLite is derived
  1027. ** from comments in this file. This file is the authoritative source
  1028. ** on how SQLite interfaces are supposed to operate.
  1029. **
  1030. ** The name of this file under configuration management is "sqlite.h.in".
  1031. ** The makefile makes some minor changes to this file (such as inserting
  1032. ** the version number) and changes its name to "sqlite3.h" as
  1033. ** part of the build process.
  1034. */
  1035. #ifndef SQLITE3_H
  1036. #define SQLITE3_H
  1037. #include <stdarg.h> /* Needed for the definition of va_list */
  1038. /*
  1039. ** Make sure we can call this stuff from C++.
  1040. */
  1041. #if 0
  1042. extern "C" {
  1043. #endif
  1044. /*
  1045. ** Provide the ability to override linkage features of the interface.
  1046. */
  1047. #ifndef SQLITE_EXTERN
  1048. # define SQLITE_EXTERN extern
  1049. #endif
  1050. #ifndef SQLITE_API
  1051. # define SQLITE_API
  1052. #endif
  1053. #ifndef SQLITE_CDECL
  1054. # define SQLITE_CDECL
  1055. #endif
  1056. #ifndef SQLITE_APICALL
  1057. # define SQLITE_APICALL
  1058. #endif
  1059. #ifndef SQLITE_STDCALL
  1060. # define SQLITE_STDCALL SQLITE_APICALL
  1061. #endif
  1062. #ifndef SQLITE_CALLBACK
  1063. # define SQLITE_CALLBACK
  1064. #endif
  1065. #ifndef SQLITE_SYSAPI
  1066. # define SQLITE_SYSAPI
  1067. #endif
  1068. /*
  1069. ** These no-op macros are used in front of interfaces to mark those
  1070. ** interfaces as either deprecated or experimental. New applications
  1071. ** should not use deprecated interfaces - they are supported for backwards
  1072. ** compatibility only. Application writers should be aware that
  1073. ** experimental interfaces are subject to change in point releases.
  1074. **
  1075. ** These macros used to resolve to various kinds of compiler magic that
  1076. ** would generate warning messages when they were used. But that
  1077. ** compiler magic ended up generating such a flurry of bug reports
  1078. ** that we have taken it all out and gone back to using simple
  1079. ** noop macros.
  1080. */
  1081. #define SQLITE_DEPRECATED
  1082. #define SQLITE_EXPERIMENTAL
  1083. /*
  1084. ** Ensure these symbols were not defined by some previous header file.
  1085. */
  1086. #ifdef SQLITE_VERSION
  1087. # undef SQLITE_VERSION
  1088. #endif
  1089. #ifdef SQLITE_VERSION_NUMBER
  1090. # undef SQLITE_VERSION_NUMBER
  1091. #endif
  1092. /*
  1093. ** CAPI3REF: Compile-Time Library Version Numbers
  1094. **
  1095. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1096. ** evaluates to a string literal that is the SQLite version in the
  1097. ** format "X.Y.Z" where X is the major version number (always 3 for
  1098. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1099. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1100. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1101. ** numbers used in [SQLITE_VERSION].)^
  1102. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1103. ** be larger than the release from which it is derived. Either Y will
  1104. ** be held constant and Z will be incremented or else Y will be incremented
  1105. ** and Z will be reset to zero.
  1106. **
  1107. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1108. ** SQLite source code has been stored in the
  1109. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1110. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1111. ** a string which identifies a particular check-in of SQLite
  1112. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1113. ** string contains the date and time of the check-in (UTC) and a SHA1
  1114. ** or SHA3-256 hash of the entire source tree. If the source code has
  1115. ** been edited in any way since it was last checked in, then the last
  1116. ** four hexadecimal digits of the hash may be modified.
  1117. **
  1118. ** See also: [sqlite3_libversion()],
  1119. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1120. ** [sqlite_version()] and [sqlite_source_id()].
  1121. */
  1122. #define SQLITE_VERSION "3.21.0"
  1123. #define SQLITE_VERSION_NUMBER 3021000
  1124. #define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827"
  1125. /*
  1126. ** CAPI3REF: Run-Time Library Version Numbers
  1127. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1128. **
  1129. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1130. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1131. ** but are associated with the library instead of the header file. ^(Cautious
  1132. ** programmers might include assert() statements in their application to
  1133. ** verify that values returned by these interfaces match the macros in
  1134. ** the header, and thus ensure that the application is
  1135. ** compiled with matching library and header files.
  1136. **
  1137. ** <blockquote><pre>
  1138. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1139. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1140. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1141. ** </pre></blockquote>)^
  1142. **
  1143. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1144. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1145. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1146. ** function is provided for use in DLLs since DLL users usually do not have
  1147. ** direct access to string constants within the DLL. ^The
  1148. ** sqlite3_libversion_number() function returns an integer equal to
  1149. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1150. ** a pointer to a string constant whose value is the same as the
  1151. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1152. ** using an edited copy of [the amalgamation], then the last four characters
  1153. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1154. **
  1155. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1156. */
  1157. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1158. SQLITE_API const char *sqlite3_libversion(void);
  1159. SQLITE_API const char *sqlite3_sourceid(void);
  1160. SQLITE_API int sqlite3_libversion_number(void);
  1161. /*
  1162. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1163. **
  1164. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1165. ** indicating whether the specified option was defined at
  1166. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1167. ** option name passed to sqlite3_compileoption_used().
  1168. **
  1169. ** ^The sqlite3_compileoption_get() function allows iterating
  1170. ** over the list of options that were defined at compile time by
  1171. ** returning the N-th compile time option string. ^If N is out of range,
  1172. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1173. ** prefix is omitted from any strings returned by
  1174. ** sqlite3_compileoption_get().
  1175. **
  1176. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1177. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1178. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1179. **
  1180. ** See also: SQL functions [sqlite_compileoption_used()] and
  1181. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1182. */
  1183. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1184. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1185. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1186. #endif
  1187. /*
  1188. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1189. **
  1190. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1191. ** SQLite was compiled with mutexing code omitted due to the
  1192. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1193. **
  1194. ** SQLite can be compiled with or without mutexes. When
  1195. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1196. ** are enabled and SQLite is threadsafe. When the
  1197. ** [SQLITE_THREADSAFE] macro is 0,
  1198. ** the mutexes are omitted. Without the mutexes, it is not safe
  1199. ** to use SQLite concurrently from more than one thread.
  1200. **
  1201. ** Enabling mutexes incurs a measurable performance penalty.
  1202. ** So if speed is of utmost importance, it makes sense to disable
  1203. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1204. ** ^The default behavior is for mutexes to be enabled.
  1205. **
  1206. ** This interface can be used by an application to make sure that the
  1207. ** version of SQLite that it is linking against was compiled with
  1208. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1209. **
  1210. ** This interface only reports on the compile-time mutex setting
  1211. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1212. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1213. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1214. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1215. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1216. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1217. ** thread safety, not any run-time changes to that setting made by
  1218. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1219. ** is unchanged by calls to sqlite3_config().)^
  1220. **
  1221. ** See the [threading mode] documentation for additional information.
  1222. */
  1223. SQLITE_API int sqlite3_threadsafe(void);
  1224. /*
  1225. ** CAPI3REF: Database Connection Handle
  1226. ** KEYWORDS: {database connection} {database connections}
  1227. **
  1228. ** Each open SQLite database is represented by a pointer to an instance of
  1229. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1230. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1231. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1232. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1233. ** interfaces (such as
  1234. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1235. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1236. ** sqlite3 object.
  1237. */
  1238. typedef struct sqlite3 sqlite3;
  1239. /*
  1240. ** CAPI3REF: 64-Bit Integer Types
  1241. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1242. **
  1243. ** Because there is no cross-platform way to specify 64-bit integer types
  1244. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1245. **
  1246. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1247. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1248. ** compatibility only.
  1249. **
  1250. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1251. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1252. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1253. ** between 0 and +18446744073709551615 inclusive.
  1254. */
  1255. #ifdef SQLITE_INT64_TYPE
  1256. typedef SQLITE_INT64_TYPE sqlite_int64;
  1257. # ifdef SQLITE_UINT64_TYPE
  1258. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1259. # else
  1260. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1261. # endif
  1262. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1263. typedef __int64 sqlite_int64;
  1264. typedef unsigned __int64 sqlite_uint64;
  1265. #else
  1266. typedef long long int sqlite_int64;
  1267. typedef unsigned long long int sqlite_uint64;
  1268. #endif
  1269. typedef sqlite_int64 sqlite3_int64;
  1270. typedef sqlite_uint64 sqlite3_uint64;
  1271. /*
  1272. ** If compiling for a processor that lacks floating point support,
  1273. ** substitute integer for floating-point.
  1274. */
  1275. #ifdef SQLITE_OMIT_FLOATING_POINT
  1276. # define double sqlite3_int64
  1277. #endif
  1278. /*
  1279. ** CAPI3REF: Closing A Database Connection
  1280. ** DESTRUCTOR: sqlite3
  1281. **
  1282. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1283. ** for the [sqlite3] object.
  1284. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1285. ** the [sqlite3] object is successfully destroyed and all associated
  1286. ** resources are deallocated.
  1287. **
  1288. ** ^If the database connection is associated with unfinalized prepared
  1289. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1290. ** will leave the database connection open and return [SQLITE_BUSY].
  1291. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1292. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1293. ** an unusable "zombie" which will automatically be deallocated when the
  1294. ** last prepared statement is finalized or the last sqlite3_backup is
  1295. ** finished. The sqlite3_close_v2() interface is intended for use with
  1296. ** host languages that are garbage collected, and where the order in which
  1297. ** destructors are called is arbitrary.
  1298. **
  1299. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1300. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1301. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1302. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1303. ** sqlite3_close_v2() is called on a [database connection] that still has
  1304. ** outstanding [prepared statements], [BLOB handles], and/or
  1305. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1306. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1307. ** and [sqlite3_backup] objects are also destroyed.
  1308. **
  1309. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1310. ** the transaction is automatically rolled back.
  1311. **
  1312. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1313. ** must be either a NULL
  1314. ** pointer or an [sqlite3] object pointer obtained
  1315. ** from [sqlite3_open()], [sqlite3_open16()], or
  1316. ** [sqlite3_open_v2()], and not previously closed.
  1317. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1318. ** argument is a harmless no-op.
  1319. */
  1320. SQLITE_API int sqlite3_close(sqlite3*);
  1321. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1322. /*
  1323. ** The type for a callback function.
  1324. ** This is legacy and deprecated. It is included for historical
  1325. ** compatibility and is not documented.
  1326. */
  1327. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1328. /*
  1329. ** CAPI3REF: One-Step Query Execution Interface
  1330. ** METHOD: sqlite3
  1331. **
  1332. ** The sqlite3_exec() interface is a convenience wrapper around
  1333. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1334. ** that allows an application to run multiple statements of SQL
  1335. ** without having to use a lot of C code.
  1336. **
  1337. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1338. ** semicolon-separate SQL statements passed into its 2nd argument,
  1339. ** in the context of the [database connection] passed in as its 1st
  1340. ** argument. ^If the callback function of the 3rd argument to
  1341. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1342. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1343. ** sqlite3_exec() is relayed through to the 1st argument of each
  1344. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1345. ** is NULL, then no callback is ever invoked and result rows are
  1346. ** ignored.
  1347. **
  1348. ** ^If an error occurs while evaluating the SQL statements passed into
  1349. ** sqlite3_exec(), then execution of the current statement stops and
  1350. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1351. ** is not NULL then any error message is written into memory obtained
  1352. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1353. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1354. ** on error message strings returned through the 5th parameter of
  1355. ** sqlite3_exec() after the error message string is no longer needed.
  1356. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1357. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1358. ** NULL before returning.
  1359. **
  1360. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1361. ** routine returns SQLITE_ABORT without invoking the callback again and
  1362. ** without running any subsequent SQL statements.
  1363. **
  1364. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1365. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1366. ** callback is an array of pointers to strings obtained as if from
  1367. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1368. ** result row is NULL then the corresponding string pointer for the
  1369. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1370. ** sqlite3_exec() callback is an array of pointers to strings where each
  1371. ** entry represents the name of corresponding result column as obtained
  1372. ** from [sqlite3_column_name()].
  1373. **
  1374. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1375. ** to an empty string, or a pointer that contains only whitespace and/or
  1376. ** SQL comments, then no SQL statements are evaluated and the database
  1377. ** is not changed.
  1378. **
  1379. ** Restrictions:
  1380. **
  1381. ** <ul>
  1382. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1383. ** is a valid and open [database connection].
  1384. ** <li> The application must not close the [database connection] specified by
  1385. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1386. ** <li> The application must not modify the SQL statement text passed into
  1387. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1388. ** </ul>
  1389. */
  1390. SQLITE_API int sqlite3_exec(
  1391. sqlite3*, /* An open database */
  1392. const char *sql, /* SQL to be evaluated */
  1393. int (*callback)(void*,int,char**,char**), /* Callback function */
  1394. void *, /* 1st argument to callback */
  1395. char **errmsg /* Error msg written here */
  1396. );
  1397. /*
  1398. ** CAPI3REF: Result Codes
  1399. ** KEYWORDS: {result code definitions}
  1400. **
  1401. ** Many SQLite functions return an integer result code from the set shown
  1402. ** here in order to indicate success or failure.
  1403. **
  1404. ** New error codes may be added in future versions of SQLite.
  1405. **
  1406. ** See also: [extended result code definitions]
  1407. */
  1408. #define SQLITE_OK 0 /* Successful result */
  1409. /* beginning-of-error-codes */
  1410. #define SQLITE_ERROR 1 /* Generic error */
  1411. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1412. #define SQLITE_PERM 3 /* Access permission denied */
  1413. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1414. #define SQLITE_BUSY 5 /* The database file is locked */
  1415. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1416. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1417. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1418. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1419. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1420. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1421. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1422. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1423. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1424. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1425. #define SQLITE_EMPTY 16 /* Internal use only */
  1426. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1427. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1428. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1429. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1430. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1431. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1432. #define SQLITE_AUTH 23 /* Authorization denied */
  1433. #define SQLITE_FORMAT 24 /* Not used */
  1434. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1435. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1436. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1437. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1438. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1439. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1440. /* end-of-error-codes */
  1441. /*
  1442. ** CAPI3REF: Extended Result Codes
  1443. ** KEYWORDS: {extended result code definitions}
  1444. **
  1445. ** In its default configuration, SQLite API routines return one of 30 integer
  1446. ** [result codes]. However, experience has shown that many of
  1447. ** these result codes are too coarse-grained. They do not provide as
  1448. ** much information about problems as programmers might like. In an effort to
  1449. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1450. ** and later) include
  1451. ** support for additional result codes that provide more detailed information
  1452. ** about errors. These [extended result codes] are enabled or disabled
  1453. ** on a per database connection basis using the
  1454. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1455. ** the most recent error can be obtained using
  1456. ** [sqlite3_extended_errcode()].
  1457. */
  1458. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1459. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1460. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1461. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1462. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1463. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1464. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1465. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1466. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1467. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1468. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1469. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1470. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1471. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1472. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1473. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1474. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1475. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1476. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1477. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1478. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1479. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1480. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1481. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1482. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1483. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1484. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1485. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1486. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1487. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1488. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1489. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1490. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1491. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1492. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1493. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1494. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1495. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1496. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1497. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1498. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1499. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1500. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1501. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1502. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1503. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1504. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1505. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1506. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1507. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1508. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1509. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1510. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1511. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1512. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1513. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1514. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1515. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1516. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1517. /*
  1518. ** CAPI3REF: Flags For File Open Operations
  1519. **
  1520. ** These bit values are intended for use in the
  1521. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1522. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1523. */
  1524. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1525. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1526. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1527. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1528. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1529. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1530. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1531. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1532. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1533. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1534. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1535. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1536. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1537. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1538. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1539. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1540. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1541. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1542. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1543. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1544. /* Reserved: 0x00F00000 */
  1545. /*
  1546. ** CAPI3REF: Device Characteristics
  1547. **
  1548. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1549. ** object returns an integer which is a vector of these
  1550. ** bit values expressing I/O characteristics of the mass storage
  1551. ** device that holds the file that the [sqlite3_io_methods]
  1552. ** refers to.
  1553. **
  1554. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1555. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1556. ** mean that writes of blocks that are nnn bytes in size and
  1557. ** are aligned to an address which is an integer multiple of
  1558. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1559. ** that when data is appended to a file, the data is appended
  1560. ** first then the size of the file is extended, never the other
  1561. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1562. ** information is written to disk in the same order as calls
  1563. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1564. ** after reboot following a crash or power loss, the only bytes in a
  1565. ** file that were written at the application level might have changed
  1566. ** and that adjacent bytes, even bytes within the same sector are
  1567. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1568. ** flag indicates that a file cannot be deleted when open. The
  1569. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1570. ** read-only media and cannot be changed even by processes with
  1571. ** elevated privileges.
  1572. **
  1573. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1574. ** filesystem supports doing multiple write operations atomically when those
  1575. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1576. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1577. */
  1578. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1579. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1580. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1581. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1582. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1583. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1584. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1585. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1586. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1587. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1588. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1589. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1590. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1591. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1592. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1593. /*
  1594. ** CAPI3REF: File Locking Levels
  1595. **
  1596. ** SQLite uses one of these integer values as the second
  1597. ** argument to calls it makes to the xLock() and xUnlock() methods
  1598. ** of an [sqlite3_io_methods] object.
  1599. */
  1600. #define SQLITE_LOCK_NONE 0
  1601. #define SQLITE_LOCK_SHARED 1
  1602. #define SQLITE_LOCK_RESERVED 2
  1603. #define SQLITE_LOCK_PENDING 3
  1604. #define SQLITE_LOCK_EXCLUSIVE 4
  1605. /*
  1606. ** CAPI3REF: Synchronization Type Flags
  1607. **
  1608. ** When SQLite invokes the xSync() method of an
  1609. ** [sqlite3_io_methods] object it uses a combination of
  1610. ** these integer values as the second argument.
  1611. **
  1612. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1613. ** sync operation only needs to flush data to mass storage. Inode
  1614. ** information need not be flushed. If the lower four bits of the flag
  1615. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1616. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1617. ** to use Mac OS X style fullsync instead of fsync().
  1618. **
  1619. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1620. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1621. ** settings. The [synchronous pragma] determines when calls to the
  1622. ** xSync VFS method occur and applies uniformly across all platforms.
  1623. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1624. ** energetic or rigorous or forceful the sync operations are and
  1625. ** only make a difference on Mac OSX for the default SQLite code.
  1626. ** (Third-party VFS implementations might also make the distinction
  1627. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1628. ** operating systems natively supported by SQLite, only Mac OSX
  1629. ** cares about the difference.)
  1630. */
  1631. #define SQLITE_SYNC_NORMAL 0x00002
  1632. #define SQLITE_SYNC_FULL 0x00003
  1633. #define SQLITE_SYNC_DATAONLY 0x00010
  1634. /*
  1635. ** CAPI3REF: OS Interface Open File Handle
  1636. **
  1637. ** An [sqlite3_file] object represents an open file in the
  1638. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1639. ** implementations will
  1640. ** want to subclass this object by appending additional fields
  1641. ** for their own use. The pMethods entry is a pointer to an
  1642. ** [sqlite3_io_methods] object that defines methods for performing
  1643. ** I/O operations on the open file.
  1644. */
  1645. typedef struct sqlite3_file sqlite3_file;
  1646. struct sqlite3_file {
  1647. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1648. };
  1649. /*
  1650. ** CAPI3REF: OS Interface File Virtual Methods Object
  1651. **
  1652. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1653. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1654. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1655. ** This object defines the methods used to perform various operations
  1656. ** against the open file represented by the [sqlite3_file] object.
  1657. **
  1658. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1659. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1660. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1661. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1662. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1663. ** to NULL.
  1664. **
  1665. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1666. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1667. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1668. ** flag may be ORed in to indicate that only the data of the file
  1669. ** and not its inode needs to be synced.
  1670. **
  1671. ** The integer values to xLock() and xUnlock() are one of
  1672. ** <ul>
  1673. ** <li> [SQLITE_LOCK_NONE],
  1674. ** <li> [SQLITE_LOCK_SHARED],
  1675. ** <li> [SQLITE_LOCK_RESERVED],
  1676. ** <li> [SQLITE_LOCK_PENDING], or
  1677. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1678. ** </ul>
  1679. ** xLock() increases the lock. xUnlock() decreases the lock.
  1680. ** The xCheckReservedLock() method checks whether any database connection,
  1681. ** either in this process or in some other process, is holding a RESERVED,
  1682. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1683. ** if such a lock exists and false otherwise.
  1684. **
  1685. ** The xFileControl() method is a generic interface that allows custom
  1686. ** VFS implementations to directly control an open file using the
  1687. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1688. ** integer opcode. The third argument is a generic pointer intended to
  1689. ** point to a structure that may contain arguments or space in which to
  1690. ** write return values. Potential uses for xFileControl() might be
  1691. ** functions to enable blocking locks with timeouts, to change the
  1692. ** locking strategy (for example to use dot-file locks), to inquire
  1693. ** about the status of a lock, or to break stale locks. The SQLite
  1694. ** core reserves all opcodes less than 100 for its own use.
  1695. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1696. ** Applications that define a custom xFileControl method should use opcodes
  1697. ** greater than 100 to avoid conflicts. VFS implementations should
  1698. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1699. ** recognize.
  1700. **
  1701. ** The xSectorSize() method returns the sector size of the
  1702. ** device that underlies the file. The sector size is the
  1703. ** minimum write that can be performed without disturbing
  1704. ** other bytes in the file. The xDeviceCharacteristics()
  1705. ** method returns a bit vector describing behaviors of the
  1706. ** underlying device:
  1707. **
  1708. ** <ul>
  1709. ** <li> [SQLITE_IOCAP_ATOMIC]
  1710. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1711. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1712. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1713. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1714. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1715. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1716. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1717. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1718. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1719. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1720. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1721. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1722. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1723. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1724. ** </ul>
  1725. **
  1726. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1727. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1728. ** mean that writes of blocks that are nnn bytes in size and
  1729. ** are aligned to an address which is an integer multiple of
  1730. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1731. ** that when data is appended to a file, the data is appended
  1732. ** first then the size of the file is extended, never the other
  1733. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1734. ** information is written to disk in the same order as calls
  1735. ** to xWrite().
  1736. **
  1737. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1738. ** in the unread portions of the buffer with zeros. A VFS that
  1739. ** fails to zero-fill short reads might seem to work. However,
  1740. ** failure to zero-fill short reads will eventually lead to
  1741. ** database corruption.
  1742. */
  1743. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1744. struct sqlite3_io_methods {
  1745. int iVersion;
  1746. int (*xClose)(sqlite3_file*);
  1747. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1748. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1749. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1750. int (*xSync)(sqlite3_file*, int flags);
  1751. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1752. int (*xLock)(sqlite3_file*, int);
  1753. int (*xUnlock)(sqlite3_file*, int);
  1754. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1755. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1756. int (*xSectorSize)(sqlite3_file*);
  1757. int (*xDeviceCharacteristics)(sqlite3_file*);
  1758. /* Methods above are valid for version 1 */
  1759. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1760. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1761. void (*xShmBarrier)(sqlite3_file*);
  1762. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1763. /* Methods above are valid for version 2 */
  1764. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1765. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1766. /* Methods above are valid for version 3 */
  1767. /* Additional methods may be added in future releases */
  1768. };
  1769. /*
  1770. ** CAPI3REF: Standard File Control Opcodes
  1771. ** KEYWORDS: {file control opcodes} {file control opcode}
  1772. **
  1773. ** These integer constants are opcodes for the xFileControl method
  1774. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1775. ** interface.
  1776. **
  1777. ** <ul>
  1778. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1779. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1780. ** opcode causes the xFileControl method to write the current state of
  1781. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1782. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1783. ** into an integer that the pArg argument points to. This capability
  1784. ** is used during testing and is only available when the SQLITE_TEST
  1785. ** compile-time option is used.
  1786. **
  1787. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1788. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1789. ** layer a hint of how large the database file will grow to be during the
  1790. ** current transaction. This hint is not guaranteed to be accurate but it
  1791. ** is often close. The underlying VFS might choose to preallocate database
  1792. ** file space based on this hint in order to help writes to the database
  1793. ** file run faster.
  1794. **
  1795. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1796. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1797. ** extends and truncates the database file in chunks of a size specified
  1798. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1799. ** point to an integer (type int) containing the new chunk-size to use
  1800. ** for the nominated database. Allocating database file space in large
  1801. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1802. ** improve performance on some systems.
  1803. **
  1804. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1805. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1806. ** to the [sqlite3_file] object associated with a particular database
  1807. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1808. **
  1809. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1810. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1811. ** to the [sqlite3_file] object associated with the journal file (either
  1812. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1813. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1814. **
  1815. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1816. ** No longer in use.
  1817. **
  1818. ** <li>[[SQLITE_FCNTL_SYNC]]
  1819. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1820. ** sent to the VFS immediately before the xSync method is invoked on a
  1821. ** database file descriptor. Or, if the xSync method is not invoked
  1822. ** because the user has configured SQLite with
  1823. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1824. ** of the xSync method. In most cases, the pointer argument passed with
  1825. ** this file-control is NULL. However, if the database file is being synced
  1826. ** as part of a multi-database commit, the argument points to a nul-terminated
  1827. ** string containing the transactions master-journal file name. VFSes that
  1828. ** do not need this signal should silently ignore this opcode. Applications
  1829. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1830. ** disrupt the operation of the specialized VFSes that do require it.
  1831. **
  1832. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1833. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1834. ** and sent to the VFS after a transaction has been committed immediately
  1835. ** but before the database is unlocked. VFSes that do not need this signal
  1836. ** should silently ignore this opcode. Applications should not call
  1837. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1838. ** operation of the specialized VFSes that do require it.
  1839. **
  1840. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1841. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1842. ** retry counts and intervals for certain disk I/O operations for the
  1843. ** windows [VFS] in order to provide robustness in the presence of
  1844. ** anti-virus programs. By default, the windows VFS will retry file read,
  1845. ** file write, and file delete operations up to 10 times, with a delay
  1846. ** of 25 milliseconds before the first retry and with the delay increasing
  1847. ** by an additional 25 milliseconds with each subsequent retry. This
  1848. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1849. ** to be adjusted. The values are changed for all database connections
  1850. ** within the same process. The argument is a pointer to an array of two
  1851. ** integers where the first integer is the new retry count and the second
  1852. ** integer is the delay. If either integer is negative, then the setting
  1853. ** is not changed but instead the prior value of that setting is written
  1854. ** into the array entry, allowing the current retry settings to be
  1855. ** interrogated. The zDbName parameter is ignored.
  1856. **
  1857. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1858. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1859. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1860. ** write ahead log and shared memory files used for transaction control
  1861. ** are automatically deleted when the latest connection to the database
  1862. ** closes. Setting persistent WAL mode causes those files to persist after
  1863. ** close. Persisting the files is useful when other processes that do not
  1864. ** have write permission on the directory containing the database file want
  1865. ** to read the database file, as the WAL and shared memory files must exist
  1866. ** in order for the database to be readable. The fourth parameter to
  1867. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1868. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1869. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1870. ** WAL persistence setting.
  1871. **
  1872. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1873. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1874. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1875. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1876. ** xDeviceCharacteristics methods. The fourth parameter to
  1877. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1878. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1879. ** mode. If the integer is -1, then it is overwritten with the current
  1880. ** zero-damage mode setting.
  1881. **
  1882. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1883. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1884. ** a write transaction to indicate that, unless it is rolled back for some
  1885. ** reason, the entire database file will be overwritten by the current
  1886. ** transaction. This is used by VACUUM operations.
  1887. **
  1888. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1889. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1890. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1891. ** final bottom-level VFS are written into memory obtained from
  1892. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1893. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1894. ** The caller is responsible for freeing the memory when done. As with
  1895. ** all file-control actions, there is no guarantee that this will actually
  1896. ** do anything. Callers should initialize the char* variable to a NULL
  1897. ** pointer in case this file-control is not implemented. This file-control
  1898. ** is intended for diagnostic use only.
  1899. **
  1900. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1901. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1902. ** [VFSes] currently in use. ^(The argument X in
  1903. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1904. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1905. ** to a pointer to the top-level VFS.)^
  1906. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1907. ** upper-most shim only.
  1908. **
  1909. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1910. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1911. ** file control is sent to the open [sqlite3_file] object corresponding
  1912. ** to the database file to which the pragma statement refers. ^The argument
  1913. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1914. ** pointers to strings (char**) in which the second element of the array
  1915. ** is the name of the pragma and the third element is the argument to the
  1916. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1917. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1918. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1919. ** or the equivalent and that string will become the result of the pragma or
  1920. ** the error message if the pragma fails. ^If the
  1921. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1922. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1923. ** file control returns [SQLITE_OK], then the parser assumes that the
  1924. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1925. ** prepared statement if result string is NULL, or that returns a copy
  1926. ** of the result string if the string is non-NULL.
  1927. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1928. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1929. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1930. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1931. ** file control occurs at the beginning of pragma statement analysis and so
  1932. ** it is able to override built-in [PRAGMA] statements.
  1933. **
  1934. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1935. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1936. ** file-control may be invoked by SQLite on the database file handle
  1937. ** shortly after it is opened in order to provide a custom VFS with access
  1938. ** to the connections busy-handler callback. The argument is of type (void **)
  1939. ** - an array of two (void *) values. The first (void *) actually points
  1940. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1941. ** busy-handler, this function should be invoked with the second (void *) in
  1942. ** the array as the only argument. If it returns non-zero, then the operation
  1943. ** should be retried. If it returns zero, the custom VFS should abandon the
  1944. ** current operation.
  1945. **
  1946. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1947. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1948. ** to have SQLite generate a
  1949. ** temporary filename using the same algorithm that is followed to generate
  1950. ** temporary filenames for TEMP tables and other internal uses. The
  1951. ** argument should be a char** which will be filled with the filename
  1952. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1953. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1954. **
  1955. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1956. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1957. ** maximum number of bytes that will be used for memory-mapped I/O.
  1958. ** The argument is a pointer to a value of type sqlite3_int64 that
  1959. ** is an advisory maximum number of bytes in the file to memory map. The
  1960. ** pointer is overwritten with the old value. The limit is not changed if
  1961. ** the value originally pointed to is negative, and so the current limit
  1962. ** can be queried by passing in a pointer to a negative number. This
  1963. ** file-control is used internally to implement [PRAGMA mmap_size].
  1964. **
  1965. ** <li>[[SQLITE_FCNTL_TRACE]]
  1966. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1967. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1968. ** This file control is used by some VFS activity tracing [shims].
  1969. ** The argument is a zero-terminated string. Higher layers in the
  1970. ** SQLite stack may generate instances of this file control if
  1971. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1972. **
  1973. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1974. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1975. ** pointer to an integer and it writes a boolean into that integer depending
  1976. ** on whether or not the file has been renamed, moved, or deleted since it
  1977. ** was first opened.
  1978. **
  1979. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  1980. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  1981. ** underlying native file handle associated with a file handle. This file
  1982. ** control interprets its argument as a pointer to a native file handle and
  1983. ** writes the resulting value there.
  1984. **
  1985. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1986. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1987. ** opcode causes the xFileControl method to swap the file handle with the one
  1988. ** pointed to by the pArg argument. This capability is used during testing
  1989. ** and only needs to be supported when SQLITE_TEST is defined.
  1990. **
  1991. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1992. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1993. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1994. ** available. The WAL subsystem issues this signal during rare
  1995. ** circumstances in order to fix a problem with priority inversion.
  1996. ** Applications should <em>not</em> use this file-control.
  1997. **
  1998. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1999. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2000. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2001. **
  2002. ** <li>[[SQLITE_FCNTL_RBU]]
  2003. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2004. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2005. ** this opcode.
  2006. **
  2007. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2008. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2009. ** the file descriptor is placed in "batch write mode", which
  2010. ** means all subsequent write operations will be deferred and done
  2011. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2012. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2013. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2014. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2015. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2016. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2017. ** except for calls to the xWrite method and the xFileControl method
  2018. ** with [SQLITE_FCNTL_SIZE_HINT].
  2019. **
  2020. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2021. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2022. ** operations since the previous successful call to
  2023. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2024. ** This file control returns [SQLITE_OK] if and only if the writes were
  2025. ** all performed successfully and have been committed to persistent storage.
  2026. ** ^Regardless of whether or not it is successful, this file control takes
  2027. ** the file descriptor out of batch write mode so that all subsequent
  2028. ** write operations are independent.
  2029. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2030. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2031. **
  2032. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2033. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2034. ** operations since the previous successful call to
  2035. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2036. ** ^This file control takes the file descriptor out of batch write mode
  2037. ** so that all subsequent write operations are independent.
  2038. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2039. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2040. ** </ul>
  2041. */
  2042. #define SQLITE_FCNTL_LOCKSTATE 1
  2043. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2044. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2045. #define SQLITE_FCNTL_LAST_ERRNO 4
  2046. #define SQLITE_FCNTL_SIZE_HINT 5
  2047. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2048. #define SQLITE_FCNTL_FILE_POINTER 7
  2049. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2050. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2051. #define SQLITE_FCNTL_PERSIST_WAL 10
  2052. #define SQLITE_FCNTL_OVERWRITE 11
  2053. #define SQLITE_FCNTL_VFSNAME 12
  2054. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2055. #define SQLITE_FCNTL_PRAGMA 14
  2056. #define SQLITE_FCNTL_BUSYHANDLER 15
  2057. #define SQLITE_FCNTL_TEMPFILENAME 16
  2058. #define SQLITE_FCNTL_MMAP_SIZE 18
  2059. #define SQLITE_FCNTL_TRACE 19
  2060. #define SQLITE_FCNTL_HAS_MOVED 20
  2061. #define SQLITE_FCNTL_SYNC 21
  2062. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2063. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2064. #define SQLITE_FCNTL_WAL_BLOCK 24
  2065. #define SQLITE_FCNTL_ZIPVFS 25
  2066. #define SQLITE_FCNTL_RBU 26
  2067. #define SQLITE_FCNTL_VFS_POINTER 27
  2068. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2069. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2070. #define SQLITE_FCNTL_PDB 30
  2071. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2072. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2073. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2074. /* deprecated names */
  2075. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2076. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2077. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2078. /*
  2079. ** CAPI3REF: Mutex Handle
  2080. **
  2081. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2082. ** abstract type for a mutex object. The SQLite core never looks
  2083. ** at the internal representation of an [sqlite3_mutex]. It only
  2084. ** deals with pointers to the [sqlite3_mutex] object.
  2085. **
  2086. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2087. */
  2088. typedef struct sqlite3_mutex sqlite3_mutex;
  2089. /*
  2090. ** CAPI3REF: Loadable Extension Thunk
  2091. **
  2092. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2093. ** the third parameter to entry points of [loadable extensions]. This
  2094. ** structure must be typedefed in order to work around compiler warnings
  2095. ** on some platforms.
  2096. */
  2097. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2098. /*
  2099. ** CAPI3REF: OS Interface Object
  2100. **
  2101. ** An instance of the sqlite3_vfs object defines the interface between
  2102. ** the SQLite core and the underlying operating system. The "vfs"
  2103. ** in the name of the object stands for "virtual file system". See
  2104. ** the [VFS | VFS documentation] for further information.
  2105. **
  2106. ** The value of the iVersion field is initially 1 but may be larger in
  2107. ** future versions of SQLite. Additional fields may be appended to this
  2108. ** object when the iVersion value is increased. Note that the structure
  2109. ** of the sqlite3_vfs object changes in the transaction between
  2110. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  2111. ** modified.
  2112. **
  2113. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2114. ** structure used by this VFS. mxPathname is the maximum length of
  2115. ** a pathname in this VFS.
  2116. **
  2117. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2118. ** the pNext pointer. The [sqlite3_vfs_register()]
  2119. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2120. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2121. ** searches the list. Neither the application code nor the VFS
  2122. ** implementation should use the pNext pointer.
  2123. **
  2124. ** The pNext field is the only field in the sqlite3_vfs
  2125. ** structure that SQLite will ever modify. SQLite will only access
  2126. ** or modify this field while holding a particular static mutex.
  2127. ** The application should never modify anything within the sqlite3_vfs
  2128. ** object once the object has been registered.
  2129. **
  2130. ** The zName field holds the name of the VFS module. The name must
  2131. ** be unique across all VFS modules.
  2132. **
  2133. ** [[sqlite3_vfs.xOpen]]
  2134. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2135. ** is either a NULL pointer or string obtained
  2136. ** from xFullPathname() with an optional suffix added.
  2137. ** ^If a suffix is added to the zFilename parameter, it will
  2138. ** consist of a single "-" character followed by no more than
  2139. ** 11 alphanumeric and/or "-" characters.
  2140. ** ^SQLite further guarantees that
  2141. ** the string will be valid and unchanged until xClose() is
  2142. ** called. Because of the previous sentence,
  2143. ** the [sqlite3_file] can safely store a pointer to the
  2144. ** filename if it needs to remember the filename for some reason.
  2145. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2146. ** must invent its own temporary name for the file. ^Whenever the
  2147. ** xFilename parameter is NULL it will also be the case that the
  2148. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2149. **
  2150. ** The flags argument to xOpen() includes all bits set in
  2151. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2152. ** or [sqlite3_open16()] is used, then flags includes at least
  2153. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2154. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2155. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2156. **
  2157. ** ^(SQLite will also add one of the following flags to the xOpen()
  2158. ** call, depending on the object being opened:
  2159. **
  2160. ** <ul>
  2161. ** <li> [SQLITE_OPEN_MAIN_DB]
  2162. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2163. ** <li> [SQLITE_OPEN_TEMP_DB]
  2164. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2165. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2166. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2167. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2168. ** <li> [SQLITE_OPEN_WAL]
  2169. ** </ul>)^
  2170. **
  2171. ** The file I/O implementation can use the object type flags to
  2172. ** change the way it deals with files. For example, an application
  2173. ** that does not care about crash recovery or rollback might make
  2174. ** the open of a journal file a no-op. Writes to this journal would
  2175. ** also be no-ops, and any attempt to read the journal would return
  2176. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2177. ** file will be doing page-aligned sector reads and writes in a random
  2178. ** order and set up its I/O subsystem accordingly.
  2179. **
  2180. ** SQLite might also add one of the following flags to the xOpen method:
  2181. **
  2182. ** <ul>
  2183. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2184. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2185. ** </ul>
  2186. **
  2187. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2188. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2189. ** will be set for TEMP databases and their journals, transient
  2190. ** databases, and subjournals.
  2191. **
  2192. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2193. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2194. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2195. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2196. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2197. ** be created, and that it is an error if it already exists.
  2198. ** It is <i>not</i> used to indicate the file should be opened
  2199. ** for exclusive access.
  2200. **
  2201. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2202. ** to hold the [sqlite3_file] structure passed as the third
  2203. ** argument to xOpen. The xOpen method does not have to
  2204. ** allocate the structure; it should just fill it in. Note that
  2205. ** the xOpen method must set the sqlite3_file.pMethods to either
  2206. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2207. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2208. ** element will be valid after xOpen returns regardless of the success
  2209. ** or failure of the xOpen call.
  2210. **
  2211. ** [[sqlite3_vfs.xAccess]]
  2212. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2213. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2214. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2215. ** to test whether a file is at least readable. The file can be a
  2216. ** directory.
  2217. **
  2218. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2219. ** output buffer xFullPathname. The exact size of the output buffer
  2220. ** is also passed as a parameter to both methods. If the output buffer
  2221. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2222. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2223. ** to prevent this by setting mxPathname to a sufficiently large value.
  2224. **
  2225. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2226. ** interfaces are not strictly a part of the filesystem, but they are
  2227. ** included in the VFS structure for completeness.
  2228. ** The xRandomness() function attempts to return nBytes bytes
  2229. ** of good-quality randomness into zOut. The return value is
  2230. ** the actual number of bytes of randomness obtained.
  2231. ** The xSleep() method causes the calling thread to sleep for at
  2232. ** least the number of microseconds given. ^The xCurrentTime()
  2233. ** method returns a Julian Day Number for the current date and time as
  2234. ** a floating point value.
  2235. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2236. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2237. ** a 24-hour day).
  2238. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2239. ** date and time if that method is available (if iVersion is 2 or
  2240. ** greater and the function pointer is not NULL) and will fall back
  2241. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2242. **
  2243. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2244. ** are not used by the SQLite core. These optional interfaces are provided
  2245. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2246. ** system calls with functions under its control, a test program can
  2247. ** simulate faults and error conditions that would otherwise be difficult
  2248. ** or impossible to induce. The set of system calls that can be overridden
  2249. ** varies from one VFS to another, and from one version of the same VFS to the
  2250. ** next. Applications that use these interfaces must be prepared for any
  2251. ** or all of these interfaces to be NULL or for their behavior to change
  2252. ** from one release to the next. Applications must not attempt to access
  2253. ** any of these methods if the iVersion of the VFS is less than 3.
  2254. */
  2255. typedef struct sqlite3_vfs sqlite3_vfs;
  2256. typedef void (*sqlite3_syscall_ptr)(void);
  2257. struct sqlite3_vfs {
  2258. int iVersion; /* Structure version number (currently 3) */
  2259. int szOsFile; /* Size of subclassed sqlite3_file */
  2260. int mxPathname; /* Maximum file pathname length */
  2261. sqlite3_vfs *pNext; /* Next registered VFS */
  2262. const char *zName; /* Name of this virtual file system */
  2263. void *pAppData; /* Pointer to application-specific data */
  2264. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2265. int flags, int *pOutFlags);
  2266. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2267. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2268. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2269. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2270. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2271. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2272. void (*xDlClose)(sqlite3_vfs*, void*);
  2273. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2274. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2275. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2276. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2277. /*
  2278. ** The methods above are in version 1 of the sqlite_vfs object
  2279. ** definition. Those that follow are added in version 2 or later
  2280. */
  2281. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2282. /*
  2283. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2284. ** Those below are for version 3 and greater.
  2285. */
  2286. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2287. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2288. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2289. /*
  2290. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2291. ** New fields may be appended in future versions. The iVersion
  2292. ** value will increment whenever this happens.
  2293. */
  2294. };
  2295. /*
  2296. ** CAPI3REF: Flags for the xAccess VFS method
  2297. **
  2298. ** These integer constants can be used as the third parameter to
  2299. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2300. ** what kind of permissions the xAccess method is looking for.
  2301. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2302. ** simply checks whether the file exists.
  2303. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2304. ** checks whether the named directory is both readable and writable
  2305. ** (in other words, if files can be added, removed, and renamed within
  2306. ** the directory).
  2307. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2308. ** [temp_store_directory pragma], though this could change in a future
  2309. ** release of SQLite.
  2310. ** With SQLITE_ACCESS_READ, the xAccess method
  2311. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2312. ** currently unused, though it might be used in a future release of
  2313. ** SQLite.
  2314. */
  2315. #define SQLITE_ACCESS_EXISTS 0
  2316. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2317. #define SQLITE_ACCESS_READ 2 /* Unused */
  2318. /*
  2319. ** CAPI3REF: Flags for the xShmLock VFS method
  2320. **
  2321. ** These integer constants define the various locking operations
  2322. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2323. ** following are the only legal combinations of flags to the
  2324. ** xShmLock method:
  2325. **
  2326. ** <ul>
  2327. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2328. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2329. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2330. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2331. ** </ul>
  2332. **
  2333. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2334. ** was given on the corresponding lock.
  2335. **
  2336. ** The xShmLock method can transition between unlocked and SHARED or
  2337. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2338. ** and EXCLUSIVE.
  2339. */
  2340. #define SQLITE_SHM_UNLOCK 1
  2341. #define SQLITE_SHM_LOCK 2
  2342. #define SQLITE_SHM_SHARED 4
  2343. #define SQLITE_SHM_EXCLUSIVE 8
  2344. /*
  2345. ** CAPI3REF: Maximum xShmLock index
  2346. **
  2347. ** The xShmLock method on [sqlite3_io_methods] may use values
  2348. ** between 0 and this upper bound as its "offset" argument.
  2349. ** The SQLite core will never attempt to acquire or release a
  2350. ** lock outside of this range
  2351. */
  2352. #define SQLITE_SHM_NLOCK 8
  2353. /*
  2354. ** CAPI3REF: Initialize The SQLite Library
  2355. **
  2356. ** ^The sqlite3_initialize() routine initializes the
  2357. ** SQLite library. ^The sqlite3_shutdown() routine
  2358. ** deallocates any resources that were allocated by sqlite3_initialize().
  2359. ** These routines are designed to aid in process initialization and
  2360. ** shutdown on embedded systems. Workstation applications using
  2361. ** SQLite normally do not need to invoke either of these routines.
  2362. **
  2363. ** A call to sqlite3_initialize() is an "effective" call if it is
  2364. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2365. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2366. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2367. ** of sqlite3_initialize() does any initialization. All other calls
  2368. ** are harmless no-ops.)^
  2369. **
  2370. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2371. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2372. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2373. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2374. **
  2375. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2376. ** is not. The sqlite3_shutdown() interface must only be called from a
  2377. ** single thread. All open [database connections] must be closed and all
  2378. ** other SQLite resources must be deallocated prior to invoking
  2379. ** sqlite3_shutdown().
  2380. **
  2381. ** Among other things, ^sqlite3_initialize() will invoke
  2382. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2383. ** will invoke sqlite3_os_end().
  2384. **
  2385. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2386. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2387. ** the library (perhaps it is unable to allocate a needed resource such
  2388. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2389. **
  2390. ** ^The sqlite3_initialize() routine is called internally by many other
  2391. ** SQLite interfaces so that an application usually does not need to
  2392. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2393. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2394. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2395. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2396. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2397. ** are omitted and the application must call sqlite3_initialize() directly
  2398. ** prior to using any other SQLite interface. For maximum portability,
  2399. ** it is recommended that applications always invoke sqlite3_initialize()
  2400. ** directly prior to using any other SQLite interface. Future releases
  2401. ** of SQLite may require this. In other words, the behavior exhibited
  2402. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2403. ** default behavior in some future release of SQLite.
  2404. **
  2405. ** The sqlite3_os_init() routine does operating-system specific
  2406. ** initialization of the SQLite library. The sqlite3_os_end()
  2407. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2408. ** performed by these routines include allocation or deallocation
  2409. ** of static resources, initialization of global variables,
  2410. ** setting up a default [sqlite3_vfs] module, or setting up
  2411. ** a default configuration using [sqlite3_config()].
  2412. **
  2413. ** The application should never invoke either sqlite3_os_init()
  2414. ** or sqlite3_os_end() directly. The application should only invoke
  2415. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2416. ** interface is called automatically by sqlite3_initialize() and
  2417. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2418. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2419. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2420. ** When [custom builds | built for other platforms]
  2421. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2422. ** option) the application must supply a suitable implementation for
  2423. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2424. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2425. ** must return [SQLITE_OK] on success and some other [error code] upon
  2426. ** failure.
  2427. */
  2428. SQLITE_API int sqlite3_initialize(void);
  2429. SQLITE_API int sqlite3_shutdown(void);
  2430. SQLITE_API int sqlite3_os_init(void);
  2431. SQLITE_API int sqlite3_os_end(void);
  2432. /*
  2433. ** CAPI3REF: Configuring The SQLite Library
  2434. **
  2435. ** The sqlite3_config() interface is used to make global configuration
  2436. ** changes to SQLite in order to tune SQLite to the specific needs of
  2437. ** the application. The default configuration is recommended for most
  2438. ** applications and so this routine is usually not necessary. It is
  2439. ** provided to support rare applications with unusual needs.
  2440. **
  2441. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2442. ** must ensure that no other SQLite interfaces are invoked by other
  2443. ** threads while sqlite3_config() is running.</b>
  2444. **
  2445. ** The sqlite3_config() interface
  2446. ** may only be invoked prior to library initialization using
  2447. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2448. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2449. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2450. ** Note, however, that ^sqlite3_config() can be called as part of the
  2451. ** implementation of an application-defined [sqlite3_os_init()].
  2452. **
  2453. ** The first argument to sqlite3_config() is an integer
  2454. ** [configuration option] that determines
  2455. ** what property of SQLite is to be configured. Subsequent arguments
  2456. ** vary depending on the [configuration option]
  2457. ** in the first argument.
  2458. **
  2459. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2460. ** ^If the option is unknown or SQLite is unable to set the option
  2461. ** then this routine returns a non-zero [error code].
  2462. */
  2463. SQLITE_API int sqlite3_config(int, ...);
  2464. /*
  2465. ** CAPI3REF: Configure database connections
  2466. ** METHOD: sqlite3
  2467. **
  2468. ** The sqlite3_db_config() interface is used to make configuration
  2469. ** changes to a [database connection]. The interface is similar to
  2470. ** [sqlite3_config()] except that the changes apply to a single
  2471. ** [database connection] (specified in the first argument).
  2472. **
  2473. ** The second argument to sqlite3_db_config(D,V,...) is the
  2474. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2475. ** that indicates what aspect of the [database connection] is being configured.
  2476. ** Subsequent arguments vary depending on the configuration verb.
  2477. **
  2478. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2479. ** the call is considered successful.
  2480. */
  2481. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2482. /*
  2483. ** CAPI3REF: Memory Allocation Routines
  2484. **
  2485. ** An instance of this object defines the interface between SQLite
  2486. ** and low-level memory allocation routines.
  2487. **
  2488. ** This object is used in only one place in the SQLite interface.
  2489. ** A pointer to an instance of this object is the argument to
  2490. ** [sqlite3_config()] when the configuration option is
  2491. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2492. ** By creating an instance of this object
  2493. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2494. ** during configuration, an application can specify an alternative
  2495. ** memory allocation subsystem for SQLite to use for all of its
  2496. ** dynamic memory needs.
  2497. **
  2498. ** Note that SQLite comes with several [built-in memory allocators]
  2499. ** that are perfectly adequate for the overwhelming majority of applications
  2500. ** and that this object is only useful to a tiny minority of applications
  2501. ** with specialized memory allocation requirements. This object is
  2502. ** also used during testing of SQLite in order to specify an alternative
  2503. ** memory allocator that simulates memory out-of-memory conditions in
  2504. ** order to verify that SQLite recovers gracefully from such
  2505. ** conditions.
  2506. **
  2507. ** The xMalloc, xRealloc, and xFree methods must work like the
  2508. ** malloc(), realloc() and free() functions from the standard C library.
  2509. ** ^SQLite guarantees that the second argument to
  2510. ** xRealloc is always a value returned by a prior call to xRoundup.
  2511. **
  2512. ** xSize should return the allocated size of a memory allocation
  2513. ** previously obtained from xMalloc or xRealloc. The allocated size
  2514. ** is always at least as big as the requested size but may be larger.
  2515. **
  2516. ** The xRoundup method returns what would be the allocated size of
  2517. ** a memory allocation given a particular requested size. Most memory
  2518. ** allocators round up memory allocations at least to the next multiple
  2519. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2520. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2521. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2522. ** that causes the corresponding memory allocation to fail.
  2523. **
  2524. ** The xInit method initializes the memory allocator. For example,
  2525. ** it might allocate any require mutexes or initialize internal data
  2526. ** structures. The xShutdown method is invoked (indirectly) by
  2527. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2528. ** by xInit. The pAppData pointer is used as the only parameter to
  2529. ** xInit and xShutdown.
  2530. **
  2531. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2532. ** the xInit method, so the xInit method need not be threadsafe. The
  2533. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2534. ** not need to be threadsafe either. For all other methods, SQLite
  2535. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2536. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2537. ** it is by default) and so the methods are automatically serialized.
  2538. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2539. ** methods must be threadsafe or else make their own arrangements for
  2540. ** serialization.
  2541. **
  2542. ** SQLite will never invoke xInit() more than once without an intervening
  2543. ** call to xShutdown().
  2544. */
  2545. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2546. struct sqlite3_mem_methods {
  2547. void *(*xMalloc)(int); /* Memory allocation function */
  2548. void (*xFree)(void*); /* Free a prior allocation */
  2549. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2550. int (*xSize)(void*); /* Return the size of an allocation */
  2551. int (*xRoundup)(int); /* Round up request size to allocation size */
  2552. int (*xInit)(void*); /* Initialize the memory allocator */
  2553. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2554. void *pAppData; /* Argument to xInit() and xShutdown() */
  2555. };
  2556. /*
  2557. ** CAPI3REF: Configuration Options
  2558. ** KEYWORDS: {configuration option}
  2559. **
  2560. ** These constants are the available integer configuration options that
  2561. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2562. **
  2563. ** New configuration options may be added in future releases of SQLite.
  2564. ** Existing configuration options might be discontinued. Applications
  2565. ** should check the return code from [sqlite3_config()] to make sure that
  2566. ** the call worked. The [sqlite3_config()] interface will return a
  2567. ** non-zero [error code] if a discontinued or unsupported configuration option
  2568. ** is invoked.
  2569. **
  2570. ** <dl>
  2571. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2572. ** <dd>There are no arguments to this option. ^This option sets the
  2573. ** [threading mode] to Single-thread. In other words, it disables
  2574. ** all mutexing and puts SQLite into a mode where it can only be used
  2575. ** by a single thread. ^If SQLite is compiled with
  2576. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2577. ** it is not possible to change the [threading mode] from its default
  2578. ** value of Single-thread and so [sqlite3_config()] will return
  2579. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2580. ** configuration option.</dd>
  2581. **
  2582. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2583. ** <dd>There are no arguments to this option. ^This option sets the
  2584. ** [threading mode] to Multi-thread. In other words, it disables
  2585. ** mutexing on [database connection] and [prepared statement] objects.
  2586. ** The application is responsible for serializing access to
  2587. ** [database connections] and [prepared statements]. But other mutexes
  2588. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2589. ** environment as long as no two threads attempt to use the same
  2590. ** [database connection] at the same time. ^If SQLite is compiled with
  2591. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2592. ** it is not possible to set the Multi-thread [threading mode] and
  2593. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2594. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2595. **
  2596. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2597. ** <dd>There are no arguments to this option. ^This option sets the
  2598. ** [threading mode] to Serialized. In other words, this option enables
  2599. ** all mutexes including the recursive
  2600. ** mutexes on [database connection] and [prepared statement] objects.
  2601. ** In this mode (which is the default when SQLite is compiled with
  2602. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2603. ** to [database connections] and [prepared statements] so that the
  2604. ** application is free to use the same [database connection] or the
  2605. ** same [prepared statement] in different threads at the same time.
  2606. ** ^If SQLite is compiled with
  2607. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2608. ** it is not possible to set the Serialized [threading mode] and
  2609. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2610. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2611. **
  2612. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2613. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2614. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2615. ** The argument specifies
  2616. ** alternative low-level memory allocation routines to be used in place of
  2617. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2618. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2619. ** before the [sqlite3_config()] call returns.</dd>
  2620. **
  2621. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2622. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2623. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2624. ** The [sqlite3_mem_methods]
  2625. ** structure is filled with the currently defined memory allocation routines.)^
  2626. ** This option can be used to overload the default memory allocation
  2627. ** routines with a wrapper that simulations memory allocation failure or
  2628. ** tracks memory usage, for example. </dd>
  2629. **
  2630. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2631. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2632. ** type int, interpreted as a boolean, which if true provides a hint to
  2633. ** SQLite that it should avoid large memory allocations if possible.
  2634. ** SQLite will run faster if it is free to make large memory allocations,
  2635. ** but some application might prefer to run slower in exchange for
  2636. ** guarantees about memory fragmentation that are possible if large
  2637. ** allocations are avoided. This hint is normally off.
  2638. ** </dd>
  2639. **
  2640. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2641. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2642. ** interpreted as a boolean, which enables or disables the collection of
  2643. ** memory allocation statistics. ^(When memory allocation statistics are
  2644. ** disabled, the following SQLite interfaces become non-operational:
  2645. ** <ul>
  2646. ** <li> [sqlite3_memory_used()]
  2647. ** <li> [sqlite3_memory_highwater()]
  2648. ** <li> [sqlite3_soft_heap_limit64()]
  2649. ** <li> [sqlite3_status64()]
  2650. ** </ul>)^
  2651. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2652. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2653. ** allocation statistics are disabled by default.
  2654. ** </dd>
  2655. **
  2656. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2657. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2658. ** </dd>
  2659. **
  2660. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2661. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2662. ** that SQLite can use for the database page cache with the default page
  2663. ** cache implementation.
  2664. ** This configuration option is a no-op if an application-define page
  2665. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2666. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2667. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2668. ** and the number of cache lines (N).
  2669. ** The sz argument should be the size of the largest database page
  2670. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2671. ** page header. ^The number of extra bytes needed by the page header
  2672. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2673. ** ^It is harmless, apart from the wasted memory,
  2674. ** for the sz parameter to be larger than necessary. The pMem
  2675. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2676. ** aligned block of memory of at least sz*N bytes, otherwise
  2677. ** subsequent behavior is undefined.
  2678. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2679. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2680. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2681. ** is exhausted.
  2682. ** ^If pMem is NULL and N is non-zero, then each database connection
  2683. ** does an initial bulk allocation for page cache memory
  2684. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2685. ** of -1024*N bytes if N is negative, . ^If additional
  2686. ** page cache memory is needed beyond what is provided by the initial
  2687. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2688. ** additional cache line. </dd>
  2689. **
  2690. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2691. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2692. ** that SQLite will use for all of its dynamic memory allocation needs
  2693. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2694. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2695. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2696. ** [SQLITE_ERROR] if invoked otherwise.
  2697. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2698. ** An 8-byte aligned pointer to the memory,
  2699. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2700. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2701. ** to using its default memory allocator (the system malloc() implementation),
  2702. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2703. ** memory pointer is not NULL then the alternative memory
  2704. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2705. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2706. ** boundary or subsequent behavior of SQLite will be undefined.
  2707. ** The minimum allocation size is capped at 2**12. Reasonable values
  2708. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2709. **
  2710. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2711. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2712. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2713. ** The argument specifies alternative low-level mutex routines to be used
  2714. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2715. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2716. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2717. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2718. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2719. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2720. ** return [SQLITE_ERROR].</dd>
  2721. **
  2722. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2723. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2724. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2725. ** [sqlite3_mutex_methods]
  2726. ** structure is filled with the currently defined mutex routines.)^
  2727. ** This option can be used to overload the default mutex allocation
  2728. ** routines with a wrapper used to track mutex usage for performance
  2729. ** profiling or testing, for example. ^If SQLite is compiled with
  2730. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2731. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2732. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2733. ** return [SQLITE_ERROR].</dd>
  2734. **
  2735. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2736. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2737. ** the default size of lookaside memory on each [database connection].
  2738. ** The first argument is the
  2739. ** size of each lookaside buffer slot and the second is the number of
  2740. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2741. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2742. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2743. ** configuration on individual connections.)^ </dd>
  2744. **
  2745. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2746. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2747. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2748. ** the interface to a custom page cache implementation.)^
  2749. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2750. **
  2751. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2752. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2753. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2754. ** the current page cache implementation into that object.)^ </dd>
  2755. **
  2756. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2757. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2758. ** global [error log].
  2759. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2760. ** function with a call signature of void(*)(void*,int,const char*),
  2761. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2762. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2763. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2764. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2765. ** passed through as the first parameter to the application-defined logger
  2766. ** function whenever that function is invoked. ^The second parameter to
  2767. ** the logger function is a copy of the first parameter to the corresponding
  2768. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2769. ** [extended result code]. ^The third parameter passed to the logger is
  2770. ** log message after formatting via [sqlite3_snprintf()].
  2771. ** The SQLite logging interface is not reentrant; the logger function
  2772. ** supplied by the application must not invoke any SQLite interface.
  2773. ** In a multi-threaded application, the application-defined logger
  2774. ** function must be threadsafe. </dd>
  2775. **
  2776. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2777. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2778. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2779. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2780. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2781. ** [sqlite3_open16()] or
  2782. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2783. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2784. ** connection is opened. ^If it is globally disabled, filenames are
  2785. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2786. ** database connection is opened. ^(By default, URI handling is globally
  2787. ** disabled. The default value may be changed by compiling with the
  2788. ** [SQLITE_USE_URI] symbol defined.)^
  2789. **
  2790. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2791. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2792. ** argument which is interpreted as a boolean in order to enable or disable
  2793. ** the use of covering indices for full table scans in the query optimizer.
  2794. ** ^The default setting is determined
  2795. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2796. ** if that compile-time option is omitted.
  2797. ** The ability to disable the use of covering indices for full table scans
  2798. ** is because some incorrectly coded legacy applications might malfunction
  2799. ** when the optimization is enabled. Providing the ability to
  2800. ** disable the optimization allows the older, buggy application code to work
  2801. ** without change even with newer versions of SQLite.
  2802. **
  2803. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2804. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2805. ** <dd> These options are obsolete and should not be used by new code.
  2806. ** They are retained for backwards compatibility but are now no-ops.
  2807. ** </dd>
  2808. **
  2809. ** [[SQLITE_CONFIG_SQLLOG]]
  2810. ** <dt>SQLITE_CONFIG_SQLLOG
  2811. ** <dd>This option is only available if sqlite is compiled with the
  2812. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2813. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2814. ** The second should be of type (void*). The callback is invoked by the library
  2815. ** in three separate circumstances, identified by the value passed as the
  2816. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2817. ** passed as the second argument has just been opened. The third argument
  2818. ** points to a buffer containing the name of the main database file. If the
  2819. ** fourth parameter is 1, then the SQL statement that the third parameter
  2820. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2821. ** the connection being passed as the second parameter is being closed. The
  2822. ** third parameter is passed NULL In this case. An example of using this
  2823. ** configuration option can be seen in the "test_sqllog.c" source file in
  2824. ** the canonical SQLite source tree.</dd>
  2825. **
  2826. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2827. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2828. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2829. ** that are the default mmap size limit (the default setting for
  2830. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2831. ** ^The default setting can be overridden by each database connection using
  2832. ** either the [PRAGMA mmap_size] command, or by using the
  2833. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2834. ** will be silently truncated if necessary so that it does not exceed the
  2835. ** compile-time maximum mmap size set by the
  2836. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2837. ** ^If either argument to this option is negative, then that argument is
  2838. ** changed to its compile-time default.
  2839. **
  2840. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2841. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2842. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2843. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2844. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2845. ** that specifies the maximum size of the created heap.
  2846. **
  2847. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2848. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2849. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2850. ** is a pointer to an integer and writes into that integer the number of extra
  2851. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2852. ** The amount of extra space required can change depending on the compiler,
  2853. ** target platform, and SQLite version.
  2854. **
  2855. ** [[SQLITE_CONFIG_PMASZ]]
  2856. ** <dt>SQLITE_CONFIG_PMASZ
  2857. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2858. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2859. ** sorter to that integer. The default minimum PMA Size is set by the
  2860. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2861. ** to help with sort operations when multithreaded sorting
  2862. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2863. ** to be sorted exceeds the page size times the minimum of the
  2864. ** [PRAGMA cache_size] setting and this value.
  2865. **
  2866. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2867. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2868. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2869. ** becomes the [statement journal] spill-to-disk threshold.
  2870. ** [Statement journals] are held in memory until their size (in bytes)
  2871. ** exceeds this threshold, at which point they are written to disk.
  2872. ** Or if the threshold is -1, statement journals are always held
  2873. ** exclusively in memory.
  2874. ** Since many statement journals never become large, setting the spill
  2875. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2876. ** I/O required to support statement rollback.
  2877. ** The default value for this setting is controlled by the
  2878. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2879. ** </dl>
  2880. */
  2881. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2882. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2883. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2884. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2885. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2886. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2887. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2888. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2889. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2890. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2891. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2892. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2893. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2894. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2895. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2896. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2897. #define SQLITE_CONFIG_URI 17 /* int */
  2898. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2899. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2900. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2901. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2902. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2903. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2904. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2905. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2906. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2907. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  2908. /*
  2909. ** CAPI3REF: Database Connection Configuration Options
  2910. **
  2911. ** These constants are the available integer configuration options that
  2912. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2913. **
  2914. ** New configuration options may be added in future releases of SQLite.
  2915. ** Existing configuration options might be discontinued. Applications
  2916. ** should check the return code from [sqlite3_db_config()] to make sure that
  2917. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2918. ** non-zero [error code] if a discontinued or unsupported configuration option
  2919. ** is invoked.
  2920. **
  2921. ** <dl>
  2922. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2923. ** <dd> ^This option takes three additional arguments that determine the
  2924. ** [lookaside memory allocator] configuration for the [database connection].
  2925. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2926. ** pointer to a memory buffer to use for lookaside memory.
  2927. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2928. ** may be NULL in which case SQLite will allocate the
  2929. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2930. ** size of each lookaside buffer slot. ^The third argument is the number of
  2931. ** slots. The size of the buffer in the first argument must be greater than
  2932. ** or equal to the product of the second and third arguments. The buffer
  2933. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2934. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2935. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2936. ** configuration for a database connection can only be changed when that
  2937. ** connection is not currently using lookaside memory, or in other words
  2938. ** when the "current value" returned by
  2939. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2940. ** Any attempt to change the lookaside memory configuration when lookaside
  2941. ** memory is in use leaves the configuration unchanged and returns
  2942. ** [SQLITE_BUSY].)^</dd>
  2943. **
  2944. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2945. ** <dd> ^This option is used to enable or disable the enforcement of
  2946. ** [foreign key constraints]. There should be two additional arguments.
  2947. ** The first argument is an integer which is 0 to disable FK enforcement,
  2948. ** positive to enable FK enforcement or negative to leave FK enforcement
  2949. ** unchanged. The second parameter is a pointer to an integer into which
  2950. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2951. ** following this call. The second parameter may be a NULL pointer, in
  2952. ** which case the FK enforcement setting is not reported back. </dd>
  2953. **
  2954. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2955. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2956. ** There should be two additional arguments.
  2957. ** The first argument is an integer which is 0 to disable triggers,
  2958. ** positive to enable triggers or negative to leave the setting unchanged.
  2959. ** The second parameter is a pointer to an integer into which
  2960. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2961. ** following this call. The second parameter may be a NULL pointer, in
  2962. ** which case the trigger setting is not reported back. </dd>
  2963. **
  2964. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  2965. ** <dd> ^This option is used to enable or disable the two-argument
  2966. ** version of the [fts3_tokenizer()] function which is part of the
  2967. ** [FTS3] full-text search engine extension.
  2968. ** There should be two additional arguments.
  2969. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  2970. ** positive to enable fts3_tokenizer() or negative to leave the setting
  2971. ** unchanged.
  2972. ** The second parameter is a pointer to an integer into which
  2973. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  2974. ** following this call. The second parameter may be a NULL pointer, in
  2975. ** which case the new setting is not reported back. </dd>
  2976. **
  2977. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  2978. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  2979. ** interface independently of the [load_extension()] SQL function.
  2980. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  2981. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  2982. ** There should be two additional arguments.
  2983. ** When the first argument to this interface is 1, then only the C-API is
  2984. ** enabled and the SQL function remains disabled. If the first argument to
  2985. ** this interface is 0, then both the C-API and the SQL function are disabled.
  2986. ** If the first argument is -1, then no changes are made to state of either the
  2987. ** C-API or the SQL function.
  2988. ** The second parameter is a pointer to an integer into which
  2989. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  2990. ** is disabled or enabled following this call. The second parameter may
  2991. ** be a NULL pointer, in which case the new setting is not reported back.
  2992. ** </dd>
  2993. **
  2994. ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  2995. ** <dd> ^This option is used to change the name of the "main" database
  2996. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  2997. ** which will become the new schema name in place of "main". ^SQLite
  2998. ** does not make a copy of the new main schema name string, so the application
  2999. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3000. ** until after the database connection closes.
  3001. ** </dd>
  3002. **
  3003. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3004. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3005. ** database handle, SQLite checks if this will mean that there are now no
  3006. ** connections at all to the database. If so, it performs a checkpoint
  3007. ** operation before closing the connection. This option may be used to
  3008. ** override this behaviour. The first parameter passed to this operation
  3009. ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
  3010. ** default) to enable them. The second parameter is a pointer to an integer
  3011. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3012. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3013. ** </dd>
  3014. **
  3015. ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3016. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3017. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3018. ** a single SQL query statement will always use the same algorithm regardless
  3019. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3020. ** that look at the values of bound parameters, which can make some queries
  3021. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3022. ** the QPSG active, SQLite will always use the same query plan in the field as
  3023. ** was used during testing in the lab.
  3024. ** </dd>
  3025. **
  3026. ** </dl>
  3027. */
  3028. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3029. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3030. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3031. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3032. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3033. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3034. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3035. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3036. /*
  3037. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3038. ** METHOD: sqlite3
  3039. **
  3040. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3041. ** [extended result codes] feature of SQLite. ^The extended result
  3042. ** codes are disabled by default for historical compatibility.
  3043. */
  3044. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3045. /*
  3046. ** CAPI3REF: Last Insert Rowid
  3047. ** METHOD: sqlite3
  3048. **
  3049. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3050. ** has a unique 64-bit signed
  3051. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3052. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3053. ** names are not also used by explicitly declared columns. ^If
  3054. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3055. ** is another alias for the rowid.
  3056. **
  3057. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3058. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3059. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3060. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3061. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3062. ** zero.
  3063. **
  3064. ** As well as being set automatically as rows are inserted into database
  3065. ** tables, the value returned by this function may be set explicitly by
  3066. ** [sqlite3_set_last_insert_rowid()]
  3067. **
  3068. ** Some virtual table implementations may INSERT rows into rowid tables as
  3069. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3070. ** to disk). In this case subsequent calls to this function return the rowid
  3071. ** associated with these internal INSERT operations, which leads to
  3072. ** unintuitive results. Virtual table implementations that do write to rowid
  3073. ** tables in this way can avoid this problem by restoring the original
  3074. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3075. ** control to the user.
  3076. **
  3077. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3078. ** return the [rowid] of the inserted row as long as the trigger is
  3079. ** running. Once the trigger program ends, the value returned
  3080. ** by this routine reverts to what it was before the trigger was fired.)^
  3081. **
  3082. ** ^An [INSERT] that fails due to a constraint violation is not a
  3083. ** successful [INSERT] and does not change the value returned by this
  3084. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3085. ** and INSERT OR ABORT make no changes to the return value of this
  3086. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3087. ** encounters a constraint violation, it does not fail. The
  3088. ** INSERT continues to completion after deleting rows that caused
  3089. ** the constraint problem so INSERT OR REPLACE will always change
  3090. ** the return value of this interface.)^
  3091. **
  3092. ** ^For the purposes of this routine, an [INSERT] is considered to
  3093. ** be successful even if it is subsequently rolled back.
  3094. **
  3095. ** This function is accessible to SQL statements via the
  3096. ** [last_insert_rowid() SQL function].
  3097. **
  3098. ** If a separate thread performs a new [INSERT] on the same
  3099. ** database connection while the [sqlite3_last_insert_rowid()]
  3100. ** function is running and thus changes the last insert [rowid],
  3101. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3102. ** unpredictable and might not equal either the old or the new
  3103. ** last insert [rowid].
  3104. */
  3105. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3106. /*
  3107. ** CAPI3REF: Set the Last Insert Rowid value.
  3108. ** METHOD: sqlite3
  3109. **
  3110. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3111. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3112. ** without inserting a row into the database.
  3113. */
  3114. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3115. /*
  3116. ** CAPI3REF: Count The Number Of Rows Modified
  3117. ** METHOD: sqlite3
  3118. **
  3119. ** ^This function returns the number of rows modified, inserted or
  3120. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3121. ** statement on the database connection specified by the only parameter.
  3122. ** ^Executing any other type of SQL statement does not modify the value
  3123. ** returned by this function.
  3124. **
  3125. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3126. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3127. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3128. **
  3129. ** Changes to a view that are intercepted by
  3130. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3131. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3132. ** DELETE statement run on a view is always zero. Only changes made to real
  3133. ** tables are counted.
  3134. **
  3135. ** Things are more complicated if the sqlite3_changes() function is
  3136. ** executed while a trigger program is running. This may happen if the
  3137. ** program uses the [changes() SQL function], or if some other callback
  3138. ** function invokes sqlite3_changes() directly. Essentially:
  3139. **
  3140. ** <ul>
  3141. ** <li> ^(Before entering a trigger program the value returned by
  3142. ** sqlite3_changes() function is saved. After the trigger program
  3143. ** has finished, the original value is restored.)^
  3144. **
  3145. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3146. ** statement sets the value returned by sqlite3_changes()
  3147. ** upon completion as normal. Of course, this value will not include
  3148. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3149. ** value will be saved and restored after each sub-trigger has run.)^
  3150. ** </ul>
  3151. **
  3152. ** ^This means that if the changes() SQL function (or similar) is used
  3153. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3154. ** returns the value as set when the calling statement began executing.
  3155. ** ^If it is used by the second or subsequent such statement within a trigger
  3156. ** program, the value returned reflects the number of rows modified by the
  3157. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3158. **
  3159. ** See also the [sqlite3_total_changes()] interface, the
  3160. ** [count_changes pragma], and the [changes() SQL function].
  3161. **
  3162. ** If a separate thread makes changes on the same database connection
  3163. ** while [sqlite3_changes()] is running then the value returned
  3164. ** is unpredictable and not meaningful.
  3165. */
  3166. SQLITE_API int sqlite3_changes(sqlite3*);
  3167. /*
  3168. ** CAPI3REF: Total Number Of Rows Modified
  3169. ** METHOD: sqlite3
  3170. **
  3171. ** ^This function returns the total number of rows inserted, modified or
  3172. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3173. ** since the database connection was opened, including those executed as
  3174. ** part of trigger programs. ^Executing any other type of SQL statement
  3175. ** does not affect the value returned by sqlite3_total_changes().
  3176. **
  3177. ** ^Changes made as part of [foreign key actions] are included in the
  3178. ** count, but those made as part of REPLACE constraint resolution are
  3179. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3180. ** are not counted.
  3181. **
  3182. ** See also the [sqlite3_changes()] interface, the
  3183. ** [count_changes pragma], and the [total_changes() SQL function].
  3184. **
  3185. ** If a separate thread makes changes on the same database connection
  3186. ** while [sqlite3_total_changes()] is running then the value
  3187. ** returned is unpredictable and not meaningful.
  3188. */
  3189. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3190. /*
  3191. ** CAPI3REF: Interrupt A Long-Running Query
  3192. ** METHOD: sqlite3
  3193. **
  3194. ** ^This function causes any pending database operation to abort and
  3195. ** return at its earliest opportunity. This routine is typically
  3196. ** called in response to a user action such as pressing "Cancel"
  3197. ** or Ctrl-C where the user wants a long query operation to halt
  3198. ** immediately.
  3199. **
  3200. ** ^It is safe to call this routine from a thread different from the
  3201. ** thread that is currently running the database operation. But it
  3202. ** is not safe to call this routine with a [database connection] that
  3203. ** is closed or might close before sqlite3_interrupt() returns.
  3204. **
  3205. ** ^If an SQL operation is very nearly finished at the time when
  3206. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3207. ** to be interrupted and might continue to completion.
  3208. **
  3209. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3210. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3211. ** that is inside an explicit transaction, then the entire transaction
  3212. ** will be rolled back automatically.
  3213. **
  3214. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3215. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3216. ** that are started after the sqlite3_interrupt() call and before the
  3217. ** running statements reaches zero are interrupted as if they had been
  3218. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3219. ** that are started after the running statement count reaches zero are
  3220. ** not effected by the sqlite3_interrupt().
  3221. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3222. ** SQL statements is a no-op and has no effect on SQL statements
  3223. ** that are started after the sqlite3_interrupt() call returns.
  3224. */
  3225. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3226. /*
  3227. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3228. **
  3229. ** These routines are useful during command-line input to determine if the
  3230. ** currently entered text seems to form a complete SQL statement or
  3231. ** if additional input is needed before sending the text into
  3232. ** SQLite for parsing. ^These routines return 1 if the input string
  3233. ** appears to be a complete SQL statement. ^A statement is judged to be
  3234. ** complete if it ends with a semicolon token and is not a prefix of a
  3235. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3236. ** string literals or quoted identifier names or comments are not
  3237. ** independent tokens (they are part of the token in which they are
  3238. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3239. ** and comments that follow the final semicolon are ignored.
  3240. **
  3241. ** ^These routines return 0 if the statement is incomplete. ^If a
  3242. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3243. **
  3244. ** ^These routines do not parse the SQL statements thus
  3245. ** will not detect syntactically incorrect SQL.
  3246. **
  3247. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3248. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3249. ** automatically by sqlite3_complete16(). If that initialization fails,
  3250. ** then the return value from sqlite3_complete16() will be non-zero
  3251. ** regardless of whether or not the input SQL is complete.)^
  3252. **
  3253. ** The input to [sqlite3_complete()] must be a zero-terminated
  3254. ** UTF-8 string.
  3255. **
  3256. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3257. ** UTF-16 string in native byte order.
  3258. */
  3259. SQLITE_API int sqlite3_complete(const char *sql);
  3260. SQLITE_API int sqlite3_complete16(const void *sql);
  3261. /*
  3262. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3263. ** KEYWORDS: {busy-handler callback} {busy handler}
  3264. ** METHOD: sqlite3
  3265. **
  3266. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3267. ** that might be invoked with argument P whenever
  3268. ** an attempt is made to access a database table associated with
  3269. ** [database connection] D when another thread
  3270. ** or process has the table locked.
  3271. ** The sqlite3_busy_handler() interface is used to implement
  3272. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3273. **
  3274. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3275. ** is returned immediately upon encountering the lock. ^If the busy callback
  3276. ** is not NULL, then the callback might be invoked with two arguments.
  3277. **
  3278. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3279. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3280. ** the busy handler callback is the number of times that the busy handler has
  3281. ** been invoked previously for the same locking event. ^If the
  3282. ** busy callback returns 0, then no additional attempts are made to
  3283. ** access the database and [SQLITE_BUSY] is returned
  3284. ** to the application.
  3285. ** ^If the callback returns non-zero, then another attempt
  3286. ** is made to access the database and the cycle repeats.
  3287. **
  3288. ** The presence of a busy handler does not guarantee that it will be invoked
  3289. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3290. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3291. ** to the application instead of invoking the
  3292. ** busy handler.
  3293. ** Consider a scenario where one process is holding a read lock that
  3294. ** it is trying to promote to a reserved lock and
  3295. ** a second process is holding a reserved lock that it is trying
  3296. ** to promote to an exclusive lock. The first process cannot proceed
  3297. ** because it is blocked by the second and the second process cannot
  3298. ** proceed because it is blocked by the first. If both processes
  3299. ** invoke the busy handlers, neither will make any progress. Therefore,
  3300. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3301. ** will induce the first process to release its read lock and allow
  3302. ** the second process to proceed.
  3303. **
  3304. ** ^The default busy callback is NULL.
  3305. **
  3306. ** ^(There can only be a single busy handler defined for each
  3307. ** [database connection]. Setting a new busy handler clears any
  3308. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3309. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3310. ** busy handler and thus clear any previously set busy handler.
  3311. **
  3312. ** The busy callback should not take any actions which modify the
  3313. ** database connection that invoked the busy handler. In other words,
  3314. ** the busy handler is not reentrant. Any such actions
  3315. ** result in undefined behavior.
  3316. **
  3317. ** A busy handler must not close the database connection
  3318. ** or [prepared statement] that invoked the busy handler.
  3319. */
  3320. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3321. /*
  3322. ** CAPI3REF: Set A Busy Timeout
  3323. ** METHOD: sqlite3
  3324. **
  3325. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3326. ** for a specified amount of time when a table is locked. ^The handler
  3327. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3328. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3329. ** the handler returns 0 which causes [sqlite3_step()] to return
  3330. ** [SQLITE_BUSY].
  3331. **
  3332. ** ^Calling this routine with an argument less than or equal to zero
  3333. ** turns off all busy handlers.
  3334. **
  3335. ** ^(There can only be a single busy handler for a particular
  3336. ** [database connection] at any given moment. If another busy handler
  3337. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3338. ** this routine, that other busy handler is cleared.)^
  3339. **
  3340. ** See also: [PRAGMA busy_timeout]
  3341. */
  3342. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3343. /*
  3344. ** CAPI3REF: Convenience Routines For Running Queries
  3345. ** METHOD: sqlite3
  3346. **
  3347. ** This is a legacy interface that is preserved for backwards compatibility.
  3348. ** Use of this interface is not recommended.
  3349. **
  3350. ** Definition: A <b>result table</b> is memory data structure created by the
  3351. ** [sqlite3_get_table()] interface. A result table records the
  3352. ** complete query results from one or more queries.
  3353. **
  3354. ** The table conceptually has a number of rows and columns. But
  3355. ** these numbers are not part of the result table itself. These
  3356. ** numbers are obtained separately. Let N be the number of rows
  3357. ** and M be the number of columns.
  3358. **
  3359. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3360. ** There are (N+1)*M elements in the array. The first M pointers point
  3361. ** to zero-terminated strings that contain the names of the columns.
  3362. ** The remaining entries all point to query results. NULL values result
  3363. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3364. ** string representation as returned by [sqlite3_column_text()].
  3365. **
  3366. ** A result table might consist of one or more memory allocations.
  3367. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3368. ** A result table should be deallocated using [sqlite3_free_table()].
  3369. **
  3370. ** ^(As an example of the result table format, suppose a query result
  3371. ** is as follows:
  3372. **
  3373. ** <blockquote><pre>
  3374. ** Name | Age
  3375. ** -----------------------
  3376. ** Alice | 43
  3377. ** Bob | 28
  3378. ** Cindy | 21
  3379. ** </pre></blockquote>
  3380. **
  3381. ** There are two column (M==2) and three rows (N==3). Thus the
  3382. ** result table has 8 entries. Suppose the result table is stored
  3383. ** in an array names azResult. Then azResult holds this content:
  3384. **
  3385. ** <blockquote><pre>
  3386. ** azResult&#91;0] = "Name";
  3387. ** azResult&#91;1] = "Age";
  3388. ** azResult&#91;2] = "Alice";
  3389. ** azResult&#91;3] = "43";
  3390. ** azResult&#91;4] = "Bob";
  3391. ** azResult&#91;5] = "28";
  3392. ** azResult&#91;6] = "Cindy";
  3393. ** azResult&#91;7] = "21";
  3394. ** </pre></blockquote>)^
  3395. **
  3396. ** ^The sqlite3_get_table() function evaluates one or more
  3397. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3398. ** string of its 2nd parameter and returns a result table to the
  3399. ** pointer given in its 3rd parameter.
  3400. **
  3401. ** After the application has finished with the result from sqlite3_get_table(),
  3402. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3403. ** release the memory that was malloced. Because of the way the
  3404. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3405. ** function must not try to call [sqlite3_free()] directly. Only
  3406. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3407. **
  3408. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3409. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3410. ** to any internal data structures of SQLite. It uses only the public
  3411. ** interface defined here. As a consequence, errors that occur in the
  3412. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3413. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3414. ** [sqlite3_errmsg()].
  3415. */
  3416. SQLITE_API int sqlite3_get_table(
  3417. sqlite3 *db, /* An open database */
  3418. const char *zSql, /* SQL to be evaluated */
  3419. char ***pazResult, /* Results of the query */
  3420. int *pnRow, /* Number of result rows written here */
  3421. int *pnColumn, /* Number of result columns written here */
  3422. char **pzErrmsg /* Error msg written here */
  3423. );
  3424. SQLITE_API void sqlite3_free_table(char **result);
  3425. /*
  3426. ** CAPI3REF: Formatted String Printing Functions
  3427. **
  3428. ** These routines are work-alikes of the "printf()" family of functions
  3429. ** from the standard C library.
  3430. ** These routines understand most of the common K&R formatting options,
  3431. ** plus some additional non-standard formats, detailed below.
  3432. ** Note that some of the more obscure formatting options from recent
  3433. ** C-library standards are omitted from this implementation.
  3434. **
  3435. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3436. ** results into memory obtained from [sqlite3_malloc()].
  3437. ** The strings returned by these two routines should be
  3438. ** released by [sqlite3_free()]. ^Both routines return a
  3439. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  3440. ** memory to hold the resulting string.
  3441. **
  3442. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3443. ** the standard C library. The result is written into the
  3444. ** buffer supplied as the second parameter whose size is given by
  3445. ** the first parameter. Note that the order of the
  3446. ** first two parameters is reversed from snprintf().)^ This is an
  3447. ** historical accident that cannot be fixed without breaking
  3448. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3449. ** returns a pointer to its buffer instead of the number of
  3450. ** characters actually written into the buffer.)^ We admit that
  3451. ** the number of characters written would be a more useful return
  3452. ** value but we cannot change the implementation of sqlite3_snprintf()
  3453. ** now without breaking compatibility.
  3454. **
  3455. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3456. ** guarantees that the buffer is always zero-terminated. ^The first
  3457. ** parameter "n" is the total size of the buffer, including space for
  3458. ** the zero terminator. So the longest string that can be completely
  3459. ** written will be n-1 characters.
  3460. **
  3461. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3462. **
  3463. ** These routines all implement some additional formatting
  3464. ** options that are useful for constructing SQL statements.
  3465. ** All of the usual printf() formatting options apply. In addition, there
  3466. ** is are "%q", "%Q", "%w" and "%z" options.
  3467. **
  3468. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  3469. ** string from the argument list. But %q also doubles every '\'' character.
  3470. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  3471. ** character it escapes that character and allows it to be inserted into
  3472. ** the string.
  3473. **
  3474. ** For example, assume the string variable zText contains text as follows:
  3475. **
  3476. ** <blockquote><pre>
  3477. ** char *zText = "It's a happy day!";
  3478. ** </pre></blockquote>
  3479. **
  3480. ** One can use this text in an SQL statement as follows:
  3481. **
  3482. ** <blockquote><pre>
  3483. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  3484. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  3485. ** sqlite3_free(zSQL);
  3486. ** </pre></blockquote>
  3487. **
  3488. ** Because the %q format string is used, the '\'' character in zText
  3489. ** is escaped and the SQL generated is as follows:
  3490. **
  3491. ** <blockquote><pre>
  3492. ** INSERT INTO table1 VALUES('It''s a happy day!')
  3493. ** </pre></blockquote>
  3494. **
  3495. ** This is correct. Had we used %s instead of %q, the generated SQL
  3496. ** would have looked like this:
  3497. **
  3498. ** <blockquote><pre>
  3499. ** INSERT INTO table1 VALUES('It's a happy day!');
  3500. ** </pre></blockquote>
  3501. **
  3502. ** This second example is an SQL syntax error. As a general rule you should
  3503. ** always use %q instead of %s when inserting text into a string literal.
  3504. **
  3505. ** ^(The %Q option works like %q except it also adds single quotes around
  3506. ** the outside of the total string. Additionally, if the parameter in the
  3507. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  3508. ** single quotes).)^ So, for example, one could say:
  3509. **
  3510. ** <blockquote><pre>
  3511. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  3512. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  3513. ** sqlite3_free(zSQL);
  3514. ** </pre></blockquote>
  3515. **
  3516. ** The code above will render a correct SQL statement in the zSQL
  3517. ** variable even if the zText variable is a NULL pointer.
  3518. **
  3519. ** ^(The "%w" formatting option is like "%q" except that it expects to
  3520. ** be contained within double-quotes instead of single quotes, and it
  3521. ** escapes the double-quote character instead of the single-quote
  3522. ** character.)^ The "%w" formatting option is intended for safely inserting
  3523. ** table and column names into a constructed SQL statement.
  3524. **
  3525. ** ^(The "%z" formatting option works like "%s" but with the
  3526. ** addition that after the string has been read and copied into
  3527. ** the result, [sqlite3_free()] is called on the input string.)^
  3528. */
  3529. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3530. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3531. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3532. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3533. /*
  3534. ** CAPI3REF: Memory Allocation Subsystem
  3535. **
  3536. ** The SQLite core uses these three routines for all of its own
  3537. ** internal memory allocation needs. "Core" in the previous sentence
  3538. ** does not include operating-system specific VFS implementation. The
  3539. ** Windows VFS uses native malloc() and free() for some operations.
  3540. **
  3541. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3542. ** of memory at least N bytes in length, where N is the parameter.
  3543. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3544. ** memory, it returns a NULL pointer. ^If the parameter N to
  3545. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3546. ** a NULL pointer.
  3547. **
  3548. ** ^The sqlite3_malloc64(N) routine works just like
  3549. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3550. ** of a signed 32-bit integer.
  3551. **
  3552. ** ^Calling sqlite3_free() with a pointer previously returned
  3553. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3554. ** that it might be reused. ^The sqlite3_free() routine is
  3555. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3556. ** to sqlite3_free() is harmless. After being freed, memory
  3557. ** should neither be read nor written. Even reading previously freed
  3558. ** memory might result in a segmentation fault or other severe error.
  3559. ** Memory corruption, a segmentation fault, or other severe error
  3560. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3561. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3562. **
  3563. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3564. ** prior memory allocation X to be at least N bytes.
  3565. ** ^If the X parameter to sqlite3_realloc(X,N)
  3566. ** is a NULL pointer then its behavior is identical to calling
  3567. ** sqlite3_malloc(N).
  3568. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3569. ** negative then the behavior is exactly the same as calling
  3570. ** sqlite3_free(X).
  3571. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3572. ** of at least N bytes in size or NULL if insufficient memory is available.
  3573. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3574. ** of the prior allocation are copied into the beginning of buffer returned
  3575. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3576. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3577. ** prior allocation is not freed.
  3578. **
  3579. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3580. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3581. ** of a 32-bit signed integer.
  3582. **
  3583. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3584. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3585. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3586. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3587. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3588. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3589. ** the beginning of memory allocation, or if it points to a formerly
  3590. ** valid memory allocation that has now been freed, then the behavior
  3591. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3592. **
  3593. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3594. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3595. ** is always aligned to at least an 8 byte boundary, or to a
  3596. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3597. ** option is used.
  3598. **
  3599. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3600. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3601. ** implementation of these routines to be omitted. That capability
  3602. ** is no longer provided. Only built-in memory allocators can be used.
  3603. **
  3604. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3605. ** the system malloc() and free() directly when converting
  3606. ** filenames between the UTF-8 encoding used by SQLite
  3607. ** and whatever filename encoding is used by the particular Windows
  3608. ** installation. Memory allocation errors were detected, but
  3609. ** they were reported back as [SQLITE_CANTOPEN] or
  3610. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3611. **
  3612. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3613. ** must be either NULL or else pointers obtained from a prior
  3614. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3615. ** not yet been released.
  3616. **
  3617. ** The application must not read or write any part of
  3618. ** a block of memory after it has been released using
  3619. ** [sqlite3_free()] or [sqlite3_realloc()].
  3620. */
  3621. SQLITE_API void *sqlite3_malloc(int);
  3622. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3623. SQLITE_API void *sqlite3_realloc(void*, int);
  3624. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3625. SQLITE_API void sqlite3_free(void*);
  3626. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3627. /*
  3628. ** CAPI3REF: Memory Allocator Statistics
  3629. **
  3630. ** SQLite provides these two interfaces for reporting on the status
  3631. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3632. ** routines, which form the built-in memory allocation subsystem.
  3633. **
  3634. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3635. ** of memory currently outstanding (malloced but not freed).
  3636. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3637. ** value of [sqlite3_memory_used()] since the high-water mark
  3638. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3639. ** [sqlite3_memory_highwater()] include any overhead
  3640. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3641. ** but not overhead added by the any underlying system library
  3642. ** routines that [sqlite3_malloc()] may call.
  3643. **
  3644. ** ^The memory high-water mark is reset to the current value of
  3645. ** [sqlite3_memory_used()] if and only if the parameter to
  3646. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3647. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3648. ** prior to the reset.
  3649. */
  3650. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3651. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3652. /*
  3653. ** CAPI3REF: Pseudo-Random Number Generator
  3654. **
  3655. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3656. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3657. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3658. ** the build-in random() and randomblob() SQL functions. This interface allows
  3659. ** applications to access the same PRNG for other purposes.
  3660. **
  3661. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3662. ** ^The P parameter can be a NULL pointer.
  3663. **
  3664. ** ^If this routine has not been previously called or if the previous
  3665. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3666. ** seeded using randomness obtained from the xRandomness method of
  3667. ** the default [sqlite3_vfs] object.
  3668. ** ^If the previous call to this routine had an N of 1 or more and a
  3669. ** non-NULL P then the pseudo-randomness is generated
  3670. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3671. ** method.
  3672. */
  3673. SQLITE_API void sqlite3_randomness(int N, void *P);
  3674. /*
  3675. ** CAPI3REF: Compile-Time Authorization Callbacks
  3676. ** METHOD: sqlite3
  3677. ** KEYWORDS: {authorizer callback}
  3678. **
  3679. ** ^This routine registers an authorizer callback with a particular
  3680. ** [database connection], supplied in the first argument.
  3681. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3682. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3683. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3684. ** and [sqlite3_prepare16_v3()]. ^At various
  3685. ** points during the compilation process, as logic is being created
  3686. ** to perform various actions, the authorizer callback is invoked to
  3687. ** see if those actions are allowed. ^The authorizer callback should
  3688. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3689. ** specific action but allow the SQL statement to continue to be
  3690. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3691. ** rejected with an error. ^If the authorizer callback returns
  3692. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3693. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3694. ** the authorizer will fail with an error message.
  3695. **
  3696. ** When the callback returns [SQLITE_OK], that means the operation
  3697. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3698. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3699. ** authorizer will fail with an error message explaining that
  3700. ** access is denied.
  3701. **
  3702. ** ^The first parameter to the authorizer callback is a copy of the third
  3703. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3704. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3705. ** the particular action to be authorized. ^The third through sixth parameters
  3706. ** to the callback are either NULL pointers or zero-terminated strings
  3707. ** that contain additional details about the action to be authorized.
  3708. ** Applications must always be prepared to encounter a NULL pointer in any
  3709. ** of the third through the sixth parameters of the authorization callback.
  3710. **
  3711. ** ^If the action code is [SQLITE_READ]
  3712. ** and the callback returns [SQLITE_IGNORE] then the
  3713. ** [prepared statement] statement is constructed to substitute
  3714. ** a NULL value in place of the table column that would have
  3715. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3716. ** return can be used to deny an untrusted user access to individual
  3717. ** columns of a table.
  3718. ** ^When a table is referenced by a [SELECT] but no column values are
  3719. ** extracted from that table (for example in a query like
  3720. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3721. ** is invoked once for that table with a column name that is an empty string.
  3722. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3723. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3724. ** [truncate optimization] is disabled and all rows are deleted individually.
  3725. **
  3726. ** An authorizer is used when [sqlite3_prepare | preparing]
  3727. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3728. ** do not try to access data they are not allowed to see, or that they do not
  3729. ** try to execute malicious statements that damage the database. For
  3730. ** example, an application may allow a user to enter arbitrary
  3731. ** SQL queries for evaluation by a database. But the application does
  3732. ** not want the user to be able to make arbitrary changes to the
  3733. ** database. An authorizer could then be put in place while the
  3734. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3735. ** disallows everything except [SELECT] statements.
  3736. **
  3737. ** Applications that need to process SQL from untrusted sources
  3738. ** might also consider lowering resource limits using [sqlite3_limit()]
  3739. ** and limiting database size using the [max_page_count] [PRAGMA]
  3740. ** in addition to using an authorizer.
  3741. **
  3742. ** ^(Only a single authorizer can be in place on a database connection
  3743. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3744. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3745. ** The authorizer is disabled by default.
  3746. **
  3747. ** The authorizer callback must not do anything that will modify
  3748. ** the database connection that invoked the authorizer callback.
  3749. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3750. ** database connections for the meaning of "modify" in this paragraph.
  3751. **
  3752. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3753. ** statement might be re-prepared during [sqlite3_step()] due to a
  3754. ** schema change. Hence, the application should ensure that the
  3755. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3756. **
  3757. ** ^Note that the authorizer callback is invoked only during
  3758. ** [sqlite3_prepare()] or its variants. Authorization is not
  3759. ** performed during statement evaluation in [sqlite3_step()], unless
  3760. ** as stated in the previous paragraph, sqlite3_step() invokes
  3761. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3762. */
  3763. SQLITE_API int sqlite3_set_authorizer(
  3764. sqlite3*,
  3765. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3766. void *pUserData
  3767. );
  3768. /*
  3769. ** CAPI3REF: Authorizer Return Codes
  3770. **
  3771. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3772. ** return either [SQLITE_OK] or one of these two constants in order
  3773. ** to signal SQLite whether or not the action is permitted. See the
  3774. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3775. ** information.
  3776. **
  3777. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3778. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3779. */
  3780. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3781. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3782. /*
  3783. ** CAPI3REF: Authorizer Action Codes
  3784. **
  3785. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3786. ** that is invoked to authorize certain SQL statement actions. The
  3787. ** second parameter to the callback is an integer code that specifies
  3788. ** what action is being authorized. These are the integer action codes that
  3789. ** the authorizer callback may be passed.
  3790. **
  3791. ** These action code values signify what kind of operation is to be
  3792. ** authorized. The 3rd and 4th parameters to the authorization
  3793. ** callback function will be parameters or NULL depending on which of these
  3794. ** codes is used as the second parameter. ^(The 5th parameter to the
  3795. ** authorizer callback is the name of the database ("main", "temp",
  3796. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3797. ** is the name of the inner-most trigger or view that is responsible for
  3798. ** the access attempt or NULL if this access attempt is directly from
  3799. ** top-level SQL code.
  3800. */
  3801. /******************************************* 3rd ************ 4th ***********/
  3802. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3803. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3804. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3805. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3806. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3807. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3808. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3809. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3810. #define SQLITE_DELETE 9 /* Table Name NULL */
  3811. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3812. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3813. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3814. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3815. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3816. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3817. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3818. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3819. #define SQLITE_INSERT 18 /* Table Name NULL */
  3820. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3821. #define SQLITE_READ 20 /* Table Name Column Name */
  3822. #define SQLITE_SELECT 21 /* NULL NULL */
  3823. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3824. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3825. #define SQLITE_ATTACH 24 /* Filename NULL */
  3826. #define SQLITE_DETACH 25 /* Database Name NULL */
  3827. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3828. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3829. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3830. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3831. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3832. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3833. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3834. #define SQLITE_COPY 0 /* No longer used */
  3835. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3836. /*
  3837. ** CAPI3REF: Tracing And Profiling Functions
  3838. ** METHOD: sqlite3
  3839. **
  3840. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3841. ** instead of the routines described here.
  3842. **
  3843. ** These routines register callback functions that can be used for
  3844. ** tracing and profiling the execution of SQL statements.
  3845. **
  3846. ** ^The callback function registered by sqlite3_trace() is invoked at
  3847. ** various times when an SQL statement is being run by [sqlite3_step()].
  3848. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3849. ** SQL statement text as the statement first begins executing.
  3850. ** ^(Additional sqlite3_trace() callbacks might occur
  3851. ** as each triggered subprogram is entered. The callbacks for triggers
  3852. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3853. **
  3854. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3855. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3856. **
  3857. ** ^The callback function registered by sqlite3_profile() is invoked
  3858. ** as each SQL statement finishes. ^The profile callback contains
  3859. ** the original statement text and an estimate of wall-clock time
  3860. ** of how long that statement took to run. ^The profile callback
  3861. ** time is in units of nanoseconds, however the current implementation
  3862. ** is only capable of millisecond resolution so the six least significant
  3863. ** digits in the time are meaningless. Future versions of SQLite
  3864. ** might provide greater resolution on the profiler callback. The
  3865. ** sqlite3_profile() function is considered experimental and is
  3866. ** subject to change in future versions of SQLite.
  3867. */
  3868. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3869. void(*xTrace)(void*,const char*), void*);
  3870. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3871. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3872. /*
  3873. ** CAPI3REF: SQL Trace Event Codes
  3874. ** KEYWORDS: SQLITE_TRACE
  3875. **
  3876. ** These constants identify classes of events that can be monitored
  3877. ** using the [sqlite3_trace_v2()] tracing logic. The third argument
  3878. ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
  3879. ** the following constants. ^The first argument to the trace callback
  3880. ** is one of the following constants.
  3881. **
  3882. ** New tracing constants may be added in future releases.
  3883. **
  3884. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3885. ** ^The T argument is one of the integer type codes above.
  3886. ** ^The C argument is a copy of the context pointer passed in as the
  3887. ** fourth argument to [sqlite3_trace_v2()].
  3888. ** The P and X arguments are pointers whose meanings depend on T.
  3889. **
  3890. ** <dl>
  3891. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3892. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3893. ** first begins running and possibly at other times during the
  3894. ** execution of the prepared statement, such as at the start of each
  3895. ** trigger subprogram. ^The P argument is a pointer to the
  3896. ** [prepared statement]. ^The X argument is a pointer to a string which
  3897. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3898. ** that indicates the invocation of a trigger. ^The callback can compute
  3899. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3900. ** interface by using the X argument when X begins with "--" and invoking
  3901. ** [sqlite3_expanded_sql(P)] otherwise.
  3902. **
  3903. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3904. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3905. ** information as is provided by the [sqlite3_profile()] callback.
  3906. ** ^The P argument is a pointer to the [prepared statement] and the
  3907. ** X argument points to a 64-bit integer which is the estimated of
  3908. ** the number of nanosecond that the prepared statement took to run.
  3909. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3910. **
  3911. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3912. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3913. ** statement generates a single row of result.
  3914. ** ^The P argument is a pointer to the [prepared statement] and the
  3915. ** X argument is unused.
  3916. **
  3917. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  3918. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  3919. ** connection closes.
  3920. ** ^The P argument is a pointer to the [database connection] object
  3921. ** and the X argument is unused.
  3922. ** </dl>
  3923. */
  3924. #define SQLITE_TRACE_STMT 0x01
  3925. #define SQLITE_TRACE_PROFILE 0x02
  3926. #define SQLITE_TRACE_ROW 0x04
  3927. #define SQLITE_TRACE_CLOSE 0x08
  3928. /*
  3929. ** CAPI3REF: SQL Trace Hook
  3930. ** METHOD: sqlite3
  3931. **
  3932. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  3933. ** function X against [database connection] D, using property mask M
  3934. ** and context pointer P. ^If the X callback is
  3935. ** NULL or if the M mask is zero, then tracing is disabled. The
  3936. ** M argument should be the bitwise OR-ed combination of
  3937. ** zero or more [SQLITE_TRACE] constants.
  3938. **
  3939. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  3940. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  3941. **
  3942. ** ^The X callback is invoked whenever any of the events identified by
  3943. ** mask M occur. ^The integer return value from the callback is currently
  3944. ** ignored, though this may change in future releases. Callback
  3945. ** implementations should return zero to ensure future compatibility.
  3946. **
  3947. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  3948. ** ^The T argument is one of the [SQLITE_TRACE]
  3949. ** constants to indicate why the callback was invoked.
  3950. ** ^The C argument is a copy of the context pointer.
  3951. ** The P and X arguments are pointers whose meanings depend on T.
  3952. **
  3953. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  3954. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  3955. ** are deprecated.
  3956. */
  3957. SQLITE_API int sqlite3_trace_v2(
  3958. sqlite3*,
  3959. unsigned uMask,
  3960. int(*xCallback)(unsigned,void*,void*,void*),
  3961. void *pCtx
  3962. );
  3963. /*
  3964. ** CAPI3REF: Query Progress Callbacks
  3965. ** METHOD: sqlite3
  3966. **
  3967. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3968. ** function X to be invoked periodically during long running calls to
  3969. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3970. ** database connection D. An example use for this
  3971. ** interface is to keep a GUI updated during a large query.
  3972. **
  3973. ** ^The parameter P is passed through as the only parameter to the
  3974. ** callback function X. ^The parameter N is the approximate number of
  3975. ** [virtual machine instructions] that are evaluated between successive
  3976. ** invocations of the callback X. ^If N is less than one then the progress
  3977. ** handler is disabled.
  3978. **
  3979. ** ^Only a single progress handler may be defined at one time per
  3980. ** [database connection]; setting a new progress handler cancels the
  3981. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3982. ** ^The progress handler is also disabled by setting N to a value less
  3983. ** than 1.
  3984. **
  3985. ** ^If the progress callback returns non-zero, the operation is
  3986. ** interrupted. This feature can be used to implement a
  3987. ** "Cancel" button on a GUI progress dialog box.
  3988. **
  3989. ** The progress handler callback must not do anything that will modify
  3990. ** the database connection that invoked the progress handler.
  3991. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3992. ** database connections for the meaning of "modify" in this paragraph.
  3993. **
  3994. */
  3995. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  3996. /*
  3997. ** CAPI3REF: Opening A New Database Connection
  3998. ** CONSTRUCTOR: sqlite3
  3999. **
  4000. ** ^These routines open an SQLite database file as specified by the
  4001. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4002. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4003. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4004. ** returned in *ppDb, even if an error occurs. The only exception is that
  4005. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4006. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4007. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4008. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4009. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4010. ** an English language description of the error following a failure of any
  4011. ** of the sqlite3_open() routines.
  4012. **
  4013. ** ^The default encoding will be UTF-8 for databases created using
  4014. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4015. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4016. **
  4017. ** Whether or not an error occurs when it is opened, resources
  4018. ** associated with the [database connection] handle should be released by
  4019. ** passing it to [sqlite3_close()] when it is no longer required.
  4020. **
  4021. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4022. ** except that it accepts two additional parameters for additional control
  4023. ** over the new database connection. ^(The flags parameter to
  4024. ** sqlite3_open_v2() can take one of
  4025. ** the following three values, optionally combined with the
  4026. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4027. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4028. **
  4029. ** <dl>
  4030. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4031. ** <dd>The database is opened in read-only mode. If the database does not
  4032. ** already exist, an error is returned.</dd>)^
  4033. **
  4034. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4035. ** <dd>The database is opened for reading and writing if possible, or reading
  4036. ** only if the file is write protected by the operating system. In either
  4037. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4038. **
  4039. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4040. ** <dd>The database is opened for reading and writing, and is created if
  4041. ** it does not already exist. This is the behavior that is always used for
  4042. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4043. ** </dl>
  4044. **
  4045. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4046. ** combinations shown above optionally combined with other
  4047. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4048. ** then the behavior is undefined.
  4049. **
  4050. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4051. ** opens in the multi-thread [threading mode] as long as the single-thread
  4052. ** mode has not been set at compile-time or start-time. ^If the
  4053. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4054. ** in the serialized [threading mode] unless single-thread was
  4055. ** previously selected at compile-time or start-time.
  4056. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4057. ** eligible to use [shared cache mode], regardless of whether or not shared
  4058. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4059. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4060. ** participate in [shared cache mode] even if it is enabled.
  4061. **
  4062. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4063. ** [sqlite3_vfs] object that defines the operating system interface that
  4064. ** the new database connection should use. ^If the fourth parameter is
  4065. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4066. **
  4067. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4068. ** is created for the connection. ^This in-memory database will vanish when
  4069. ** the database connection is closed. Future versions of SQLite might
  4070. ** make use of additional special filenames that begin with the ":" character.
  4071. ** It is recommended that when a database filename actually does begin with
  4072. ** a ":" character you should prefix the filename with a pathname such as
  4073. ** "./" to avoid ambiguity.
  4074. **
  4075. ** ^If the filename is an empty string, then a private, temporary
  4076. ** on-disk database will be created. ^This private database will be
  4077. ** automatically deleted as soon as the database connection is closed.
  4078. **
  4079. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4080. **
  4081. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4082. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4083. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4084. ** set in the third argument to sqlite3_open_v2(), or if it has
  4085. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4086. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4087. ** URI filename interpretation is turned off
  4088. ** by default, but future releases of SQLite might enable URI filename
  4089. ** interpretation by default. See "[URI filenames]" for additional
  4090. ** information.
  4091. **
  4092. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4093. ** authority, then it must be either an empty string or the string
  4094. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4095. ** error is returned to the caller. ^The fragment component of a URI, if
  4096. ** present, is ignored.
  4097. **
  4098. ** ^SQLite uses the path component of the URI as the name of the disk file
  4099. ** which contains the database. ^If the path begins with a '/' character,
  4100. ** then it is interpreted as an absolute path. ^If the path does not begin
  4101. ** with a '/' (meaning that the authority section is omitted from the URI)
  4102. ** then the path is interpreted as a relative path.
  4103. ** ^(On windows, the first component of an absolute path
  4104. ** is a drive specification (e.g. "C:").)^
  4105. **
  4106. ** [[core URI query parameters]]
  4107. ** The query component of a URI may contain parameters that are interpreted
  4108. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4109. ** SQLite and its built-in [VFSes] interpret the
  4110. ** following query parameters:
  4111. **
  4112. ** <ul>
  4113. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4114. ** a VFS object that provides the operating system interface that should
  4115. ** be used to access the database file on disk. ^If this option is set to
  4116. ** an empty string the default VFS object is used. ^Specifying an unknown
  4117. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4118. ** present, then the VFS specified by the option takes precedence over
  4119. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4120. **
  4121. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4122. ** "rwc", or "memory". Attempting to set it to any other value is
  4123. ** an error)^.
  4124. ** ^If "ro" is specified, then the database is opened for read-only
  4125. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4126. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4127. ** "rw", then the database is opened for read-write (but not create)
  4128. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4129. ** been set. ^Value "rwc" is equivalent to setting both
  4130. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4131. ** set to "memory" then a pure [in-memory database] that never reads
  4132. ** or writes from disk is used. ^It is an error to specify a value for
  4133. ** the mode parameter that is less restrictive than that specified by
  4134. ** the flags passed in the third parameter to sqlite3_open_v2().
  4135. **
  4136. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4137. ** "private". ^Setting it to "shared" is equivalent to setting the
  4138. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4139. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4140. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4141. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4142. ** a URI filename, its value overrides any behavior requested by setting
  4143. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4144. **
  4145. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4146. ** [powersafe overwrite] property does or does not apply to the
  4147. ** storage media on which the database file resides.
  4148. **
  4149. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4150. ** which if set disables file locking in rollback journal modes. This
  4151. ** is useful for accessing a database on a filesystem that does not
  4152. ** support locking. Caution: Database corruption might result if two
  4153. ** or more processes write to the same database and any one of those
  4154. ** processes uses nolock=1.
  4155. **
  4156. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4157. ** parameter that indicates that the database file is stored on
  4158. ** read-only media. ^When immutable is set, SQLite assumes that the
  4159. ** database file cannot be changed, even by a process with higher
  4160. ** privilege, and so the database is opened read-only and all locking
  4161. ** and change detection is disabled. Caution: Setting the immutable
  4162. ** property on a database file that does in fact change can result
  4163. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4164. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4165. **
  4166. ** </ul>
  4167. **
  4168. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4169. ** error. Future versions of SQLite might understand additional query
  4170. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4171. ** additional information.
  4172. **
  4173. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4174. **
  4175. ** <table border="1" align=center cellpadding=5>
  4176. ** <tr><th> URI filenames <th> Results
  4177. ** <tr><td> file:data.db <td>
  4178. ** Open the file "data.db" in the current directory.
  4179. ** <tr><td> file:/home/fred/data.db<br>
  4180. ** file:///home/fred/data.db <br>
  4181. ** file://localhost/home/fred/data.db <br> <td>
  4182. ** Open the database file "/home/fred/data.db".
  4183. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4184. ** An error. "darkstar" is not a recognized authority.
  4185. ** <tr><td style="white-space:nowrap">
  4186. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4187. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4188. ** C:. Note that the %20 escaping in this example is not strictly
  4189. ** necessary - space characters can be used literally
  4190. ** in URI filenames.
  4191. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4192. ** Open file "data.db" in the current directory for read-only access.
  4193. ** Regardless of whether or not shared-cache mode is enabled by
  4194. ** default, use a private cache.
  4195. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4196. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4197. ** that uses dot-files in place of posix advisory locking.
  4198. ** <tr><td> file:data.db?mode=readonly <td>
  4199. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4200. ** </table>
  4201. **
  4202. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4203. ** query components of a URI. A hexadecimal escape sequence consists of a
  4204. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4205. ** specifying an octet value. ^Before the path or query components of a
  4206. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4207. ** hexadecimal escape sequences replaced by a single byte containing the
  4208. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4209. ** the results are undefined.
  4210. **
  4211. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4212. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4213. ** codepage is currently defined. Filenames containing international
  4214. ** characters must be converted to UTF-8 prior to passing them into
  4215. ** sqlite3_open() or sqlite3_open_v2().
  4216. **
  4217. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4218. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4219. ** features that require the use of temporary files may fail.
  4220. **
  4221. ** See also: [sqlite3_temp_directory]
  4222. */
  4223. SQLITE_API int sqlite3_open(
  4224. const char *filename, /* Database filename (UTF-8) */
  4225. sqlite3 **ppDb /* OUT: SQLite db handle */
  4226. );
  4227. SQLITE_API int sqlite3_open16(
  4228. const void *filename, /* Database filename (UTF-16) */
  4229. sqlite3 **ppDb /* OUT: SQLite db handle */
  4230. );
  4231. SQLITE_API int sqlite3_open_v2(
  4232. const char *filename, /* Database filename (UTF-8) */
  4233. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4234. int flags, /* Flags */
  4235. const char *zVfs /* Name of VFS module to use */
  4236. );
  4237. /*
  4238. ** CAPI3REF: Obtain Values For URI Parameters
  4239. **
  4240. ** These are utility routines, useful to VFS implementations, that check
  4241. ** to see if a database file was a URI that contained a specific query
  4242. ** parameter, and if so obtains the value of that query parameter.
  4243. **
  4244. ** If F is the database filename pointer passed into the xOpen() method of
  4245. ** a VFS implementation when the flags parameter to xOpen() has one or
  4246. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4247. ** P is the name of the query parameter, then
  4248. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4249. ** parameter if it exists or a NULL pointer if P does not appear as a
  4250. ** query parameter on F. If P is a query parameter of F
  4251. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4252. ** a pointer to an empty string.
  4253. **
  4254. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4255. ** parameter and returns true (1) or false (0) according to the value
  4256. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4257. ** value of query parameter P is one of "yes", "true", or "on" in any
  4258. ** case or if the value begins with a non-zero number. The
  4259. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4260. ** query parameter P is one of "no", "false", or "off" in any case or
  4261. ** if the value begins with a numeric zero. If P is not a query
  4262. ** parameter on F or if the value of P is does not match any of the
  4263. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4264. **
  4265. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4266. ** 64-bit signed integer and returns that integer, or D if P does not
  4267. ** exist. If the value of P is something other than an integer, then
  4268. ** zero is returned.
  4269. **
  4270. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4271. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4272. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4273. ** VFS method, then the behavior of this routine is undefined and probably
  4274. ** undesirable.
  4275. */
  4276. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4277. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4278. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4279. /*
  4280. ** CAPI3REF: Error Codes And Messages
  4281. ** METHOD: sqlite3
  4282. **
  4283. ** ^If the most recent sqlite3_* API call associated with
  4284. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4285. ** returns the numeric [result code] or [extended result code] for that
  4286. ** API call.
  4287. ** If the most recent API call was successful,
  4288. ** then the return value from sqlite3_errcode() is undefined.
  4289. ** ^The sqlite3_extended_errcode()
  4290. ** interface is the same except that it always returns the
  4291. ** [extended result code] even when extended result codes are
  4292. ** disabled.
  4293. **
  4294. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4295. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4296. ** ^(Memory to hold the error message string is managed internally.
  4297. ** The application does not need to worry about freeing the result.
  4298. ** However, the error string might be overwritten or deallocated by
  4299. ** subsequent calls to other SQLite interface functions.)^
  4300. **
  4301. ** ^The sqlite3_errstr() interface returns the English-language text
  4302. ** that describes the [result code], as UTF-8.
  4303. ** ^(Memory to hold the error message string is managed internally
  4304. ** and must not be freed by the application)^.
  4305. **
  4306. ** When the serialized [threading mode] is in use, it might be the
  4307. ** case that a second error occurs on a separate thread in between
  4308. ** the time of the first error and the call to these interfaces.
  4309. ** When that happens, the second error will be reported since these
  4310. ** interfaces always report the most recent result. To avoid
  4311. ** this, each thread can obtain exclusive use of the [database connection] D
  4312. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4313. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4314. ** all calls to the interfaces listed here are completed.
  4315. **
  4316. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4317. ** was invoked incorrectly by the application. In that case, the
  4318. ** error code and message may or may not be set.
  4319. */
  4320. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4321. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4322. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4323. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4324. SQLITE_API const char *sqlite3_errstr(int);
  4325. /*
  4326. ** CAPI3REF: Prepared Statement Object
  4327. ** KEYWORDS: {prepared statement} {prepared statements}
  4328. **
  4329. ** An instance of this object represents a single SQL statement that
  4330. ** has been compiled into binary form and is ready to be evaluated.
  4331. **
  4332. ** Think of each SQL statement as a separate computer program. The
  4333. ** original SQL text is source code. A prepared statement object
  4334. ** is the compiled object code. All SQL must be converted into a
  4335. ** prepared statement before it can be run.
  4336. **
  4337. ** The life-cycle of a prepared statement object usually goes like this:
  4338. **
  4339. ** <ol>
  4340. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4341. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4342. ** interfaces.
  4343. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4344. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4345. ** to step 2. Do this zero or more times.
  4346. ** <li> Destroy the object using [sqlite3_finalize()].
  4347. ** </ol>
  4348. */
  4349. typedef struct sqlite3_stmt sqlite3_stmt;
  4350. /*
  4351. ** CAPI3REF: Run-time Limits
  4352. ** METHOD: sqlite3
  4353. **
  4354. ** ^(This interface allows the size of various constructs to be limited
  4355. ** on a connection by connection basis. The first parameter is the
  4356. ** [database connection] whose limit is to be set or queried. The
  4357. ** second parameter is one of the [limit categories] that define a
  4358. ** class of constructs to be size limited. The third parameter is the
  4359. ** new limit for that construct.)^
  4360. **
  4361. ** ^If the new limit is a negative number, the limit is unchanged.
  4362. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4363. ** [limits | hard upper bound]
  4364. ** set at compile-time by a C preprocessor macro called
  4365. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4366. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4367. ** ^Attempts to increase a limit above its hard upper bound are
  4368. ** silently truncated to the hard upper bound.
  4369. **
  4370. ** ^Regardless of whether or not the limit was changed, the
  4371. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4372. ** ^Hence, to find the current value of a limit without changing it,
  4373. ** simply invoke this interface with the third parameter set to -1.
  4374. **
  4375. ** Run-time limits are intended for use in applications that manage
  4376. ** both their own internal database and also databases that are controlled
  4377. ** by untrusted external sources. An example application might be a
  4378. ** web browser that has its own databases for storing history and
  4379. ** separate databases controlled by JavaScript applications downloaded
  4380. ** off the Internet. The internal databases can be given the
  4381. ** large, default limits. Databases managed by external sources can
  4382. ** be given much smaller limits designed to prevent a denial of service
  4383. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4384. ** interface to further control untrusted SQL. The size of the database
  4385. ** created by an untrusted script can be contained using the
  4386. ** [max_page_count] [PRAGMA].
  4387. **
  4388. ** New run-time limit categories may be added in future releases.
  4389. */
  4390. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4391. /*
  4392. ** CAPI3REF: Run-Time Limit Categories
  4393. ** KEYWORDS: {limit category} {*limit categories}
  4394. **
  4395. ** These constants define various performance limits
  4396. ** that can be lowered at run-time using [sqlite3_limit()].
  4397. ** The synopsis of the meanings of the various limits is shown below.
  4398. ** Additional information is available at [limits | Limits in SQLite].
  4399. **
  4400. ** <dl>
  4401. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4402. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4403. **
  4404. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4405. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4406. **
  4407. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4408. ** <dd>The maximum number of columns in a table definition or in the
  4409. ** result set of a [SELECT] or the maximum number of columns in an index
  4410. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4411. **
  4412. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4413. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4414. **
  4415. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4416. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4417. **
  4418. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4419. ** <dd>The maximum number of instructions in a virtual machine program
  4420. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4421. ** the equivalent tries to allocate space for more than this many opcodes
  4422. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4423. **
  4424. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4425. ** <dd>The maximum number of arguments on a function.</dd>)^
  4426. **
  4427. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4428. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4429. **
  4430. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4431. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4432. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4433. ** [GLOB] operators.</dd>)^
  4434. **
  4435. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4436. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4437. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4438. **
  4439. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4440. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4441. **
  4442. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4443. ** <dd>The maximum number of auxiliary worker threads that a single
  4444. ** [prepared statement] may start.</dd>)^
  4445. ** </dl>
  4446. */
  4447. #define SQLITE_LIMIT_LENGTH 0
  4448. #define SQLITE_LIMIT_SQL_LENGTH 1
  4449. #define SQLITE_LIMIT_COLUMN 2
  4450. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4451. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4452. #define SQLITE_LIMIT_VDBE_OP 5
  4453. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4454. #define SQLITE_LIMIT_ATTACHED 7
  4455. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4456. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4457. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4458. #define SQLITE_LIMIT_WORKER_THREADS 11
  4459. /*
  4460. ** CAPI3REF: Prepare Flags
  4461. **
  4462. ** These constants define various flags that can be passed into
  4463. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4464. ** [sqlite3_prepare16_v3()] interfaces.
  4465. **
  4466. ** New flags may be added in future releases of SQLite.
  4467. **
  4468. ** <dl>
  4469. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4470. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4471. ** that the prepared statement will be retained for a long time and
  4472. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4473. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4474. ** be used just once or at most a few times and then destroyed using
  4475. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4476. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4477. ** deplete the limited store of lookaside memory. Future versions of
  4478. ** SQLite may act on this hint differently.
  4479. ** </dl>
  4480. */
  4481. #define SQLITE_PREPARE_PERSISTENT 0x01
  4482. /*
  4483. ** CAPI3REF: Compiling An SQL Statement
  4484. ** KEYWORDS: {SQL statement compiler}
  4485. ** METHOD: sqlite3
  4486. ** CONSTRUCTOR: sqlite3_stmt
  4487. **
  4488. ** To execute an SQL statement, it must first be compiled into a byte-code
  4489. ** program using one of these routines. Or, in other words, these routines
  4490. ** are constructors for the [prepared statement] object.
  4491. **
  4492. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4493. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4494. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4495. ** for special purposes.
  4496. **
  4497. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4498. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4499. ** as a convenience. The UTF-16 interfaces work by converting the
  4500. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4501. **
  4502. ** The first argument, "db", is a [database connection] obtained from a
  4503. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4504. ** [sqlite3_open16()]. The database connection must not have been closed.
  4505. **
  4506. ** The second argument, "zSql", is the statement to be compiled, encoded
  4507. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4508. ** and sqlite3_prepare_v3()
  4509. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4510. ** and sqlite3_prepare16_v3() use UTF-16.
  4511. **
  4512. ** ^If the nByte argument is negative, then zSql is read up to the
  4513. ** first zero terminator. ^If nByte is positive, then it is the
  4514. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4515. ** statement is generated.
  4516. ** If the caller knows that the supplied string is nul-terminated, then
  4517. ** there is a small performance advantage to passing an nByte parameter that
  4518. ** is the number of bytes in the input string <i>including</i>
  4519. ** the nul-terminator.
  4520. **
  4521. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4522. ** past the end of the first SQL statement in zSql. These routines only
  4523. ** compile the first statement in zSql, so *pzTail is left pointing to
  4524. ** what remains uncompiled.
  4525. **
  4526. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4527. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4528. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4529. ** string or a comment) then *ppStmt is set to NULL.
  4530. ** The calling procedure is responsible for deleting the compiled
  4531. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4532. ** ppStmt may not be NULL.
  4533. **
  4534. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4535. ** otherwise an [error code] is returned.
  4536. **
  4537. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4538. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4539. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4540. ** are retained for backwards compatibility, but their use is discouraged.
  4541. ** ^In the "vX" interfaces, the prepared statement
  4542. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4543. ** original SQL text. This causes the [sqlite3_step()] interface to
  4544. ** behave differently in three ways:
  4545. **
  4546. ** <ol>
  4547. ** <li>
  4548. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4549. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4550. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4551. ** retries will occur before sqlite3_step() gives up and returns an error.
  4552. ** </li>
  4553. **
  4554. ** <li>
  4555. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4556. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4557. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4558. ** and the application would have to make a second call to [sqlite3_reset()]
  4559. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4560. ** interfaces, the underlying reason for the error is returned immediately.
  4561. ** </li>
  4562. **
  4563. ** <li>
  4564. ** ^If the specific value bound to [parameter | host parameter] in the
  4565. ** WHERE clause might influence the choice of query plan for a statement,
  4566. ** then the statement will be automatically recompiled, as if there had been
  4567. ** a schema change, on the first [sqlite3_step()] call following any change
  4568. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4569. ** ^The specific value of WHERE-clause [parameter] might influence the
  4570. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4571. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4572. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4573. ** </li>
  4574. **
  4575. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4576. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4577. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4578. ** sqlite3_prepare_v2() interface works exactly the same as
  4579. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4580. ** </ol>
  4581. */
  4582. SQLITE_API int sqlite3_prepare(
  4583. sqlite3 *db, /* Database handle */
  4584. const char *zSql, /* SQL statement, UTF-8 encoded */
  4585. int nByte, /* Maximum length of zSql in bytes. */
  4586. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4587. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4588. );
  4589. SQLITE_API int sqlite3_prepare_v2(
  4590. sqlite3 *db, /* Database handle */
  4591. const char *zSql, /* SQL statement, UTF-8 encoded */
  4592. int nByte, /* Maximum length of zSql in bytes. */
  4593. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4594. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4595. );
  4596. SQLITE_API int sqlite3_prepare_v3(
  4597. sqlite3 *db, /* Database handle */
  4598. const char *zSql, /* SQL statement, UTF-8 encoded */
  4599. int nByte, /* Maximum length of zSql in bytes. */
  4600. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4601. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4602. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4603. );
  4604. SQLITE_API int sqlite3_prepare16(
  4605. sqlite3 *db, /* Database handle */
  4606. const void *zSql, /* SQL statement, UTF-16 encoded */
  4607. int nByte, /* Maximum length of zSql in bytes. */
  4608. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4609. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4610. );
  4611. SQLITE_API int sqlite3_prepare16_v2(
  4612. sqlite3 *db, /* Database handle */
  4613. const void *zSql, /* SQL statement, UTF-16 encoded */
  4614. int nByte, /* Maximum length of zSql in bytes. */
  4615. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4616. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4617. );
  4618. SQLITE_API int sqlite3_prepare16_v3(
  4619. sqlite3 *db, /* Database handle */
  4620. const void *zSql, /* SQL statement, UTF-16 encoded */
  4621. int nByte, /* Maximum length of zSql in bytes. */
  4622. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4623. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4624. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4625. );
  4626. /*
  4627. ** CAPI3REF: Retrieving Statement SQL
  4628. ** METHOD: sqlite3_stmt
  4629. **
  4630. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4631. ** SQL text used to create [prepared statement] P if P was
  4632. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4633. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4634. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4635. ** string containing the SQL text of prepared statement P with
  4636. ** [bound parameters] expanded.
  4637. **
  4638. ** ^(For example, if a prepared statement is created using the SQL
  4639. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4640. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4641. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4642. ** will return "SELECT 2345,NULL".)^
  4643. **
  4644. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4645. ** is available to hold the result, or if the result would exceed the
  4646. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4647. **
  4648. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4649. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4650. ** option causes sqlite3_expanded_sql() to always return NULL.
  4651. **
  4652. ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  4653. ** automatically freed when the prepared statement is finalized.
  4654. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4655. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4656. ** by passing it to [sqlite3_free()].
  4657. */
  4658. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4659. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4660. /*
  4661. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4662. ** METHOD: sqlite3_stmt
  4663. **
  4664. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4665. ** and only if the [prepared statement] X makes no direct changes to
  4666. ** the content of the database file.
  4667. **
  4668. ** Note that [application-defined SQL functions] or
  4669. ** [virtual tables] might change the database indirectly as a side effect.
  4670. ** ^(For example, if an application defines a function "eval()" that
  4671. ** calls [sqlite3_exec()], then the following SQL statement would
  4672. ** change the database file through side-effects:
  4673. **
  4674. ** <blockquote><pre>
  4675. ** SELECT eval('DELETE FROM t1') FROM t2;
  4676. ** </pre></blockquote>
  4677. **
  4678. ** But because the [SELECT] statement does not change the database file
  4679. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4680. **
  4681. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4682. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4683. ** since the statements themselves do not actually modify the database but
  4684. ** rather they control the timing of when other statements modify the
  4685. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4686. ** sqlite3_stmt_readonly() to return true since, while those statements
  4687. ** change the configuration of a database connection, they do not make
  4688. ** changes to the content of the database files on disk.
  4689. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4690. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4691. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4692. ** sqlite3_stmt_readonly() returns false for those commands.
  4693. */
  4694. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4695. /*
  4696. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4697. ** METHOD: sqlite3_stmt
  4698. **
  4699. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4700. ** [prepared statement] S has been stepped at least once using
  4701. ** [sqlite3_step(S)] but has neither run to completion (returned
  4702. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4703. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4704. ** interface returns false if S is a NULL pointer. If S is not a
  4705. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4706. ** object, then the behavior is undefined and probably undesirable.
  4707. **
  4708. ** This interface can be used in combination [sqlite3_next_stmt()]
  4709. ** to locate all prepared statements associated with a database
  4710. ** connection that are in need of being reset. This can be used,
  4711. ** for example, in diagnostic routines to search for prepared
  4712. ** statements that are holding a transaction open.
  4713. */
  4714. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4715. /*
  4716. ** CAPI3REF: Dynamically Typed Value Object
  4717. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4718. **
  4719. ** SQLite uses the sqlite3_value object to represent all values
  4720. ** that can be stored in a database table. SQLite uses dynamic typing
  4721. ** for the values it stores. ^Values stored in sqlite3_value objects
  4722. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4723. **
  4724. ** An sqlite3_value object may be either "protected" or "unprotected".
  4725. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4726. ** will accept either a protected or an unprotected sqlite3_value.
  4727. ** Every interface that accepts sqlite3_value arguments specifies
  4728. ** whether or not it requires a protected sqlite3_value. The
  4729. ** [sqlite3_value_dup()] interface can be used to construct a new
  4730. ** protected sqlite3_value from an unprotected sqlite3_value.
  4731. **
  4732. ** The terms "protected" and "unprotected" refer to whether or not
  4733. ** a mutex is held. An internal mutex is held for a protected
  4734. ** sqlite3_value object but no mutex is held for an unprotected
  4735. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4736. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4737. ** or if SQLite is run in one of reduced mutex modes
  4738. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4739. ** then there is no distinction between protected and unprotected
  4740. ** sqlite3_value objects and they can be used interchangeably. However,
  4741. ** for maximum code portability it is recommended that applications
  4742. ** still make the distinction between protected and unprotected
  4743. ** sqlite3_value objects even when not strictly required.
  4744. **
  4745. ** ^The sqlite3_value objects that are passed as parameters into the
  4746. ** implementation of [application-defined SQL functions] are protected.
  4747. ** ^The sqlite3_value object returned by
  4748. ** [sqlite3_column_value()] is unprotected.
  4749. ** Unprotected sqlite3_value objects may only be used as arguments
  4750. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4751. ** [sqlite3_value_dup()].
  4752. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4753. ** interfaces require protected sqlite3_value objects.
  4754. */
  4755. typedef struct sqlite3_value sqlite3_value;
  4756. /*
  4757. ** CAPI3REF: SQL Function Context Object
  4758. **
  4759. ** The context in which an SQL function executes is stored in an
  4760. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4761. ** is always first parameter to [application-defined SQL functions].
  4762. ** The application-defined SQL function implementation will pass this
  4763. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4764. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4765. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4766. ** and/or [sqlite3_set_auxdata()].
  4767. */
  4768. typedef struct sqlite3_context sqlite3_context;
  4769. /*
  4770. ** CAPI3REF: Binding Values To Prepared Statements
  4771. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4772. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4773. ** METHOD: sqlite3_stmt
  4774. **
  4775. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4776. ** literals may be replaced by a [parameter] that matches one of following
  4777. ** templates:
  4778. **
  4779. ** <ul>
  4780. ** <li> ?
  4781. ** <li> ?NNN
  4782. ** <li> :VVV
  4783. ** <li> @VVV
  4784. ** <li> $VVV
  4785. ** </ul>
  4786. **
  4787. ** In the templates above, NNN represents an integer literal,
  4788. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  4789. ** parameters (also called "host parameter names" or "SQL parameters")
  4790. ** can be set using the sqlite3_bind_*() routines defined here.
  4791. **
  4792. ** ^The first argument to the sqlite3_bind_*() routines is always
  4793. ** a pointer to the [sqlite3_stmt] object returned from
  4794. ** [sqlite3_prepare_v2()] or its variants.
  4795. **
  4796. ** ^The second argument is the index of the SQL parameter to be set.
  4797. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  4798. ** SQL parameter is used more than once, second and subsequent
  4799. ** occurrences have the same index as the first occurrence.
  4800. ** ^The index for named parameters can be looked up using the
  4801. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  4802. ** for "?NNN" parameters is the value of NNN.
  4803. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4804. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4805. **
  4806. ** ^The third argument is the value to bind to the parameter.
  4807. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4808. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4809. ** is ignored and the end result is the same as sqlite3_bind_null().
  4810. **
  4811. ** ^(In those routines that have a fourth argument, its value is the
  4812. ** number of bytes in the parameter. To be clear: the value is the
  4813. ** number of <u>bytes</u> in the value, not the number of characters.)^
  4814. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4815. ** is negative, then the length of the string is
  4816. ** the number of bytes up to the first zero terminator.
  4817. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4818. ** the behavior is undefined.
  4819. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4820. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4821. ** that parameter must be the byte offset
  4822. ** where the NUL terminator would occur assuming the string were NUL
  4823. ** terminated. If any NUL characters occur at byte offsets less than
  4824. ** the value of the fourth parameter then the resulting string value will
  4825. ** contain embedded NULs. The result of expressions involving strings
  4826. ** with embedded NULs is undefined.
  4827. **
  4828. ** ^The fifth argument to the BLOB and string binding interfaces
  4829. ** is a destructor used to dispose of the BLOB or
  4830. ** string after SQLite has finished with it. ^The destructor is called
  4831. ** to dispose of the BLOB or string even if the call to bind API fails.
  4832. ** ^If the fifth argument is
  4833. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  4834. ** information is in static, unmanaged space and does not need to be freed.
  4835. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  4836. ** SQLite makes its own private copy of the data immediately, before
  4837. ** the sqlite3_bind_*() routine returns.
  4838. **
  4839. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  4840. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  4841. ** to specify the encoding of the text in the third parameter. If
  4842. ** the sixth argument to sqlite3_bind_text64() is not one of the
  4843. ** allowed values shown above, or if the text encoding is different
  4844. ** from the encoding specified by the sixth parameter, then the behavior
  4845. ** is undefined.
  4846. **
  4847. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  4848. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  4849. ** (just an integer to hold its size) while it is being processed.
  4850. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  4851. ** content is later written using
  4852. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  4853. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  4854. **
  4855. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  4856. ** [prepared statement] S to have an SQL value of NULL, but to also be
  4857. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  4858. ** a pointer to a destructor function for P. ^SQLite will invoke the
  4859. ** destructor D with a single argument of P when it is finished using
  4860. ** P. The T parameter should be a static string, preferably a string
  4861. ** literal. The sqlite3_bind_pointer() routine is part of the
  4862. ** [pointer passing interface] added for SQLite 3.20.0.
  4863. **
  4864. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4865. ** for the [prepared statement] or with a prepared statement for which
  4866. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4867. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4868. ** routine is passed a [prepared statement] that has been finalized, the
  4869. ** result is undefined and probably harmful.
  4870. **
  4871. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4872. ** ^Unbound parameters are interpreted as NULL.
  4873. **
  4874. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4875. ** [error code] if anything goes wrong.
  4876. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4877. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4878. ** [SQLITE_MAX_LENGTH].
  4879. ** ^[SQLITE_RANGE] is returned if the parameter
  4880. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4881. **
  4882. ** See also: [sqlite3_bind_parameter_count()],
  4883. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4884. */
  4885. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4886. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4887. void(*)(void*));
  4888. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4889. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4890. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4891. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4892. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4893. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4894. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4895. void(*)(void*), unsigned char encoding);
  4896. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4897. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  4898. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4899. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  4900. /*
  4901. ** CAPI3REF: Number Of SQL Parameters
  4902. ** METHOD: sqlite3_stmt
  4903. **
  4904. ** ^This routine can be used to find the number of [SQL parameters]
  4905. ** in a [prepared statement]. SQL parameters are tokens of the
  4906. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  4907. ** placeholders for values that are [sqlite3_bind_blob | bound]
  4908. ** to the parameters at a later time.
  4909. **
  4910. ** ^(This routine actually returns the index of the largest (rightmost)
  4911. ** parameter. For all forms except ?NNN, this will correspond to the
  4912. ** number of unique parameters. If parameters of the ?NNN form are used,
  4913. ** there may be gaps in the list.)^
  4914. **
  4915. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4916. ** [sqlite3_bind_parameter_name()], and
  4917. ** [sqlite3_bind_parameter_index()].
  4918. */
  4919. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  4920. /*
  4921. ** CAPI3REF: Name Of A Host Parameter
  4922. ** METHOD: sqlite3_stmt
  4923. **
  4924. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  4925. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  4926. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4927. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4928. ** respectively.
  4929. ** In other words, the initial ":" or "$" or "@" or "?"
  4930. ** is included as part of the name.)^
  4931. ** ^Parameters of the form "?" without a following integer have no name
  4932. ** and are referred to as "nameless" or "anonymous parameters".
  4933. **
  4934. ** ^The first host parameter has an index of 1, not 0.
  4935. **
  4936. ** ^If the value N is out of range or if the N-th parameter is
  4937. ** nameless, then NULL is returned. ^The returned string is
  4938. ** always in UTF-8 encoding even if the named parameter was
  4939. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  4940. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4941. **
  4942. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4943. ** [sqlite3_bind_parameter_count()], and
  4944. ** [sqlite3_bind_parameter_index()].
  4945. */
  4946. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  4947. /*
  4948. ** CAPI3REF: Index Of A Parameter With A Given Name
  4949. ** METHOD: sqlite3_stmt
  4950. **
  4951. ** ^Return the index of an SQL parameter given its name. ^The
  4952. ** index value returned is suitable for use as the second
  4953. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  4954. ** is returned if no matching parameter is found. ^The parameter
  4955. ** name must be given in UTF-8 even if the original statement
  4956. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  4957. ** [sqlite3_prepare16_v3()].
  4958. **
  4959. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4960. ** [sqlite3_bind_parameter_count()], and
  4961. ** [sqlite3_bind_parameter_name()].
  4962. */
  4963. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  4964. /*
  4965. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  4966. ** METHOD: sqlite3_stmt
  4967. **
  4968. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  4969. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  4970. ** ^Use this routine to reset all host parameters to NULL.
  4971. */
  4972. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  4973. /*
  4974. ** CAPI3REF: Number Of Columns In A Result Set
  4975. ** METHOD: sqlite3_stmt
  4976. **
  4977. ** ^Return the number of columns in the result set returned by the
  4978. ** [prepared statement]. ^If this routine returns 0, that means the
  4979. ** [prepared statement] returns no data (for example an [UPDATE]).
  4980. ** ^However, just because this routine returns a positive number does not
  4981. ** mean that one or more rows of data will be returned. ^A SELECT statement
  4982. ** will always have a positive sqlite3_column_count() but depending on the
  4983. ** WHERE clause constraints and the table content, it might return no rows.
  4984. **
  4985. ** See also: [sqlite3_data_count()]
  4986. */
  4987. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  4988. /*
  4989. ** CAPI3REF: Column Names In A Result Set
  4990. ** METHOD: sqlite3_stmt
  4991. **
  4992. ** ^These routines return the name assigned to a particular column
  4993. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  4994. ** interface returns a pointer to a zero-terminated UTF-8 string
  4995. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  4996. ** UTF-16 string. ^The first parameter is the [prepared statement]
  4997. ** that implements the [SELECT] statement. ^The second parameter is the
  4998. ** column number. ^The leftmost column is number 0.
  4999. **
  5000. ** ^The returned string pointer is valid until either the [prepared statement]
  5001. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5002. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5003. ** or until the next call to
  5004. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5005. **
  5006. ** ^If sqlite3_malloc() fails during the processing of either routine
  5007. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5008. ** NULL pointer is returned.
  5009. **
  5010. ** ^The name of a result column is the value of the "AS" clause for
  5011. ** that column, if there is an AS clause. If there is no AS clause
  5012. ** then the name of the column is unspecified and may change from
  5013. ** one release of SQLite to the next.
  5014. */
  5015. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5016. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5017. /*
  5018. ** CAPI3REF: Source Of Data In A Query Result
  5019. ** METHOD: sqlite3_stmt
  5020. **
  5021. ** ^These routines provide a means to determine the database, table, and
  5022. ** table column that is the origin of a particular result column in
  5023. ** [SELECT] statement.
  5024. ** ^The name of the database or table or column can be returned as
  5025. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5026. ** the database name, the _table_ routines return the table name, and
  5027. ** the origin_ routines return the column name.
  5028. ** ^The returned string is valid until the [prepared statement] is destroyed
  5029. ** using [sqlite3_finalize()] or until the statement is automatically
  5030. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5031. ** or until the same information is requested
  5032. ** again in a different encoding.
  5033. **
  5034. ** ^The names returned are the original un-aliased names of the
  5035. ** database, table, and column.
  5036. **
  5037. ** ^The first argument to these interfaces is a [prepared statement].
  5038. ** ^These functions return information about the Nth result column returned by
  5039. ** the statement, where N is the second function argument.
  5040. ** ^The left-most column is column 0 for these routines.
  5041. **
  5042. ** ^If the Nth column returned by the statement is an expression or
  5043. ** subquery and is not a column value, then all of these functions return
  5044. ** NULL. ^These routine might also return NULL if a memory allocation error
  5045. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5046. ** or column that query result column was extracted from.
  5047. **
  5048. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5049. ** UTF-16 encoded strings and the other functions return UTF-8.
  5050. **
  5051. ** ^These APIs are only available if the library was compiled with the
  5052. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5053. **
  5054. ** If two or more threads call one or more of these routines against the same
  5055. ** prepared statement and column at the same time then the results are
  5056. ** undefined.
  5057. **
  5058. ** If two or more threads call one or more
  5059. ** [sqlite3_column_database_name | column metadata interfaces]
  5060. ** for the same [prepared statement] and result column
  5061. ** at the same time then the results are undefined.
  5062. */
  5063. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5064. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5065. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5066. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5067. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5068. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5069. /*
  5070. ** CAPI3REF: Declared Datatype Of A Query Result
  5071. ** METHOD: sqlite3_stmt
  5072. **
  5073. ** ^(The first parameter is a [prepared statement].
  5074. ** If this statement is a [SELECT] statement and the Nth column of the
  5075. ** returned result set of that [SELECT] is a table column (not an
  5076. ** expression or subquery) then the declared type of the table
  5077. ** column is returned.)^ ^If the Nth column of the result set is an
  5078. ** expression or subquery, then a NULL pointer is returned.
  5079. ** ^The returned string is always UTF-8 encoded.
  5080. **
  5081. ** ^(For example, given the database schema:
  5082. **
  5083. ** CREATE TABLE t1(c1 VARIANT);
  5084. **
  5085. ** and the following statement to be compiled:
  5086. **
  5087. ** SELECT c1 + 1, c1 FROM t1;
  5088. **
  5089. ** this routine would return the string "VARIANT" for the second result
  5090. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5091. **
  5092. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5093. ** is declared to contain a particular type does not mean that the
  5094. ** data stored in that column is of the declared type. SQLite is
  5095. ** strongly typed, but the typing is dynamic not static. ^Type
  5096. ** is associated with individual values, not with the containers
  5097. ** used to hold those values.
  5098. */
  5099. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5100. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5101. /*
  5102. ** CAPI3REF: Evaluate An SQL Statement
  5103. ** METHOD: sqlite3_stmt
  5104. **
  5105. ** After a [prepared statement] has been prepared using any of
  5106. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5107. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5108. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5109. ** must be called one or more times to evaluate the statement.
  5110. **
  5111. ** The details of the behavior of the sqlite3_step() interface depend
  5112. ** on whether the statement was prepared using the newer "vX" interfaces
  5113. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5114. ** [sqlite3_prepare16_v2()] or the older legacy
  5115. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5116. ** new "vX" interface is recommended for new applications but the legacy
  5117. ** interface will continue to be supported.
  5118. **
  5119. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5120. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5121. ** ^With the "v2" interface, any of the other [result codes] or
  5122. ** [extended result codes] might be returned as well.
  5123. **
  5124. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5125. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5126. ** or occurs outside of an explicit transaction, then you can retry the
  5127. ** statement. If the statement is not a [COMMIT] and occurs within an
  5128. ** explicit transaction then you should rollback the transaction before
  5129. ** continuing.
  5130. **
  5131. ** ^[SQLITE_DONE] means that the statement has finished executing
  5132. ** successfully. sqlite3_step() should not be called again on this virtual
  5133. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5134. ** machine back to its initial state.
  5135. **
  5136. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5137. ** is returned each time a new row of data is ready for processing by the
  5138. ** caller. The values may be accessed using the [column access functions].
  5139. ** sqlite3_step() is called again to retrieve the next row of data.
  5140. **
  5141. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5142. ** violation) has occurred. sqlite3_step() should not be called again on
  5143. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5144. ** ^With the legacy interface, a more specific error code (for example,
  5145. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5146. ** can be obtained by calling [sqlite3_reset()] on the
  5147. ** [prepared statement]. ^In the "v2" interface,
  5148. ** the more specific error code is returned directly by sqlite3_step().
  5149. **
  5150. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5151. ** Perhaps it was called on a [prepared statement] that has
  5152. ** already been [sqlite3_finalize | finalized] or on one that had
  5153. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5154. ** be the case that the same database connection is being used by two or
  5155. ** more threads at the same moment in time.
  5156. **
  5157. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5158. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5159. ** other than [SQLITE_ROW] before any subsequent invocation of
  5160. ** sqlite3_step(). Failure to reset the prepared statement using
  5161. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5162. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5163. ** sqlite3_step() began
  5164. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5165. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5166. ** break because any application that ever receives an SQLITE_MISUSE error
  5167. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5168. ** can be used to restore the legacy behavior.
  5169. **
  5170. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5171. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5172. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5173. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5174. ** specific [error codes] that better describes the error.
  5175. ** We admit that this is a goofy design. The problem has been fixed
  5176. ** with the "v2" interface. If you prepare all of your SQL statements
  5177. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5178. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5179. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5180. ** then the more specific [error codes] are returned directly
  5181. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5182. */
  5183. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5184. /*
  5185. ** CAPI3REF: Number of columns in a result set
  5186. ** METHOD: sqlite3_stmt
  5187. **
  5188. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5189. ** current row of the result set of [prepared statement] P.
  5190. ** ^If prepared statement P does not have results ready to return
  5191. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5192. ** interfaces) then sqlite3_data_count(P) returns 0.
  5193. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5194. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5195. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5196. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5197. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5198. ** where it always returns zero since each step of that multi-step
  5199. ** pragma returns 0 columns of data.
  5200. **
  5201. ** See also: [sqlite3_column_count()]
  5202. */
  5203. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5204. /*
  5205. ** CAPI3REF: Fundamental Datatypes
  5206. ** KEYWORDS: SQLITE_TEXT
  5207. **
  5208. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5209. **
  5210. ** <ul>
  5211. ** <li> 64-bit signed integer
  5212. ** <li> 64-bit IEEE floating point number
  5213. ** <li> string
  5214. ** <li> BLOB
  5215. ** <li> NULL
  5216. ** </ul>)^
  5217. **
  5218. ** These constants are codes for each of those types.
  5219. **
  5220. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5221. ** for a completely different meaning. Software that links against both
  5222. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5223. ** SQLITE_TEXT.
  5224. */
  5225. #define SQLITE_INTEGER 1
  5226. #define SQLITE_FLOAT 2
  5227. #define SQLITE_BLOB 4
  5228. #define SQLITE_NULL 5
  5229. #ifdef SQLITE_TEXT
  5230. # undef SQLITE_TEXT
  5231. #else
  5232. # define SQLITE_TEXT 3
  5233. #endif
  5234. #define SQLITE3_TEXT 3
  5235. /*
  5236. ** CAPI3REF: Result Values From A Query
  5237. ** KEYWORDS: {column access functions}
  5238. ** METHOD: sqlite3_stmt
  5239. **
  5240. ** <b>Summary:</b>
  5241. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5242. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5243. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5244. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5245. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5246. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5247. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5248. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5249. ** [sqlite3_value|unprotected sqlite3_value] object.
  5250. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5251. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5252. ** or a UTF-8 TEXT result in bytes
  5253. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5254. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5255. ** TEXT in bytes
  5256. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5257. ** datatype of the result
  5258. ** </table></blockquote>
  5259. **
  5260. ** <b>Details:</b>
  5261. **
  5262. ** ^These routines return information about a single column of the current
  5263. ** result row of a query. ^In every case the first argument is a pointer
  5264. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5265. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5266. ** and the second argument is the index of the column for which information
  5267. ** should be returned. ^The leftmost column of the result set has the index 0.
  5268. ** ^The number of columns in the result can be determined using
  5269. ** [sqlite3_column_count()].
  5270. **
  5271. ** If the SQL statement does not currently point to a valid row, or if the
  5272. ** column index is out of range, the result is undefined.
  5273. ** These routines may only be called when the most recent call to
  5274. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5275. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5276. ** If any of these routines are called after [sqlite3_reset()] or
  5277. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5278. ** something other than [SQLITE_ROW], the results are undefined.
  5279. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5280. ** are called from a different thread while any of these routines
  5281. ** are pending, then the results are undefined.
  5282. **
  5283. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5284. ** each return the value of a result column in a specific data format. If
  5285. ** the result column is not initially in the requested format (for example,
  5286. ** if the query returns an integer but the sqlite3_column_text() interface
  5287. ** is used to extract the value) then an automatic type conversion is performed.
  5288. **
  5289. ** ^The sqlite3_column_type() routine returns the
  5290. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5291. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5292. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5293. ** The return value of sqlite3_column_type() can be used to decide which
  5294. ** of the first six interface should be used to extract the column value.
  5295. ** The value returned by sqlite3_column_type() is only meaningful if no
  5296. ** automatic type conversions have occurred for the value in question.
  5297. ** After a type conversion, the result of calling sqlite3_column_type()
  5298. ** is undefined, though harmless. Future
  5299. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5300. ** following a type conversion.
  5301. **
  5302. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5303. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5304. ** of that BLOB or string.
  5305. **
  5306. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5307. ** routine returns the number of bytes in that BLOB or string.
  5308. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5309. ** the string to UTF-8 and then returns the number of bytes.
  5310. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5311. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5312. ** the number of bytes in that string.
  5313. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5314. **
  5315. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5316. ** routine returns the number of bytes in that BLOB or string.
  5317. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5318. ** the string to UTF-16 and then returns the number of bytes.
  5319. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5320. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5321. ** the number of bytes in that string.
  5322. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5323. **
  5324. ** ^The values returned by [sqlite3_column_bytes()] and
  5325. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5326. ** of the string. ^For clarity: the values returned by
  5327. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5328. ** bytes in the string, not the number of characters.
  5329. **
  5330. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5331. ** even empty strings, are always zero-terminated. ^The return
  5332. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5333. **
  5334. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5335. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5336. ** an unprotected sqlite3_value object may only be used safely with
  5337. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5338. ** If the [unprotected sqlite3_value] object returned by
  5339. ** [sqlite3_column_value()] is used in any other way, including calls
  5340. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5341. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5342. ** Hence, the sqlite3_column_value() interface
  5343. ** is normally only useful within the implementation of
  5344. ** [application-defined SQL functions] or [virtual tables], not within
  5345. ** top-level application code.
  5346. **
  5347. ** The these routines may attempt to convert the datatype of the result.
  5348. ** ^For example, if the internal representation is FLOAT and a text result
  5349. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5350. ** conversion automatically. ^(The following table details the conversions
  5351. ** that are applied:
  5352. **
  5353. ** <blockquote>
  5354. ** <table border="1">
  5355. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5356. **
  5357. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5358. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5359. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5360. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5361. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5362. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5363. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5364. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5365. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5366. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5367. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5368. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5369. ** <tr><td> TEXT <td> BLOB <td> No change
  5370. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5371. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5372. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5373. ** </table>
  5374. ** </blockquote>)^
  5375. **
  5376. ** Note that when type conversions occur, pointers returned by prior
  5377. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5378. ** sqlite3_column_text16() may be invalidated.
  5379. ** Type conversions and pointer invalidations might occur
  5380. ** in the following cases:
  5381. **
  5382. ** <ul>
  5383. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5384. ** sqlite3_column_text16() is called. A zero-terminator might
  5385. ** need to be added to the string.</li>
  5386. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5387. ** sqlite3_column_text16() is called. The content must be converted
  5388. ** to UTF-16.</li>
  5389. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5390. ** sqlite3_column_text() is called. The content must be converted
  5391. ** to UTF-8.</li>
  5392. ** </ul>
  5393. **
  5394. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5395. ** not invalidate a prior pointer, though of course the content of the buffer
  5396. ** that the prior pointer references will have been modified. Other kinds
  5397. ** of conversion are done in place when it is possible, but sometimes they
  5398. ** are not possible and in those cases prior pointers are invalidated.
  5399. **
  5400. ** The safest policy is to invoke these routines
  5401. ** in one of the following ways:
  5402. **
  5403. ** <ul>
  5404. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5405. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5406. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5407. ** </ul>
  5408. **
  5409. ** In other words, you should call sqlite3_column_text(),
  5410. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5411. ** into the desired format, then invoke sqlite3_column_bytes() or
  5412. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5413. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5414. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5415. ** with calls to sqlite3_column_bytes().
  5416. **
  5417. ** ^The pointers returned are valid until a type conversion occurs as
  5418. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5419. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5420. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5421. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5422. ** [sqlite3_free()].
  5423. **
  5424. ** ^(If a memory allocation error occurs during the evaluation of any
  5425. ** of these routines, a default value is returned. The default value
  5426. ** is either the integer 0, the floating point number 0.0, or a NULL
  5427. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  5428. ** [SQLITE_NOMEM].)^
  5429. */
  5430. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5431. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5432. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5433. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5434. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5435. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5436. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5437. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5438. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5439. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5440. /*
  5441. ** CAPI3REF: Destroy A Prepared Statement Object
  5442. ** DESTRUCTOR: sqlite3_stmt
  5443. **
  5444. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5445. ** ^If the most recent evaluation of the statement encountered no errors
  5446. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5447. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5448. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5449. ** [extended error code].
  5450. **
  5451. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5452. ** the life cycle of [prepared statement] S:
  5453. ** before statement S is ever evaluated, after
  5454. ** one or more calls to [sqlite3_reset()], or after any call
  5455. ** to [sqlite3_step()] regardless of whether or not the statement has
  5456. ** completed execution.
  5457. **
  5458. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5459. **
  5460. ** The application must finalize every [prepared statement] in order to avoid
  5461. ** resource leaks. It is a grievous error for the application to try to use
  5462. ** a prepared statement after it has been finalized. Any use of a prepared
  5463. ** statement after it has been finalized can result in undefined and
  5464. ** undesirable behavior such as segfaults and heap corruption.
  5465. */
  5466. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5467. /*
  5468. ** CAPI3REF: Reset A Prepared Statement Object
  5469. ** METHOD: sqlite3_stmt
  5470. **
  5471. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5472. ** object back to its initial state, ready to be re-executed.
  5473. ** ^Any SQL statement variables that had values bound to them using
  5474. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5475. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5476. **
  5477. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5478. ** back to the beginning of its program.
  5479. **
  5480. ** ^If the most recent call to [sqlite3_step(S)] for the
  5481. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5482. ** or if [sqlite3_step(S)] has never before been called on S,
  5483. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5484. **
  5485. ** ^If the most recent call to [sqlite3_step(S)] for the
  5486. ** [prepared statement] S indicated an error, then
  5487. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5488. **
  5489. ** ^The [sqlite3_reset(S)] interface does not change the values
  5490. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5491. */
  5492. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5493. /*
  5494. ** CAPI3REF: Create Or Redefine SQL Functions
  5495. ** KEYWORDS: {function creation routines}
  5496. ** KEYWORDS: {application-defined SQL function}
  5497. ** KEYWORDS: {application-defined SQL functions}
  5498. ** METHOD: sqlite3
  5499. **
  5500. ** ^These functions (collectively known as "function creation routines")
  5501. ** are used to add SQL functions or aggregates or to redefine the behavior
  5502. ** of existing SQL functions or aggregates. The only differences between
  5503. ** these routines are the text encoding expected for
  5504. ** the second parameter (the name of the function being created)
  5505. ** and the presence or absence of a destructor callback for
  5506. ** the application data pointer.
  5507. **
  5508. ** ^The first parameter is the [database connection] to which the SQL
  5509. ** function is to be added. ^If an application uses more than one database
  5510. ** connection then application-defined SQL functions must be added
  5511. ** to each database connection separately.
  5512. **
  5513. ** ^The second parameter is the name of the SQL function to be created or
  5514. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5515. ** representation, exclusive of the zero-terminator. ^Note that the name
  5516. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5517. ** ^Any attempt to create a function with a longer name
  5518. ** will result in [SQLITE_MISUSE] being returned.
  5519. **
  5520. ** ^The third parameter (nArg)
  5521. ** is the number of arguments that the SQL function or
  5522. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5523. ** aggregate may take any number of arguments between 0 and the limit
  5524. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5525. ** parameter is less than -1 or greater than 127 then the behavior is
  5526. ** undefined.
  5527. **
  5528. ** ^The fourth parameter, eTextRep, specifies what
  5529. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5530. ** its parameters. The application should set this parameter to
  5531. ** [SQLITE_UTF16LE] if the function implementation invokes
  5532. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5533. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5534. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5535. ** otherwise. ^The same SQL function may be registered multiple times using
  5536. ** different preferred text encodings, with different implementations for
  5537. ** each encoding.
  5538. ** ^When multiple implementations of the same function are available, SQLite
  5539. ** will pick the one that involves the least amount of data conversion.
  5540. **
  5541. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5542. ** to signal that the function will always return the same result given
  5543. ** the same inputs within a single SQL statement. Most SQL functions are
  5544. ** deterministic. The built-in [random()] SQL function is an example of a
  5545. ** function that is not deterministic. The SQLite query planner is able to
  5546. ** perform additional optimizations on deterministic functions, so use
  5547. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5548. **
  5549. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5550. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5551. **
  5552. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  5553. ** pointers to C-language functions that implement the SQL function or
  5554. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5555. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5556. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5557. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5558. ** SQL function or aggregate, pass NULL pointers for all three function
  5559. ** callbacks.
  5560. **
  5561. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  5562. ** then it is destructor for the application data pointer.
  5563. ** The destructor is invoked when the function is deleted, either by being
  5564. ** overloaded or when the database connection closes.)^
  5565. ** ^The destructor is also invoked if the call to
  5566. ** sqlite3_create_function_v2() fails.
  5567. ** ^When the destructor callback of the tenth parameter is invoked, it
  5568. ** is passed a single argument which is a copy of the application data
  5569. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  5570. **
  5571. ** ^It is permitted to register multiple implementations of the same
  5572. ** functions with the same name but with either differing numbers of
  5573. ** arguments or differing preferred text encodings. ^SQLite will use
  5574. ** the implementation that most closely matches the way in which the
  5575. ** SQL function is used. ^A function implementation with a non-negative
  5576. ** nArg parameter is a better match than a function implementation with
  5577. ** a negative nArg. ^A function where the preferred text encoding
  5578. ** matches the database encoding is a better
  5579. ** match than a function where the encoding is different.
  5580. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5581. ** is a closer match than a function where the encoding difference is
  5582. ** between UTF8 and UTF16.
  5583. **
  5584. ** ^Built-in functions may be overloaded by new application-defined functions.
  5585. **
  5586. ** ^An application-defined function is permitted to call other
  5587. ** SQLite interfaces. However, such calls must not
  5588. ** close the database connection nor finalize or reset the prepared
  5589. ** statement in which the function is running.
  5590. */
  5591. SQLITE_API int sqlite3_create_function(
  5592. sqlite3 *db,
  5593. const char *zFunctionName,
  5594. int nArg,
  5595. int eTextRep,
  5596. void *pApp,
  5597. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5598. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5599. void (*xFinal)(sqlite3_context*)
  5600. );
  5601. SQLITE_API int sqlite3_create_function16(
  5602. sqlite3 *db,
  5603. const void *zFunctionName,
  5604. int nArg,
  5605. int eTextRep,
  5606. void *pApp,
  5607. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5608. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5609. void (*xFinal)(sqlite3_context*)
  5610. );
  5611. SQLITE_API int sqlite3_create_function_v2(
  5612. sqlite3 *db,
  5613. const char *zFunctionName,
  5614. int nArg,
  5615. int eTextRep,
  5616. void *pApp,
  5617. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5618. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5619. void (*xFinal)(sqlite3_context*),
  5620. void(*xDestroy)(void*)
  5621. );
  5622. /*
  5623. ** CAPI3REF: Text Encodings
  5624. **
  5625. ** These constant define integer codes that represent the various
  5626. ** text encodings supported by SQLite.
  5627. */
  5628. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5629. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5630. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5631. #define SQLITE_UTF16 4 /* Use native byte order */
  5632. #define SQLITE_ANY 5 /* Deprecated */
  5633. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5634. /*
  5635. ** CAPI3REF: Function Flags
  5636. **
  5637. ** These constants may be ORed together with the
  5638. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5639. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5640. ** [sqlite3_create_function_v2()].
  5641. */
  5642. #define SQLITE_DETERMINISTIC 0x800
  5643. /*
  5644. ** CAPI3REF: Deprecated Functions
  5645. ** DEPRECATED
  5646. **
  5647. ** These functions are [deprecated]. In order to maintain
  5648. ** backwards compatibility with older code, these functions continue
  5649. ** to be supported. However, new applications should avoid
  5650. ** the use of these functions. To encourage programmers to avoid
  5651. ** these functions, we will not explain what they do.
  5652. */
  5653. #ifndef SQLITE_OMIT_DEPRECATED
  5654. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5655. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5656. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5657. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5658. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5659. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5660. void*,sqlite3_int64);
  5661. #endif
  5662. /*
  5663. ** CAPI3REF: Obtaining SQL Values
  5664. ** METHOD: sqlite3_value
  5665. **
  5666. ** <b>Summary:</b>
  5667. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5668. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5669. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5670. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5671. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5672. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5673. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5674. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5675. ** the native byteorder
  5676. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5677. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5678. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5679. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5680. ** or a UTF-8 TEXT in bytes
  5681. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5682. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5683. ** TEXT in bytes
  5684. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5685. ** datatype of the value
  5686. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5687. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5688. ** </table></blockquote>
  5689. **
  5690. ** <b>Details:</b>
  5691. **
  5692. ** These routines extract type, size, and content information from
  5693. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5694. ** are used to pass parameter information into implementation of
  5695. ** [application-defined SQL functions] and [virtual tables].
  5696. **
  5697. ** These routines work only with [protected sqlite3_value] objects.
  5698. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5699. ** is not threadsafe.
  5700. **
  5701. ** ^These routines work just like the corresponding [column access functions]
  5702. ** except that these routines take a single [protected sqlite3_value] object
  5703. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5704. **
  5705. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5706. ** in the native byte-order of the host machine. ^The
  5707. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5708. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5709. **
  5710. ** ^If [sqlite3_value] object V was initialized
  5711. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5712. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5713. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5714. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5715. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5716. **
  5717. ** ^(The sqlite3_value_type(V) interface returns the
  5718. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5719. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5720. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5721. ** Other interfaces might change the datatype for an sqlite3_value object.
  5722. ** For example, if the datatype is initially SQLITE_INTEGER and
  5723. ** sqlite3_value_text(V) is called to extract a text value for that
  5724. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5725. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5726. ** occurs is undefined and may change from one release of SQLite to the next.
  5727. **
  5728. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5729. ** numeric affinity to the value. This means that an attempt is
  5730. ** made to convert the value to an integer or floating point. If
  5731. ** such a conversion is possible without loss of information (in other
  5732. ** words, if the value is a string that looks like a number)
  5733. ** then the conversion is performed. Otherwise no conversion occurs.
  5734. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5735. **
  5736. ** Please pay particular attention to the fact that the pointer returned
  5737. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5738. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5739. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5740. ** or [sqlite3_value_text16()].
  5741. **
  5742. ** These routines must be called from the same thread as
  5743. ** the SQL function that supplied the [sqlite3_value*] parameters.
  5744. */
  5745. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  5746. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  5747. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  5748. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  5749. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  5750. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  5751. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  5752. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  5753. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  5754. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  5755. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  5756. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  5757. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  5758. /*
  5759. ** CAPI3REF: Finding The Subtype Of SQL Values
  5760. ** METHOD: sqlite3_value
  5761. **
  5762. ** The sqlite3_value_subtype(V) function returns the subtype for
  5763. ** an [application-defined SQL function] argument V. The subtype
  5764. ** information can be used to pass a limited amount of context from
  5765. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  5766. ** routine to set the subtype for the return value of an SQL function.
  5767. */
  5768. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  5769. /*
  5770. ** CAPI3REF: Copy And Free SQL Values
  5771. ** METHOD: sqlite3_value
  5772. **
  5773. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  5774. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  5775. ** is a [protected sqlite3_value] object even if the input is not.
  5776. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  5777. ** memory allocation fails.
  5778. **
  5779. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  5780. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  5781. ** then sqlite3_value_free(V) is a harmless no-op.
  5782. */
  5783. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  5784. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  5785. /*
  5786. ** CAPI3REF: Obtain Aggregate Function Context
  5787. ** METHOD: sqlite3_context
  5788. **
  5789. ** Implementations of aggregate SQL functions use this
  5790. ** routine to allocate memory for storing their state.
  5791. **
  5792. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  5793. ** for a particular aggregate function, SQLite
  5794. ** allocates N of memory, zeroes out that memory, and returns a pointer
  5795. ** to the new memory. ^On second and subsequent calls to
  5796. ** sqlite3_aggregate_context() for the same aggregate function instance,
  5797. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  5798. ** called once for each invocation of the xStep callback and then one
  5799. ** last time when the xFinal callback is invoked. ^(When no rows match
  5800. ** an aggregate query, the xStep() callback of the aggregate function
  5801. ** implementation is never called and xFinal() is called exactly once.
  5802. ** In those cases, sqlite3_aggregate_context() might be called for the
  5803. ** first time from within xFinal().)^
  5804. **
  5805. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  5806. ** when first called if N is less than or equal to zero or if a memory
  5807. ** allocate error occurs.
  5808. **
  5809. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  5810. ** determined by the N parameter on first successful call. Changing the
  5811. ** value of N in subsequent call to sqlite3_aggregate_context() within
  5812. ** the same aggregate function instance will not resize the memory
  5813. ** allocation.)^ Within the xFinal callback, it is customary to set
  5814. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  5815. ** pointless memory allocations occur.
  5816. **
  5817. ** ^SQLite automatically frees the memory allocated by
  5818. ** sqlite3_aggregate_context() when the aggregate query concludes.
  5819. **
  5820. ** The first parameter must be a copy of the
  5821. ** [sqlite3_context | SQL function context] that is the first parameter
  5822. ** to the xStep or xFinal callback routine that implements the aggregate
  5823. ** function.
  5824. **
  5825. ** This routine must be called from the same thread in which
  5826. ** the aggregate SQL function is running.
  5827. */
  5828. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  5829. /*
  5830. ** CAPI3REF: User Data For Functions
  5831. ** METHOD: sqlite3_context
  5832. **
  5833. ** ^The sqlite3_user_data() interface returns a copy of
  5834. ** the pointer that was the pUserData parameter (the 5th parameter)
  5835. ** of the [sqlite3_create_function()]
  5836. ** and [sqlite3_create_function16()] routines that originally
  5837. ** registered the application defined function.
  5838. **
  5839. ** This routine must be called from the same thread in which
  5840. ** the application-defined function is running.
  5841. */
  5842. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  5843. /*
  5844. ** CAPI3REF: Database Connection For Functions
  5845. ** METHOD: sqlite3_context
  5846. **
  5847. ** ^The sqlite3_context_db_handle() interface returns a copy of
  5848. ** the pointer to the [database connection] (the 1st parameter)
  5849. ** of the [sqlite3_create_function()]
  5850. ** and [sqlite3_create_function16()] routines that originally
  5851. ** registered the application defined function.
  5852. */
  5853. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  5854. /*
  5855. ** CAPI3REF: Function Auxiliary Data
  5856. ** METHOD: sqlite3_context
  5857. **
  5858. ** These functions may be used by (non-aggregate) SQL functions to
  5859. ** associate metadata with argument values. If the same value is passed to
  5860. ** multiple invocations of the same SQL function during query execution, under
  5861. ** some circumstances the associated metadata may be preserved. An example
  5862. ** of where this might be useful is in a regular-expression matching
  5863. ** function. The compiled version of the regular expression can be stored as
  5864. ** metadata associated with the pattern string.
  5865. ** Then as long as the pattern string remains the same,
  5866. ** the compiled regular expression can be reused on multiple
  5867. ** invocations of the same function.
  5868. **
  5869. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  5870. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  5871. ** value to the application-defined function. ^N is zero for the left-most
  5872. ** function argument. ^If there is no metadata
  5873. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  5874. ** returns a NULL pointer.
  5875. **
  5876. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  5877. ** argument of the application-defined function. ^Subsequent
  5878. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  5879. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  5880. ** NULL if the metadata has been discarded.
  5881. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  5882. ** SQLite will invoke the destructor function X with parameter P exactly
  5883. ** once, when the metadata is discarded.
  5884. ** SQLite is free to discard the metadata at any time, including: <ul>
  5885. ** <li> ^(when the corresponding function parameter changes)^, or
  5886. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  5887. ** SQL statement)^, or
  5888. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  5889. ** parameter)^, or
  5890. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  5891. ** allocation error occurs.)^ </ul>
  5892. **
  5893. ** Note the last bullet in particular. The destructor X in
  5894. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  5895. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  5896. ** should be called near the end of the function implementation and the
  5897. ** function implementation should not make any use of P after
  5898. ** sqlite3_set_auxdata() has been called.
  5899. **
  5900. ** ^(In practice, metadata is preserved between function calls for
  5901. ** function parameters that are compile-time constants, including literal
  5902. ** values and [parameters] and expressions composed from the same.)^
  5903. **
  5904. ** The value of the N parameter to these interfaces should be non-negative.
  5905. ** Future enhancements may make use of negative N values to define new
  5906. ** kinds of function caching behavior.
  5907. **
  5908. ** These routines must be called from the same thread in which
  5909. ** the SQL function is running.
  5910. */
  5911. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  5912. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  5913. /*
  5914. ** CAPI3REF: Constants Defining Special Destructor Behavior
  5915. **
  5916. ** These are special values for the destructor that is passed in as the
  5917. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  5918. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  5919. ** and will never change. It does not need to be destroyed. ^The
  5920. ** SQLITE_TRANSIENT value means that the content will likely change in
  5921. ** the near future and that SQLite should make its own private copy of
  5922. ** the content before returning.
  5923. **
  5924. ** The typedef is necessary to work around problems in certain
  5925. ** C++ compilers.
  5926. */
  5927. typedef void (*sqlite3_destructor_type)(void*);
  5928. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  5929. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  5930. /*
  5931. ** CAPI3REF: Setting The Result Of An SQL Function
  5932. ** METHOD: sqlite3_context
  5933. **
  5934. ** These routines are used by the xFunc or xFinal callbacks that
  5935. ** implement SQL functions and aggregates. See
  5936. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  5937. ** for additional information.
  5938. **
  5939. ** These functions work very much like the [parameter binding] family of
  5940. ** functions used to bind values to host parameters in prepared statements.
  5941. ** Refer to the [SQL parameter] documentation for additional information.
  5942. **
  5943. ** ^The sqlite3_result_blob() interface sets the result from
  5944. ** an application-defined function to be the BLOB whose content is pointed
  5945. ** to by the second parameter and which is N bytes long where N is the
  5946. ** third parameter.
  5947. **
  5948. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  5949. ** interfaces set the result of the application-defined function to be
  5950. ** a BLOB containing all zero bytes and N bytes in size.
  5951. **
  5952. ** ^The sqlite3_result_double() interface sets the result from
  5953. ** an application-defined function to be a floating point value specified
  5954. ** by its 2nd argument.
  5955. **
  5956. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  5957. ** cause the implemented SQL function to throw an exception.
  5958. ** ^SQLite uses the string pointed to by the
  5959. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  5960. ** as the text of an error message. ^SQLite interprets the error
  5961. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  5962. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  5963. ** byte order. ^If the third parameter to sqlite3_result_error()
  5964. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  5965. ** message all text up through the first zero character.
  5966. ** ^If the third parameter to sqlite3_result_error() or
  5967. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  5968. ** bytes (not characters) from the 2nd parameter as the error message.
  5969. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  5970. ** routines make a private copy of the error message text before
  5971. ** they return. Hence, the calling function can deallocate or
  5972. ** modify the text after they return without harm.
  5973. ** ^The sqlite3_result_error_code() function changes the error code
  5974. ** returned by SQLite as a result of an error in a function. ^By default,
  5975. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  5976. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  5977. **
  5978. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  5979. ** error indicating that a string or BLOB is too long to represent.
  5980. **
  5981. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  5982. ** error indicating that a memory allocation failed.
  5983. **
  5984. ** ^The sqlite3_result_int() interface sets the return value
  5985. ** of the application-defined function to be the 32-bit signed integer
  5986. ** value given in the 2nd argument.
  5987. ** ^The sqlite3_result_int64() interface sets the return value
  5988. ** of the application-defined function to be the 64-bit signed integer
  5989. ** value given in the 2nd argument.
  5990. **
  5991. ** ^The sqlite3_result_null() interface sets the return value
  5992. ** of the application-defined function to be NULL.
  5993. **
  5994. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  5995. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  5996. ** set the return value of the application-defined function to be
  5997. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  5998. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  5999. ** ^The sqlite3_result_text64() interface sets the return value of an
  6000. ** application-defined function to be a text string in an encoding
  6001. ** specified by the fifth (and last) parameter, which must be one
  6002. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6003. ** ^SQLite takes the text result from the application from
  6004. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6005. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6006. ** is negative, then SQLite takes result text from the 2nd parameter
  6007. ** through the first zero character.
  6008. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6009. ** is non-negative, then as many bytes (not characters) of the text
  6010. ** pointed to by the 2nd parameter are taken as the application-defined
  6011. ** function result. If the 3rd parameter is non-negative, then it
  6012. ** must be the byte offset into the string where the NUL terminator would
  6013. ** appear if the string where NUL terminated. If any NUL characters occur
  6014. ** in the string at a byte offset that is less than the value of the 3rd
  6015. ** parameter, then the resulting string will contain embedded NULs and the
  6016. ** result of expressions operating on strings with embedded NULs is undefined.
  6017. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6018. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6019. ** function as the destructor on the text or BLOB result when it has
  6020. ** finished using that result.
  6021. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6022. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6023. ** assumes that the text or BLOB result is in constant space and does not
  6024. ** copy the content of the parameter nor call a destructor on the content
  6025. ** when it has finished using that result.
  6026. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6027. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6028. ** then SQLite makes a copy of the result into space obtained
  6029. ** from [sqlite3_malloc()] before it returns.
  6030. **
  6031. ** ^The sqlite3_result_value() interface sets the result of
  6032. ** the application-defined function to be a copy of the
  6033. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6034. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6035. ** so that the [sqlite3_value] specified in the parameter may change or
  6036. ** be deallocated after sqlite3_result_value() returns without harm.
  6037. ** ^A [protected sqlite3_value] object may always be used where an
  6038. ** [unprotected sqlite3_value] object is required, so either
  6039. ** kind of [sqlite3_value] object can be used with this interface.
  6040. **
  6041. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6042. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6043. ** also associates the host-language pointer P or type T with that
  6044. ** NULL value such that the pointer can be retrieved within an
  6045. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6046. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6047. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6048. ** when SQLite is finished with P. The T parameter should be a static
  6049. ** string and preferably a string literal. The sqlite3_result_pointer()
  6050. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6051. **
  6052. ** If these routines are called from within the different thread
  6053. ** than the one containing the application-defined function that received
  6054. ** the [sqlite3_context] pointer, the results are undefined.
  6055. */
  6056. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6057. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6058. sqlite3_uint64,void(*)(void*));
  6059. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6060. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6061. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6062. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6063. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6064. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6065. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6066. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6067. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6068. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6069. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6070. void(*)(void*), unsigned char encoding);
  6071. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6072. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6073. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6074. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6075. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6076. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6077. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6078. /*
  6079. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6080. ** METHOD: sqlite3_context
  6081. **
  6082. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6083. ** the result from the [application-defined SQL function] with
  6084. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6085. ** of the subtype T are preserved in current versions of SQLite;
  6086. ** higher order bits are discarded.
  6087. ** The number of subtype bytes preserved by SQLite might increase
  6088. ** in future releases of SQLite.
  6089. */
  6090. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6091. /*
  6092. ** CAPI3REF: Define New Collating Sequences
  6093. ** METHOD: sqlite3
  6094. **
  6095. ** ^These functions add, remove, or modify a [collation] associated
  6096. ** with the [database connection] specified as the first argument.
  6097. **
  6098. ** ^The name of the collation is a UTF-8 string
  6099. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6100. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6101. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6102. ** considered to be the same name.
  6103. **
  6104. ** ^(The third argument (eTextRep) must be one of the constants:
  6105. ** <ul>
  6106. ** <li> [SQLITE_UTF8],
  6107. ** <li> [SQLITE_UTF16LE],
  6108. ** <li> [SQLITE_UTF16BE],
  6109. ** <li> [SQLITE_UTF16], or
  6110. ** <li> [SQLITE_UTF16_ALIGNED].
  6111. ** </ul>)^
  6112. ** ^The eTextRep argument determines the encoding of strings passed
  6113. ** to the collating function callback, xCallback.
  6114. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6115. ** force strings to be UTF16 with native byte order.
  6116. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6117. ** on an even byte address.
  6118. **
  6119. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6120. ** through as the first argument to the collating function callback.
  6121. **
  6122. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6123. ** ^Multiple collating functions can be registered using the same name but
  6124. ** with different eTextRep parameters and SQLite will use whichever
  6125. ** function requires the least amount of data transformation.
  6126. ** ^If the xCallback argument is NULL then the collating function is
  6127. ** deleted. ^When all collating functions having the same name are deleted,
  6128. ** that collation is no longer usable.
  6129. **
  6130. ** ^The collating function callback is invoked with a copy of the pArg
  6131. ** application data pointer and with two strings in the encoding specified
  6132. ** by the eTextRep argument. The collating function must return an
  6133. ** integer that is negative, zero, or positive
  6134. ** if the first string is less than, equal to, or greater than the second,
  6135. ** respectively. A collating function must always return the same answer
  6136. ** given the same inputs. If two or more collating functions are registered
  6137. ** to the same collation name (using different eTextRep values) then all
  6138. ** must give an equivalent answer when invoked with equivalent strings.
  6139. ** The collating function must obey the following properties for all
  6140. ** strings A, B, and C:
  6141. **
  6142. ** <ol>
  6143. ** <li> If A==B then B==A.
  6144. ** <li> If A==B and B==C then A==C.
  6145. ** <li> If A&lt;B THEN B&gt;A.
  6146. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6147. ** </ol>
  6148. **
  6149. ** If a collating function fails any of the above constraints and that
  6150. ** collating function is registered and used, then the behavior of SQLite
  6151. ** is undefined.
  6152. **
  6153. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6154. ** with the addition that the xDestroy callback is invoked on pArg when
  6155. ** the collating function is deleted.
  6156. ** ^Collating functions are deleted when they are overridden by later
  6157. ** calls to the collation creation functions or when the
  6158. ** [database connection] is closed using [sqlite3_close()].
  6159. **
  6160. ** ^The xDestroy callback is <u>not</u> called if the
  6161. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6162. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6163. ** check the return code and dispose of the application data pointer
  6164. ** themselves rather than expecting SQLite to deal with it for them.
  6165. ** This is different from every other SQLite interface. The inconsistency
  6166. ** is unfortunate but cannot be changed without breaking backwards
  6167. ** compatibility.
  6168. **
  6169. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6170. */
  6171. SQLITE_API int sqlite3_create_collation(
  6172. sqlite3*,
  6173. const char *zName,
  6174. int eTextRep,
  6175. void *pArg,
  6176. int(*xCompare)(void*,int,const void*,int,const void*)
  6177. );
  6178. SQLITE_API int sqlite3_create_collation_v2(
  6179. sqlite3*,
  6180. const char *zName,
  6181. int eTextRep,
  6182. void *pArg,
  6183. int(*xCompare)(void*,int,const void*,int,const void*),
  6184. void(*xDestroy)(void*)
  6185. );
  6186. SQLITE_API int sqlite3_create_collation16(
  6187. sqlite3*,
  6188. const void *zName,
  6189. int eTextRep,
  6190. void *pArg,
  6191. int(*xCompare)(void*,int,const void*,int,const void*)
  6192. );
  6193. /*
  6194. ** CAPI3REF: Collation Needed Callbacks
  6195. ** METHOD: sqlite3
  6196. **
  6197. ** ^To avoid having to register all collation sequences before a database
  6198. ** can be used, a single callback function may be registered with the
  6199. ** [database connection] to be invoked whenever an undefined collation
  6200. ** sequence is required.
  6201. **
  6202. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6203. ** then it is passed the names of undefined collation sequences as strings
  6204. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6205. ** the names are passed as UTF-16 in machine native byte order.
  6206. ** ^A call to either function replaces the existing collation-needed callback.
  6207. **
  6208. ** ^(When the callback is invoked, the first argument passed is a copy
  6209. ** of the second argument to sqlite3_collation_needed() or
  6210. ** sqlite3_collation_needed16(). The second argument is the database
  6211. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6212. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6213. ** sequence function required. The fourth parameter is the name of the
  6214. ** required collation sequence.)^
  6215. **
  6216. ** The callback function should register the desired collation using
  6217. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6218. ** [sqlite3_create_collation_v2()].
  6219. */
  6220. SQLITE_API int sqlite3_collation_needed(
  6221. sqlite3*,
  6222. void*,
  6223. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6224. );
  6225. SQLITE_API int sqlite3_collation_needed16(
  6226. sqlite3*,
  6227. void*,
  6228. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6229. );
  6230. #ifdef SQLITE_HAS_CODEC
  6231. /*
  6232. ** Specify the key for an encrypted database. This routine should be
  6233. ** called right after sqlite3_open().
  6234. **
  6235. ** The code to implement this API is not available in the public release
  6236. ** of SQLite.
  6237. */
  6238. SQLITE_API int sqlite3_key(
  6239. sqlite3 *db, /* Database to be rekeyed */
  6240. const void *pKey, int nKey /* The key */
  6241. );
  6242. SQLITE_API int sqlite3_key_v2(
  6243. sqlite3 *db, /* Database to be rekeyed */
  6244. const char *zDbName, /* Name of the database */
  6245. const void *pKey, int nKey /* The key */
  6246. );
  6247. /*
  6248. ** Change the key on an open database. If the current database is not
  6249. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6250. ** database is decrypted.
  6251. **
  6252. ** The code to implement this API is not available in the public release
  6253. ** of SQLite.
  6254. */
  6255. SQLITE_API int sqlite3_rekey(
  6256. sqlite3 *db, /* Database to be rekeyed */
  6257. const void *pKey, int nKey /* The new key */
  6258. );
  6259. SQLITE_API int sqlite3_rekey_v2(
  6260. sqlite3 *db, /* Database to be rekeyed */
  6261. const char *zDbName, /* Name of the database */
  6262. const void *pKey, int nKey /* The new key */
  6263. );
  6264. /*
  6265. ** Specify the activation key for a SEE database. Unless
  6266. ** activated, none of the SEE routines will work.
  6267. */
  6268. SQLITE_API void sqlite3_activate_see(
  6269. const char *zPassPhrase /* Activation phrase */
  6270. );
  6271. #endif
  6272. #ifdef SQLITE_ENABLE_CEROD
  6273. /*
  6274. ** Specify the activation key for a CEROD database. Unless
  6275. ** activated, none of the CEROD routines will work.
  6276. */
  6277. SQLITE_API void sqlite3_activate_cerod(
  6278. const char *zPassPhrase /* Activation phrase */
  6279. );
  6280. #endif
  6281. /*
  6282. ** CAPI3REF: Suspend Execution For A Short Time
  6283. **
  6284. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6285. ** for at least a number of milliseconds specified in its parameter.
  6286. **
  6287. ** If the operating system does not support sleep requests with
  6288. ** millisecond time resolution, then the time will be rounded up to
  6289. ** the nearest second. The number of milliseconds of sleep actually
  6290. ** requested from the operating system is returned.
  6291. **
  6292. ** ^SQLite implements this interface by calling the xSleep()
  6293. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6294. ** of the default VFS is not implemented correctly, or not implemented at
  6295. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6296. ** in the previous paragraphs.
  6297. */
  6298. SQLITE_API int sqlite3_sleep(int);
  6299. /*
  6300. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6301. **
  6302. ** ^(If this global variable is made to point to a string which is
  6303. ** the name of a folder (a.k.a. directory), then all temporary files
  6304. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6305. ** will be placed in that directory.)^ ^If this variable
  6306. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6307. ** temporary file directory.
  6308. **
  6309. ** Applications are strongly discouraged from using this global variable.
  6310. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6311. ** But for all other platforms, it is highly recommended that applications
  6312. ** neither read nor write this variable. This global variable is a relic
  6313. ** that exists for backwards compatibility of legacy applications and should
  6314. ** be avoided in new projects.
  6315. **
  6316. ** It is not safe to read or modify this variable in more than one
  6317. ** thread at a time. It is not safe to read or modify this variable
  6318. ** if a [database connection] is being used at the same time in a separate
  6319. ** thread.
  6320. ** It is intended that this variable be set once
  6321. ** as part of process initialization and before any SQLite interface
  6322. ** routines have been called and that this variable remain unchanged
  6323. ** thereafter.
  6324. **
  6325. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6326. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6327. ** the [temp_store_directory pragma] always assumes that any string
  6328. ** that this variable points to is held in memory obtained from
  6329. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6330. ** using [sqlite3_free].
  6331. ** Hence, if this variable is modified directly, either it should be
  6332. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6333. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6334. ** Except when requested by the [temp_store_directory pragma], SQLite
  6335. ** does not free the memory that sqlite3_temp_directory points to. If
  6336. ** the application wants that memory to be freed, it must do
  6337. ** so itself, taking care to only do so after all [database connection]
  6338. ** objects have been destroyed.
  6339. **
  6340. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6341. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6342. ** features that require the use of temporary files may fail. Here is an
  6343. ** example of how to do this using C++ with the Windows Runtime:
  6344. **
  6345. ** <blockquote><pre>
  6346. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6347. ** &nbsp; TemporaryFolder->Path->Data();
  6348. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6349. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6350. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6351. ** &nbsp; NULL, NULL);
  6352. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6353. ** </pre></blockquote>
  6354. */
  6355. SQLITE_API char *sqlite3_temp_directory;
  6356. /*
  6357. ** CAPI3REF: Name Of The Folder Holding Database Files
  6358. **
  6359. ** ^(If this global variable is made to point to a string which is
  6360. ** the name of a folder (a.k.a. directory), then all database files
  6361. ** specified with a relative pathname and created or accessed by
  6362. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6363. ** to be relative to that directory.)^ ^If this variable is a NULL
  6364. ** pointer, then SQLite assumes that all database files specified
  6365. ** with a relative pathname are relative to the current directory
  6366. ** for the process. Only the windows VFS makes use of this global
  6367. ** variable; it is ignored by the unix VFS.
  6368. **
  6369. ** Changing the value of this variable while a database connection is
  6370. ** open can result in a corrupt database.
  6371. **
  6372. ** It is not safe to read or modify this variable in more than one
  6373. ** thread at a time. It is not safe to read or modify this variable
  6374. ** if a [database connection] is being used at the same time in a separate
  6375. ** thread.
  6376. ** It is intended that this variable be set once
  6377. ** as part of process initialization and before any SQLite interface
  6378. ** routines have been called and that this variable remain unchanged
  6379. ** thereafter.
  6380. **
  6381. ** ^The [data_store_directory pragma] may modify this variable and cause
  6382. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6383. ** the [data_store_directory pragma] always assumes that any string
  6384. ** that this variable points to is held in memory obtained from
  6385. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6386. ** using [sqlite3_free].
  6387. ** Hence, if this variable is modified directly, either it should be
  6388. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6389. ** or else the use of the [data_store_directory pragma] should be avoided.
  6390. */
  6391. SQLITE_API char *sqlite3_data_directory;
  6392. /*
  6393. ** CAPI3REF: Test For Auto-Commit Mode
  6394. ** KEYWORDS: {autocommit mode}
  6395. ** METHOD: sqlite3
  6396. **
  6397. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6398. ** zero if the given database connection is or is not in autocommit mode,
  6399. ** respectively. ^Autocommit mode is on by default.
  6400. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6401. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6402. **
  6403. ** If certain kinds of errors occur on a statement within a multi-statement
  6404. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6405. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6406. ** transaction might be rolled back automatically. The only way to
  6407. ** find out whether SQLite automatically rolled back the transaction after
  6408. ** an error is to use this function.
  6409. **
  6410. ** If another thread changes the autocommit status of the database
  6411. ** connection while this routine is running, then the return value
  6412. ** is undefined.
  6413. */
  6414. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6415. /*
  6416. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6417. ** METHOD: sqlite3_stmt
  6418. **
  6419. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6420. ** to which a [prepared statement] belongs. ^The [database connection]
  6421. ** returned by sqlite3_db_handle is the same [database connection]
  6422. ** that was the first argument
  6423. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6424. ** create the statement in the first place.
  6425. */
  6426. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6427. /*
  6428. ** CAPI3REF: Return The Filename For A Database Connection
  6429. ** METHOD: sqlite3
  6430. **
  6431. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6432. ** associated with database N of connection D. ^The main database file
  6433. ** has the name "main". If there is no attached database N on the database
  6434. ** connection D, or if database N is a temporary or in-memory database, then
  6435. ** a NULL pointer is returned.
  6436. **
  6437. ** ^The filename returned by this function is the output of the
  6438. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6439. ** will be an absolute pathname, even if the filename used
  6440. ** to open the database originally was a URI or relative pathname.
  6441. */
  6442. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6443. /*
  6444. ** CAPI3REF: Determine if a database is read-only
  6445. ** METHOD: sqlite3
  6446. **
  6447. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6448. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6449. ** the name of a database on connection D.
  6450. */
  6451. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6452. /*
  6453. ** CAPI3REF: Find the next prepared statement
  6454. ** METHOD: sqlite3
  6455. **
  6456. ** ^This interface returns a pointer to the next [prepared statement] after
  6457. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6458. ** then this interface returns a pointer to the first prepared statement
  6459. ** associated with the database connection pDb. ^If no prepared statement
  6460. ** satisfies the conditions of this routine, it returns NULL.
  6461. **
  6462. ** The [database connection] pointer D in a call to
  6463. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6464. ** connection and in particular must not be a NULL pointer.
  6465. */
  6466. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6467. /*
  6468. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6469. ** METHOD: sqlite3
  6470. **
  6471. ** ^The sqlite3_commit_hook() interface registers a callback
  6472. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6473. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6474. ** for the same database connection is overridden.
  6475. ** ^The sqlite3_rollback_hook() interface registers a callback
  6476. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6477. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6478. ** for the same database connection is overridden.
  6479. ** ^The pArg argument is passed through to the callback.
  6480. ** ^If the callback on a commit hook function returns non-zero,
  6481. ** then the commit is converted into a rollback.
  6482. **
  6483. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6484. ** return the P argument from the previous call of the same function
  6485. ** on the same [database connection] D, or NULL for
  6486. ** the first call for each function on D.
  6487. **
  6488. ** The commit and rollback hook callbacks are not reentrant.
  6489. ** The callback implementation must not do anything that will modify
  6490. ** the database connection that invoked the callback. Any actions
  6491. ** to modify the database connection must be deferred until after the
  6492. ** completion of the [sqlite3_step()] call that triggered the commit
  6493. ** or rollback hook in the first place.
  6494. ** Note that running any other SQL statements, including SELECT statements,
  6495. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6496. ** the database connections for the meaning of "modify" in this paragraph.
  6497. **
  6498. ** ^Registering a NULL function disables the callback.
  6499. **
  6500. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6501. ** operation is allowed to continue normally. ^If the commit hook
  6502. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6503. ** ^The rollback hook is invoked on a rollback that results from a commit
  6504. ** hook returning non-zero, just as it would be with any other rollback.
  6505. **
  6506. ** ^For the purposes of this API, a transaction is said to have been
  6507. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6508. ** an error or constraint causes an implicit rollback to occur.
  6509. ** ^The rollback callback is not invoked if a transaction is
  6510. ** automatically rolled back because the database connection is closed.
  6511. **
  6512. ** See also the [sqlite3_update_hook()] interface.
  6513. */
  6514. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6515. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6516. /*
  6517. ** CAPI3REF: Data Change Notification Callbacks
  6518. ** METHOD: sqlite3
  6519. **
  6520. ** ^The sqlite3_update_hook() interface registers a callback function
  6521. ** with the [database connection] identified by the first argument
  6522. ** to be invoked whenever a row is updated, inserted or deleted in
  6523. ** a [rowid table].
  6524. ** ^Any callback set by a previous call to this function
  6525. ** for the same database connection is overridden.
  6526. **
  6527. ** ^The second argument is a pointer to the function to invoke when a
  6528. ** row is updated, inserted or deleted in a rowid table.
  6529. ** ^The first argument to the callback is a copy of the third argument
  6530. ** to sqlite3_update_hook().
  6531. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6532. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6533. ** to be invoked.
  6534. ** ^The third and fourth arguments to the callback contain pointers to the
  6535. ** database and table name containing the affected row.
  6536. ** ^The final callback parameter is the [rowid] of the row.
  6537. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6538. **
  6539. ** ^(The update hook is not invoked when internal system tables are
  6540. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6541. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6542. **
  6543. ** ^In the current implementation, the update hook
  6544. ** is not invoked when conflicting rows are deleted because of an
  6545. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6546. ** invoked when rows are deleted using the [truncate optimization].
  6547. ** The exceptions defined in this paragraph might change in a future
  6548. ** release of SQLite.
  6549. **
  6550. ** The update hook implementation must not do anything that will modify
  6551. ** the database connection that invoked the update hook. Any actions
  6552. ** to modify the database connection must be deferred until after the
  6553. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6554. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6555. ** database connections for the meaning of "modify" in this paragraph.
  6556. **
  6557. ** ^The sqlite3_update_hook(D,C,P) function
  6558. ** returns the P argument from the previous call
  6559. ** on the same [database connection] D, or NULL for
  6560. ** the first call on D.
  6561. **
  6562. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6563. ** and [sqlite3_preupdate_hook()] interfaces.
  6564. */
  6565. SQLITE_API void *sqlite3_update_hook(
  6566. sqlite3*,
  6567. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6568. void*
  6569. );
  6570. /*
  6571. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6572. **
  6573. ** ^(This routine enables or disables the sharing of the database cache
  6574. ** and schema data structures between [database connection | connections]
  6575. ** to the same database. Sharing is enabled if the argument is true
  6576. ** and disabled if the argument is false.)^
  6577. **
  6578. ** ^Cache sharing is enabled and disabled for an entire process.
  6579. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6580. ** In prior versions of SQLite,
  6581. ** sharing was enabled or disabled for each thread separately.
  6582. **
  6583. ** ^(The cache sharing mode set by this interface effects all subsequent
  6584. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6585. ** Existing database connections continue use the sharing mode
  6586. ** that was in effect at the time they were opened.)^
  6587. **
  6588. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6589. ** successfully. An [error code] is returned otherwise.)^
  6590. **
  6591. ** ^Shared cache is disabled by default. But this might change in
  6592. ** future releases of SQLite. Applications that care about shared
  6593. ** cache setting should set it explicitly.
  6594. **
  6595. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6596. ** and will always return SQLITE_MISUSE. On those systems,
  6597. ** shared cache mode should be enabled per-database connection via
  6598. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6599. **
  6600. ** This interface is threadsafe on processors where writing a
  6601. ** 32-bit integer is atomic.
  6602. **
  6603. ** See Also: [SQLite Shared-Cache Mode]
  6604. */
  6605. SQLITE_API int sqlite3_enable_shared_cache(int);
  6606. /*
  6607. ** CAPI3REF: Attempt To Free Heap Memory
  6608. **
  6609. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6610. ** of heap memory by deallocating non-essential memory allocations
  6611. ** held by the database library. Memory used to cache database
  6612. ** pages to improve performance is an example of non-essential memory.
  6613. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6614. ** which might be more or less than the amount requested.
  6615. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6616. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6617. **
  6618. ** See also: [sqlite3_db_release_memory()]
  6619. */
  6620. SQLITE_API int sqlite3_release_memory(int);
  6621. /*
  6622. ** CAPI3REF: Free Memory Used By A Database Connection
  6623. ** METHOD: sqlite3
  6624. **
  6625. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6626. ** memory as possible from database connection D. Unlike the
  6627. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6628. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6629. ** omitted.
  6630. **
  6631. ** See also: [sqlite3_release_memory()]
  6632. */
  6633. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6634. /*
  6635. ** CAPI3REF: Impose A Limit On Heap Size
  6636. **
  6637. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6638. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6639. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6640. ** limit by reducing the number of pages held in the page cache
  6641. ** as heap memory usages approaches the limit.
  6642. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6643. ** below the limit, it will exceed the limit rather than generate
  6644. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6645. ** is advisory only.
  6646. **
  6647. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6648. ** the soft heap limit prior to the call, or negative in the case of an
  6649. ** error. ^If the argument N is negative
  6650. ** then no change is made to the soft heap limit. Hence, the current
  6651. ** size of the soft heap limit can be determined by invoking
  6652. ** sqlite3_soft_heap_limit64() with a negative argument.
  6653. **
  6654. ** ^If the argument N is zero then the soft heap limit is disabled.
  6655. **
  6656. ** ^(The soft heap limit is not enforced in the current implementation
  6657. ** if one or more of following conditions are true:
  6658. **
  6659. ** <ul>
  6660. ** <li> The soft heap limit is set to zero.
  6661. ** <li> Memory accounting is disabled using a combination of the
  6662. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6663. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6664. ** <li> An alternative page cache implementation is specified using
  6665. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6666. ** <li> The page cache allocates from its own memory pool supplied
  6667. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6668. ** from the heap.
  6669. ** </ul>)^
  6670. **
  6671. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  6672. ** the soft heap limit is enforced
  6673. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6674. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6675. ** the soft heap limit is enforced on every memory allocation. Without
  6676. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6677. ** when memory is allocated by the page cache. Testing suggests that because
  6678. ** the page cache is the predominate memory user in SQLite, most
  6679. ** applications will achieve adequate soft heap limit enforcement without
  6680. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6681. **
  6682. ** The circumstances under which SQLite will enforce the soft heap limit may
  6683. ** changes in future releases of SQLite.
  6684. */
  6685. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6686. /*
  6687. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6688. ** DEPRECATED
  6689. **
  6690. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6691. ** interface. This routine is provided for historical compatibility
  6692. ** only. All new applications should use the
  6693. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6694. */
  6695. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6696. /*
  6697. ** CAPI3REF: Extract Metadata About A Column Of A Table
  6698. ** METHOD: sqlite3
  6699. **
  6700. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6701. ** information about column C of table T in database D
  6702. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  6703. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6704. ** the final five arguments with appropriate values if the specified
  6705. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  6706. ** SQLITE_ERROR and if the specified column does not exist.
  6707. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6708. ** NULL pointer, then this routine simply checks for the existence of the
  6709. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  6710. ** does not. If the table name parameter T in a call to
  6711. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  6712. ** undefined behavior.
  6713. **
  6714. ** ^The column is identified by the second, third and fourth parameters to
  6715. ** this function. ^(The second parameter is either the name of the database
  6716. ** (i.e. "main", "temp", or an attached database) containing the specified
  6717. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  6718. ** for the table using the same algorithm used by the database engine to
  6719. ** resolve unqualified table references.
  6720. **
  6721. ** ^The third and fourth parameters to this function are the table and column
  6722. ** name of the desired column, respectively.
  6723. **
  6724. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  6725. ** and subsequent parameters to this function. ^Any of these arguments may be
  6726. ** NULL, in which case the corresponding element of metadata is omitted.
  6727. **
  6728. ** ^(<blockquote>
  6729. ** <table border="1">
  6730. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  6731. **
  6732. ** <tr><td> 5th <td> const char* <td> Data type
  6733. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  6734. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  6735. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  6736. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  6737. ** </table>
  6738. ** </blockquote>)^
  6739. **
  6740. ** ^The memory pointed to by the character pointers returned for the
  6741. ** declaration type and collation sequence is valid until the next
  6742. ** call to any SQLite API function.
  6743. **
  6744. ** ^If the specified table is actually a view, an [error code] is returned.
  6745. **
  6746. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  6747. ** is not a [WITHOUT ROWID] table and an
  6748. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  6749. ** parameters are set for the explicitly declared column. ^(If there is no
  6750. ** [INTEGER PRIMARY KEY] column, then the outputs
  6751. ** for the [rowid] are set as follows:
  6752. **
  6753. ** <pre>
  6754. ** data type: "INTEGER"
  6755. ** collation sequence: "BINARY"
  6756. ** not null: 0
  6757. ** primary key: 1
  6758. ** auto increment: 0
  6759. ** </pre>)^
  6760. **
  6761. ** ^This function causes all database schemas to be read from disk and
  6762. ** parsed, if that has not already been done, and returns an error if
  6763. ** any errors are encountered while loading the schema.
  6764. */
  6765. SQLITE_API int sqlite3_table_column_metadata(
  6766. sqlite3 *db, /* Connection handle */
  6767. const char *zDbName, /* Database name or NULL */
  6768. const char *zTableName, /* Table name */
  6769. const char *zColumnName, /* Column name */
  6770. char const **pzDataType, /* OUTPUT: Declared data type */
  6771. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  6772. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  6773. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  6774. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  6775. );
  6776. /*
  6777. ** CAPI3REF: Load An Extension
  6778. ** METHOD: sqlite3
  6779. **
  6780. ** ^This interface loads an SQLite extension library from the named file.
  6781. **
  6782. ** ^The sqlite3_load_extension() interface attempts to load an
  6783. ** [SQLite extension] library contained in the file zFile. If
  6784. ** the file cannot be loaded directly, attempts are made to load
  6785. ** with various operating-system specific extensions added.
  6786. ** So for example, if "samplelib" cannot be loaded, then names like
  6787. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  6788. ** be tried also.
  6789. **
  6790. ** ^The entry point is zProc.
  6791. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  6792. ** entry point name on its own. It first tries "sqlite3_extension_init".
  6793. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  6794. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  6795. ** characters in the filename from the last "/" to the first following
  6796. ** "." and omitting any initial "lib".)^
  6797. ** ^The sqlite3_load_extension() interface returns
  6798. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  6799. ** ^If an error occurs and pzErrMsg is not 0, then the
  6800. ** [sqlite3_load_extension()] interface shall attempt to
  6801. ** fill *pzErrMsg with error message text stored in memory
  6802. ** obtained from [sqlite3_malloc()]. The calling function
  6803. ** should free this memory by calling [sqlite3_free()].
  6804. **
  6805. ** ^Extension loading must be enabled using
  6806. ** [sqlite3_enable_load_extension()] or
  6807. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  6808. ** prior to calling this API,
  6809. ** otherwise an error will be returned.
  6810. **
  6811. ** <b>Security warning:</b> It is recommended that the
  6812. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  6813. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  6814. ** should be avoided. This will keep the SQL function [load_extension()]
  6815. ** disabled and prevent SQL injections from giving attackers
  6816. ** access to extension loading capabilities.
  6817. **
  6818. ** See also the [load_extension() SQL function].
  6819. */
  6820. SQLITE_API int sqlite3_load_extension(
  6821. sqlite3 *db, /* Load the extension into this database connection */
  6822. const char *zFile, /* Name of the shared library containing extension */
  6823. const char *zProc, /* Entry point. Derived from zFile if 0 */
  6824. char **pzErrMsg /* Put error message here if not 0 */
  6825. );
  6826. /*
  6827. ** CAPI3REF: Enable Or Disable Extension Loading
  6828. ** METHOD: sqlite3
  6829. **
  6830. ** ^So as not to open security holes in older applications that are
  6831. ** unprepared to deal with [extension loading], and as a means of disabling
  6832. ** [extension loading] while evaluating user-entered SQL, the following API
  6833. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  6834. **
  6835. ** ^Extension loading is off by default.
  6836. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  6837. ** to turn extension loading on and call it with onoff==0 to turn
  6838. ** it back off again.
  6839. **
  6840. ** ^This interface enables or disables both the C-API
  6841. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  6842. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  6843. ** to enable or disable only the C-API.)^
  6844. **
  6845. ** <b>Security warning:</b> It is recommended that extension loading
  6846. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  6847. ** rather than this interface, so the [load_extension()] SQL function
  6848. ** remains disabled. This will prevent SQL injections from giving attackers
  6849. ** access to extension loading capabilities.
  6850. */
  6851. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  6852. /*
  6853. ** CAPI3REF: Automatically Load Statically Linked Extensions
  6854. **
  6855. ** ^This interface causes the xEntryPoint() function to be invoked for
  6856. ** each new [database connection] that is created. The idea here is that
  6857. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  6858. ** that is to be automatically loaded into all new database connections.
  6859. **
  6860. ** ^(Even though the function prototype shows that xEntryPoint() takes
  6861. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  6862. ** arguments and expects an integer result as if the signature of the
  6863. ** entry point where as follows:
  6864. **
  6865. ** <blockquote><pre>
  6866. ** &nbsp; int xEntryPoint(
  6867. ** &nbsp; sqlite3 *db,
  6868. ** &nbsp; const char **pzErrMsg,
  6869. ** &nbsp; const struct sqlite3_api_routines *pThunk
  6870. ** &nbsp; );
  6871. ** </pre></blockquote>)^
  6872. **
  6873. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  6874. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  6875. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  6876. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  6877. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  6878. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  6879. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  6880. **
  6881. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  6882. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  6883. ** will be called more than once for each database connection that is opened.
  6884. **
  6885. ** See also: [sqlite3_reset_auto_extension()]
  6886. ** and [sqlite3_cancel_auto_extension()]
  6887. */
  6888. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  6889. /*
  6890. ** CAPI3REF: Cancel Automatic Extension Loading
  6891. **
  6892. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  6893. ** initialization routine X that was registered using a prior call to
  6894. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  6895. ** routine returns 1 if initialization routine X was successfully
  6896. ** unregistered and it returns 0 if X was not on the list of initialization
  6897. ** routines.
  6898. */
  6899. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  6900. /*
  6901. ** CAPI3REF: Reset Automatic Extension Loading
  6902. **
  6903. ** ^This interface disables all automatic extensions previously
  6904. ** registered using [sqlite3_auto_extension()].
  6905. */
  6906. SQLITE_API void sqlite3_reset_auto_extension(void);
  6907. /*
  6908. ** The interface to the virtual-table mechanism is currently considered
  6909. ** to be experimental. The interface might change in incompatible ways.
  6910. ** If this is a problem for you, do not use the interface at this time.
  6911. **
  6912. ** When the virtual-table mechanism stabilizes, we will declare the
  6913. ** interface fixed, support it indefinitely, and remove this comment.
  6914. */
  6915. /*
  6916. ** Structures used by the virtual table interface
  6917. */
  6918. typedef struct sqlite3_vtab sqlite3_vtab;
  6919. typedef struct sqlite3_index_info sqlite3_index_info;
  6920. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  6921. typedef struct sqlite3_module sqlite3_module;
  6922. /*
  6923. ** CAPI3REF: Virtual Table Object
  6924. ** KEYWORDS: sqlite3_module {virtual table module}
  6925. **
  6926. ** This structure, sometimes called a "virtual table module",
  6927. ** defines the implementation of a [virtual tables].
  6928. ** This structure consists mostly of methods for the module.
  6929. **
  6930. ** ^A virtual table module is created by filling in a persistent
  6931. ** instance of this structure and passing a pointer to that instance
  6932. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  6933. ** ^The registration remains valid until it is replaced by a different
  6934. ** module or until the [database connection] closes. The content
  6935. ** of this structure must not change while it is registered with
  6936. ** any database connection.
  6937. */
  6938. struct sqlite3_module {
  6939. int iVersion;
  6940. int (*xCreate)(sqlite3*, void *pAux,
  6941. int argc, const char *const*argv,
  6942. sqlite3_vtab **ppVTab, char**);
  6943. int (*xConnect)(sqlite3*, void *pAux,
  6944. int argc, const char *const*argv,
  6945. sqlite3_vtab **ppVTab, char**);
  6946. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  6947. int (*xDisconnect)(sqlite3_vtab *pVTab);
  6948. int (*xDestroy)(sqlite3_vtab *pVTab);
  6949. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  6950. int (*xClose)(sqlite3_vtab_cursor*);
  6951. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  6952. int argc, sqlite3_value **argv);
  6953. int (*xNext)(sqlite3_vtab_cursor*);
  6954. int (*xEof)(sqlite3_vtab_cursor*);
  6955. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  6956. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  6957. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  6958. int (*xBegin)(sqlite3_vtab *pVTab);
  6959. int (*xSync)(sqlite3_vtab *pVTab);
  6960. int (*xCommit)(sqlite3_vtab *pVTab);
  6961. int (*xRollback)(sqlite3_vtab *pVTab);
  6962. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  6963. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  6964. void **ppArg);
  6965. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  6966. /* The methods above are in version 1 of the sqlite_module object. Those
  6967. ** below are for version 2 and greater. */
  6968. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  6969. int (*xRelease)(sqlite3_vtab *pVTab, int);
  6970. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  6971. };
  6972. /*
  6973. ** CAPI3REF: Virtual Table Indexing Information
  6974. ** KEYWORDS: sqlite3_index_info
  6975. **
  6976. ** The sqlite3_index_info structure and its substructures is used as part
  6977. ** of the [virtual table] interface to
  6978. ** pass information into and receive the reply from the [xBestIndex]
  6979. ** method of a [virtual table module]. The fields under **Inputs** are the
  6980. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  6981. ** results into the **Outputs** fields.
  6982. **
  6983. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  6984. **
  6985. ** <blockquote>column OP expr</blockquote>
  6986. **
  6987. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  6988. ** stored in aConstraint[].op using one of the
  6989. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  6990. ** ^(The index of the column is stored in
  6991. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  6992. ** expr on the right-hand side can be evaluated (and thus the constraint
  6993. ** is usable) and false if it cannot.)^
  6994. **
  6995. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  6996. ** and makes other simplifications to the WHERE clause in an attempt to
  6997. ** get as many WHERE clause terms into the form shown above as possible.
  6998. ** ^The aConstraint[] array only reports WHERE clause terms that are
  6999. ** relevant to the particular virtual table being queried.
  7000. **
  7001. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7002. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7003. **
  7004. ** The colUsed field indicates which columns of the virtual table may be
  7005. ** required by the current scan. Virtual table columns are numbered from
  7006. ** zero in the order in which they appear within the CREATE TABLE statement
  7007. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7008. ** the corresponding bit is set within the colUsed mask if the column may be
  7009. ** required by SQLite. If the table has at least 64 columns and any column
  7010. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7011. ** set. In other words, column iCol may be required if the expression
  7012. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7013. ** non-zero.
  7014. **
  7015. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7016. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7017. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7018. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7019. ** is true, then the constraint is assumed to be fully handled by the
  7020. ** virtual table and is not checked again by SQLite.)^
  7021. **
  7022. ** ^The idxNum and idxPtr values are recorded and passed into the
  7023. ** [xFilter] method.
  7024. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7025. ** needToFreeIdxPtr is true.
  7026. **
  7027. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7028. ** the correct order to satisfy the ORDER BY clause so that no separate
  7029. ** sorting step is required.
  7030. **
  7031. ** ^The estimatedCost value is an estimate of the cost of a particular
  7032. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7033. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7034. ** indicates that the expense of the operation is similar to that of a
  7035. ** binary search on a unique indexed field of an SQLite table with N rows.
  7036. **
  7037. ** ^The estimatedRows value is an estimate of the number of rows that
  7038. ** will be returned by the strategy.
  7039. **
  7040. ** The xBestIndex method may optionally populate the idxFlags field with a
  7041. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7042. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7043. ** assumes that the strategy may visit at most one row.
  7044. **
  7045. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7046. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7047. ** part of the same statement to delete or update a virtual table row and the
  7048. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7049. ** any database changes. In other words, if the xUpdate() returns
  7050. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7051. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7052. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7053. ** the xUpdate method are automatically rolled back by SQLite.
  7054. **
  7055. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7056. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7057. ** If a virtual table extension is
  7058. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7059. ** to read or write the estimatedRows field are undefined (but are likely
  7060. ** to included crashing the application). The estimatedRows field should
  7061. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7062. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7063. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7064. ** It may therefore only be used if
  7065. ** sqlite3_libversion_number() returns a value greater than or equal to
  7066. ** 3009000.
  7067. */
  7068. struct sqlite3_index_info {
  7069. /* Inputs */
  7070. int nConstraint; /* Number of entries in aConstraint */
  7071. struct sqlite3_index_constraint {
  7072. int iColumn; /* Column constrained. -1 for ROWID */
  7073. unsigned char op; /* Constraint operator */
  7074. unsigned char usable; /* True if this constraint is usable */
  7075. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7076. } *aConstraint; /* Table of WHERE clause constraints */
  7077. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7078. struct sqlite3_index_orderby {
  7079. int iColumn; /* Column number */
  7080. unsigned char desc; /* True for DESC. False for ASC. */
  7081. } *aOrderBy; /* The ORDER BY clause */
  7082. /* Outputs */
  7083. struct sqlite3_index_constraint_usage {
  7084. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7085. unsigned char omit; /* Do not code a test for this constraint */
  7086. } *aConstraintUsage;
  7087. int idxNum; /* Number used to identify the index */
  7088. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7089. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7090. int orderByConsumed; /* True if output is already ordered */
  7091. double estimatedCost; /* Estimated cost of using this index */
  7092. /* Fields below are only available in SQLite 3.8.2 and later */
  7093. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7094. /* Fields below are only available in SQLite 3.9.0 and later */
  7095. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7096. /* Fields below are only available in SQLite 3.10.0 and later */
  7097. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7098. };
  7099. /*
  7100. ** CAPI3REF: Virtual Table Scan Flags
  7101. */
  7102. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7103. /*
  7104. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7105. **
  7106. ** These macros defined the allowed values for the
  7107. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7108. ** an operator that is part of a constraint term in the wHERE clause of
  7109. ** a query that uses a [virtual table].
  7110. */
  7111. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7112. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7113. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7114. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7115. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7116. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7117. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7118. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7119. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7120. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7121. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7122. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7123. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7124. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7125. /*
  7126. ** CAPI3REF: Register A Virtual Table Implementation
  7127. ** METHOD: sqlite3
  7128. **
  7129. ** ^These routines are used to register a new [virtual table module] name.
  7130. ** ^Module names must be registered before
  7131. ** creating a new [virtual table] using the module and before using a
  7132. ** preexisting [virtual table] for the module.
  7133. **
  7134. ** ^The module name is registered on the [database connection] specified
  7135. ** by the first parameter. ^The name of the module is given by the
  7136. ** second parameter. ^The third parameter is a pointer to
  7137. ** the implementation of the [virtual table module]. ^The fourth
  7138. ** parameter is an arbitrary client data pointer that is passed through
  7139. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7140. ** when a new virtual table is be being created or reinitialized.
  7141. **
  7142. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7143. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7144. ** invoke the destructor function (if it is not NULL) when SQLite
  7145. ** no longer needs the pClientData pointer. ^The destructor will also
  7146. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7147. ** ^The sqlite3_create_module()
  7148. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7149. ** destructor.
  7150. */
  7151. SQLITE_API int sqlite3_create_module(
  7152. sqlite3 *db, /* SQLite connection to register module with */
  7153. const char *zName, /* Name of the module */
  7154. const sqlite3_module *p, /* Methods for the module */
  7155. void *pClientData /* Client data for xCreate/xConnect */
  7156. );
  7157. SQLITE_API int sqlite3_create_module_v2(
  7158. sqlite3 *db, /* SQLite connection to register module with */
  7159. const char *zName, /* Name of the module */
  7160. const sqlite3_module *p, /* Methods for the module */
  7161. void *pClientData, /* Client data for xCreate/xConnect */
  7162. void(*xDestroy)(void*) /* Module destructor function */
  7163. );
  7164. /*
  7165. ** CAPI3REF: Virtual Table Instance Object
  7166. ** KEYWORDS: sqlite3_vtab
  7167. **
  7168. ** Every [virtual table module] implementation uses a subclass
  7169. ** of this object to describe a particular instance
  7170. ** of the [virtual table]. Each subclass will
  7171. ** be tailored to the specific needs of the module implementation.
  7172. ** The purpose of this superclass is to define certain fields that are
  7173. ** common to all module implementations.
  7174. **
  7175. ** ^Virtual tables methods can set an error message by assigning a
  7176. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7177. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7178. ** prior to assigning a new string to zErrMsg. ^After the error message
  7179. ** is delivered up to the client application, the string will be automatically
  7180. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7181. */
  7182. struct sqlite3_vtab {
  7183. const sqlite3_module *pModule; /* The module for this virtual table */
  7184. int nRef; /* Number of open cursors */
  7185. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7186. /* Virtual table implementations will typically add additional fields */
  7187. };
  7188. /*
  7189. ** CAPI3REF: Virtual Table Cursor Object
  7190. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7191. **
  7192. ** Every [virtual table module] implementation uses a subclass of the
  7193. ** following structure to describe cursors that point into the
  7194. ** [virtual table] and are used
  7195. ** to loop through the virtual table. Cursors are created using the
  7196. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7197. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7198. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7199. ** of the module. Each module implementation will define
  7200. ** the content of a cursor structure to suit its own needs.
  7201. **
  7202. ** This superclass exists in order to define fields of the cursor that
  7203. ** are common to all implementations.
  7204. */
  7205. struct sqlite3_vtab_cursor {
  7206. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7207. /* Virtual table implementations will typically add additional fields */
  7208. };
  7209. /*
  7210. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7211. **
  7212. ** ^The [xCreate] and [xConnect] methods of a
  7213. ** [virtual table module] call this interface
  7214. ** to declare the format (the names and datatypes of the columns) of
  7215. ** the virtual tables they implement.
  7216. */
  7217. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7218. /*
  7219. ** CAPI3REF: Overload A Function For A Virtual Table
  7220. ** METHOD: sqlite3
  7221. **
  7222. ** ^(Virtual tables can provide alternative implementations of functions
  7223. ** using the [xFindFunction] method of the [virtual table module].
  7224. ** But global versions of those functions
  7225. ** must exist in order to be overloaded.)^
  7226. **
  7227. ** ^(This API makes sure a global version of a function with a particular
  7228. ** name and number of parameters exists. If no such function exists
  7229. ** before this API is called, a new function is created.)^ ^The implementation
  7230. ** of the new function always causes an exception to be thrown. So
  7231. ** the new function is not good for anything by itself. Its only
  7232. ** purpose is to be a placeholder function that can be overloaded
  7233. ** by a [virtual table].
  7234. */
  7235. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7236. /*
  7237. ** The interface to the virtual-table mechanism defined above (back up
  7238. ** to a comment remarkably similar to this one) is currently considered
  7239. ** to be experimental. The interface might change in incompatible ways.
  7240. ** If this is a problem for you, do not use the interface at this time.
  7241. **
  7242. ** When the virtual-table mechanism stabilizes, we will declare the
  7243. ** interface fixed, support it indefinitely, and remove this comment.
  7244. */
  7245. /*
  7246. ** CAPI3REF: A Handle To An Open BLOB
  7247. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7248. **
  7249. ** An instance of this object represents an open BLOB on which
  7250. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7251. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7252. ** and destroyed by [sqlite3_blob_close()].
  7253. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7254. ** can be used to read or write small subsections of the BLOB.
  7255. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7256. */
  7257. typedef struct sqlite3_blob sqlite3_blob;
  7258. /*
  7259. ** CAPI3REF: Open A BLOB For Incremental I/O
  7260. ** METHOD: sqlite3
  7261. ** CONSTRUCTOR: sqlite3_blob
  7262. **
  7263. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7264. ** in row iRow, column zColumn, table zTable in database zDb;
  7265. ** in other words, the same BLOB that would be selected by:
  7266. **
  7267. ** <pre>
  7268. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7269. ** </pre>)^
  7270. **
  7271. ** ^(Parameter zDb is not the filename that contains the database, but
  7272. ** rather the symbolic name of the database. For attached databases, this is
  7273. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7274. ** For the main database file, the database name is "main". For TEMP
  7275. ** tables, the database name is "temp".)^
  7276. **
  7277. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7278. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7279. ** read-only access.
  7280. **
  7281. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7282. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7283. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7284. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7285. ** on *ppBlob after this function it returns.
  7286. **
  7287. ** This function fails with SQLITE_ERROR if any of the following are true:
  7288. ** <ul>
  7289. ** <li> ^(Database zDb does not exist)^,
  7290. ** <li> ^(Table zTable does not exist within database zDb)^,
  7291. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7292. ** <li> ^(Column zColumn does not exist)^,
  7293. ** <li> ^(Row iRow is not present in the table)^,
  7294. ** <li> ^(The specified column of row iRow contains a value that is not
  7295. ** a TEXT or BLOB value)^,
  7296. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7297. ** constraint and the blob is being opened for read/write access)^,
  7298. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7299. ** column zColumn is part of a [child key] definition and the blob is
  7300. ** being opened for read/write access)^.
  7301. ** </ul>
  7302. **
  7303. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7304. ** [database connection] error code and message accessible via
  7305. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7306. **
  7307. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7308. ** [sqlite3_blob_read()] interface and modified by using
  7309. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7310. ** different row of the same table using the [sqlite3_blob_reopen()]
  7311. ** interface. However, the column, table, or database of a [BLOB handle]
  7312. ** cannot be changed after the [BLOB handle] is opened.
  7313. **
  7314. ** ^(If the row that a BLOB handle points to is modified by an
  7315. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7316. ** then the BLOB handle is marked as "expired".
  7317. ** This is true if any column of the row is changed, even a column
  7318. ** other than the one the BLOB handle is open on.)^
  7319. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7320. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7321. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7322. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7323. ** commit if the transaction continues to completion.)^
  7324. **
  7325. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7326. ** the opened blob. ^The size of a blob may not be changed by this
  7327. ** interface. Use the [UPDATE] SQL command to change the size of a
  7328. ** blob.
  7329. **
  7330. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7331. ** and the built-in [zeroblob] SQL function may be used to create a
  7332. ** zero-filled blob to read or write using the incremental-blob interface.
  7333. **
  7334. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7335. ** be released by a call to [sqlite3_blob_close()].
  7336. **
  7337. ** See also: [sqlite3_blob_close()],
  7338. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7339. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7340. */
  7341. SQLITE_API int sqlite3_blob_open(
  7342. sqlite3*,
  7343. const char *zDb,
  7344. const char *zTable,
  7345. const char *zColumn,
  7346. sqlite3_int64 iRow,
  7347. int flags,
  7348. sqlite3_blob **ppBlob
  7349. );
  7350. /*
  7351. ** CAPI3REF: Move a BLOB Handle to a New Row
  7352. ** METHOD: sqlite3_blob
  7353. **
  7354. ** ^This function is used to move an existing [BLOB handle] so that it points
  7355. ** to a different row of the same database table. ^The new row is identified
  7356. ** by the rowid value passed as the second argument. Only the row can be
  7357. ** changed. ^The database, table and column on which the blob handle is open
  7358. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7359. ** faster than closing the existing handle and opening a new one.
  7360. **
  7361. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7362. ** it must exist and there must be either a blob or text value stored in
  7363. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7364. ** it does not contain a blob or text value, or if another error occurs, an
  7365. ** SQLite error code is returned and the blob handle is considered aborted.
  7366. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7367. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7368. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7369. ** always returns zero.
  7370. **
  7371. ** ^This function sets the database handle error code and message.
  7372. */
  7373. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7374. /*
  7375. ** CAPI3REF: Close A BLOB Handle
  7376. ** DESTRUCTOR: sqlite3_blob
  7377. **
  7378. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7379. ** unconditionally. Even if this routine returns an error code, the
  7380. ** handle is still closed.)^
  7381. **
  7382. ** ^If the blob handle being closed was opened for read-write access, and if
  7383. ** the database is in auto-commit mode and there are no other open read-write
  7384. ** blob handles or active write statements, the current transaction is
  7385. ** committed. ^If an error occurs while committing the transaction, an error
  7386. ** code is returned and the transaction rolled back.
  7387. **
  7388. ** Calling this function with an argument that is not a NULL pointer or an
  7389. ** open blob handle results in undefined behaviour. ^Calling this routine
  7390. ** with a null pointer (such as would be returned by a failed call to
  7391. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7392. ** is passed a valid open blob handle, the values returned by the
  7393. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7394. */
  7395. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7396. /*
  7397. ** CAPI3REF: Return The Size Of An Open BLOB
  7398. ** METHOD: sqlite3_blob
  7399. **
  7400. ** ^Returns the size in bytes of the BLOB accessible via the
  7401. ** successfully opened [BLOB handle] in its only argument. ^The
  7402. ** incremental blob I/O routines can only read or overwriting existing
  7403. ** blob content; they cannot change the size of a blob.
  7404. **
  7405. ** This routine only works on a [BLOB handle] which has been created
  7406. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7407. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7408. ** to this routine results in undefined and probably undesirable behavior.
  7409. */
  7410. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7411. /*
  7412. ** CAPI3REF: Read Data From A BLOB Incrementally
  7413. ** METHOD: sqlite3_blob
  7414. **
  7415. ** ^(This function is used to read data from an open [BLOB handle] into a
  7416. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7417. ** from the open BLOB, starting at offset iOffset.)^
  7418. **
  7419. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7420. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7421. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7422. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7423. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7424. **
  7425. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7426. ** error code of [SQLITE_ABORT].
  7427. **
  7428. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7429. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7430. **
  7431. ** This routine only works on a [BLOB handle] which has been created
  7432. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7433. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7434. ** to this routine results in undefined and probably undesirable behavior.
  7435. **
  7436. ** See also: [sqlite3_blob_write()].
  7437. */
  7438. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7439. /*
  7440. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7441. ** METHOD: sqlite3_blob
  7442. **
  7443. ** ^(This function is used to write data into an open [BLOB handle] from a
  7444. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7445. ** into the open BLOB, starting at offset iOffset.)^
  7446. **
  7447. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7448. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7449. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7450. ** [database connection] error code and message accessible via
  7451. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7452. **
  7453. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7454. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7455. ** this function returns [SQLITE_READONLY].
  7456. **
  7457. ** This function may only modify the contents of the BLOB; it is
  7458. ** not possible to increase the size of a BLOB using this API.
  7459. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7460. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7461. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7462. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7463. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7464. **
  7465. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7466. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7467. ** before the [BLOB handle] expired are not rolled back by the
  7468. ** expiration of the handle, though of course those changes might
  7469. ** have been overwritten by the statement that expired the BLOB handle
  7470. ** or by other independent statements.
  7471. **
  7472. ** This routine only works on a [BLOB handle] which has been created
  7473. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7474. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7475. ** to this routine results in undefined and probably undesirable behavior.
  7476. **
  7477. ** See also: [sqlite3_blob_read()].
  7478. */
  7479. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7480. /*
  7481. ** CAPI3REF: Virtual File System Objects
  7482. **
  7483. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7484. ** that SQLite uses to interact
  7485. ** with the underlying operating system. Most SQLite builds come with a
  7486. ** single default VFS that is appropriate for the host computer.
  7487. ** New VFSes can be registered and existing VFSes can be unregistered.
  7488. ** The following interfaces are provided.
  7489. **
  7490. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7491. ** ^Names are case sensitive.
  7492. ** ^Names are zero-terminated UTF-8 strings.
  7493. ** ^If there is no match, a NULL pointer is returned.
  7494. ** ^If zVfsName is NULL then the default VFS is returned.
  7495. **
  7496. ** ^New VFSes are registered with sqlite3_vfs_register().
  7497. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7498. ** ^The same VFS can be registered multiple times without injury.
  7499. ** ^To make an existing VFS into the default VFS, register it again
  7500. ** with the makeDflt flag set. If two different VFSes with the
  7501. ** same name are registered, the behavior is undefined. If a
  7502. ** VFS is registered with a name that is NULL or an empty string,
  7503. ** then the behavior is undefined.
  7504. **
  7505. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7506. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7507. ** the default. The choice for the new VFS is arbitrary.)^
  7508. */
  7509. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7510. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7511. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7512. /*
  7513. ** CAPI3REF: Mutexes
  7514. **
  7515. ** The SQLite core uses these routines for thread
  7516. ** synchronization. Though they are intended for internal
  7517. ** use by SQLite, code that links against SQLite is
  7518. ** permitted to use any of these routines.
  7519. **
  7520. ** The SQLite source code contains multiple implementations
  7521. ** of these mutex routines. An appropriate implementation
  7522. ** is selected automatically at compile-time. The following
  7523. ** implementations are available in the SQLite core:
  7524. **
  7525. ** <ul>
  7526. ** <li> SQLITE_MUTEX_PTHREADS
  7527. ** <li> SQLITE_MUTEX_W32
  7528. ** <li> SQLITE_MUTEX_NOOP
  7529. ** </ul>
  7530. **
  7531. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7532. ** that does no real locking and is appropriate for use in
  7533. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7534. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7535. ** and Windows.
  7536. **
  7537. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7538. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7539. ** implementation is included with the library. In this case the
  7540. ** application must supply a custom mutex implementation using the
  7541. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7542. ** before calling sqlite3_initialize() or any other public sqlite3_
  7543. ** function that calls sqlite3_initialize().
  7544. **
  7545. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7546. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7547. ** routine returns NULL if it is unable to allocate the requested
  7548. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7549. ** integer constants:
  7550. **
  7551. ** <ul>
  7552. ** <li> SQLITE_MUTEX_FAST
  7553. ** <li> SQLITE_MUTEX_RECURSIVE
  7554. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7555. ** <li> SQLITE_MUTEX_STATIC_MEM
  7556. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7557. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7558. ** <li> SQLITE_MUTEX_STATIC_LRU
  7559. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7560. ** <li> SQLITE_MUTEX_STATIC_APP1
  7561. ** <li> SQLITE_MUTEX_STATIC_APP2
  7562. ** <li> SQLITE_MUTEX_STATIC_APP3
  7563. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7564. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7565. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7566. ** </ul>
  7567. **
  7568. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7569. ** cause sqlite3_mutex_alloc() to create
  7570. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7571. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7572. ** The mutex implementation does not need to make a distinction
  7573. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7574. ** not want to. SQLite will only request a recursive mutex in
  7575. ** cases where it really needs one. If a faster non-recursive mutex
  7576. ** implementation is available on the host platform, the mutex subsystem
  7577. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7578. **
  7579. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7580. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7581. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7582. ** used by the current version of SQLite. Future versions of SQLite
  7583. ** may add additional static mutexes. Static mutexes are for internal
  7584. ** use by SQLite only. Applications that use SQLite mutexes should
  7585. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7586. ** SQLITE_MUTEX_RECURSIVE.
  7587. **
  7588. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7589. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7590. ** returns a different mutex on every call. ^For the static
  7591. ** mutex types, the same mutex is returned on every call that has
  7592. ** the same type number.
  7593. **
  7594. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7595. ** allocated dynamic mutex. Attempting to deallocate a static
  7596. ** mutex results in undefined behavior.
  7597. **
  7598. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7599. ** to enter a mutex. ^If another thread is already within the mutex,
  7600. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7601. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7602. ** upon successful entry. ^(Mutexes created using
  7603. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7604. ** In such cases, the
  7605. ** mutex must be exited an equal number of times before another thread
  7606. ** can enter.)^ If the same thread tries to enter any mutex other
  7607. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7608. **
  7609. ** ^(Some systems (for example, Windows 95) do not support the operation
  7610. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7611. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7612. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7613. ** behavior.)^
  7614. **
  7615. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7616. ** previously entered by the same thread. The behavior
  7617. ** is undefined if the mutex is not currently entered by the
  7618. ** calling thread or is not currently allocated.
  7619. **
  7620. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7621. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7622. ** behave as no-ops.
  7623. **
  7624. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7625. */
  7626. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7627. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7628. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7629. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7630. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7631. /*
  7632. ** CAPI3REF: Mutex Methods Object
  7633. **
  7634. ** An instance of this structure defines the low-level routines
  7635. ** used to allocate and use mutexes.
  7636. **
  7637. ** Usually, the default mutex implementations provided by SQLite are
  7638. ** sufficient, however the application has the option of substituting a custom
  7639. ** implementation for specialized deployments or systems for which SQLite
  7640. ** does not provide a suitable implementation. In this case, the application
  7641. ** creates and populates an instance of this structure to pass
  7642. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7643. ** Additionally, an instance of this structure can be used as an
  7644. ** output variable when querying the system for the current mutex
  7645. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7646. **
  7647. ** ^The xMutexInit method defined by this structure is invoked as
  7648. ** part of system initialization by the sqlite3_initialize() function.
  7649. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7650. ** effective call to [sqlite3_initialize()].
  7651. **
  7652. ** ^The xMutexEnd method defined by this structure is invoked as
  7653. ** part of system shutdown by the sqlite3_shutdown() function. The
  7654. ** implementation of this method is expected to release all outstanding
  7655. ** resources obtained by the mutex methods implementation, especially
  7656. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7657. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7658. **
  7659. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7660. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7661. ** xMutexNotheld) implement the following interfaces (respectively):
  7662. **
  7663. ** <ul>
  7664. ** <li> [sqlite3_mutex_alloc()] </li>
  7665. ** <li> [sqlite3_mutex_free()] </li>
  7666. ** <li> [sqlite3_mutex_enter()] </li>
  7667. ** <li> [sqlite3_mutex_try()] </li>
  7668. ** <li> [sqlite3_mutex_leave()] </li>
  7669. ** <li> [sqlite3_mutex_held()] </li>
  7670. ** <li> [sqlite3_mutex_notheld()] </li>
  7671. ** </ul>)^
  7672. **
  7673. ** The only difference is that the public sqlite3_XXX functions enumerated
  7674. ** above silently ignore any invocations that pass a NULL pointer instead
  7675. ** of a valid mutex handle. The implementations of the methods defined
  7676. ** by this structure are not required to handle this case, the results
  7677. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7678. ** (i.e. it is acceptable to provide an implementation that segfaults if
  7679. ** it is passed a NULL pointer).
  7680. **
  7681. ** The xMutexInit() method must be threadsafe. It must be harmless to
  7682. ** invoke xMutexInit() multiple times within the same process and without
  7683. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  7684. ** xMutexInit() must be no-ops.
  7685. **
  7686. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7687. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  7688. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  7689. ** memory allocation for a fast or recursive mutex.
  7690. **
  7691. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7692. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7693. ** If xMutexInit fails in any way, it is expected to clean up after itself
  7694. ** prior to returning.
  7695. */
  7696. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7697. struct sqlite3_mutex_methods {
  7698. int (*xMutexInit)(void);
  7699. int (*xMutexEnd)(void);
  7700. sqlite3_mutex *(*xMutexAlloc)(int);
  7701. void (*xMutexFree)(sqlite3_mutex *);
  7702. void (*xMutexEnter)(sqlite3_mutex *);
  7703. int (*xMutexTry)(sqlite3_mutex *);
  7704. void (*xMutexLeave)(sqlite3_mutex *);
  7705. int (*xMutexHeld)(sqlite3_mutex *);
  7706. int (*xMutexNotheld)(sqlite3_mutex *);
  7707. };
  7708. /*
  7709. ** CAPI3REF: Mutex Verification Routines
  7710. **
  7711. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  7712. ** are intended for use inside assert() statements. The SQLite core
  7713. ** never uses these routines except inside an assert() and applications
  7714. ** are advised to follow the lead of the core. The SQLite core only
  7715. ** provides implementations for these routines when it is compiled
  7716. ** with the SQLITE_DEBUG flag. External mutex implementations
  7717. ** are only required to provide these routines if SQLITE_DEBUG is
  7718. ** defined and if NDEBUG is not defined.
  7719. **
  7720. ** These routines should return true if the mutex in their argument
  7721. ** is held or not held, respectively, by the calling thread.
  7722. **
  7723. ** The implementation is not required to provide versions of these
  7724. ** routines that actually work. If the implementation does not provide working
  7725. ** versions of these routines, it should at least provide stubs that always
  7726. ** return true so that one does not get spurious assertion failures.
  7727. **
  7728. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  7729. ** the routine should return 1. This seems counter-intuitive since
  7730. ** clearly the mutex cannot be held if it does not exist. But
  7731. ** the reason the mutex does not exist is because the build is not
  7732. ** using mutexes. And we do not want the assert() containing the
  7733. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  7734. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  7735. ** interface should also return 1 when given a NULL pointer.
  7736. */
  7737. #ifndef NDEBUG
  7738. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  7739. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  7740. #endif
  7741. /*
  7742. ** CAPI3REF: Mutex Types
  7743. **
  7744. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  7745. ** which is one of these integer constants.
  7746. **
  7747. ** The set of static mutexes may change from one SQLite release to the
  7748. ** next. Applications that override the built-in mutex logic must be
  7749. ** prepared to accommodate additional static mutexes.
  7750. */
  7751. #define SQLITE_MUTEX_FAST 0
  7752. #define SQLITE_MUTEX_RECURSIVE 1
  7753. #define SQLITE_MUTEX_STATIC_MASTER 2
  7754. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  7755. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  7756. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  7757. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  7758. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  7759. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  7760. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  7761. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  7762. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  7763. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  7764. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  7765. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  7766. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  7767. /*
  7768. ** CAPI3REF: Retrieve the mutex for a database connection
  7769. ** METHOD: sqlite3
  7770. **
  7771. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  7772. ** serializes access to the [database connection] given in the argument
  7773. ** when the [threading mode] is Serialized.
  7774. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  7775. ** routine returns a NULL pointer.
  7776. */
  7777. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  7778. /*
  7779. ** CAPI3REF: Low-Level Control Of Database Files
  7780. ** METHOD: sqlite3
  7781. **
  7782. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  7783. ** xFileControl method for the [sqlite3_io_methods] object associated
  7784. ** with a particular database identified by the second argument. ^The
  7785. ** name of the database is "main" for the main database or "temp" for the
  7786. ** TEMP database, or the name that appears after the AS keyword for
  7787. ** databases that are added using the [ATTACH] SQL command.
  7788. ** ^A NULL pointer can be used in place of "main" to refer to the
  7789. ** main database file.
  7790. ** ^The third and fourth parameters to this routine
  7791. ** are passed directly through to the second and third parameters of
  7792. ** the xFileControl method. ^The return value of the xFileControl
  7793. ** method becomes the return value of this routine.
  7794. **
  7795. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  7796. ** a pointer to the underlying [sqlite3_file] object to be written into
  7797. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  7798. ** case is a short-circuit path which does not actually invoke the
  7799. ** underlying sqlite3_io_methods.xFileControl method.
  7800. **
  7801. ** ^If the second parameter (zDbName) does not match the name of any
  7802. ** open database file, then SQLITE_ERROR is returned. ^This error
  7803. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  7804. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  7805. ** also return SQLITE_ERROR. There is no way to distinguish between
  7806. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  7807. ** xFileControl method.
  7808. **
  7809. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  7810. */
  7811. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  7812. /*
  7813. ** CAPI3REF: Testing Interface
  7814. **
  7815. ** ^The sqlite3_test_control() interface is used to read out internal
  7816. ** state of SQLite and to inject faults into SQLite for testing
  7817. ** purposes. ^The first parameter is an operation code that determines
  7818. ** the number, meaning, and operation of all subsequent parameters.
  7819. **
  7820. ** This interface is not for use by applications. It exists solely
  7821. ** for verifying the correct operation of the SQLite library. Depending
  7822. ** on how the SQLite library is compiled, this interface might not exist.
  7823. **
  7824. ** The details of the operation codes, their meanings, the parameters
  7825. ** they take, and what they do are all subject to change without notice.
  7826. ** Unlike most of the SQLite API, this function is not guaranteed to
  7827. ** operate consistently from one release to the next.
  7828. */
  7829. SQLITE_API int sqlite3_test_control(int op, ...);
  7830. /*
  7831. ** CAPI3REF: Testing Interface Operation Codes
  7832. **
  7833. ** These constants are the valid operation code parameters used
  7834. ** as the first argument to [sqlite3_test_control()].
  7835. **
  7836. ** These parameters and their meanings are subject to change
  7837. ** without notice. These values are for testing purposes only.
  7838. ** Applications should not use any of these parameters or the
  7839. ** [sqlite3_test_control()] interface.
  7840. */
  7841. #define SQLITE_TESTCTRL_FIRST 5
  7842. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  7843. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  7844. #define SQLITE_TESTCTRL_PRNG_RESET 7
  7845. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  7846. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  7847. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  7848. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  7849. #define SQLITE_TESTCTRL_ASSERT 12
  7850. #define SQLITE_TESTCTRL_ALWAYS 13
  7851. #define SQLITE_TESTCTRL_RESERVE 14
  7852. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  7853. #define SQLITE_TESTCTRL_ISKEYWORD 16
  7854. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  7855. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  7856. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  7857. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  7858. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  7859. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  7860. #define SQLITE_TESTCTRL_BYTEORDER 22
  7861. #define SQLITE_TESTCTRL_ISINIT 23
  7862. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  7863. #define SQLITE_TESTCTRL_IMPOSTER 25
  7864. #define SQLITE_TESTCTRL_LAST 25
  7865. /*
  7866. ** CAPI3REF: SQLite Runtime Status
  7867. **
  7868. ** ^These interfaces are used to retrieve runtime status information
  7869. ** about the performance of SQLite, and optionally to reset various
  7870. ** highwater marks. ^The first argument is an integer code for
  7871. ** the specific parameter to measure. ^(Recognized integer codes
  7872. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  7873. ** ^The current value of the parameter is returned into *pCurrent.
  7874. ** ^The highest recorded value is returned in *pHighwater. ^If the
  7875. ** resetFlag is true, then the highest record value is reset after
  7876. ** *pHighwater is written. ^(Some parameters do not record the highest
  7877. ** value. For those parameters
  7878. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  7879. ** ^(Other parameters record only the highwater mark and not the current
  7880. ** value. For these latter parameters nothing is written into *pCurrent.)^
  7881. **
  7882. ** ^The sqlite3_status() and sqlite3_status64() routines return
  7883. ** SQLITE_OK on success and a non-zero [error code] on failure.
  7884. **
  7885. ** If either the current value or the highwater mark is too large to
  7886. ** be represented by a 32-bit integer, then the values returned by
  7887. ** sqlite3_status() are undefined.
  7888. **
  7889. ** See also: [sqlite3_db_status()]
  7890. */
  7891. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  7892. SQLITE_API int sqlite3_status64(
  7893. int op,
  7894. sqlite3_int64 *pCurrent,
  7895. sqlite3_int64 *pHighwater,
  7896. int resetFlag
  7897. );
  7898. /*
  7899. ** CAPI3REF: Status Parameters
  7900. ** KEYWORDS: {status parameters}
  7901. **
  7902. ** These integer constants designate various run-time status parameters
  7903. ** that can be returned by [sqlite3_status()].
  7904. **
  7905. ** <dl>
  7906. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  7907. ** <dd>This parameter is the current amount of memory checked out
  7908. ** using [sqlite3_malloc()], either directly or indirectly. The
  7909. ** figure includes calls made to [sqlite3_malloc()] by the application
  7910. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  7911. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  7912. ** this parameter. The amount returned is the sum of the allocation
  7913. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  7914. **
  7915. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  7916. ** <dd>This parameter records the largest memory allocation request
  7917. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  7918. ** internal equivalents). Only the value returned in the
  7919. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7920. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7921. **
  7922. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  7923. ** <dd>This parameter records the number of separate memory allocations
  7924. ** currently checked out.</dd>)^
  7925. **
  7926. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  7927. ** <dd>This parameter returns the number of pages used out of the
  7928. ** [pagecache memory allocator] that was configured using
  7929. ** [SQLITE_CONFIG_PAGECACHE]. The
  7930. ** value returned is in pages, not in bytes.</dd>)^
  7931. **
  7932. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  7933. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  7934. ** <dd>This parameter returns the number of bytes of page cache
  7935. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  7936. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  7937. ** returned value includes allocations that overflowed because they
  7938. ** where too large (they were larger than the "sz" parameter to
  7939. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  7940. ** no space was left in the page cache.</dd>)^
  7941. **
  7942. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  7943. ** <dd>This parameter records the largest memory allocation request
  7944. ** handed to [pagecache memory allocator]. Only the value returned in the
  7945. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7946. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7947. **
  7948. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  7949. ** <dd>No longer used.</dd>
  7950. **
  7951. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  7952. ** <dd>No longer used.</dd>
  7953. **
  7954. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  7955. ** <dd>No longer used.</dd>
  7956. **
  7957. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  7958. ** <dd>The *pHighwater parameter records the deepest parser stack.
  7959. ** The *pCurrent value is undefined. The *pHighwater value is only
  7960. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  7961. ** </dl>
  7962. **
  7963. ** New status parameters may be added from time to time.
  7964. */
  7965. #define SQLITE_STATUS_MEMORY_USED 0
  7966. #define SQLITE_STATUS_PAGECACHE_USED 1
  7967. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  7968. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  7969. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  7970. #define SQLITE_STATUS_MALLOC_SIZE 5
  7971. #define SQLITE_STATUS_PARSER_STACK 6
  7972. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  7973. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  7974. #define SQLITE_STATUS_MALLOC_COUNT 9
  7975. /*
  7976. ** CAPI3REF: Database Connection Status
  7977. ** METHOD: sqlite3
  7978. **
  7979. ** ^This interface is used to retrieve runtime status information
  7980. ** about a single [database connection]. ^The first argument is the
  7981. ** database connection object to be interrogated. ^The second argument
  7982. ** is an integer constant, taken from the set of
  7983. ** [SQLITE_DBSTATUS options], that
  7984. ** determines the parameter to interrogate. The set of
  7985. ** [SQLITE_DBSTATUS options] is likely
  7986. ** to grow in future releases of SQLite.
  7987. **
  7988. ** ^The current value of the requested parameter is written into *pCur
  7989. ** and the highest instantaneous value is written into *pHiwtr. ^If
  7990. ** the resetFlg is true, then the highest instantaneous value is
  7991. ** reset back down to the current value.
  7992. **
  7993. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  7994. ** non-zero [error code] on failure.
  7995. **
  7996. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  7997. */
  7998. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  7999. /*
  8000. ** CAPI3REF: Status Parameters for database connections
  8001. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8002. **
  8003. ** These constants are the available integer "verbs" that can be passed as
  8004. ** the second argument to the [sqlite3_db_status()] interface.
  8005. **
  8006. ** New verbs may be added in future releases of SQLite. Existing verbs
  8007. ** might be discontinued. Applications should check the return code from
  8008. ** [sqlite3_db_status()] to make sure that the call worked.
  8009. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8010. ** if a discontinued or unsupported verb is invoked.
  8011. **
  8012. ** <dl>
  8013. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8014. ** <dd>This parameter returns the number of lookaside memory slots currently
  8015. ** checked out.</dd>)^
  8016. **
  8017. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8018. ** <dd>This parameter returns the number malloc attempts that were
  8019. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8020. ** the current value is always zero.)^
  8021. **
  8022. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8023. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8024. ** <dd>This parameter returns the number malloc attempts that might have
  8025. ** been satisfied using lookaside memory but failed due to the amount of
  8026. ** memory requested being larger than the lookaside slot size.
  8027. ** Only the high-water value is meaningful;
  8028. ** the current value is always zero.)^
  8029. **
  8030. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8031. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8032. ** <dd>This parameter returns the number malloc attempts that might have
  8033. ** been satisfied using lookaside memory but failed due to all lookaside
  8034. ** memory already being in use.
  8035. ** Only the high-water value is meaningful;
  8036. ** the current value is always zero.)^
  8037. **
  8038. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8039. ** <dd>This parameter returns the approximate number of bytes of heap
  8040. ** memory used by all pager caches associated with the database connection.)^
  8041. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8042. **
  8043. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8044. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8045. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8046. ** pager cache is shared between two or more connections the bytes of heap
  8047. ** memory used by that pager cache is divided evenly between the attached
  8048. ** connections.)^ In other words, if none of the pager caches associated
  8049. ** with the database connection are shared, this request returns the same
  8050. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8051. ** shared, the value returned by this call will be smaller than that returned
  8052. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8053. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8054. **
  8055. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8056. ** <dd>This parameter returns the approximate number of bytes of heap
  8057. ** memory used to store the schema for all databases associated
  8058. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8059. ** ^The full amount of memory used by the schemas is reported, even if the
  8060. ** schema memory is shared with other database connections due to
  8061. ** [shared cache mode] being enabled.
  8062. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8063. **
  8064. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8065. ** <dd>This parameter returns the approximate number of bytes of heap
  8066. ** and lookaside memory used by all prepared statements associated with
  8067. ** the database connection.)^
  8068. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8069. ** </dd>
  8070. **
  8071. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8072. ** <dd>This parameter returns the number of pager cache hits that have
  8073. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8074. ** is always 0.
  8075. ** </dd>
  8076. **
  8077. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8078. ** <dd>This parameter returns the number of pager cache misses that have
  8079. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8080. ** is always 0.
  8081. ** </dd>
  8082. **
  8083. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8084. ** <dd>This parameter returns the number of dirty cache entries that have
  8085. ** been written to disk. Specifically, the number of pages written to the
  8086. ** wal file in wal mode databases, or the number of pages written to the
  8087. ** database file in rollback mode databases. Any pages written as part of
  8088. ** transaction rollback or database recovery operations are not included.
  8089. ** If an IO or other error occurs while writing a page to disk, the effect
  8090. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8091. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8092. ** </dd>
  8093. **
  8094. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8095. ** <dd>This parameter returns zero for the current value if and only if
  8096. ** all foreign key constraints (deferred or immediate) have been
  8097. ** resolved.)^ ^The highwater mark is always 0.
  8098. ** </dd>
  8099. ** </dl>
  8100. */
  8101. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8102. #define SQLITE_DBSTATUS_CACHE_USED 1
  8103. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8104. #define SQLITE_DBSTATUS_STMT_USED 3
  8105. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8106. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8107. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8108. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8109. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8110. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8111. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8112. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8113. #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
  8114. /*
  8115. ** CAPI3REF: Prepared Statement Status
  8116. ** METHOD: sqlite3_stmt
  8117. **
  8118. ** ^(Each prepared statement maintains various
  8119. ** [SQLITE_STMTSTATUS counters] that measure the number
  8120. ** of times it has performed specific operations.)^ These counters can
  8121. ** be used to monitor the performance characteristics of the prepared
  8122. ** statements. For example, if the number of table steps greatly exceeds
  8123. ** the number of table searches or result rows, that would tend to indicate
  8124. ** that the prepared statement is using a full table scan rather than
  8125. ** an index.
  8126. **
  8127. ** ^(This interface is used to retrieve and reset counter values from
  8128. ** a [prepared statement]. The first argument is the prepared statement
  8129. ** object to be interrogated. The second argument
  8130. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8131. ** to be interrogated.)^
  8132. ** ^The current value of the requested counter is returned.
  8133. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8134. ** interface call returns.
  8135. **
  8136. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8137. */
  8138. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8139. /*
  8140. ** CAPI3REF: Status Parameters for prepared statements
  8141. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8142. **
  8143. ** These preprocessor macros define integer codes that name counter
  8144. ** values associated with the [sqlite3_stmt_status()] interface.
  8145. ** The meanings of the various counters are as follows:
  8146. **
  8147. ** <dl>
  8148. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8149. ** <dd>^This is the number of times that SQLite has stepped forward in
  8150. ** a table as part of a full table scan. Large numbers for this counter
  8151. ** may indicate opportunities for performance improvement through
  8152. ** careful use of indices.</dd>
  8153. **
  8154. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8155. ** <dd>^This is the number of sort operations that have occurred.
  8156. ** A non-zero value in this counter may indicate an opportunity to
  8157. ** improvement performance through careful use of indices.</dd>
  8158. **
  8159. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8160. ** <dd>^This is the number of rows inserted into transient indices that
  8161. ** were created automatically in order to help joins run faster.
  8162. ** A non-zero value in this counter may indicate an opportunity to
  8163. ** improvement performance by adding permanent indices that do not
  8164. ** need to be reinitialized each time the statement is run.</dd>
  8165. **
  8166. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8167. ** <dd>^This is the number of virtual machine operations executed
  8168. ** by the prepared statement if that number is less than or equal
  8169. ** to 2147483647. The number of virtual machine operations can be
  8170. ** used as a proxy for the total work done by the prepared statement.
  8171. ** If the number of virtual machine operations exceeds 2147483647
  8172. ** then the value returned by this statement status code is undefined.
  8173. **
  8174. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8175. ** <dd>^This is the number of times that the prepare statement has been
  8176. ** automatically regenerated due to schema changes or change to
  8177. ** [bound parameters] that might affect the query plan.
  8178. **
  8179. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8180. ** <dd>^This is the number of times that the prepared statement has
  8181. ** been run. A single "run" for the purposes of this counter is one
  8182. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8183. ** The counter is incremented on the first [sqlite3_step()] call of each
  8184. ** cycle.
  8185. **
  8186. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8187. ** <dd>^This is the approximate number of bytes of heap memory
  8188. ** used to store the prepared statement. ^This value is not actually
  8189. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8190. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8191. ** </dd>
  8192. ** </dl>
  8193. */
  8194. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8195. #define SQLITE_STMTSTATUS_SORT 2
  8196. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8197. #define SQLITE_STMTSTATUS_VM_STEP 4
  8198. #define SQLITE_STMTSTATUS_REPREPARE 5
  8199. #define SQLITE_STMTSTATUS_RUN 6
  8200. #define SQLITE_STMTSTATUS_MEMUSED 99
  8201. /*
  8202. ** CAPI3REF: Custom Page Cache Object
  8203. **
  8204. ** The sqlite3_pcache type is opaque. It is implemented by
  8205. ** the pluggable module. The SQLite core has no knowledge of
  8206. ** its size or internal structure and never deals with the
  8207. ** sqlite3_pcache object except by holding and passing pointers
  8208. ** to the object.
  8209. **
  8210. ** See [sqlite3_pcache_methods2] for additional information.
  8211. */
  8212. typedef struct sqlite3_pcache sqlite3_pcache;
  8213. /*
  8214. ** CAPI3REF: Custom Page Cache Object
  8215. **
  8216. ** The sqlite3_pcache_page object represents a single page in the
  8217. ** page cache. The page cache will allocate instances of this
  8218. ** object. Various methods of the page cache use pointers to instances
  8219. ** of this object as parameters or as their return value.
  8220. **
  8221. ** See [sqlite3_pcache_methods2] for additional information.
  8222. */
  8223. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8224. struct sqlite3_pcache_page {
  8225. void *pBuf; /* The content of the page */
  8226. void *pExtra; /* Extra information associated with the page */
  8227. };
  8228. /*
  8229. ** CAPI3REF: Application Defined Page Cache.
  8230. ** KEYWORDS: {page cache}
  8231. **
  8232. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8233. ** register an alternative page cache implementation by passing in an
  8234. ** instance of the sqlite3_pcache_methods2 structure.)^
  8235. ** In many applications, most of the heap memory allocated by
  8236. ** SQLite is used for the page cache.
  8237. ** By implementing a
  8238. ** custom page cache using this API, an application can better control
  8239. ** the amount of memory consumed by SQLite, the way in which
  8240. ** that memory is allocated and released, and the policies used to
  8241. ** determine exactly which parts of a database file are cached and for
  8242. ** how long.
  8243. **
  8244. ** The alternative page cache mechanism is an
  8245. ** extreme measure that is only needed by the most demanding applications.
  8246. ** The built-in page cache is recommended for most uses.
  8247. **
  8248. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8249. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8250. ** the application may discard the parameter after the call to
  8251. ** [sqlite3_config()] returns.)^
  8252. **
  8253. ** [[the xInit() page cache method]]
  8254. ** ^(The xInit() method is called once for each effective
  8255. ** call to [sqlite3_initialize()])^
  8256. ** (usually only once during the lifetime of the process). ^(The xInit()
  8257. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8258. ** The intent of the xInit() method is to set up global data structures
  8259. ** required by the custom page cache implementation.
  8260. ** ^(If the xInit() method is NULL, then the
  8261. ** built-in default page cache is used instead of the application defined
  8262. ** page cache.)^
  8263. **
  8264. ** [[the xShutdown() page cache method]]
  8265. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8266. ** It can be used to clean up
  8267. ** any outstanding resources before process shutdown, if required.
  8268. ** ^The xShutdown() method may be NULL.
  8269. **
  8270. ** ^SQLite automatically serializes calls to the xInit method,
  8271. ** so the xInit method need not be threadsafe. ^The
  8272. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8273. ** not need to be threadsafe either. All other methods must be threadsafe
  8274. ** in multithreaded applications.
  8275. **
  8276. ** ^SQLite will never invoke xInit() more than once without an intervening
  8277. ** call to xShutdown().
  8278. **
  8279. ** [[the xCreate() page cache methods]]
  8280. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8281. ** SQLite will typically create one cache instance for each open database file,
  8282. ** though this is not guaranteed. ^The
  8283. ** first parameter, szPage, is the size in bytes of the pages that must
  8284. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8285. ** second parameter szExtra is a number of bytes of extra storage
  8286. ** associated with each page cache entry. ^The szExtra parameter will
  8287. ** a number less than 250. SQLite will use the
  8288. ** extra szExtra bytes on each page to store metadata about the underlying
  8289. ** database page on disk. The value passed into szExtra depends
  8290. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8291. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8292. ** created will be used to cache database pages of a file stored on disk, or
  8293. ** false if it is used for an in-memory database. The cache implementation
  8294. ** does not have to do anything special based with the value of bPurgeable;
  8295. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8296. ** never invoke xUnpin() except to deliberately delete a page.
  8297. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8298. ** false will always have the "discard" flag set to true.
  8299. ** ^Hence, a cache created with bPurgeable false will
  8300. ** never contain any unpinned pages.
  8301. **
  8302. ** [[the xCachesize() page cache method]]
  8303. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8304. ** suggested maximum cache-size (number of pages stored by) the cache
  8305. ** instance passed as the first argument. This is the value configured using
  8306. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8307. ** parameter, the implementation is not required to do anything with this
  8308. ** value; it is advisory only.
  8309. **
  8310. ** [[the xPagecount() page cache methods]]
  8311. ** The xPagecount() method must return the number of pages currently
  8312. ** stored in the cache, both pinned and unpinned.
  8313. **
  8314. ** [[the xFetch() page cache methods]]
  8315. ** The xFetch() method locates a page in the cache and returns a pointer to
  8316. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8317. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8318. ** pointer to a buffer of szPage bytes used to store the content of a
  8319. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8320. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8321. ** for each entry in the page cache.
  8322. **
  8323. ** The page to be fetched is determined by the key. ^The minimum key value
  8324. ** is 1. After it has been retrieved using xFetch, the page is considered
  8325. ** to be "pinned".
  8326. **
  8327. ** If the requested page is already in the page cache, then the page cache
  8328. ** implementation must return a pointer to the page buffer with its content
  8329. ** intact. If the requested page is not already in the cache, then the
  8330. ** cache implementation should use the value of the createFlag
  8331. ** parameter to help it determined what action to take:
  8332. **
  8333. ** <table border=1 width=85% align=center>
  8334. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8335. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8336. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8337. ** Otherwise return NULL.
  8338. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8339. ** NULL if allocating a new page is effectively impossible.
  8340. ** </table>
  8341. **
  8342. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8343. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8344. ** failed.)^ In between the to xFetch() calls, SQLite may
  8345. ** attempt to unpin one or more cache pages by spilling the content of
  8346. ** pinned pages to disk and synching the operating system disk cache.
  8347. **
  8348. ** [[the xUnpin() page cache method]]
  8349. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8350. ** as its second argument. If the third parameter, discard, is non-zero,
  8351. ** then the page must be evicted from the cache.
  8352. ** ^If the discard parameter is
  8353. ** zero, then the page may be discarded or retained at the discretion of
  8354. ** page cache implementation. ^The page cache implementation
  8355. ** may choose to evict unpinned pages at any time.
  8356. **
  8357. ** The cache must not perform any reference counting. A single
  8358. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8359. ** to xFetch().
  8360. **
  8361. ** [[the xRekey() page cache methods]]
  8362. ** The xRekey() method is used to change the key value associated with the
  8363. ** page passed as the second argument. If the cache
  8364. ** previously contains an entry associated with newKey, it must be
  8365. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8366. ** to be pinned.
  8367. **
  8368. ** When SQLite calls the xTruncate() method, the cache must discard all
  8369. ** existing cache entries with page numbers (keys) greater than or equal
  8370. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8371. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8372. ** they can be safely discarded.
  8373. **
  8374. ** [[the xDestroy() page cache method]]
  8375. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8376. ** All resources associated with the specified cache should be freed. ^After
  8377. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8378. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8379. ** functions.
  8380. **
  8381. ** [[the xShrink() page cache method]]
  8382. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8383. ** free up as much of heap memory as possible. The page cache implementation
  8384. ** is not obligated to free any memory, but well-behaved implementations should
  8385. ** do their best.
  8386. */
  8387. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8388. struct sqlite3_pcache_methods2 {
  8389. int iVersion;
  8390. void *pArg;
  8391. int (*xInit)(void*);
  8392. void (*xShutdown)(void*);
  8393. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8394. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8395. int (*xPagecount)(sqlite3_pcache*);
  8396. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8397. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8398. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8399. unsigned oldKey, unsigned newKey);
  8400. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8401. void (*xDestroy)(sqlite3_pcache*);
  8402. void (*xShrink)(sqlite3_pcache*);
  8403. };
  8404. /*
  8405. ** This is the obsolete pcache_methods object that has now been replaced
  8406. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8407. ** retained in the header file for backwards compatibility only.
  8408. */
  8409. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8410. struct sqlite3_pcache_methods {
  8411. void *pArg;
  8412. int (*xInit)(void*);
  8413. void (*xShutdown)(void*);
  8414. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8415. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8416. int (*xPagecount)(sqlite3_pcache*);
  8417. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8418. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8419. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8420. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8421. void (*xDestroy)(sqlite3_pcache*);
  8422. };
  8423. /*
  8424. ** CAPI3REF: Online Backup Object
  8425. **
  8426. ** The sqlite3_backup object records state information about an ongoing
  8427. ** online backup operation. ^The sqlite3_backup object is created by
  8428. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8429. ** [sqlite3_backup_finish()].
  8430. **
  8431. ** See Also: [Using the SQLite Online Backup API]
  8432. */
  8433. typedef struct sqlite3_backup sqlite3_backup;
  8434. /*
  8435. ** CAPI3REF: Online Backup API.
  8436. **
  8437. ** The backup API copies the content of one database into another.
  8438. ** It is useful either for creating backups of databases or
  8439. ** for copying in-memory databases to or from persistent files.
  8440. **
  8441. ** See Also: [Using the SQLite Online Backup API]
  8442. **
  8443. ** ^SQLite holds a write transaction open on the destination database file
  8444. ** for the duration of the backup operation.
  8445. ** ^The source database is read-locked only while it is being read;
  8446. ** it is not locked continuously for the entire backup operation.
  8447. ** ^Thus, the backup may be performed on a live source database without
  8448. ** preventing other database connections from
  8449. ** reading or writing to the source database while the backup is underway.
  8450. **
  8451. ** ^(To perform a backup operation:
  8452. ** <ol>
  8453. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8454. ** backup,
  8455. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8456. ** the data between the two databases, and finally
  8457. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8458. ** associated with the backup operation.
  8459. ** </ol>)^
  8460. ** There should be exactly one call to sqlite3_backup_finish() for each
  8461. ** successful call to sqlite3_backup_init().
  8462. **
  8463. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8464. **
  8465. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  8466. ** [database connection] associated with the destination database
  8467. ** and the database name, respectively.
  8468. ** ^The database name is "main" for the main database, "temp" for the
  8469. ** temporary database, or the name specified after the AS keyword in
  8470. ** an [ATTACH] statement for an attached database.
  8471. ** ^The S and M arguments passed to
  8472. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8473. ** and database name of the source database, respectively.
  8474. ** ^The source and destination [database connections] (parameters S and D)
  8475. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8476. ** an error.
  8477. **
  8478. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  8479. ** there is already a read or read-write transaction open on the
  8480. ** destination database.
  8481. **
  8482. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8483. ** returned and an error code and error message are stored in the
  8484. ** destination [database connection] D.
  8485. ** ^The error code and message for the failed call to sqlite3_backup_init()
  8486. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8487. ** [sqlite3_errmsg16()] functions.
  8488. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8489. ** [sqlite3_backup] object.
  8490. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8491. ** sqlite3_backup_finish() functions to perform the specified backup
  8492. ** operation.
  8493. **
  8494. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8495. **
  8496. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  8497. ** the source and destination databases specified by [sqlite3_backup] object B.
  8498. ** ^If N is negative, all remaining source pages are copied.
  8499. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8500. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8501. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8502. ** from source to destination, then it returns [SQLITE_DONE].
  8503. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8504. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  8505. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  8506. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  8507. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  8508. **
  8509. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  8510. ** <ol>
  8511. ** <li> the destination database was opened read-only, or
  8512. ** <li> the destination database is using write-ahead-log journaling
  8513. ** and the destination and source page sizes differ, or
  8514. ** <li> the destination database is an in-memory database and the
  8515. ** destination and source page sizes differ.
  8516. ** </ol>)^
  8517. **
  8518. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  8519. ** the [sqlite3_busy_handler | busy-handler function]
  8520. ** is invoked (if one is specified). ^If the
  8521. ** busy-handler returns non-zero before the lock is available, then
  8522. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  8523. ** sqlite3_backup_step() can be retried later. ^If the source
  8524. ** [database connection]
  8525. ** is being used to write to the source database when sqlite3_backup_step()
  8526. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  8527. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  8528. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  8529. ** [SQLITE_READONLY] is returned, then
  8530. ** there is no point in retrying the call to sqlite3_backup_step(). These
  8531. ** errors are considered fatal.)^ The application must accept
  8532. ** that the backup operation has failed and pass the backup operation handle
  8533. ** to the sqlite3_backup_finish() to release associated resources.
  8534. **
  8535. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  8536. ** on the destination file. ^The exclusive lock is not released until either
  8537. ** sqlite3_backup_finish() is called or the backup operation is complete
  8538. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  8539. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  8540. ** lasts for the duration of the sqlite3_backup_step() call.
  8541. ** ^Because the source database is not locked between calls to
  8542. ** sqlite3_backup_step(), the source database may be modified mid-way
  8543. ** through the backup process. ^If the source database is modified by an
  8544. ** external process or via a database connection other than the one being
  8545. ** used by the backup operation, then the backup will be automatically
  8546. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  8547. ** database is modified by the using the same database connection as is used
  8548. ** by the backup operation, then the backup database is automatically
  8549. ** updated at the same time.
  8550. **
  8551. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  8552. **
  8553. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  8554. ** application wishes to abandon the backup operation, the application
  8555. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  8556. ** ^The sqlite3_backup_finish() interfaces releases all
  8557. ** resources associated with the [sqlite3_backup] object.
  8558. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  8559. ** active write-transaction on the destination database is rolled back.
  8560. ** The [sqlite3_backup] object is invalid
  8561. ** and may not be used following a call to sqlite3_backup_finish().
  8562. **
  8563. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  8564. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  8565. ** sqlite3_backup_step() completed.
  8566. ** ^If an out-of-memory condition or IO error occurred during any prior
  8567. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  8568. ** sqlite3_backup_finish() returns the corresponding [error code].
  8569. **
  8570. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  8571. ** is not a permanent error and does not affect the return value of
  8572. ** sqlite3_backup_finish().
  8573. **
  8574. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  8575. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  8576. **
  8577. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  8578. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  8579. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  8580. ** in the source database at the conclusion of the most recent
  8581. ** sqlite3_backup_step().
  8582. ** ^(The values returned by these functions are only updated by
  8583. ** sqlite3_backup_step(). If the source database is modified in a way that
  8584. ** changes the size of the source database or the number of pages remaining,
  8585. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  8586. ** and sqlite3_backup_remaining() until after the next
  8587. ** sqlite3_backup_step().)^
  8588. **
  8589. ** <b>Concurrent Usage of Database Handles</b>
  8590. **
  8591. ** ^The source [database connection] may be used by the application for other
  8592. ** purposes while a backup operation is underway or being initialized.
  8593. ** ^If SQLite is compiled and configured to support threadsafe database
  8594. ** connections, then the source database connection may be used concurrently
  8595. ** from within other threads.
  8596. **
  8597. ** However, the application must guarantee that the destination
  8598. ** [database connection] is not passed to any other API (by any thread) after
  8599. ** sqlite3_backup_init() is called and before the corresponding call to
  8600. ** sqlite3_backup_finish(). SQLite does not currently check to see
  8601. ** if the application incorrectly accesses the destination [database connection]
  8602. ** and so no error code is reported, but the operations may malfunction
  8603. ** nevertheless. Use of the destination database connection while a
  8604. ** backup is in progress might also also cause a mutex deadlock.
  8605. **
  8606. ** If running in [shared cache mode], the application must
  8607. ** guarantee that the shared cache used by the destination database
  8608. ** is not accessed while the backup is running. In practice this means
  8609. ** that the application must guarantee that the disk file being
  8610. ** backed up to is not accessed by any connection within the process,
  8611. ** not just the specific connection that was passed to sqlite3_backup_init().
  8612. **
  8613. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  8614. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  8615. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  8616. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  8617. ** same time as another thread is invoking sqlite3_backup_step() it is
  8618. ** possible that they return invalid values.
  8619. */
  8620. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  8621. sqlite3 *pDest, /* Destination database handle */
  8622. const char *zDestName, /* Destination database name */
  8623. sqlite3 *pSource, /* Source database handle */
  8624. const char *zSourceName /* Source database name */
  8625. );
  8626. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  8627. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  8628. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  8629. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  8630. /*
  8631. ** CAPI3REF: Unlock Notification
  8632. ** METHOD: sqlite3
  8633. **
  8634. ** ^When running in shared-cache mode, a database operation may fail with
  8635. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  8636. ** individual tables within the shared-cache cannot be obtained. See
  8637. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  8638. ** ^This API may be used to register a callback that SQLite will invoke
  8639. ** when the connection currently holding the required lock relinquishes it.
  8640. ** ^This API is only available if the library was compiled with the
  8641. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  8642. **
  8643. ** See Also: [Using the SQLite Unlock Notification Feature].
  8644. **
  8645. ** ^Shared-cache locks are released when a database connection concludes
  8646. ** its current transaction, either by committing it or rolling it back.
  8647. **
  8648. ** ^When a connection (known as the blocked connection) fails to obtain a
  8649. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  8650. ** identity of the database connection (the blocking connection) that
  8651. ** has locked the required resource is stored internally. ^After an
  8652. ** application receives an SQLITE_LOCKED error, it may call the
  8653. ** sqlite3_unlock_notify() method with the blocked connection handle as
  8654. ** the first argument to register for a callback that will be invoked
  8655. ** when the blocking connections current transaction is concluded. ^The
  8656. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  8657. ** call that concludes the blocking connections transaction.
  8658. **
  8659. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  8660. ** there is a chance that the blocking connection will have already
  8661. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  8662. ** If this happens, then the specified callback is invoked immediately,
  8663. ** from within the call to sqlite3_unlock_notify().)^
  8664. **
  8665. ** ^If the blocked connection is attempting to obtain a write-lock on a
  8666. ** shared-cache table, and more than one other connection currently holds
  8667. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  8668. ** the other connections to use as the blocking connection.
  8669. **
  8670. ** ^(There may be at most one unlock-notify callback registered by a
  8671. ** blocked connection. If sqlite3_unlock_notify() is called when the
  8672. ** blocked connection already has a registered unlock-notify callback,
  8673. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  8674. ** called with a NULL pointer as its second argument, then any existing
  8675. ** unlock-notify callback is canceled. ^The blocked connections
  8676. ** unlock-notify callback may also be canceled by closing the blocked
  8677. ** connection using [sqlite3_close()].
  8678. **
  8679. ** The unlock-notify callback is not reentrant. If an application invokes
  8680. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  8681. ** crash or deadlock may be the result.
  8682. **
  8683. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  8684. ** returns SQLITE_OK.
  8685. **
  8686. ** <b>Callback Invocation Details</b>
  8687. **
  8688. ** When an unlock-notify callback is registered, the application provides a
  8689. ** single void* pointer that is passed to the callback when it is invoked.
  8690. ** However, the signature of the callback function allows SQLite to pass
  8691. ** it an array of void* context pointers. The first argument passed to
  8692. ** an unlock-notify callback is a pointer to an array of void* pointers,
  8693. ** and the second is the number of entries in the array.
  8694. **
  8695. ** When a blocking connections transaction is concluded, there may be
  8696. ** more than one blocked connection that has registered for an unlock-notify
  8697. ** callback. ^If two or more such blocked connections have specified the
  8698. ** same callback function, then instead of invoking the callback function
  8699. ** multiple times, it is invoked once with the set of void* context pointers
  8700. ** specified by the blocked connections bundled together into an array.
  8701. ** This gives the application an opportunity to prioritize any actions
  8702. ** related to the set of unblocked database connections.
  8703. **
  8704. ** <b>Deadlock Detection</b>
  8705. **
  8706. ** Assuming that after registering for an unlock-notify callback a
  8707. ** database waits for the callback to be issued before taking any further
  8708. ** action (a reasonable assumption), then using this API may cause the
  8709. ** application to deadlock. For example, if connection X is waiting for
  8710. ** connection Y's transaction to be concluded, and similarly connection
  8711. ** Y is waiting on connection X's transaction, then neither connection
  8712. ** will proceed and the system may remain deadlocked indefinitely.
  8713. **
  8714. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  8715. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  8716. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  8717. ** unlock-notify callback is registered. The system is said to be in
  8718. ** a deadlocked state if connection A has registered for an unlock-notify
  8719. ** callback on the conclusion of connection B's transaction, and connection
  8720. ** B has itself registered for an unlock-notify callback when connection
  8721. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  8722. ** the system is also considered to be deadlocked if connection B has
  8723. ** registered for an unlock-notify callback on the conclusion of connection
  8724. ** C's transaction, where connection C is waiting on connection A. ^Any
  8725. ** number of levels of indirection are allowed.
  8726. **
  8727. ** <b>The "DROP TABLE" Exception</b>
  8728. **
  8729. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  8730. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  8731. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  8732. ** SQLite checks if there are any currently executing SELECT statements
  8733. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  8734. ** returned. In this case there is no "blocking connection", so invoking
  8735. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  8736. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  8737. ** or "DROP INDEX" query, an infinite loop might be the result.
  8738. **
  8739. ** One way around this problem is to check the extended error code returned
  8740. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  8741. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  8742. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  8743. ** SQLITE_LOCKED.)^
  8744. */
  8745. SQLITE_API int sqlite3_unlock_notify(
  8746. sqlite3 *pBlocked, /* Waiting connection */
  8747. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  8748. void *pNotifyArg /* Argument to pass to xNotify */
  8749. );
  8750. /*
  8751. ** CAPI3REF: String Comparison
  8752. **
  8753. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  8754. ** and extensions to compare the contents of two buffers containing UTF-8
  8755. ** strings in a case-independent fashion, using the same definition of "case
  8756. ** independence" that SQLite uses internally when comparing identifiers.
  8757. */
  8758. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  8759. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  8760. /*
  8761. ** CAPI3REF: String Globbing
  8762. *
  8763. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  8764. ** string X matches the [GLOB] pattern P.
  8765. ** ^The definition of [GLOB] pattern matching used in
  8766. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  8767. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  8768. ** is case sensitive.
  8769. **
  8770. ** Note that this routine returns zero on a match and non-zero if the strings
  8771. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  8772. **
  8773. ** See also: [sqlite3_strlike()].
  8774. */
  8775. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  8776. /*
  8777. ** CAPI3REF: String LIKE Matching
  8778. *
  8779. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  8780. ** string X matches the [LIKE] pattern P with escape character E.
  8781. ** ^The definition of [LIKE] pattern matching used in
  8782. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  8783. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  8784. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  8785. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  8786. ** insensitive - equivalent upper and lower case ASCII characters match
  8787. ** one another.
  8788. **
  8789. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  8790. ** only ASCII characters are case folded.
  8791. **
  8792. ** Note that this routine returns zero on a match and non-zero if the strings
  8793. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  8794. **
  8795. ** See also: [sqlite3_strglob()].
  8796. */
  8797. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  8798. /*
  8799. ** CAPI3REF: Error Logging Interface
  8800. **
  8801. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  8802. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  8803. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  8804. ** used with [sqlite3_snprintf()] to generate the final output string.
  8805. **
  8806. ** The sqlite3_log() interface is intended for use by extensions such as
  8807. ** virtual tables, collating functions, and SQL functions. While there is
  8808. ** nothing to prevent an application from calling sqlite3_log(), doing so
  8809. ** is considered bad form.
  8810. **
  8811. ** The zFormat string must not be NULL.
  8812. **
  8813. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  8814. ** will not use dynamically allocated memory. The log message is stored in
  8815. ** a fixed-length buffer on the stack. If the log message is longer than
  8816. ** a few hundred characters, it will be truncated to the length of the
  8817. ** buffer.
  8818. */
  8819. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  8820. /*
  8821. ** CAPI3REF: Write-Ahead Log Commit Hook
  8822. ** METHOD: sqlite3
  8823. **
  8824. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  8825. ** is invoked each time data is committed to a database in wal mode.
  8826. **
  8827. ** ^(The callback is invoked by SQLite after the commit has taken place and
  8828. ** the associated write-lock on the database released)^, so the implementation
  8829. ** may read, write or [checkpoint] the database as required.
  8830. **
  8831. ** ^The first parameter passed to the callback function when it is invoked
  8832. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  8833. ** registering the callback. ^The second is a copy of the database handle.
  8834. ** ^The third parameter is the name of the database that was written to -
  8835. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  8836. ** is the number of pages currently in the write-ahead log file,
  8837. ** including those that were just committed.
  8838. **
  8839. ** The callback function should normally return [SQLITE_OK]. ^If an error
  8840. ** code is returned, that error will propagate back up through the
  8841. ** SQLite code base to cause the statement that provoked the callback
  8842. ** to report an error, though the commit will have still occurred. If the
  8843. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  8844. ** that does not correspond to any valid SQLite error code, the results
  8845. ** are undefined.
  8846. **
  8847. ** A single database handle may have at most a single write-ahead log callback
  8848. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  8849. ** previously registered write-ahead log callback. ^Note that the
  8850. ** [sqlite3_wal_autocheckpoint()] interface and the
  8851. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  8852. ** overwrite any prior [sqlite3_wal_hook()] settings.
  8853. */
  8854. SQLITE_API void *sqlite3_wal_hook(
  8855. sqlite3*,
  8856. int(*)(void *,sqlite3*,const char*,int),
  8857. void*
  8858. );
  8859. /*
  8860. ** CAPI3REF: Configure an auto-checkpoint
  8861. ** METHOD: sqlite3
  8862. **
  8863. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  8864. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  8865. ** to automatically [checkpoint]
  8866. ** after committing a transaction if there are N or
  8867. ** more frames in the [write-ahead log] file. ^Passing zero or
  8868. ** a negative value as the nFrame parameter disables automatic
  8869. ** checkpoints entirely.
  8870. **
  8871. ** ^The callback registered by this function replaces any existing callback
  8872. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  8873. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  8874. ** configured by this function.
  8875. **
  8876. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  8877. ** from SQL.
  8878. **
  8879. ** ^Checkpoints initiated by this mechanism are
  8880. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  8881. **
  8882. ** ^Every new [database connection] defaults to having the auto-checkpoint
  8883. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  8884. ** pages. The use of this interface
  8885. ** is only necessary if the default setting is found to be suboptimal
  8886. ** for a particular application.
  8887. */
  8888. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  8889. /*
  8890. ** CAPI3REF: Checkpoint a database
  8891. ** METHOD: sqlite3
  8892. **
  8893. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  8894. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  8895. **
  8896. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  8897. ** [write-ahead log] for database X on [database connection] D to be
  8898. ** transferred into the database file and for the write-ahead log to
  8899. ** be reset. See the [checkpointing] documentation for addition
  8900. ** information.
  8901. **
  8902. ** This interface used to be the only way to cause a checkpoint to
  8903. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  8904. ** interface was added. This interface is retained for backwards
  8905. ** compatibility and as a convenience for applications that need to manually
  8906. ** start a callback but which do not need the full power (and corresponding
  8907. ** complication) of [sqlite3_wal_checkpoint_v2()].
  8908. */
  8909. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  8910. /*
  8911. ** CAPI3REF: Checkpoint a database
  8912. ** METHOD: sqlite3
  8913. **
  8914. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  8915. ** operation on database X of [database connection] D in mode M. Status
  8916. ** information is written back into integers pointed to by L and C.)^
  8917. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  8918. **
  8919. ** <dl>
  8920. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  8921. ** ^Checkpoint as many frames as possible without waiting for any database
  8922. ** readers or writers to finish, then sync the database file if all frames
  8923. ** in the log were checkpointed. ^The [busy-handler callback]
  8924. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  8925. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  8926. ** if there are concurrent readers or writers.
  8927. **
  8928. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  8929. ** ^This mode blocks (it invokes the
  8930. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  8931. ** database writer and all readers are reading from the most recent database
  8932. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  8933. ** database file. ^This mode blocks new database writers while it is pending,
  8934. ** but new database readers are allowed to continue unimpeded.
  8935. **
  8936. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  8937. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  8938. ** that after checkpointing the log file it blocks (calls the
  8939. ** [busy-handler callback])
  8940. ** until all readers are reading from the database file only. ^This ensures
  8941. ** that the next writer will restart the log file from the beginning.
  8942. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  8943. ** database writer attempts while it is pending, but does not impede readers.
  8944. **
  8945. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  8946. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  8947. ** addition that it also truncates the log file to zero bytes just prior
  8948. ** to a successful return.
  8949. ** </dl>
  8950. **
  8951. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  8952. ** the log file or to -1 if the checkpoint could not run because
  8953. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  8954. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  8955. ** log file (including any that were already checkpointed before the function
  8956. ** was called) or to -1 if the checkpoint could not run due to an error or
  8957. ** because the database is not in WAL mode. ^Note that upon successful
  8958. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  8959. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  8960. **
  8961. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  8962. ** any other process is running a checkpoint operation at the same time, the
  8963. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  8964. ** busy-handler configured, it will not be invoked in this case.
  8965. **
  8966. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  8967. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  8968. ** obtained immediately, and a busy-handler is configured, it is invoked and
  8969. ** the writer lock retried until either the busy-handler returns 0 or the lock
  8970. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  8971. ** database readers as described above. ^If the busy-handler returns 0 before
  8972. ** the writer lock is obtained or while waiting for database readers, the
  8973. ** checkpoint operation proceeds from that point in the same way as
  8974. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  8975. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  8976. **
  8977. ** ^If parameter zDb is NULL or points to a zero length string, then the
  8978. ** specified operation is attempted on all WAL databases [attached] to
  8979. ** [database connection] db. In this case the
  8980. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  8981. ** an SQLITE_BUSY error is encountered when processing one or more of the
  8982. ** attached WAL databases, the operation is still attempted on any remaining
  8983. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  8984. ** error occurs while processing an attached database, processing is abandoned
  8985. ** and the error code is returned to the caller immediately. ^If no error
  8986. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  8987. ** databases, SQLITE_OK is returned.
  8988. **
  8989. ** ^If database zDb is the name of an attached database that is not in WAL
  8990. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  8991. ** zDb is not NULL (or a zero length string) and is not the name of any
  8992. ** attached database, SQLITE_ERROR is returned to the caller.
  8993. **
  8994. ** ^Unless it returns SQLITE_MISUSE,
  8995. ** the sqlite3_wal_checkpoint_v2() interface
  8996. ** sets the error information that is queried by
  8997. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  8998. **
  8999. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9000. ** from SQL.
  9001. */
  9002. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9003. sqlite3 *db, /* Database handle */
  9004. const char *zDb, /* Name of attached database (or NULL) */
  9005. int eMode, /* SQLITE_CHECKPOINT_* value */
  9006. int *pnLog, /* OUT: Size of WAL log in frames */
  9007. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9008. );
  9009. /*
  9010. ** CAPI3REF: Checkpoint Mode Values
  9011. ** KEYWORDS: {checkpoint mode}
  9012. **
  9013. ** These constants define all valid values for the "checkpoint mode" passed
  9014. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9015. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9016. ** meaning of each of these checkpoint modes.
  9017. */
  9018. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9019. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9020. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9021. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9022. /*
  9023. ** CAPI3REF: Virtual Table Interface Configuration
  9024. **
  9025. ** This function may be called by either the [xConnect] or [xCreate] method
  9026. ** of a [virtual table] implementation to configure
  9027. ** various facets of the virtual table interface.
  9028. **
  9029. ** If this interface is invoked outside the context of an xConnect or
  9030. ** xCreate virtual table method then the behavior is undefined.
  9031. **
  9032. ** At present, there is only one option that may be configured using
  9033. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9034. ** may be added in the future.
  9035. */
  9036. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9037. /*
  9038. ** CAPI3REF: Virtual Table Configuration Options
  9039. **
  9040. ** These macros define the various options to the
  9041. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9042. ** can use to customize and optimize their behavior.
  9043. **
  9044. ** <dl>
  9045. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9046. ** <dd>Calls of the form
  9047. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9048. ** where X is an integer. If X is zero, then the [virtual table] whose
  9049. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9050. ** support constraints. In this configuration (which is the default) if
  9051. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9052. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9053. ** specified as part of the users SQL statement, regardless of the actual
  9054. ** ON CONFLICT mode specified.
  9055. **
  9056. ** If X is non-zero, then the virtual table implementation guarantees
  9057. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9058. ** any modifications to internal or persistent data structures have been made.
  9059. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9060. ** is able to roll back a statement or database transaction, and abandon
  9061. ** or continue processing the current SQL statement as appropriate.
  9062. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9063. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9064. ** had been ABORT.
  9065. **
  9066. ** Virtual table implementations that are required to handle OR REPLACE
  9067. ** must do so within the [xUpdate] method. If a call to the
  9068. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9069. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9070. ** silently replace the appropriate rows within the xUpdate callback and
  9071. ** return SQLITE_OK. Or, if this is not possible, it may return
  9072. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9073. ** constraint handling.
  9074. ** </dl>
  9075. */
  9076. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9077. /*
  9078. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9079. **
  9080. ** This function may only be called from within a call to the [xUpdate] method
  9081. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9082. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9083. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9084. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9085. ** [virtual table].
  9086. */
  9087. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9088. /*
  9089. ** CAPI3REF: Conflict resolution modes
  9090. ** KEYWORDS: {conflict resolution mode}
  9091. **
  9092. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9093. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9094. ** is for the SQL statement being evaluated.
  9095. **
  9096. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9097. ** return value from the [sqlite3_set_authorizer()] callback and that
  9098. ** [SQLITE_ABORT] is also a [result code].
  9099. */
  9100. #define SQLITE_ROLLBACK 1
  9101. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9102. #define SQLITE_FAIL 3
  9103. /* #define SQLITE_ABORT 4 // Also an error code */
  9104. #define SQLITE_REPLACE 5
  9105. /*
  9106. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9107. ** KEYWORDS: {scanstatus options}
  9108. **
  9109. ** The following constants can be used for the T parameter to the
  9110. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9111. ** different metric for sqlite3_stmt_scanstatus() to return.
  9112. **
  9113. ** When the value returned to V is a string, space to hold that string is
  9114. ** managed by the prepared statement S and will be automatically freed when
  9115. ** S is finalized.
  9116. **
  9117. ** <dl>
  9118. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9119. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9120. ** set to the total number of times that the X-th loop has run.</dd>
  9121. **
  9122. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9123. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9124. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9125. **
  9126. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9127. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9128. ** query planner's estimate for the average number of rows output from each
  9129. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9130. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9131. ** product of this value for all prior loops with the same SELECTID will
  9132. ** be the NLOOP value for the current loop.
  9133. **
  9134. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9135. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9136. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9137. ** used for the X-th loop.
  9138. **
  9139. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9140. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9141. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9142. ** description for the X-th loop.
  9143. **
  9144. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9145. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9146. ** "select-id" for the X-th loop. The select-id identifies which query or
  9147. ** subquery the loop is part of. The main query has a select-id of zero.
  9148. ** The select-id is the same value as is output in the first column
  9149. ** of an [EXPLAIN QUERY PLAN] query.
  9150. ** </dl>
  9151. */
  9152. #define SQLITE_SCANSTAT_NLOOP 0
  9153. #define SQLITE_SCANSTAT_NVISIT 1
  9154. #define SQLITE_SCANSTAT_EST 2
  9155. #define SQLITE_SCANSTAT_NAME 3
  9156. #define SQLITE_SCANSTAT_EXPLAIN 4
  9157. #define SQLITE_SCANSTAT_SELECTID 5
  9158. /*
  9159. ** CAPI3REF: Prepared Statement Scan Status
  9160. ** METHOD: sqlite3_stmt
  9161. **
  9162. ** This interface returns information about the predicted and measured
  9163. ** performance for pStmt. Advanced applications can use this
  9164. ** interface to compare the predicted and the measured performance and
  9165. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9166. **
  9167. ** Since this interface is expected to be rarely used, it is only
  9168. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9169. ** compile-time option.
  9170. **
  9171. ** The "iScanStatusOp" parameter determines which status information to return.
  9172. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9173. ** of this interface is undefined.
  9174. ** ^The requested measurement is written into a variable pointed to by
  9175. ** the "pOut" parameter.
  9176. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9177. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9178. ** zero or greater than or equal to the total number of loops used to implement
  9179. ** the statement - a non-zero value is returned and the variable that pOut
  9180. ** points to is unchanged.
  9181. **
  9182. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9183. ** where there exist loops with no available statistics, this function behaves
  9184. ** as if the loop did not exist - it returns non-zero and leave the variable
  9185. ** that pOut points to unchanged.
  9186. **
  9187. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9188. */
  9189. SQLITE_API int sqlite3_stmt_scanstatus(
  9190. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9191. int idx, /* Index of loop to report on */
  9192. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9193. void *pOut /* Result written here */
  9194. );
  9195. /*
  9196. ** CAPI3REF: Zero Scan-Status Counters
  9197. ** METHOD: sqlite3_stmt
  9198. **
  9199. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9200. **
  9201. ** This API is only available if the library is built with pre-processor
  9202. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9203. */
  9204. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9205. /*
  9206. ** CAPI3REF: Flush caches to disk mid-transaction
  9207. **
  9208. ** ^If a write-transaction is open on [database connection] D when the
  9209. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9210. ** pages in the pager-cache that are not currently in use are written out
  9211. ** to disk. A dirty page may be in use if a database cursor created by an
  9212. ** active SQL statement is reading from it, or if it is page 1 of a database
  9213. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9214. ** interface flushes caches for all schemas - "main", "temp", and
  9215. ** any [attached] databases.
  9216. **
  9217. ** ^If this function needs to obtain extra database locks before dirty pages
  9218. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9219. ** immediately and there is a busy-handler callback configured, it is invoked
  9220. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9221. ** the database is skipped and an attempt made to flush any dirty pages
  9222. ** belonging to the next (if any) database. ^If any databases are skipped
  9223. ** because locks cannot be obtained, but no other error occurs, this
  9224. ** function returns SQLITE_BUSY.
  9225. **
  9226. ** ^If any other error occurs while flushing dirty pages to disk (for
  9227. ** example an IO error or out-of-memory condition), then processing is
  9228. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9229. **
  9230. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9231. **
  9232. ** ^This function does not set the database handle error code or message
  9233. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9234. */
  9235. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9236. /*
  9237. ** CAPI3REF: The pre-update hook.
  9238. **
  9239. ** ^These interfaces are only available if SQLite is compiled using the
  9240. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9241. **
  9242. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9243. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9244. ** on a database table.
  9245. ** ^At most one preupdate hook may be registered at a time on a single
  9246. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9247. ** the previous setting.
  9248. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9249. ** with a NULL pointer as the second parameter.
  9250. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9251. ** the first parameter to callbacks.
  9252. **
  9253. ** ^The preupdate hook only fires for changes to real database tables; the
  9254. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9255. ** system tables like sqlite_master or sqlite_stat1.
  9256. **
  9257. ** ^The second parameter to the preupdate callback is a pointer to
  9258. ** the [database connection] that registered the preupdate hook.
  9259. ** ^The third parameter to the preupdate callback is one of the constants
  9260. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9261. ** kind of update operation that is about to occur.
  9262. ** ^(The fourth parameter to the preupdate callback is the name of the
  9263. ** database within the database connection that is being modified. This
  9264. ** will be "main" for the main database or "temp" for TEMP tables or
  9265. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9266. ** databases.)^
  9267. ** ^The fifth parameter to the preupdate callback is the name of the
  9268. ** table that is being modified.
  9269. **
  9270. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9271. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9272. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9273. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9274. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9275. ** seventh parameter is the final rowid value of the row being inserted
  9276. ** or updated. The value of the seventh parameter passed to the callback
  9277. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9278. ** INSERT operations on rowid tables.
  9279. **
  9280. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9281. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9282. ** provide additional information about a preupdate event. These routines
  9283. ** may only be called from within a preupdate callback. Invoking any of
  9284. ** these routines from outside of a preupdate callback or with a
  9285. ** [database connection] pointer that is different from the one supplied
  9286. ** to the preupdate callback results in undefined and probably undesirable
  9287. ** behavior.
  9288. **
  9289. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9290. ** in the row that is being inserted, updated, or deleted.
  9291. **
  9292. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9293. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9294. ** the table row before it is updated. The N parameter must be between 0
  9295. ** and one less than the number of columns or the behavior will be
  9296. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9297. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9298. ** behavior is undefined. The [sqlite3_value] that P points to
  9299. ** will be destroyed when the preupdate callback returns.
  9300. **
  9301. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9302. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9303. ** the table row after it is updated. The N parameter must be between 0
  9304. ** and one less than the number of columns or the behavior will be
  9305. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9306. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9307. ** behavior is undefined. The [sqlite3_value] that P points to
  9308. ** will be destroyed when the preupdate callback returns.
  9309. **
  9310. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9311. ** callback was invoked as a result of a direct insert, update, or delete
  9312. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9313. ** triggers; or 2 for changes resulting from triggers called by top-level
  9314. ** triggers; and so forth.
  9315. **
  9316. ** See also: [sqlite3_update_hook()]
  9317. */
  9318. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9319. SQLITE_API void *sqlite3_preupdate_hook(
  9320. sqlite3 *db,
  9321. void(*xPreUpdate)(
  9322. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9323. sqlite3 *db, /* Database handle */
  9324. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9325. char const *zDb, /* Database name */
  9326. char const *zName, /* Table name */
  9327. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9328. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9329. ),
  9330. void*
  9331. );
  9332. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9333. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9334. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9335. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9336. #endif
  9337. /*
  9338. ** CAPI3REF: Low-level system error code
  9339. **
  9340. ** ^Attempt to return the underlying operating system error code or error
  9341. ** number that caused the most recent I/O error or failure to open a file.
  9342. ** The return value is OS-dependent. For example, on unix systems, after
  9343. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9344. ** called to get back the underlying "errno" that caused the problem, such
  9345. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9346. */
  9347. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9348. /*
  9349. ** CAPI3REF: Database Snapshot
  9350. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9351. ** EXPERIMENTAL
  9352. **
  9353. ** An instance of the snapshot object records the state of a [WAL mode]
  9354. ** database for some specific point in history.
  9355. **
  9356. ** In [WAL mode], multiple [database connections] that are open on the
  9357. ** same database file can each be reading a different historical version
  9358. ** of the database file. When a [database connection] begins a read
  9359. ** transaction, that connection sees an unchanging copy of the database
  9360. ** as it existed for the point in time when the transaction first started.
  9361. ** Subsequent changes to the database from other connections are not seen
  9362. ** by the reader until a new read transaction is started.
  9363. **
  9364. ** The sqlite3_snapshot object records state information about an historical
  9365. ** version of the database file so that it is possible to later open a new read
  9366. ** transaction that sees that historical version of the database rather than
  9367. ** the most recent version.
  9368. **
  9369. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  9370. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  9371. ** to an historical snapshot (if possible). The destructor for
  9372. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  9373. */
  9374. typedef struct sqlite3_snapshot {
  9375. unsigned char hidden[48];
  9376. } sqlite3_snapshot;
  9377. /*
  9378. ** CAPI3REF: Record A Database Snapshot
  9379. ** EXPERIMENTAL
  9380. **
  9381. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9382. ** new [sqlite3_snapshot] object that records the current state of
  9383. ** schema S in database connection D. ^On success, the
  9384. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9385. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9386. ** If there is not already a read-transaction open on schema S when
  9387. ** this function is called, one is opened automatically.
  9388. **
  9389. ** The following must be true for this function to succeed. If any of
  9390. ** the following statements are false when sqlite3_snapshot_get() is
  9391. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9392. ** in this case.
  9393. **
  9394. ** <ul>
  9395. ** <li> The database handle must be in [autocommit mode].
  9396. **
  9397. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9398. **
  9399. ** <li> There must not be a write transaction open on schema S of database
  9400. ** connection D.
  9401. **
  9402. ** <li> One or more transactions must have been written to the current wal
  9403. ** file since it was created on disk (by any connection). This means
  9404. ** that a snapshot cannot be taken on a wal mode database with no wal
  9405. ** file immediately after it is first opened. At least one transaction
  9406. ** must be written to it first.
  9407. ** </ul>
  9408. **
  9409. ** This function may also return SQLITE_NOMEM. If it is called with the
  9410. ** database handle in autocommit mode but fails for some other reason,
  9411. ** whether or not a read transaction is opened on schema S is undefined.
  9412. **
  9413. ** The [sqlite3_snapshot] object returned from a successful call to
  9414. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9415. ** to avoid a memory leak.
  9416. **
  9417. ** The [sqlite3_snapshot_get()] interface is only available when the
  9418. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9419. */
  9420. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9421. sqlite3 *db,
  9422. const char *zSchema,
  9423. sqlite3_snapshot **ppSnapshot
  9424. );
  9425. /*
  9426. ** CAPI3REF: Start a read transaction on an historical snapshot
  9427. ** EXPERIMENTAL
  9428. **
  9429. ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  9430. ** read transaction for schema S of
  9431. ** [database connection] D such that the read transaction
  9432. ** refers to historical [snapshot] P, rather than the most
  9433. ** recent change to the database.
  9434. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  9435. ** or an appropriate [error code] if it fails.
  9436. **
  9437. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  9438. ** the first operation following the [BEGIN] that takes the schema S
  9439. ** out of [autocommit mode].
  9440. ** ^In other words, schema S must not currently be in
  9441. ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  9442. ** database connection D must be out of [autocommit mode].
  9443. ** ^A [snapshot] will fail to open if it has been overwritten by a
  9444. ** [checkpoint].
  9445. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9446. ** database connection D does not know that the database file for
  9447. ** schema S is in [WAL mode]. A database connection might not know
  9448. ** that the database file is in [WAL mode] if there has been no prior
  9449. ** I/O on that database connection, or if the database entered [WAL mode]
  9450. ** after the most recent I/O on the database connection.)^
  9451. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9452. ** database connection in order to make it ready to use snapshots.)
  9453. **
  9454. ** The [sqlite3_snapshot_open()] interface is only available when the
  9455. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9456. */
  9457. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9458. sqlite3 *db,
  9459. const char *zSchema,
  9460. sqlite3_snapshot *pSnapshot
  9461. );
  9462. /*
  9463. ** CAPI3REF: Destroy a snapshot
  9464. ** EXPERIMENTAL
  9465. **
  9466. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  9467. ** The application must eventually free every [sqlite3_snapshot] object
  9468. ** using this routine to avoid a memory leak.
  9469. **
  9470. ** The [sqlite3_snapshot_free()] interface is only available when the
  9471. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9472. */
  9473. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  9474. /*
  9475. ** CAPI3REF: Compare the ages of two snapshot handles.
  9476. ** EXPERIMENTAL
  9477. **
  9478. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  9479. ** of two valid snapshot handles.
  9480. **
  9481. ** If the two snapshot handles are not associated with the same database
  9482. ** file, the result of the comparison is undefined.
  9483. **
  9484. ** Additionally, the result of the comparison is only valid if both of the
  9485. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  9486. ** last time the wal file was deleted. The wal file is deleted when the
  9487. ** database is changed back to rollback mode or when the number of database
  9488. ** clients drops to zero. If either snapshot handle was obtained before the
  9489. ** wal file was last deleted, the value returned by this function
  9490. ** is undefined.
  9491. **
  9492. ** Otherwise, this API returns a negative value if P1 refers to an older
  9493. ** snapshot than P2, zero if the two handles refer to the same database
  9494. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  9495. */
  9496. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  9497. sqlite3_snapshot *p1,
  9498. sqlite3_snapshot *p2
  9499. );
  9500. /*
  9501. ** CAPI3REF: Recover snapshots from a wal file
  9502. ** EXPERIMENTAL
  9503. **
  9504. ** If all connections disconnect from a database file but do not perform
  9505. ** a checkpoint, the existing wal file is opened along with the database
  9506. ** file the next time the database is opened. At this point it is only
  9507. ** possible to successfully call sqlite3_snapshot_open() to open the most
  9508. ** recent snapshot of the database (the one at the head of the wal file),
  9509. ** even though the wal file may contain other valid snapshots for which
  9510. ** clients have sqlite3_snapshot handles.
  9511. **
  9512. ** This function attempts to scan the wal file associated with database zDb
  9513. ** of database handle db and make all valid snapshots available to
  9514. ** sqlite3_snapshot_open(). It is an error if there is already a read
  9515. ** transaction open on the database, or if the database is not a wal mode
  9516. ** database.
  9517. **
  9518. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  9519. */
  9520. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  9521. /*
  9522. ** Undo the hack that converts floating point types to integer for
  9523. ** builds on processors without floating point support.
  9524. */
  9525. #ifdef SQLITE_OMIT_FLOATING_POINT
  9526. # undef double
  9527. #endif
  9528. #if 0
  9529. } /* End of the 'extern "C"' block */
  9530. #endif
  9531. #endif /* SQLITE3_H */
  9532. /******** Begin file sqlite3rtree.h *********/
  9533. /*
  9534. ** 2010 August 30
  9535. **
  9536. ** The author disclaims copyright to this source code. In place of
  9537. ** a legal notice, here is a blessing:
  9538. **
  9539. ** May you do good and not evil.
  9540. ** May you find forgiveness for yourself and forgive others.
  9541. ** May you share freely, never taking more than you give.
  9542. **
  9543. *************************************************************************
  9544. */
  9545. #ifndef _SQLITE3RTREE_H_
  9546. #define _SQLITE3RTREE_H_
  9547. #if 0
  9548. extern "C" {
  9549. #endif
  9550. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  9551. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  9552. /* The double-precision datatype used by RTree depends on the
  9553. ** SQLITE_RTREE_INT_ONLY compile-time option.
  9554. */
  9555. #ifdef SQLITE_RTREE_INT_ONLY
  9556. typedef sqlite3_int64 sqlite3_rtree_dbl;
  9557. #else
  9558. typedef double sqlite3_rtree_dbl;
  9559. #endif
  9560. /*
  9561. ** Register a geometry callback named zGeom that can be used as part of an
  9562. ** R-Tree geometry query as follows:
  9563. **
  9564. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  9565. */
  9566. SQLITE_API int sqlite3_rtree_geometry_callback(
  9567. sqlite3 *db,
  9568. const char *zGeom,
  9569. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  9570. void *pContext
  9571. );
  9572. /*
  9573. ** A pointer to a structure of the following type is passed as the first
  9574. ** argument to callbacks registered using rtree_geometry_callback().
  9575. */
  9576. struct sqlite3_rtree_geometry {
  9577. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  9578. int nParam; /* Size of array aParam[] */
  9579. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  9580. void *pUser; /* Callback implementation user data */
  9581. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  9582. };
  9583. /*
  9584. ** Register a 2nd-generation geometry callback named zScore that can be
  9585. ** used as part of an R-Tree geometry query as follows:
  9586. **
  9587. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  9588. */
  9589. SQLITE_API int sqlite3_rtree_query_callback(
  9590. sqlite3 *db,
  9591. const char *zQueryFunc,
  9592. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  9593. void *pContext,
  9594. void (*xDestructor)(void*)
  9595. );
  9596. /*
  9597. ** A pointer to a structure of the following type is passed as the
  9598. ** argument to scored geometry callback registered using
  9599. ** sqlite3_rtree_query_callback().
  9600. **
  9601. ** Note that the first 5 fields of this structure are identical to
  9602. ** sqlite3_rtree_geometry. This structure is a subclass of
  9603. ** sqlite3_rtree_geometry.
  9604. */
  9605. struct sqlite3_rtree_query_info {
  9606. void *pContext; /* pContext from when function registered */
  9607. int nParam; /* Number of function parameters */
  9608. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  9609. void *pUser; /* callback can use this, if desired */
  9610. void (*xDelUser)(void*); /* function to free pUser */
  9611. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  9612. unsigned int *anQueue; /* Number of pending entries in the queue */
  9613. int nCoord; /* Number of coordinates */
  9614. int iLevel; /* Level of current node or entry */
  9615. int mxLevel; /* The largest iLevel value in the tree */
  9616. sqlite3_int64 iRowid; /* Rowid for current entry */
  9617. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  9618. int eParentWithin; /* Visibility of parent node */
  9619. int eWithin; /* OUT: Visiblity */
  9620. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  9621. /* The following fields are only available in 3.8.11 and later */
  9622. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  9623. };
  9624. /*
  9625. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  9626. */
  9627. #define NOT_WITHIN 0 /* Object completely outside of query region */
  9628. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  9629. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  9630. #if 0
  9631. } /* end of the 'extern "C"' block */
  9632. #endif
  9633. #endif /* ifndef _SQLITE3RTREE_H_ */
  9634. /******** End of sqlite3rtree.h *********/
  9635. /******** Begin file sqlite3session.h *********/
  9636. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  9637. #define __SQLITESESSION_H_ 1
  9638. /*
  9639. ** Make sure we can call this stuff from C++.
  9640. */
  9641. #if 0
  9642. extern "C" {
  9643. #endif
  9644. /*
  9645. ** CAPI3REF: Session Object Handle
  9646. */
  9647. typedef struct sqlite3_session sqlite3_session;
  9648. /*
  9649. ** CAPI3REF: Changeset Iterator Handle
  9650. */
  9651. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  9652. /*
  9653. ** CAPI3REF: Create A New Session Object
  9654. **
  9655. ** Create a new session object attached to database handle db. If successful,
  9656. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  9657. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  9658. ** error code (e.g. SQLITE_NOMEM) is returned.
  9659. **
  9660. ** It is possible to create multiple session objects attached to a single
  9661. ** database handle.
  9662. **
  9663. ** Session objects created using this function should be deleted using the
  9664. ** [sqlite3session_delete()] function before the database handle that they
  9665. ** are attached to is itself closed. If the database handle is closed before
  9666. ** the session object is deleted, then the results of calling any session
  9667. ** module function, including [sqlite3session_delete()] on the session object
  9668. ** are undefined.
  9669. **
  9670. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  9671. ** is not possible for an application to register a pre-update hook on a
  9672. ** database handle that has one or more session objects attached. Nor is
  9673. ** it possible to create a session object attached to a database handle for
  9674. ** which a pre-update hook is already defined. The results of attempting
  9675. ** either of these things are undefined.
  9676. **
  9677. ** The session object will be used to create changesets for tables in
  9678. ** database zDb, where zDb is either "main", or "temp", or the name of an
  9679. ** attached database. It is not an error if database zDb is not attached
  9680. ** to the database when the session object is created.
  9681. */
  9682. SQLITE_API int sqlite3session_create(
  9683. sqlite3 *db, /* Database handle */
  9684. const char *zDb, /* Name of db (e.g. "main") */
  9685. sqlite3_session **ppSession /* OUT: New session object */
  9686. );
  9687. /*
  9688. ** CAPI3REF: Delete A Session Object
  9689. **
  9690. ** Delete a session object previously allocated using
  9691. ** [sqlite3session_create()]. Once a session object has been deleted, the
  9692. ** results of attempting to use pSession with any other session module
  9693. ** function are undefined.
  9694. **
  9695. ** Session objects must be deleted before the database handle to which they
  9696. ** are attached is closed. Refer to the documentation for
  9697. ** [sqlite3session_create()] for details.
  9698. */
  9699. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  9700. /*
  9701. ** CAPI3REF: Enable Or Disable A Session Object
  9702. **
  9703. ** Enable or disable the recording of changes by a session object. When
  9704. ** enabled, a session object records changes made to the database. When
  9705. ** disabled - it does not. A newly created session object is enabled.
  9706. ** Refer to the documentation for [sqlite3session_changeset()] for further
  9707. ** details regarding how enabling and disabling a session object affects
  9708. ** the eventual changesets.
  9709. **
  9710. ** Passing zero to this function disables the session. Passing a value
  9711. ** greater than zero enables it. Passing a value less than zero is a
  9712. ** no-op, and may be used to query the current state of the session.
  9713. **
  9714. ** The return value indicates the final state of the session object: 0 if
  9715. ** the session is disabled, or 1 if it is enabled.
  9716. */
  9717. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  9718. /*
  9719. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  9720. **
  9721. ** Each change recorded by a session object is marked as either direct or
  9722. ** indirect. A change is marked as indirect if either:
  9723. **
  9724. ** <ul>
  9725. ** <li> The session object "indirect" flag is set when the change is
  9726. ** made, or
  9727. ** <li> The change is made by an SQL trigger or foreign key action
  9728. ** instead of directly as a result of a users SQL statement.
  9729. ** </ul>
  9730. **
  9731. ** If a single row is affected by more than one operation within a session,
  9732. ** then the change is considered indirect if all operations meet the criteria
  9733. ** for an indirect change above, or direct otherwise.
  9734. **
  9735. ** This function is used to set, clear or query the session object indirect
  9736. ** flag. If the second argument passed to this function is zero, then the
  9737. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  9738. ** is set. Passing a value less than zero does not modify the current value
  9739. ** of the indirect flag, and may be used to query the current state of the
  9740. ** indirect flag for the specified session object.
  9741. **
  9742. ** The return value indicates the final state of the indirect flag: 0 if
  9743. ** it is clear, or 1 if it is set.
  9744. */
  9745. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  9746. /*
  9747. ** CAPI3REF: Attach A Table To A Session Object
  9748. **
  9749. ** If argument zTab is not NULL, then it is the name of a table to attach
  9750. ** to the session object passed as the first argument. All subsequent changes
  9751. ** made to the table while the session object is enabled will be recorded. See
  9752. ** documentation for [sqlite3session_changeset()] for further details.
  9753. **
  9754. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  9755. ** in the database. If additional tables are added to the database (by
  9756. ** executing "CREATE TABLE" statements) after this call is made, changes for
  9757. ** the new tables are also recorded.
  9758. **
  9759. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  9760. ** defined as part of their CREATE TABLE statement. It does not matter if the
  9761. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  9762. ** KEY may consist of a single column, or may be a composite key.
  9763. **
  9764. ** It is not an error if the named table does not exist in the database. Nor
  9765. ** is it an error if the named table does not have a PRIMARY KEY. However,
  9766. ** no changes will be recorded in either of these scenarios.
  9767. **
  9768. ** Changes are not recorded for individual rows that have NULL values stored
  9769. ** in one or more of their PRIMARY KEY columns.
  9770. **
  9771. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  9772. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  9773. */
  9774. SQLITE_API int sqlite3session_attach(
  9775. sqlite3_session *pSession, /* Session object */
  9776. const char *zTab /* Table name */
  9777. );
  9778. /*
  9779. ** CAPI3REF: Set a table filter on a Session Object.
  9780. **
  9781. ** The second argument (xFilter) is the "filter callback". For changes to rows
  9782. ** in tables that are not attached to the Session object, the filter is called
  9783. ** to determine whether changes to the table's rows should be tracked or not.
  9784. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  9785. ** attached, xFilter will not be called again.
  9786. */
  9787. SQLITE_API void sqlite3session_table_filter(
  9788. sqlite3_session *pSession, /* Session object */
  9789. int(*xFilter)(
  9790. void *pCtx, /* Copy of third arg to _filter_table() */
  9791. const char *zTab /* Table name */
  9792. ),
  9793. void *pCtx /* First argument passed to xFilter */
  9794. );
  9795. /*
  9796. ** CAPI3REF: Generate A Changeset From A Session Object
  9797. **
  9798. ** Obtain a changeset containing changes to the tables attached to the
  9799. ** session object passed as the first argument. If successful,
  9800. ** set *ppChangeset to point to a buffer containing the changeset
  9801. ** and *pnChangeset to the size of the changeset in bytes before returning
  9802. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  9803. ** zero and return an SQLite error code.
  9804. **
  9805. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  9806. ** each representing a change to a single row of an attached table. An INSERT
  9807. ** change contains the values of each field of a new database row. A DELETE
  9808. ** contains the original values of each field of a deleted database row. An
  9809. ** UPDATE change contains the original values of each field of an updated
  9810. ** database row along with the updated values for each updated non-primary-key
  9811. ** column. It is not possible for an UPDATE change to represent a change that
  9812. ** modifies the values of primary key columns. If such a change is made, it
  9813. ** is represented in a changeset as a DELETE followed by an INSERT.
  9814. **
  9815. ** Changes are not recorded for rows that have NULL values stored in one or
  9816. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  9817. ** no corresponding change is present in the changesets returned by this
  9818. ** function. If an existing row with one or more NULL values stored in
  9819. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  9820. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  9821. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  9822. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  9823. ** DELETE change only.
  9824. **
  9825. ** The contents of a changeset may be traversed using an iterator created
  9826. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  9827. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  9828. ** API.
  9829. **
  9830. ** Within a changeset generated by this function, all changes related to a
  9831. ** single table are grouped together. In other words, when iterating through
  9832. ** a changeset or when applying a changeset to a database, all changes related
  9833. ** to a single table are processed before moving on to the next table. Tables
  9834. ** are sorted in the same order in which they were attached (or auto-attached)
  9835. ** to the sqlite3_session object. The order in which the changes related to
  9836. ** a single table are stored is undefined.
  9837. **
  9838. ** Following a successful call to this function, it is the responsibility of
  9839. ** the caller to eventually free the buffer that *ppChangeset points to using
  9840. ** [sqlite3_free()].
  9841. **
  9842. ** <h3>Changeset Generation</h3>
  9843. **
  9844. ** Once a table has been attached to a session object, the session object
  9845. ** records the primary key values of all new rows inserted into the table.
  9846. ** It also records the original primary key and other column values of any
  9847. ** deleted or updated rows. For each unique primary key value, data is only
  9848. ** recorded once - the first time a row with said primary key is inserted,
  9849. ** updated or deleted in the lifetime of the session.
  9850. **
  9851. ** There is one exception to the previous paragraph: when a row is inserted,
  9852. ** updated or deleted, if one or more of its primary key columns contain a
  9853. ** NULL value, no record of the change is made.
  9854. **
  9855. ** The session object therefore accumulates two types of records - those
  9856. ** that consist of primary key values only (created when the user inserts
  9857. ** a new record) and those that consist of the primary key values and the
  9858. ** original values of other table columns (created when the users deletes
  9859. ** or updates a record).
  9860. **
  9861. ** When this function is called, the requested changeset is created using
  9862. ** both the accumulated records and the current contents of the database
  9863. ** file. Specifically:
  9864. **
  9865. ** <ul>
  9866. ** <li> For each record generated by an insert, the database is queried
  9867. ** for a row with a matching primary key. If one is found, an INSERT
  9868. ** change is added to the changeset. If no such row is found, no change
  9869. ** is added to the changeset.
  9870. **
  9871. ** <li> For each record generated by an update or delete, the database is
  9872. ** queried for a row with a matching primary key. If such a row is
  9873. ** found and one or more of the non-primary key fields have been
  9874. ** modified from their original values, an UPDATE change is added to
  9875. ** the changeset. Or, if no such row is found in the table, a DELETE
  9876. ** change is added to the changeset. If there is a row with a matching
  9877. ** primary key in the database, but all fields contain their original
  9878. ** values, no change is added to the changeset.
  9879. ** </ul>
  9880. **
  9881. ** This means, amongst other things, that if a row is inserted and then later
  9882. ** deleted while a session object is active, neither the insert nor the delete
  9883. ** will be present in the changeset. Or if a row is deleted and then later a
  9884. ** row with the same primary key values inserted while a session object is
  9885. ** active, the resulting changeset will contain an UPDATE change instead of
  9886. ** a DELETE and an INSERT.
  9887. **
  9888. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  9889. ** it does not accumulate records when rows are inserted, updated or deleted.
  9890. ** This may appear to have some counter-intuitive effects if a single row
  9891. ** is written to more than once during a session. For example, if a row
  9892. ** is inserted while a session object is enabled, then later deleted while
  9893. ** the same session object is disabled, no INSERT record will appear in the
  9894. ** changeset, even though the delete took place while the session was disabled.
  9895. ** Or, if one field of a row is updated while a session is disabled, and
  9896. ** another field of the same row is updated while the session is enabled, the
  9897. ** resulting changeset will contain an UPDATE change that updates both fields.
  9898. */
  9899. SQLITE_API int sqlite3session_changeset(
  9900. sqlite3_session *pSession, /* Session object */
  9901. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  9902. void **ppChangeset /* OUT: Buffer containing changeset */
  9903. );
  9904. /*
  9905. ** CAPI3REF: Load The Difference Between Tables Into A Session
  9906. **
  9907. ** If it is not already attached to the session object passed as the first
  9908. ** argument, this function attaches table zTbl in the same manner as the
  9909. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  9910. ** does not have a primary key, this function is a no-op (but does not return
  9911. ** an error).
  9912. **
  9913. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  9914. ** attached to the same database handle as the session object that contains
  9915. ** a table compatible with the table attached to the session by this function.
  9916. ** A table is considered compatible if it:
  9917. **
  9918. ** <ul>
  9919. ** <li> Has the same name,
  9920. ** <li> Has the same set of columns declared in the same order, and
  9921. ** <li> Has the same PRIMARY KEY definition.
  9922. ** </ul>
  9923. **
  9924. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  9925. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  9926. ** but no changes are added to the session object. As with other session
  9927. ** APIs, tables without PRIMARY KEYs are simply ignored.
  9928. **
  9929. ** This function adds a set of changes to the session object that could be
  9930. ** used to update the table in database zFrom (call this the "from-table")
  9931. ** so that its content is the same as the table attached to the session
  9932. ** object (call this the "to-table"). Specifically:
  9933. **
  9934. ** <ul>
  9935. ** <li> For each row (primary key) that exists in the to-table but not in
  9936. ** the from-table, an INSERT record is added to the session object.
  9937. **
  9938. ** <li> For each row (primary key) that exists in the to-table but not in
  9939. ** the from-table, a DELETE record is added to the session object.
  9940. **
  9941. ** <li> For each row (primary key) that exists in both tables, but features
  9942. ** different non-PK values in each, an UPDATE record is added to the
  9943. ** session.
  9944. ** </ul>
  9945. **
  9946. ** To clarify, if this function is called and then a changeset constructed
  9947. ** using [sqlite3session_changeset()], then after applying that changeset to
  9948. ** database zFrom the contents of the two compatible tables would be
  9949. ** identical.
  9950. **
  9951. ** It an error if database zFrom does not exist or does not contain the
  9952. ** required compatible table.
  9953. **
  9954. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  9955. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  9956. ** may be set to point to a buffer containing an English language error
  9957. ** message. It is the responsibility of the caller to free this buffer using
  9958. ** sqlite3_free().
  9959. */
  9960. SQLITE_API int sqlite3session_diff(
  9961. sqlite3_session *pSession,
  9962. const char *zFromDb,
  9963. const char *zTbl,
  9964. char **pzErrMsg
  9965. );
  9966. /*
  9967. ** CAPI3REF: Generate A Patchset From A Session Object
  9968. **
  9969. ** The differences between a patchset and a changeset are that:
  9970. **
  9971. ** <ul>
  9972. ** <li> DELETE records consist of the primary key fields only. The
  9973. ** original values of other fields are omitted.
  9974. ** <li> The original values of any modified fields are omitted from
  9975. ** UPDATE records.
  9976. ** </ul>
  9977. **
  9978. ** A patchset blob may be used with up to date versions of all
  9979. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  9980. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  9981. ** attempting to use a patchset blob with old versions of the
  9982. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  9983. **
  9984. ** Because the non-primary key "old.*" fields are omitted, no
  9985. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  9986. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  9987. ** in the same way as for changesets.
  9988. **
  9989. ** Changes within a patchset are ordered in the same way as for changesets
  9990. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  9991. ** a single table are grouped together, tables appear in the order in which
  9992. ** they were attached to the session object).
  9993. */
  9994. SQLITE_API int sqlite3session_patchset(
  9995. sqlite3_session *pSession, /* Session object */
  9996. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  9997. void **ppPatchset /* OUT: Buffer containing patchset */
  9998. );
  9999. /*
  10000. ** CAPI3REF: Test if a changeset has recorded any changes.
  10001. **
  10002. ** Return non-zero if no changes to attached tables have been recorded by
  10003. ** the session object passed as the first argument. Otherwise, if one or
  10004. ** more changes have been recorded, return zero.
  10005. **
  10006. ** Even if this function returns zero, it is possible that calling
  10007. ** [sqlite3session_changeset()] on the session handle may still return a
  10008. ** changeset that contains no changes. This can happen when a row in
  10009. ** an attached table is modified and then later on the original values
  10010. ** are restored. However, if this function returns non-zero, then it is
  10011. ** guaranteed that a call to sqlite3session_changeset() will return a
  10012. ** changeset containing zero changes.
  10013. */
  10014. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10015. /*
  10016. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10017. **
  10018. ** Create an iterator used to iterate through the contents of a changeset.
  10019. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10020. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10021. ** SQLite error code is returned.
  10022. **
  10023. ** The following functions can be used to advance and query a changeset
  10024. ** iterator created by this function:
  10025. **
  10026. ** <ul>
  10027. ** <li> [sqlite3changeset_next()]
  10028. ** <li> [sqlite3changeset_op()]
  10029. ** <li> [sqlite3changeset_new()]
  10030. ** <li> [sqlite3changeset_old()]
  10031. ** </ul>
  10032. **
  10033. ** It is the responsibility of the caller to eventually destroy the iterator
  10034. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10035. ** changeset (pChangeset) must remain valid until after the iterator is
  10036. ** destroyed.
  10037. **
  10038. ** Assuming the changeset blob was created by one of the
  10039. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10040. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10041. ** that apply to a single table are grouped together. This means that when
  10042. ** an application iterates through a changeset using an iterator created by
  10043. ** this function, all changes that relate to a single table are visited
  10044. ** consecutively. There is no chance that the iterator will visit a change
  10045. ** the applies to table X, then one for table Y, and then later on visit
  10046. ** another change for table X.
  10047. */
  10048. SQLITE_API int sqlite3changeset_start(
  10049. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10050. int nChangeset, /* Size of changeset blob in bytes */
  10051. void *pChangeset /* Pointer to blob containing changeset */
  10052. );
  10053. /*
  10054. ** CAPI3REF: Advance A Changeset Iterator
  10055. **
  10056. ** This function may only be used with iterators created by function
  10057. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10058. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10059. ** is returned and the call has no effect.
  10060. **
  10061. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10062. ** does not point to any change in the changeset. Assuming the changeset
  10063. ** is not empty, the first call to this function advances the iterator to
  10064. ** point to the first change in the changeset. Each subsequent call advances
  10065. ** the iterator to point to the next change in the changeset (if any). If
  10066. ** no error occurs and the iterator points to a valid change after a call
  10067. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10068. ** Otherwise, if all changes in the changeset have already been visited,
  10069. ** SQLITE_DONE is returned.
  10070. **
  10071. ** If an error occurs, an SQLite error code is returned. Possible error
  10072. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10073. ** SQLITE_NOMEM.
  10074. */
  10075. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10076. /*
  10077. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10078. **
  10079. ** The pIter argument passed to this function may either be an iterator
  10080. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10081. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10082. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10083. ** is not the case, this function returns [SQLITE_MISUSE].
  10084. **
  10085. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10086. ** nul-terminated utf-8 encoded string containing the name of the table
  10087. ** affected by the current change. The buffer remains valid until either
  10088. ** sqlite3changeset_next() is called on the iterator or until the
  10089. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10090. ** set to the number of columns in the table affected by the change. If
  10091. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  10092. ** is an indirect change, or false (0) otherwise. See the documentation for
  10093. ** [sqlite3session_indirect()] for a description of direct and indirect
  10094. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10095. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10096. ** type of change that the iterator currently points to.
  10097. **
  10098. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10099. ** SQLite error code is returned. The values of the output variables may not
  10100. ** be trusted in this case.
  10101. */
  10102. SQLITE_API int sqlite3changeset_op(
  10103. sqlite3_changeset_iter *pIter, /* Iterator object */
  10104. const char **pzTab, /* OUT: Pointer to table name */
  10105. int *pnCol, /* OUT: Number of columns in table */
  10106. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10107. int *pbIndirect /* OUT: True for an 'indirect' change */
  10108. );
  10109. /*
  10110. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10111. **
  10112. ** For each modified table, a changeset includes the following:
  10113. **
  10114. ** <ul>
  10115. ** <li> The number of columns in the table, and
  10116. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10117. ** </ul>
  10118. **
  10119. ** This function is used to find which columns comprise the PRIMARY KEY of
  10120. ** the table modified by the change that iterator pIter currently points to.
  10121. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10122. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10123. ** 0x01 if the corresponding column is part of the tables primary key, or
  10124. ** 0x00 if it is not.
  10125. **
  10126. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10127. ** in the table.
  10128. **
  10129. ** If this function is called when the iterator does not point to a valid
  10130. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10131. ** SQLITE_OK is returned and the output variables populated as described
  10132. ** above.
  10133. */
  10134. SQLITE_API int sqlite3changeset_pk(
  10135. sqlite3_changeset_iter *pIter, /* Iterator object */
  10136. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10137. int *pnCol /* OUT: Number of entries in output array */
  10138. );
  10139. /*
  10140. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10141. **
  10142. ** The pIter argument passed to this function may either be an iterator
  10143. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10144. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10145. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10146. ** Furthermore, it may only be called if the type of change that the iterator
  10147. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10148. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10149. **
  10150. ** Argument iVal must be greater than or equal to 0, and less than the number
  10151. ** of columns in the table affected by the current change. Otherwise,
  10152. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10153. **
  10154. ** If successful, this function sets *ppValue to point to a protected
  10155. ** sqlite3_value object containing the iVal'th value from the vector of
  10156. ** original row values stored as part of the UPDATE or DELETE change and
  10157. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10158. ** is similar to the "old.*" columns available to update or delete triggers.
  10159. **
  10160. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10161. ** is returned and *ppValue is set to NULL.
  10162. */
  10163. SQLITE_API int sqlite3changeset_old(
  10164. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10165. int iVal, /* Column number */
  10166. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10167. );
  10168. /*
  10169. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10170. **
  10171. ** The pIter argument passed to this function may either be an iterator
  10172. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10173. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10174. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10175. ** Furthermore, it may only be called if the type of change that the iterator
  10176. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10177. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10178. **
  10179. ** Argument iVal must be greater than or equal to 0, and less than the number
  10180. ** of columns in the table affected by the current change. Otherwise,
  10181. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10182. **
  10183. ** If successful, this function sets *ppValue to point to a protected
  10184. ** sqlite3_value object containing the iVal'th value from the vector of
  10185. ** new row values stored as part of the UPDATE or INSERT change and
  10186. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10187. ** a new value for the requested column, *ppValue is set to NULL and
  10188. ** SQLITE_OK returned. The name of the function comes from the fact that
  10189. ** this is similar to the "new.*" columns available to update or delete
  10190. ** triggers.
  10191. **
  10192. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10193. ** is returned and *ppValue is set to NULL.
  10194. */
  10195. SQLITE_API int sqlite3changeset_new(
  10196. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10197. int iVal, /* Column number */
  10198. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10199. );
  10200. /*
  10201. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10202. **
  10203. ** This function should only be used with iterator objects passed to a
  10204. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10205. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10206. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10207. ** is set to NULL.
  10208. **
  10209. ** Argument iVal must be greater than or equal to 0, and less than the number
  10210. ** of columns in the table affected by the current change. Otherwise,
  10211. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10212. **
  10213. ** If successful, this function sets *ppValue to point to a protected
  10214. ** sqlite3_value object containing the iVal'th value from the
  10215. ** "conflicting row" associated with the current conflict-handler callback
  10216. ** and returns SQLITE_OK.
  10217. **
  10218. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10219. ** is returned and *ppValue is set to NULL.
  10220. */
  10221. SQLITE_API int sqlite3changeset_conflict(
  10222. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10223. int iVal, /* Column number */
  10224. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  10225. );
  10226. /*
  10227. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  10228. **
  10229. ** This function may only be called with an iterator passed to an
  10230. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  10231. ** it sets the output variable to the total number of known foreign key
  10232. ** violations in the destination database and returns SQLITE_OK.
  10233. **
  10234. ** In all other cases this function returns SQLITE_MISUSE.
  10235. */
  10236. SQLITE_API int sqlite3changeset_fk_conflicts(
  10237. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10238. int *pnOut /* OUT: Number of FK violations */
  10239. );
  10240. /*
  10241. ** CAPI3REF: Finalize A Changeset Iterator
  10242. **
  10243. ** This function is used to finalize an iterator allocated with
  10244. ** [sqlite3changeset_start()].
  10245. **
  10246. ** This function should only be called on iterators created using the
  10247. ** [sqlite3changeset_start()] function. If an application calls this
  10248. ** function with an iterator passed to a conflict-handler by
  10249. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  10250. ** call has no effect.
  10251. **
  10252. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  10253. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  10254. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  10255. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  10256. ** returned. This is to allow the following pattern (pseudo-code):
  10257. **
  10258. ** sqlite3changeset_start();
  10259. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  10260. ** // Do something with change.
  10261. ** }
  10262. ** rc = sqlite3changeset_finalize();
  10263. ** if( rc!=SQLITE_OK ){
  10264. ** // An error has occurred
  10265. ** }
  10266. */
  10267. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  10268. /*
  10269. ** CAPI3REF: Invert A Changeset
  10270. **
  10271. ** This function is used to "invert" a changeset object. Applying an inverted
  10272. ** changeset to a database reverses the effects of applying the uninverted
  10273. ** changeset. Specifically:
  10274. **
  10275. ** <ul>
  10276. ** <li> Each DELETE change is changed to an INSERT, and
  10277. ** <li> Each INSERT change is changed to a DELETE, and
  10278. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  10279. ** </ul>
  10280. **
  10281. ** This function does not change the order in which changes appear within
  10282. ** the changeset. It merely reverses the sense of each individual change.
  10283. **
  10284. ** If successful, a pointer to a buffer containing the inverted changeset
  10285. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  10286. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  10287. ** zeroed and an SQLite error code returned.
  10288. **
  10289. ** It is the responsibility of the caller to eventually call sqlite3_free()
  10290. ** on the *ppOut pointer to free the buffer allocation following a successful
  10291. ** call to this function.
  10292. **
  10293. ** WARNING/TODO: This function currently assumes that the input is a valid
  10294. ** changeset. If it is not, the results are undefined.
  10295. */
  10296. SQLITE_API int sqlite3changeset_invert(
  10297. int nIn, const void *pIn, /* Input changeset */
  10298. int *pnOut, void **ppOut /* OUT: Inverse of input */
  10299. );
  10300. /*
  10301. ** CAPI3REF: Concatenate Two Changeset Objects
  10302. **
  10303. ** This function is used to concatenate two changesets, A and B, into a
  10304. ** single changeset. The result is a changeset equivalent to applying
  10305. ** changeset A followed by changeset B.
  10306. **
  10307. ** This function combines the two input changesets using an
  10308. ** sqlite3_changegroup object. Calling it produces similar results as the
  10309. ** following code fragment:
  10310. **
  10311. ** sqlite3_changegroup *pGrp;
  10312. ** rc = sqlite3_changegroup_new(&pGrp);
  10313. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  10314. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  10315. ** if( rc==SQLITE_OK ){
  10316. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  10317. ** }else{
  10318. ** *ppOut = 0;
  10319. ** *pnOut = 0;
  10320. ** }
  10321. **
  10322. ** Refer to the sqlite3_changegroup documentation below for details.
  10323. */
  10324. SQLITE_API int sqlite3changeset_concat(
  10325. int nA, /* Number of bytes in buffer pA */
  10326. void *pA, /* Pointer to buffer containing changeset A */
  10327. int nB, /* Number of bytes in buffer pB */
  10328. void *pB, /* Pointer to buffer containing changeset B */
  10329. int *pnOut, /* OUT: Number of bytes in output changeset */
  10330. void **ppOut /* OUT: Buffer containing output changeset */
  10331. );
  10332. /*
  10333. ** CAPI3REF: Changegroup Handle
  10334. */
  10335. typedef struct sqlite3_changegroup sqlite3_changegroup;
  10336. /*
  10337. ** CAPI3REF: Create A New Changegroup Object
  10338. **
  10339. ** An sqlite3_changegroup object is used to combine two or more changesets
  10340. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  10341. ** object may combine changesets or patchsets, but not both. The output is
  10342. ** always in the same format as the input.
  10343. **
  10344. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  10345. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  10346. ** should eventually free the returned object using a call to
  10347. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  10348. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  10349. **
  10350. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  10351. **
  10352. ** <ul>
  10353. ** <li> It is created using a call to sqlite3changegroup_new().
  10354. **
  10355. ** <li> Zero or more changesets (or patchsets) are added to the object
  10356. ** by calling sqlite3changegroup_add().
  10357. **
  10358. ** <li> The result of combining all input changesets together is obtained
  10359. ** by the application via a call to sqlite3changegroup_output().
  10360. **
  10361. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  10362. ** </ul>
  10363. **
  10364. ** Any number of calls to add() and output() may be made between the calls to
  10365. ** new() and delete(), and in any order.
  10366. **
  10367. ** As well as the regular sqlite3changegroup_add() and
  10368. ** sqlite3changegroup_output() functions, also available are the streaming
  10369. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  10370. */
  10371. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  10372. /*
  10373. ** CAPI3REF: Add A Changeset To A Changegroup
  10374. **
  10375. ** Add all changes within the changeset (or patchset) in buffer pData (size
  10376. ** nData bytes) to the changegroup.
  10377. **
  10378. ** If the buffer contains a patchset, then all prior calls to this function
  10379. ** on the same changegroup object must also have specified patchsets. Or, if
  10380. ** the buffer contains a changeset, so must have the earlier calls to this
  10381. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  10382. ** to the changegroup.
  10383. **
  10384. ** Rows within the changeset and changegroup are identified by the values in
  10385. ** their PRIMARY KEY columns. A change in the changeset is considered to
  10386. ** apply to the same row as a change already present in the changegroup if
  10387. ** the two rows have the same primary key.
  10388. **
  10389. ** Changes to rows that do not already appear in the changegroup are
  10390. ** simply copied into it. Or, if both the new changeset and the changegroup
  10391. ** contain changes that apply to a single row, the final contents of the
  10392. ** changegroup depends on the type of each change, as follows:
  10393. **
  10394. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  10395. ** <tr><th style="white-space:pre">Existing Change </th>
  10396. ** <th style="white-space:pre">New Change </th>
  10397. ** <th>Output Change
  10398. ** <tr><td>INSERT <td>INSERT <td>
  10399. ** The new change is ignored. This case does not occur if the new
  10400. ** changeset was recorded immediately after the changesets already
  10401. ** added to the changegroup.
  10402. ** <tr><td>INSERT <td>UPDATE <td>
  10403. ** The INSERT change remains in the changegroup. The values in the
  10404. ** INSERT change are modified as if the row was inserted by the
  10405. ** existing change and then updated according to the new change.
  10406. ** <tr><td>INSERT <td>DELETE <td>
  10407. ** The existing INSERT is removed from the changegroup. The DELETE is
  10408. ** not added.
  10409. ** <tr><td>UPDATE <td>INSERT <td>
  10410. ** The new change is ignored. This case does not occur if the new
  10411. ** changeset was recorded immediately after the changesets already
  10412. ** added to the changegroup.
  10413. ** <tr><td>UPDATE <td>UPDATE <td>
  10414. ** The existing UPDATE remains within the changegroup. It is amended
  10415. ** so that the accompanying values are as if the row was updated once
  10416. ** by the existing change and then again by the new change.
  10417. ** <tr><td>UPDATE <td>DELETE <td>
  10418. ** The existing UPDATE is replaced by the new DELETE within the
  10419. ** changegroup.
  10420. ** <tr><td>DELETE <td>INSERT <td>
  10421. ** If one or more of the column values in the row inserted by the
  10422. ** new change differ from those in the row deleted by the existing
  10423. ** change, the existing DELETE is replaced by an UPDATE within the
  10424. ** changegroup. Otherwise, if the inserted row is exactly the same
  10425. ** as the deleted row, the existing DELETE is simply discarded.
  10426. ** <tr><td>DELETE <td>UPDATE <td>
  10427. ** The new change is ignored. This case does not occur if the new
  10428. ** changeset was recorded immediately after the changesets already
  10429. ** added to the changegroup.
  10430. ** <tr><td>DELETE <td>DELETE <td>
  10431. ** The new change is ignored. This case does not occur if the new
  10432. ** changeset was recorded immediately after the changesets already
  10433. ** added to the changegroup.
  10434. ** </table>
  10435. **
  10436. ** If the new changeset contains changes to a table that is already present
  10437. ** in the changegroup, then the number of columns and the position of the
  10438. ** primary key columns for the table must be consistent. If this is not the
  10439. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  10440. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  10441. ** returned. Or, if an out-of-memory condition occurs during processing, this
  10442. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  10443. ** final contents of the changegroup is undefined.
  10444. **
  10445. ** If no error occurs, SQLITE_OK is returned.
  10446. */
  10447. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  10448. /*
  10449. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  10450. **
  10451. ** Obtain a buffer containing a changeset (or patchset) representing the
  10452. ** current contents of the changegroup. If the inputs to the changegroup
  10453. ** were themselves changesets, the output is a changeset. Or, if the
  10454. ** inputs were patchsets, the output is also a patchset.
  10455. **
  10456. ** As with the output of the sqlite3session_changeset() and
  10457. ** sqlite3session_patchset() functions, all changes related to a single
  10458. ** table are grouped together in the output of this function. Tables appear
  10459. ** in the same order as for the very first changeset added to the changegroup.
  10460. ** If the second or subsequent changesets added to the changegroup contain
  10461. ** changes for tables that do not appear in the first changeset, they are
  10462. ** appended onto the end of the output changeset, again in the order in
  10463. ** which they are first encountered.
  10464. **
  10465. ** If an error occurs, an SQLite error code is returned and the output
  10466. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  10467. ** is returned and the output variables are set to the size of and a
  10468. ** pointer to the output buffer, respectively. In this case it is the
  10469. ** responsibility of the caller to eventually free the buffer using a
  10470. ** call to sqlite3_free().
  10471. */
  10472. SQLITE_API int sqlite3changegroup_output(
  10473. sqlite3_changegroup*,
  10474. int *pnData, /* OUT: Size of output buffer in bytes */
  10475. void **ppData /* OUT: Pointer to output buffer */
  10476. );
  10477. /*
  10478. ** CAPI3REF: Delete A Changegroup Object
  10479. */
  10480. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  10481. /*
  10482. ** CAPI3REF: Apply A Changeset To A Database
  10483. **
  10484. ** Apply a changeset to a database. This function attempts to update the
  10485. ** "main" database attached to handle db with the changes found in the
  10486. ** changeset passed via the second and third arguments.
  10487. **
  10488. ** The fourth argument (xFilter) passed to this function is the "filter
  10489. ** callback". If it is not NULL, then for each table affected by at least one
  10490. ** change in the changeset, the filter callback is invoked with
  10491. ** the table name as the second argument, and a copy of the context pointer
  10492. ** passed as the sixth argument to this function as the first. If the "filter
  10493. ** callback" returns zero, then no attempt is made to apply any changes to
  10494. ** the table. Otherwise, if the return value is non-zero or the xFilter
  10495. ** argument to this function is NULL, all changes related to the table are
  10496. ** attempted.
  10497. **
  10498. ** For each table that is not excluded by the filter callback, this function
  10499. ** tests that the target database contains a compatible table. A table is
  10500. ** considered compatible if all of the following are true:
  10501. **
  10502. ** <ul>
  10503. ** <li> The table has the same name as the name recorded in the
  10504. ** changeset, and
  10505. ** <li> The table has at least as many columns as recorded in the
  10506. ** changeset, and
  10507. ** <li> The table has primary key columns in the same position as
  10508. ** recorded in the changeset.
  10509. ** </ul>
  10510. **
  10511. ** If there is no compatible table, it is not an error, but none of the
  10512. ** changes associated with the table are applied. A warning message is issued
  10513. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  10514. ** one such warning is issued for each table in the changeset.
  10515. **
  10516. ** For each change for which there is a compatible table, an attempt is made
  10517. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  10518. ** change. If a change cannot be applied cleanly, the conflict handler
  10519. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  10520. ** invoked. A description of exactly when the conflict handler is invoked for
  10521. ** each type of change is below.
  10522. **
  10523. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  10524. ** of passing anything other than a valid function pointer as the xConflict
  10525. ** argument are undefined.
  10526. **
  10527. ** Each time the conflict handler function is invoked, it must return one
  10528. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  10529. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  10530. ** if the second argument passed to the conflict handler is either
  10531. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  10532. ** returns an illegal value, any changes already made are rolled back and
  10533. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  10534. ** actions are taken by sqlite3changeset_apply() depending on the value
  10535. ** returned by each invocation of the conflict-handler function. Refer to
  10536. ** the documentation for the three
  10537. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  10538. **
  10539. ** <dl>
  10540. ** <dt>DELETE Changes<dd>
  10541. ** For each DELETE change, this function checks if the target database
  10542. ** contains a row with the same primary key value (or values) as the
  10543. ** original row values stored in the changeset. If it does, and the values
  10544. ** stored in all non-primary key columns also match the values stored in
  10545. ** the changeset the row is deleted from the target database.
  10546. **
  10547. ** If a row with matching primary key values is found, but one or more of
  10548. ** the non-primary key fields contains a value different from the original
  10549. ** row value stored in the changeset, the conflict-handler function is
  10550. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  10551. ** database table has more columns than are recorded in the changeset,
  10552. ** only the values of those non-primary key fields are compared against
  10553. ** the current database contents - any trailing database table columns
  10554. ** are ignored.
  10555. **
  10556. ** If no row with matching primary key values is found in the database,
  10557. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  10558. ** passed as the second argument.
  10559. **
  10560. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  10561. ** (which can only happen if a foreign key constraint is violated), the
  10562. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  10563. ** passed as the second argument. This includes the case where the DELETE
  10564. ** operation is attempted because an earlier call to the conflict handler
  10565. ** function returned [SQLITE_CHANGESET_REPLACE].
  10566. **
  10567. ** <dt>INSERT Changes<dd>
  10568. ** For each INSERT change, an attempt is made to insert the new row into
  10569. ** the database. If the changeset row contains fewer fields than the
  10570. ** database table, the trailing fields are populated with their default
  10571. ** values.
  10572. **
  10573. ** If the attempt to insert the row fails because the database already
  10574. ** contains a row with the same primary key values, the conflict handler
  10575. ** function is invoked with the second argument set to
  10576. ** [SQLITE_CHANGESET_CONFLICT].
  10577. **
  10578. ** If the attempt to insert the row fails because of some other constraint
  10579. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  10580. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  10581. ** This includes the case where the INSERT operation is re-attempted because
  10582. ** an earlier call to the conflict handler function returned
  10583. ** [SQLITE_CHANGESET_REPLACE].
  10584. **
  10585. ** <dt>UPDATE Changes<dd>
  10586. ** For each UPDATE change, this function checks if the target database
  10587. ** contains a row with the same primary key value (or values) as the
  10588. ** original row values stored in the changeset. If it does, and the values
  10589. ** stored in all modified non-primary key columns also match the values
  10590. ** stored in the changeset the row is updated within the target database.
  10591. **
  10592. ** If a row with matching primary key values is found, but one or more of
  10593. ** the modified non-primary key fields contains a value different from an
  10594. ** original row value stored in the changeset, the conflict-handler function
  10595. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  10596. ** UPDATE changes only contain values for non-primary key fields that are
  10597. ** to be modified, only those fields need to match the original values to
  10598. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  10599. **
  10600. ** If no row with matching primary key values is found in the database,
  10601. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  10602. ** passed as the second argument.
  10603. **
  10604. ** If the UPDATE operation is attempted, but SQLite returns
  10605. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  10606. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  10607. ** This includes the case where the UPDATE operation is attempted after
  10608. ** an earlier call to the conflict handler function returned
  10609. ** [SQLITE_CHANGESET_REPLACE].
  10610. ** </dl>
  10611. **
  10612. ** It is safe to execute SQL statements, including those that write to the
  10613. ** table that the callback related to, from within the xConflict callback.
  10614. ** This can be used to further customize the applications conflict
  10615. ** resolution strategy.
  10616. **
  10617. ** All changes made by this function are enclosed in a savepoint transaction.
  10618. ** If any other error (aside from a constraint failure when attempting to
  10619. ** write to the target database) occurs, then the savepoint transaction is
  10620. ** rolled back, restoring the target database to its original state, and an
  10621. ** SQLite error code returned.
  10622. */
  10623. SQLITE_API int sqlite3changeset_apply(
  10624. sqlite3 *db, /* Apply change to "main" db of this handle */
  10625. int nChangeset, /* Size of changeset in bytes */
  10626. void *pChangeset, /* Changeset blob */
  10627. int(*xFilter)(
  10628. void *pCtx, /* Copy of sixth arg to _apply() */
  10629. const char *zTab /* Table name */
  10630. ),
  10631. int(*xConflict)(
  10632. void *pCtx, /* Copy of sixth arg to _apply() */
  10633. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  10634. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  10635. ),
  10636. void *pCtx /* First argument passed to xConflict */
  10637. );
  10638. /*
  10639. ** CAPI3REF: Constants Passed To The Conflict Handler
  10640. **
  10641. ** Values that may be passed as the second argument to a conflict-handler.
  10642. **
  10643. ** <dl>
  10644. ** <dt>SQLITE_CHANGESET_DATA<dd>
  10645. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  10646. ** when processing a DELETE or UPDATE change if a row with the required
  10647. ** PRIMARY KEY fields is present in the database, but one or more other
  10648. ** (non primary-key) fields modified by the update do not contain the
  10649. ** expected "before" values.
  10650. **
  10651. ** The conflicting row, in this case, is the database row with the matching
  10652. ** primary key.
  10653. **
  10654. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  10655. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  10656. ** argument when processing a DELETE or UPDATE change if a row with the
  10657. ** required PRIMARY KEY fields is not present in the database.
  10658. **
  10659. ** There is no conflicting row in this case. The results of invoking the
  10660. ** sqlite3changeset_conflict() API are undefined.
  10661. **
  10662. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  10663. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  10664. ** handler while processing an INSERT change if the operation would result
  10665. ** in duplicate primary key values.
  10666. **
  10667. ** The conflicting row in this case is the database row with the matching
  10668. ** primary key.
  10669. **
  10670. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  10671. ** If foreign key handling is enabled, and applying a changeset leaves the
  10672. ** database in a state containing foreign key violations, the conflict
  10673. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  10674. ** exactly once before the changeset is committed. If the conflict handler
  10675. ** returns CHANGESET_OMIT, the changes, including those that caused the
  10676. ** foreign key constraint violation, are committed. Or, if it returns
  10677. ** CHANGESET_ABORT, the changeset is rolled back.
  10678. **
  10679. ** No current or conflicting row information is provided. The only function
  10680. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  10681. ** is sqlite3changeset_fk_conflicts().
  10682. **
  10683. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  10684. ** If any other constraint violation occurs while applying a change (i.e.
  10685. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  10686. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  10687. **
  10688. ** There is no conflicting row in this case. The results of invoking the
  10689. ** sqlite3changeset_conflict() API are undefined.
  10690. **
  10691. ** </dl>
  10692. */
  10693. #define SQLITE_CHANGESET_DATA 1
  10694. #define SQLITE_CHANGESET_NOTFOUND 2
  10695. #define SQLITE_CHANGESET_CONFLICT 3
  10696. #define SQLITE_CHANGESET_CONSTRAINT 4
  10697. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  10698. /*
  10699. ** CAPI3REF: Constants Returned By The Conflict Handler
  10700. **
  10701. ** A conflict handler callback must return one of the following three values.
  10702. **
  10703. ** <dl>
  10704. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  10705. ** If a conflict handler returns this value no special action is taken. The
  10706. ** change that caused the conflict is not applied. The session module
  10707. ** continues to the next change in the changeset.
  10708. **
  10709. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  10710. ** This value may only be returned if the second argument to the conflict
  10711. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  10712. ** is not the case, any changes applied so far are rolled back and the
  10713. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  10714. **
  10715. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  10716. ** handler, then the conflicting row is either updated or deleted, depending
  10717. ** on the type of change.
  10718. **
  10719. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  10720. ** handler, then the conflicting row is removed from the database and a
  10721. ** second attempt to apply the change is made. If this second attempt fails,
  10722. ** the original row is restored to the database before continuing.
  10723. **
  10724. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  10725. ** If this value is returned, any changes applied so far are rolled back
  10726. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  10727. ** </dl>
  10728. */
  10729. #define SQLITE_CHANGESET_OMIT 0
  10730. #define SQLITE_CHANGESET_REPLACE 1
  10731. #define SQLITE_CHANGESET_ABORT 2
  10732. /*
  10733. ** CAPI3REF: Streaming Versions of API functions.
  10734. **
  10735. ** The six streaming API xxx_strm() functions serve similar purposes to the
  10736. ** corresponding non-streaming API functions:
  10737. **
  10738. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  10739. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  10740. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  10741. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  10742. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  10743. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  10744. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  10745. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  10746. ** </table>
  10747. **
  10748. ** Non-streaming functions that accept changesets (or patchsets) as input
  10749. ** require that the entire changeset be stored in a single buffer in memory.
  10750. ** Similarly, those that return a changeset or patchset do so by returning
  10751. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  10752. ** Normally this is convenient. However, if an application running in a
  10753. ** low-memory environment is required to handle very large changesets, the
  10754. ** large contiguous memory allocations required can become onerous.
  10755. **
  10756. ** In order to avoid this problem, instead of a single large buffer, input
  10757. ** is passed to a streaming API functions by way of a callback function that
  10758. ** the sessions module invokes to incrementally request input data as it is
  10759. ** required. In all cases, a pair of API function parameters such as
  10760. **
  10761. ** <pre>
  10762. ** &nbsp; int nChangeset,
  10763. ** &nbsp; void *pChangeset,
  10764. ** </pre>
  10765. **
  10766. ** Is replaced by:
  10767. **
  10768. ** <pre>
  10769. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  10770. ** &nbsp; void *pIn,
  10771. ** </pre>
  10772. **
  10773. ** Each time the xInput callback is invoked by the sessions module, the first
  10774. ** argument passed is a copy of the supplied pIn context pointer. The second
  10775. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  10776. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  10777. ** into the buffer and set (*pnData) to the actual number of bytes copied
  10778. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  10779. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  10780. ** error code should be returned. In all cases, if an xInput callback returns
  10781. ** an error, all processing is abandoned and the streaming API function
  10782. ** returns a copy of the error code to the caller.
  10783. **
  10784. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  10785. ** invoked by the sessions module at any point during the lifetime of the
  10786. ** iterator. If such an xInput callback returns an error, the iterator enters
  10787. ** an error state, whereby all subsequent calls to iterator functions
  10788. ** immediately fail with the same error code as returned by xInput.
  10789. **
  10790. ** Similarly, streaming API functions that return changesets (or patchsets)
  10791. ** return them in chunks by way of a callback function instead of via a
  10792. ** pointer to a single large buffer. In this case, a pair of parameters such
  10793. ** as:
  10794. **
  10795. ** <pre>
  10796. ** &nbsp; int *pnChangeset,
  10797. ** &nbsp; void **ppChangeset,
  10798. ** </pre>
  10799. **
  10800. ** Is replaced by:
  10801. **
  10802. ** <pre>
  10803. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  10804. ** &nbsp; void *pOut
  10805. ** </pre>
  10806. **
  10807. ** The xOutput callback is invoked zero or more times to return data to
  10808. ** the application. The first parameter passed to each call is a copy of the
  10809. ** pOut pointer supplied by the application. The second parameter, pData,
  10810. ** points to a buffer nData bytes in size containing the chunk of output
  10811. ** data being returned. If the xOutput callback successfully processes the
  10812. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  10813. ** it should return some other SQLite error code. In this case processing
  10814. ** is immediately abandoned and the streaming API function returns a copy
  10815. ** of the xOutput error code to the application.
  10816. **
  10817. ** The sessions module never invokes an xOutput callback with the third
  10818. ** parameter set to a value less than or equal to zero. Other than this,
  10819. ** no guarantees are made as to the size of the chunks of data returned.
  10820. */
  10821. SQLITE_API int sqlite3changeset_apply_strm(
  10822. sqlite3 *db, /* Apply change to "main" db of this handle */
  10823. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  10824. void *pIn, /* First arg for xInput */
  10825. int(*xFilter)(
  10826. void *pCtx, /* Copy of sixth arg to _apply() */
  10827. const char *zTab /* Table name */
  10828. ),
  10829. int(*xConflict)(
  10830. void *pCtx, /* Copy of sixth arg to _apply() */
  10831. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  10832. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  10833. ),
  10834. void *pCtx /* First argument passed to xConflict */
  10835. );
  10836. SQLITE_API int sqlite3changeset_concat_strm(
  10837. int (*xInputA)(void *pIn, void *pData, int *pnData),
  10838. void *pInA,
  10839. int (*xInputB)(void *pIn, void *pData, int *pnData),
  10840. void *pInB,
  10841. int (*xOutput)(void *pOut, const void *pData, int nData),
  10842. void *pOut
  10843. );
  10844. SQLITE_API int sqlite3changeset_invert_strm(
  10845. int (*xInput)(void *pIn, void *pData, int *pnData),
  10846. void *pIn,
  10847. int (*xOutput)(void *pOut, const void *pData, int nData),
  10848. void *pOut
  10849. );
  10850. SQLITE_API int sqlite3changeset_start_strm(
  10851. sqlite3_changeset_iter **pp,
  10852. int (*xInput)(void *pIn, void *pData, int *pnData),
  10853. void *pIn
  10854. );
  10855. SQLITE_API int sqlite3session_changeset_strm(
  10856. sqlite3_session *pSession,
  10857. int (*xOutput)(void *pOut, const void *pData, int nData),
  10858. void *pOut
  10859. );
  10860. SQLITE_API int sqlite3session_patchset_strm(
  10861. sqlite3_session *pSession,
  10862. int (*xOutput)(void *pOut, const void *pData, int nData),
  10863. void *pOut
  10864. );
  10865. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  10866. int (*xInput)(void *pIn, void *pData, int *pnData),
  10867. void *pIn
  10868. );
  10869. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  10870. int (*xOutput)(void *pOut, const void *pData, int nData),
  10871. void *pOut
  10872. );
  10873. /*
  10874. ** Make sure we can call this stuff from C++.
  10875. */
  10876. #if 0
  10877. }
  10878. #endif
  10879. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  10880. /******** End of sqlite3session.h *********/
  10881. /******** Begin file fts5.h *********/
  10882. /*
  10883. ** 2014 May 31
  10884. **
  10885. ** The author disclaims copyright to this source code. In place of
  10886. ** a legal notice, here is a blessing:
  10887. **
  10888. ** May you do good and not evil.
  10889. ** May you find forgiveness for yourself and forgive others.
  10890. ** May you share freely, never taking more than you give.
  10891. **
  10892. ******************************************************************************
  10893. **
  10894. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  10895. ** FTS5 may be extended with:
  10896. **
  10897. ** * custom tokenizers, and
  10898. ** * custom auxiliary functions.
  10899. */
  10900. #ifndef _FTS5_H
  10901. #define _FTS5_H
  10902. #if 0
  10903. extern "C" {
  10904. #endif
  10905. /*************************************************************************
  10906. ** CUSTOM AUXILIARY FUNCTIONS
  10907. **
  10908. ** Virtual table implementations may overload SQL functions by implementing
  10909. ** the sqlite3_module.xFindFunction() method.
  10910. */
  10911. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  10912. typedef struct Fts5Context Fts5Context;
  10913. typedef struct Fts5PhraseIter Fts5PhraseIter;
  10914. typedef void (*fts5_extension_function)(
  10915. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  10916. Fts5Context *pFts, /* First arg to pass to pApi functions */
  10917. sqlite3_context *pCtx, /* Context for returning result/error */
  10918. int nVal, /* Number of values in apVal[] array */
  10919. sqlite3_value **apVal /* Array of trailing arguments */
  10920. );
  10921. struct Fts5PhraseIter {
  10922. const unsigned char *a;
  10923. const unsigned char *b;
  10924. };
  10925. /*
  10926. ** EXTENSION API FUNCTIONS
  10927. **
  10928. ** xUserData(pFts):
  10929. ** Return a copy of the context pointer the extension function was
  10930. ** registered with.
  10931. **
  10932. ** xColumnTotalSize(pFts, iCol, pnToken):
  10933. ** If parameter iCol is less than zero, set output variable *pnToken
  10934. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  10935. ** non-negative but less than the number of columns in the table, return
  10936. ** the total number of tokens in column iCol, considering all rows in
  10937. ** the FTS5 table.
  10938. **
  10939. ** If parameter iCol is greater than or equal to the number of columns
  10940. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  10941. ** an OOM condition or IO error), an appropriate SQLite error code is
  10942. ** returned.
  10943. **
  10944. ** xColumnCount(pFts):
  10945. ** Return the number of columns in the table.
  10946. **
  10947. ** xColumnSize(pFts, iCol, pnToken):
  10948. ** If parameter iCol is less than zero, set output variable *pnToken
  10949. ** to the total number of tokens in the current row. Or, if iCol is
  10950. ** non-negative but less than the number of columns in the table, set
  10951. ** *pnToken to the number of tokens in column iCol of the current row.
  10952. **
  10953. ** If parameter iCol is greater than or equal to the number of columns
  10954. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  10955. ** an OOM condition or IO error), an appropriate SQLite error code is
  10956. ** returned.
  10957. **
  10958. ** This function may be quite inefficient if used with an FTS5 table
  10959. ** created with the "columnsize=0" option.
  10960. **
  10961. ** xColumnText:
  10962. ** This function attempts to retrieve the text of column iCol of the
  10963. ** current document. If successful, (*pz) is set to point to a buffer
  10964. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  10965. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  10966. ** if an error occurs, an SQLite error code is returned and the final values
  10967. ** of (*pz) and (*pn) are undefined.
  10968. **
  10969. ** xPhraseCount:
  10970. ** Returns the number of phrases in the current query expression.
  10971. **
  10972. ** xPhraseSize:
  10973. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  10974. ** are numbered starting from zero.
  10975. **
  10976. ** xInstCount:
  10977. ** Set *pnInst to the total number of occurrences of all phrases within
  10978. ** the query within the current row. Return SQLITE_OK if successful, or
  10979. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  10980. **
  10981. ** This API can be quite slow if used with an FTS5 table created with the
  10982. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  10983. ** with either "detail=none" or "detail=column" and "content=" option
  10984. ** (i.e. if it is a contentless table), then this API always returns 0.
  10985. **
  10986. ** xInst:
  10987. ** Query for the details of phrase match iIdx within the current row.
  10988. ** Phrase matches are numbered starting from zero, so the iIdx argument
  10989. ** should be greater than or equal to zero and smaller than the value
  10990. ** output by xInstCount().
  10991. **
  10992. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  10993. ** to the column in which it occurs and *piOff the token offset of the
  10994. ** first token of the phrase. The exception is if the table was created
  10995. ** with the offsets=0 option specified. In this case *piOff is always
  10996. ** set to -1.
  10997. **
  10998. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  10999. ** if an error occurs.
  11000. **
  11001. ** This API can be quite slow if used with an FTS5 table created with the
  11002. ** "detail=none" or "detail=column" option.
  11003. **
  11004. ** xRowid:
  11005. ** Returns the rowid of the current row.
  11006. **
  11007. ** xTokenize:
  11008. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  11009. **
  11010. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  11011. ** This API function is used to query the FTS table for phrase iPhrase
  11012. ** of the current query. Specifically, a query equivalent to:
  11013. **
  11014. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  11015. **
  11016. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  11017. ** current query is executed. Any column filter that applies to
  11018. ** phrase iPhrase of the current query is included in $p. For each
  11019. ** row visited, the callback function passed as the fourth argument
  11020. ** is invoked. The context and API objects passed to the callback
  11021. ** function may be used to access the properties of each matched row.
  11022. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  11023. ** the third argument to pUserData.
  11024. **
  11025. ** If the callback function returns any value other than SQLITE_OK, the
  11026. ** query is abandoned and the xQueryPhrase function returns immediately.
  11027. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  11028. ** Otherwise, the error code is propagated upwards.
  11029. **
  11030. ** If the query runs to completion without incident, SQLITE_OK is returned.
  11031. ** Or, if some error occurs before the query completes or is aborted by
  11032. ** the callback, an SQLite error code is returned.
  11033. **
  11034. **
  11035. ** xSetAuxdata(pFts5, pAux, xDelete)
  11036. **
  11037. ** Save the pointer passed as the second argument as the extension functions
  11038. ** "auxiliary data". The pointer may then be retrieved by the current or any
  11039. ** future invocation of the same fts5 extension function made as part of
  11040. ** of the same MATCH query using the xGetAuxdata() API.
  11041. **
  11042. ** Each extension function is allocated a single auxiliary data slot for
  11043. ** each FTS query (MATCH expression). If the extension function is invoked
  11044. ** more than once for a single FTS query, then all invocations share a
  11045. ** single auxiliary data context.
  11046. **
  11047. ** If there is already an auxiliary data pointer when this function is
  11048. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  11049. ** was specified along with the original pointer, it is invoked at this
  11050. ** point.
  11051. **
  11052. ** The xDelete callback, if one is specified, is also invoked on the
  11053. ** auxiliary data pointer after the FTS5 query has finished.
  11054. **
  11055. ** If an error (e.g. an OOM condition) occurs within this function, an
  11056. ** the auxiliary data is set to NULL and an error code returned. If the
  11057. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  11058. ** pointer before returning.
  11059. **
  11060. **
  11061. ** xGetAuxdata(pFts5, bClear)
  11062. **
  11063. ** Returns the current auxiliary data pointer for the fts5 extension
  11064. ** function. See the xSetAuxdata() method for details.
  11065. **
  11066. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  11067. ** (set to NULL) before this function returns. In this case the xDelete,
  11068. ** if any, is not invoked.
  11069. **
  11070. **
  11071. ** xRowCount(pFts5, pnRow)
  11072. **
  11073. ** This function is used to retrieve the total number of rows in the table.
  11074. ** In other words, the same value that would be returned by:
  11075. **
  11076. ** SELECT count(*) FROM ftstable;
  11077. **
  11078. ** xPhraseFirst()
  11079. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  11080. ** method, to iterate through all instances of a single query phrase within
  11081. ** the current row. This is the same information as is accessible via the
  11082. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  11083. ** to use, this API may be faster under some circumstances. To iterate
  11084. ** through instances of phrase iPhrase, use the following code:
  11085. **
  11086. ** Fts5PhraseIter iter;
  11087. ** int iCol, iOff;
  11088. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  11089. ** iCol>=0;
  11090. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  11091. ** ){
  11092. ** // An instance of phrase iPhrase at offset iOff of column iCol
  11093. ** }
  11094. **
  11095. ** The Fts5PhraseIter structure is defined above. Applications should not
  11096. ** modify this structure directly - it should only be used as shown above
  11097. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  11098. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  11099. **
  11100. ** This API can be quite slow if used with an FTS5 table created with the
  11101. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11102. ** with either "detail=none" or "detail=column" and "content=" option
  11103. ** (i.e. if it is a contentless table), then this API always iterates
  11104. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  11105. **
  11106. ** xPhraseNext()
  11107. ** See xPhraseFirst above.
  11108. **
  11109. ** xPhraseFirstColumn()
  11110. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  11111. ** and xPhraseNext() APIs described above. The difference is that instead
  11112. ** of iterating through all instances of a phrase in the current row, these
  11113. ** APIs are used to iterate through the set of columns in the current row
  11114. ** that contain one or more instances of a specified phrase. For example:
  11115. **
  11116. ** Fts5PhraseIter iter;
  11117. ** int iCol;
  11118. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  11119. ** iCol>=0;
  11120. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  11121. ** ){
  11122. ** // Column iCol contains at least one instance of phrase iPhrase
  11123. ** }
  11124. **
  11125. ** This API can be quite slow if used with an FTS5 table created with the
  11126. ** "detail=none" option. If the FTS5 table is created with either
  11127. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  11128. ** then this API always iterates through an empty set (all calls to
  11129. ** xPhraseFirstColumn() set iCol to -1).
  11130. **
  11131. ** The information accessed using this API and its companion
  11132. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  11133. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  11134. ** significantly more efficient than those alternatives when used with
  11135. ** "detail=column" tables.
  11136. **
  11137. ** xPhraseNextColumn()
  11138. ** See xPhraseFirstColumn above.
  11139. */
  11140. struct Fts5ExtensionApi {
  11141. int iVersion; /* Currently always set to 3 */
  11142. void *(*xUserData)(Fts5Context*);
  11143. int (*xColumnCount)(Fts5Context*);
  11144. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  11145. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  11146. int (*xTokenize)(Fts5Context*,
  11147. const char *pText, int nText, /* Text to tokenize */
  11148. void *pCtx, /* Context passed to xToken() */
  11149. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  11150. );
  11151. int (*xPhraseCount)(Fts5Context*);
  11152. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  11153. int (*xInstCount)(Fts5Context*, int *pnInst);
  11154. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  11155. sqlite3_int64 (*xRowid)(Fts5Context*);
  11156. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  11157. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  11158. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  11159. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  11160. );
  11161. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  11162. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  11163. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  11164. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  11165. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  11166. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  11167. };
  11168. /*
  11169. ** CUSTOM AUXILIARY FUNCTIONS
  11170. *************************************************************************/
  11171. /*************************************************************************
  11172. ** CUSTOM TOKENIZERS
  11173. **
  11174. ** Applications may also register custom tokenizer types. A tokenizer
  11175. ** is registered by providing fts5 with a populated instance of the
  11176. ** following structure. All structure methods must be defined, setting
  11177. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  11178. ** behaviour. The structure methods are expected to function as follows:
  11179. **
  11180. ** xCreate:
  11181. ** This function is used to allocate and initialize a tokenizer instance.
  11182. ** A tokenizer instance is required to actually tokenize text.
  11183. **
  11184. ** The first argument passed to this function is a copy of the (void*)
  11185. ** pointer provided by the application when the fts5_tokenizer object
  11186. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  11187. ** The second and third arguments are an array of nul-terminated strings
  11188. ** containing the tokenizer arguments, if any, specified following the
  11189. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  11190. ** to create the FTS5 table.
  11191. **
  11192. ** The final argument is an output variable. If successful, (*ppOut)
  11193. ** should be set to point to the new tokenizer handle and SQLITE_OK
  11194. ** returned. If an error occurs, some value other than SQLITE_OK should
  11195. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  11196. ** is undefined.
  11197. **
  11198. ** xDelete:
  11199. ** This function is invoked to delete a tokenizer handle previously
  11200. ** allocated using xCreate(). Fts5 guarantees that this function will
  11201. ** be invoked exactly once for each successful call to xCreate().
  11202. **
  11203. ** xTokenize:
  11204. ** This function is expected to tokenize the nText byte string indicated
  11205. ** by argument pText. pText may or may not be nul-terminated. The first
  11206. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  11207. ** returned by an earlier call to xCreate().
  11208. **
  11209. ** The second argument indicates the reason that FTS5 is requesting
  11210. ** tokenization of the supplied text. This is always one of the following
  11211. ** four values:
  11212. **
  11213. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  11214. ** or removed from the FTS table. The tokenizer is being invoked to
  11215. ** determine the set of tokens to add to (or delete from) the
  11216. ** FTS index.
  11217. **
  11218. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  11219. ** against the FTS index. The tokenizer is being called to tokenize
  11220. ** a bareword or quoted string specified as part of the query.
  11221. **
  11222. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  11223. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  11224. ** followed by a "*" character, indicating that the last token
  11225. ** returned by the tokenizer will be treated as a token prefix.
  11226. **
  11227. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  11228. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  11229. ** function. Or an fts5_api.xColumnSize() request made by the same
  11230. ** on a columnsize=0 database.
  11231. ** </ul>
  11232. **
  11233. ** For each token in the input string, the supplied callback xToken() must
  11234. ** be invoked. The first argument to it should be a copy of the pointer
  11235. ** passed as the second argument to xTokenize(). The third and fourth
  11236. ** arguments are a pointer to a buffer containing the token text, and the
  11237. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  11238. ** of the first byte of and first byte immediately following the text from
  11239. ** which the token is derived within the input.
  11240. **
  11241. ** The second argument passed to the xToken() callback ("tflags") should
  11242. ** normally be set to 0. The exception is if the tokenizer supports
  11243. ** synonyms. In this case see the discussion below for details.
  11244. **
  11245. ** FTS5 assumes the xToken() callback is invoked for each token in the
  11246. ** order that they occur within the input text.
  11247. **
  11248. ** If an xToken() callback returns any value other than SQLITE_OK, then
  11249. ** the tokenization should be abandoned and the xTokenize() method should
  11250. ** immediately return a copy of the xToken() return value. Or, if the
  11251. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  11252. ** if an error occurs with the xTokenize() implementation itself, it
  11253. ** may abandon the tokenization and return any error code other than
  11254. ** SQLITE_OK or SQLITE_DONE.
  11255. **
  11256. ** SYNONYM SUPPORT
  11257. **
  11258. ** Custom tokenizers may also support synonyms. Consider a case in which a
  11259. ** user wishes to query for a phrase such as "first place". Using the
  11260. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  11261. ** of "first place" within the document set, but not alternative forms
  11262. ** such as "1st place". In some applications, it would be better to match
  11263. ** all instances of "first place" or "1st place" regardless of which form
  11264. ** the user specified in the MATCH query text.
  11265. **
  11266. ** There are several ways to approach this in FTS5:
  11267. **
  11268. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  11269. ** In the above example, this means that the tokenizer returns the
  11270. ** same token for inputs "first" and "1st". Say that token is in
  11271. ** fact "first", so that when the user inserts the document "I won
  11272. ** 1st place" entries are added to the index for tokens "i", "won",
  11273. ** "first" and "place". If the user then queries for '1st + place',
  11274. ** the tokenizer substitutes "first" for "1st" and the query works
  11275. ** as expected.
  11276. **
  11277. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11278. ** In this case, when tokenizing query text, the tokenizer may
  11279. ** provide multiple synonyms for a single term within the document.
  11280. ** FTS5 then queries the index for each synonym individually. For
  11281. ** example, faced with the query:
  11282. **
  11283. ** <codeblock>
  11284. ** ... MATCH 'first place'</codeblock>
  11285. **
  11286. ** the tokenizer offers both "1st" and "first" as synonyms for the
  11287. ** first token in the MATCH query and FTS5 effectively runs a query
  11288. ** similar to:
  11289. **
  11290. ** <codeblock>
  11291. ** ... MATCH '(first OR 1st) place'</codeblock>
  11292. **
  11293. ** except that, for the purposes of auxiliary functions, the query
  11294. ** still appears to contain just two phrases - "(first OR 1st)"
  11295. ** being treated as a single phrase.
  11296. **
  11297. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11298. ** Using this method, when tokenizing document text, the tokenizer
  11299. ** provides multiple synonyms for each token. So that when a
  11300. ** document such as "I won first place" is tokenized, entries are
  11301. ** added to the FTS index for "i", "won", "first", "1st" and
  11302. ** "place".
  11303. **
  11304. ** This way, even if the tokenizer does not provide synonyms
  11305. ** when tokenizing query text (it should not - to do would be
  11306. ** inefficient), it doesn't matter if the user queries for
  11307. ** 'first + place' or '1st + place', as there are entires in the
  11308. ** FTS index corresponding to both forms of the first token.
  11309. ** </ol>
  11310. **
  11311. ** Whether it is parsing document or query text, any call to xToken that
  11312. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  11313. ** is considered to supply a synonym for the previous token. For example,
  11314. ** when parsing the document "I won first place", a tokenizer that supports
  11315. ** synonyms would call xToken() 5 times, as follows:
  11316. **
  11317. ** <codeblock>
  11318. ** xToken(pCtx, 0, "i", 1, 0, 1);
  11319. ** xToken(pCtx, 0, "won", 3, 2, 5);
  11320. ** xToken(pCtx, 0, "first", 5, 6, 11);
  11321. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  11322. ** xToken(pCtx, 0, "place", 5, 12, 17);
  11323. **</codeblock>
  11324. **
  11325. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  11326. ** xToken() is called. Multiple synonyms may be specified for a single token
  11327. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  11328. ** There is no limit to the number of synonyms that may be provided for a
  11329. ** single token.
  11330. **
  11331. ** In many cases, method (1) above is the best approach. It does not add
  11332. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  11333. ** so it is efficient in terms of disk space and query speed. However, it
  11334. ** does not support prefix queries very well. If, as suggested above, the
  11335. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  11336. **
  11337. ** <codeblock>
  11338. ** ... MATCH '1s*'</codeblock>
  11339. **
  11340. ** will not match documents that contain the token "1st" (as the tokenizer
  11341. ** will probably not map "1s" to any prefix of "first").
  11342. **
  11343. ** For full prefix support, method (3) may be preferred. In this case,
  11344. ** because the index contains entries for both "first" and "1st", prefix
  11345. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  11346. ** extra entries are added to the FTS index, this method uses more space
  11347. ** within the database.
  11348. **
  11349. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  11350. ** a query such as '1s*' will match documents that contain the literal
  11351. ** token "1st", but not "first" (assuming the tokenizer is not able to
  11352. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  11353. ** will match against "1st" and "first". This method does not require
  11354. ** extra disk space, as no extra entries are added to the FTS index.
  11355. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  11356. ** as separate queries of the FTS index are required for each synonym.
  11357. **
  11358. ** When using methods (2) or (3), it is important that the tokenizer only
  11359. ** provide synonyms when tokenizing document text (method (2)) or query
  11360. ** text (method (3)), not both. Doing so will not cause any errors, but is
  11361. ** inefficient.
  11362. */
  11363. typedef struct Fts5Tokenizer Fts5Tokenizer;
  11364. typedef struct fts5_tokenizer fts5_tokenizer;
  11365. struct fts5_tokenizer {
  11366. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  11367. void (*xDelete)(Fts5Tokenizer*);
  11368. int (*xTokenize)(Fts5Tokenizer*,
  11369. void *pCtx,
  11370. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  11371. const char *pText, int nText,
  11372. int (*xToken)(
  11373. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  11374. int tflags, /* Mask of FTS5_TOKEN_* flags */
  11375. const char *pToken, /* Pointer to buffer containing token */
  11376. int nToken, /* Size of token in bytes */
  11377. int iStart, /* Byte offset of token within input text */
  11378. int iEnd /* Byte offset of end of token within input text */
  11379. )
  11380. );
  11381. };
  11382. /* Flags that may be passed as the third argument to xTokenize() */
  11383. #define FTS5_TOKENIZE_QUERY 0x0001
  11384. #define FTS5_TOKENIZE_PREFIX 0x0002
  11385. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  11386. #define FTS5_TOKENIZE_AUX 0x0008
  11387. /* Flags that may be passed by the tokenizer implementation back to FTS5
  11388. ** as the third argument to the supplied xToken callback. */
  11389. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  11390. /*
  11391. ** END OF CUSTOM TOKENIZERS
  11392. *************************************************************************/
  11393. /*************************************************************************
  11394. ** FTS5 EXTENSION REGISTRATION API
  11395. */
  11396. typedef struct fts5_api fts5_api;
  11397. struct fts5_api {
  11398. int iVersion; /* Currently always set to 2 */
  11399. /* Create a new tokenizer */
  11400. int (*xCreateTokenizer)(
  11401. fts5_api *pApi,
  11402. const char *zName,
  11403. void *pContext,
  11404. fts5_tokenizer *pTokenizer,
  11405. void (*xDestroy)(void*)
  11406. );
  11407. /* Find an existing tokenizer */
  11408. int (*xFindTokenizer)(
  11409. fts5_api *pApi,
  11410. const char *zName,
  11411. void **ppContext,
  11412. fts5_tokenizer *pTokenizer
  11413. );
  11414. /* Create a new auxiliary function */
  11415. int (*xCreateFunction)(
  11416. fts5_api *pApi,
  11417. const char *zName,
  11418. void *pContext,
  11419. fts5_extension_function xFunction,
  11420. void (*xDestroy)(void*)
  11421. );
  11422. };
  11423. /*
  11424. ** END OF REGISTRATION API
  11425. *************************************************************************/
  11426. #if 0
  11427. } /* end of the 'extern "C"' block */
  11428. #endif
  11429. #endif /* _FTS5_H */
  11430. /******** End of fts5.h *********/
  11431. /************** End of sqlite3.h *********************************************/
  11432. /************** Continuing where we left off in sqliteInt.h ******************/
  11433. /*
  11434. ** Include the configuration header output by 'configure' if we're using the
  11435. ** autoconf-based build
  11436. */
  11437. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  11438. /* #include "config.h" */
  11439. #define SQLITECONFIG_H 1
  11440. #endif
  11441. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  11442. /************** Begin file sqliteLimit.h *************************************/
  11443. /*
  11444. ** 2007 May 7
  11445. **
  11446. ** The author disclaims copyright to this source code. In place of
  11447. ** a legal notice, here is a blessing:
  11448. **
  11449. ** May you do good and not evil.
  11450. ** May you find forgiveness for yourself and forgive others.
  11451. ** May you share freely, never taking more than you give.
  11452. **
  11453. *************************************************************************
  11454. **
  11455. ** This file defines various limits of what SQLite can process.
  11456. */
  11457. /*
  11458. ** The maximum length of a TEXT or BLOB in bytes. This also
  11459. ** limits the size of a row in a table or index.
  11460. **
  11461. ** The hard limit is the ability of a 32-bit signed integer
  11462. ** to count the size: 2^31-1 or 2147483647.
  11463. */
  11464. #ifndef SQLITE_MAX_LENGTH
  11465. # define SQLITE_MAX_LENGTH 1000000000
  11466. #endif
  11467. /*
  11468. ** This is the maximum number of
  11469. **
  11470. ** * Columns in a table
  11471. ** * Columns in an index
  11472. ** * Columns in a view
  11473. ** * Terms in the SET clause of an UPDATE statement
  11474. ** * Terms in the result set of a SELECT statement
  11475. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  11476. ** * Terms in the VALUES clause of an INSERT statement
  11477. **
  11478. ** The hard upper limit here is 32676. Most database people will
  11479. ** tell you that in a well-normalized database, you usually should
  11480. ** not have more than a dozen or so columns in any table. And if
  11481. ** that is the case, there is no point in having more than a few
  11482. ** dozen values in any of the other situations described above.
  11483. */
  11484. #ifndef SQLITE_MAX_COLUMN
  11485. # define SQLITE_MAX_COLUMN 2000
  11486. #endif
  11487. /*
  11488. ** The maximum length of a single SQL statement in bytes.
  11489. **
  11490. ** It used to be the case that setting this value to zero would
  11491. ** turn the limit off. That is no longer true. It is not possible
  11492. ** to turn this limit off.
  11493. */
  11494. #ifndef SQLITE_MAX_SQL_LENGTH
  11495. # define SQLITE_MAX_SQL_LENGTH 1000000000
  11496. #endif
  11497. /*
  11498. ** The maximum depth of an expression tree. This is limited to
  11499. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  11500. ** want to place more severe limits on the complexity of an
  11501. ** expression.
  11502. **
  11503. ** A value of 0 used to mean that the limit was not enforced.
  11504. ** But that is no longer true. The limit is now strictly enforced
  11505. ** at all times.
  11506. */
  11507. #ifndef SQLITE_MAX_EXPR_DEPTH
  11508. # define SQLITE_MAX_EXPR_DEPTH 1000
  11509. #endif
  11510. /*
  11511. ** The maximum number of terms in a compound SELECT statement.
  11512. ** The code generator for compound SELECT statements does one
  11513. ** level of recursion for each term. A stack overflow can result
  11514. ** if the number of terms is too large. In practice, most SQL
  11515. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  11516. ** any limit on the number of terms in a compount SELECT.
  11517. */
  11518. #ifndef SQLITE_MAX_COMPOUND_SELECT
  11519. # define SQLITE_MAX_COMPOUND_SELECT 500
  11520. #endif
  11521. /*
  11522. ** The maximum number of opcodes in a VDBE program.
  11523. ** Not currently enforced.
  11524. */
  11525. #ifndef SQLITE_MAX_VDBE_OP
  11526. # define SQLITE_MAX_VDBE_OP 250000000
  11527. #endif
  11528. /*
  11529. ** The maximum number of arguments to an SQL function.
  11530. */
  11531. #ifndef SQLITE_MAX_FUNCTION_ARG
  11532. # define SQLITE_MAX_FUNCTION_ARG 127
  11533. #endif
  11534. /*
  11535. ** The suggested maximum number of in-memory pages to use for
  11536. ** the main database table and for temporary tables.
  11537. **
  11538. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  11539. ** which means the cache size is limited to 2048000 bytes of memory.
  11540. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  11541. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  11542. */
  11543. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  11544. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  11545. #endif
  11546. /*
  11547. ** The default number of frames to accumulate in the log file before
  11548. ** checkpointing the database in WAL mode.
  11549. */
  11550. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  11551. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  11552. #endif
  11553. /*
  11554. ** The maximum number of attached databases. This must be between 0
  11555. ** and 125. The upper bound of 125 is because the attached databases are
  11556. ** counted using a signed 8-bit integer which has a maximum value of 127
  11557. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  11558. */
  11559. #ifndef SQLITE_MAX_ATTACHED
  11560. # define SQLITE_MAX_ATTACHED 10
  11561. #endif
  11562. /*
  11563. ** The maximum value of a ?nnn wildcard that the parser will accept.
  11564. */
  11565. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  11566. # define SQLITE_MAX_VARIABLE_NUMBER 999
  11567. #endif
  11568. /* Maximum page size. The upper bound on this value is 65536. This a limit
  11569. ** imposed by the use of 16-bit offsets within each page.
  11570. **
  11571. ** Earlier versions of SQLite allowed the user to change this value at
  11572. ** compile time. This is no longer permitted, on the grounds that it creates
  11573. ** a library that is technically incompatible with an SQLite library
  11574. ** compiled with a different limit. If a process operating on a database
  11575. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  11576. ** compiled with the default page-size limit will not be able to rollback
  11577. ** the aborted transaction. This could lead to database corruption.
  11578. */
  11579. #ifdef SQLITE_MAX_PAGE_SIZE
  11580. # undef SQLITE_MAX_PAGE_SIZE
  11581. #endif
  11582. #define SQLITE_MAX_PAGE_SIZE 65536
  11583. /*
  11584. ** The default size of a database page.
  11585. */
  11586. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  11587. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  11588. #endif
  11589. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  11590. # undef SQLITE_DEFAULT_PAGE_SIZE
  11591. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  11592. #endif
  11593. /*
  11594. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  11595. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  11596. ** device characteristics (sector-size and atomic write() support),
  11597. ** SQLite may choose a larger value. This constant is the maximum value
  11598. ** SQLite will choose on its own.
  11599. */
  11600. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  11601. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  11602. #endif
  11603. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  11604. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  11605. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  11606. #endif
  11607. /*
  11608. ** Maximum number of pages in one database file.
  11609. **
  11610. ** This is really just the default value for the max_page_count pragma.
  11611. ** This value can be lowered (or raised) at run-time using that the
  11612. ** max_page_count macro.
  11613. */
  11614. #ifndef SQLITE_MAX_PAGE_COUNT
  11615. # define SQLITE_MAX_PAGE_COUNT 1073741823
  11616. #endif
  11617. /*
  11618. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  11619. ** operator.
  11620. */
  11621. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  11622. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  11623. #endif
  11624. /*
  11625. ** Maximum depth of recursion for triggers.
  11626. **
  11627. ** A value of 1 means that a trigger program will not be able to itself
  11628. ** fire any triggers. A value of 0 means that no trigger programs at all
  11629. ** may be executed.
  11630. */
  11631. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  11632. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  11633. #endif
  11634. /************** End of sqliteLimit.h *****************************************/
  11635. /************** Continuing where we left off in sqliteInt.h ******************/
  11636. /* Disable nuisance warnings on Borland compilers */
  11637. #if defined(__BORLANDC__)
  11638. #pragma warn -rch /* unreachable code */
  11639. #pragma warn -ccc /* Condition is always true or false */
  11640. #pragma warn -aus /* Assigned value is never used */
  11641. #pragma warn -csu /* Comparing signed and unsigned */
  11642. #pragma warn -spa /* Suspicious pointer arithmetic */
  11643. #endif
  11644. /*
  11645. ** Include standard header files as necessary
  11646. */
  11647. #ifdef HAVE_STDINT_H
  11648. #include <stdint.h>
  11649. #endif
  11650. #ifdef HAVE_INTTYPES_H
  11651. #include <inttypes.h>
  11652. #endif
  11653. /*
  11654. ** The following macros are used to cast pointers to integers and
  11655. ** integers to pointers. The way you do this varies from one compiler
  11656. ** to the next, so we have developed the following set of #if statements
  11657. ** to generate appropriate macros for a wide range of compilers.
  11658. **
  11659. ** The correct "ANSI" way to do this is to use the intptr_t type.
  11660. ** Unfortunately, that typedef is not available on all compilers, or
  11661. ** if it is available, it requires an #include of specific headers
  11662. ** that vary from one machine to the next.
  11663. **
  11664. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  11665. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  11666. ** So we have to define the macros in different ways depending on the
  11667. ** compiler.
  11668. */
  11669. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  11670. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  11671. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  11672. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  11673. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  11674. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  11675. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  11676. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  11677. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  11678. #else /* Generates a warning - but it always works */
  11679. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  11680. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  11681. #endif
  11682. /*
  11683. ** A macro to hint to the compiler that a function should not be
  11684. ** inlined.
  11685. */
  11686. #if defined(__GNUC__)
  11687. # define SQLITE_NOINLINE __attribute__((noinline))
  11688. #elif defined(_MSC_VER) && _MSC_VER>=1310
  11689. # define SQLITE_NOINLINE __declspec(noinline)
  11690. #else
  11691. # define SQLITE_NOINLINE
  11692. #endif
  11693. /*
  11694. ** Make sure that the compiler intrinsics we desire are enabled when
  11695. ** compiling with an appropriate version of MSVC unless prevented by
  11696. ** the SQLITE_DISABLE_INTRINSIC define.
  11697. */
  11698. #if !defined(SQLITE_DISABLE_INTRINSIC)
  11699. # if defined(_MSC_VER) && _MSC_VER>=1400
  11700. # if !defined(_WIN32_WCE)
  11701. # include <intrin.h>
  11702. # pragma intrinsic(_byteswap_ushort)
  11703. # pragma intrinsic(_byteswap_ulong)
  11704. # pragma intrinsic(_byteswap_uint64)
  11705. # pragma intrinsic(_ReadWriteBarrier)
  11706. # else
  11707. # include <cmnintrin.h>
  11708. # endif
  11709. # endif
  11710. #endif
  11711. /*
  11712. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  11713. ** 0 means mutexes are permanently disable and the library is never
  11714. ** threadsafe. 1 means the library is serialized which is the highest
  11715. ** level of threadsafety. 2 means the library is multithreaded - multiple
  11716. ** threads can use SQLite as long as no two threads try to use the same
  11717. ** database connection at the same time.
  11718. **
  11719. ** Older versions of SQLite used an optional THREADSAFE macro.
  11720. ** We support that for legacy.
  11721. **
  11722. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  11723. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  11724. ** logic is partially replicated in ctime.c. If it is updated here, it should
  11725. ** also be updated there.
  11726. */
  11727. #if !defined(SQLITE_THREADSAFE)
  11728. # if defined(THREADSAFE)
  11729. # define SQLITE_THREADSAFE THREADSAFE
  11730. # else
  11731. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  11732. # endif
  11733. #endif
  11734. /*
  11735. ** Powersafe overwrite is on by default. But can be turned off using
  11736. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  11737. */
  11738. #ifndef SQLITE_POWERSAFE_OVERWRITE
  11739. # define SQLITE_POWERSAFE_OVERWRITE 1
  11740. #endif
  11741. /*
  11742. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  11743. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  11744. ** which case memory allocation statistics are disabled by default.
  11745. */
  11746. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  11747. # define SQLITE_DEFAULT_MEMSTATUS 1
  11748. #endif
  11749. /*
  11750. ** Exactly one of the following macros must be defined in order to
  11751. ** specify which memory allocation subsystem to use.
  11752. **
  11753. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  11754. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  11755. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  11756. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  11757. **
  11758. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  11759. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  11760. ** will cause HeapValidate to be called. If heap validation should fail, an
  11761. ** assertion will be triggered.
  11762. **
  11763. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  11764. ** the default.
  11765. */
  11766. #if defined(SQLITE_SYSTEM_MALLOC) \
  11767. + defined(SQLITE_WIN32_MALLOC) \
  11768. + defined(SQLITE_ZERO_MALLOC) \
  11769. + defined(SQLITE_MEMDEBUG)>1
  11770. # error "Two or more of the following compile-time configuration options\
  11771. are defined but at most one is allowed:\
  11772. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  11773. SQLITE_ZERO_MALLOC"
  11774. #endif
  11775. #if defined(SQLITE_SYSTEM_MALLOC) \
  11776. + defined(SQLITE_WIN32_MALLOC) \
  11777. + defined(SQLITE_ZERO_MALLOC) \
  11778. + defined(SQLITE_MEMDEBUG)==0
  11779. # define SQLITE_SYSTEM_MALLOC 1
  11780. #endif
  11781. /*
  11782. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  11783. ** sizes of memory allocations below this value where possible.
  11784. */
  11785. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  11786. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  11787. #endif
  11788. /*
  11789. ** We need to define _XOPEN_SOURCE as follows in order to enable
  11790. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  11791. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  11792. ** it.
  11793. */
  11794. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  11795. # define _XOPEN_SOURCE 600
  11796. #endif
  11797. /*
  11798. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  11799. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  11800. ** make it true by defining or undefining NDEBUG.
  11801. **
  11802. ** Setting NDEBUG makes the code smaller and faster by disabling the
  11803. ** assert() statements in the code. So we want the default action
  11804. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  11805. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  11806. ** feature.
  11807. */
  11808. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  11809. # define NDEBUG 1
  11810. #endif
  11811. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  11812. # undef NDEBUG
  11813. #endif
  11814. /*
  11815. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  11816. */
  11817. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  11818. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  11819. #endif
  11820. /*
  11821. ** The testcase() macro is used to aid in coverage testing. When
  11822. ** doing coverage testing, the condition inside the argument to
  11823. ** testcase() must be evaluated both true and false in order to
  11824. ** get full branch coverage. The testcase() macro is inserted
  11825. ** to help ensure adequate test coverage in places where simple
  11826. ** condition/decision coverage is inadequate. For example, testcase()
  11827. ** can be used to make sure boundary values are tested. For
  11828. ** bitmask tests, testcase() can be used to make sure each bit
  11829. ** is significant and used at least once. On switch statements
  11830. ** where multiple cases go to the same block of code, testcase()
  11831. ** can insure that all cases are evaluated.
  11832. **
  11833. */
  11834. #ifdef SQLITE_COVERAGE_TEST
  11835. SQLITE_PRIVATE void sqlite3Coverage(int);
  11836. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  11837. #else
  11838. # define testcase(X)
  11839. #endif
  11840. /*
  11841. ** The TESTONLY macro is used to enclose variable declarations or
  11842. ** other bits of code that are needed to support the arguments
  11843. ** within testcase() and assert() macros.
  11844. */
  11845. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  11846. # define TESTONLY(X) X
  11847. #else
  11848. # define TESTONLY(X)
  11849. #endif
  11850. /*
  11851. ** Sometimes we need a small amount of code such as a variable initialization
  11852. ** to setup for a later assert() statement. We do not want this code to
  11853. ** appear when assert() is disabled. The following macro is therefore
  11854. ** used to contain that setup code. The "VVA" acronym stands for
  11855. ** "Verification, Validation, and Accreditation". In other words, the
  11856. ** code within VVA_ONLY() will only run during verification processes.
  11857. */
  11858. #ifndef NDEBUG
  11859. # define VVA_ONLY(X) X
  11860. #else
  11861. # define VVA_ONLY(X)
  11862. #endif
  11863. /*
  11864. ** The ALWAYS and NEVER macros surround boolean expressions which
  11865. ** are intended to always be true or false, respectively. Such
  11866. ** expressions could be omitted from the code completely. But they
  11867. ** are included in a few cases in order to enhance the resilience
  11868. ** of SQLite to unexpected behavior - to make the code "self-healing"
  11869. ** or "ductile" rather than being "brittle" and crashing at the first
  11870. ** hint of unplanned behavior.
  11871. **
  11872. ** In other words, ALWAYS and NEVER are added for defensive code.
  11873. **
  11874. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  11875. ** be true and false so that the unreachable code they specify will
  11876. ** not be counted as untested code.
  11877. */
  11878. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  11879. # define ALWAYS(X) (1)
  11880. # define NEVER(X) (0)
  11881. #elif !defined(NDEBUG)
  11882. # define ALWAYS(X) ((X)?1:(assert(0),0))
  11883. # define NEVER(X) ((X)?(assert(0),1):0)
  11884. #else
  11885. # define ALWAYS(X) (X)
  11886. # define NEVER(X) (X)
  11887. #endif
  11888. /*
  11889. ** Some conditionals are optimizations only. In other words, if the
  11890. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  11891. ** the correct answer is still obtained, though perhaps not as quickly.
  11892. **
  11893. ** The following macros mark these optimizations conditionals.
  11894. */
  11895. #if defined(SQLITE_MUTATION_TEST)
  11896. # define OK_IF_ALWAYS_TRUE(X) (1)
  11897. # define OK_IF_ALWAYS_FALSE(X) (0)
  11898. #else
  11899. # define OK_IF_ALWAYS_TRUE(X) (X)
  11900. # define OK_IF_ALWAYS_FALSE(X) (X)
  11901. #endif
  11902. /*
  11903. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  11904. ** defined. We need to defend against those failures when testing with
  11905. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  11906. ** during a normal build. The following macro can be used to disable tests
  11907. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  11908. */
  11909. #if defined(SQLITE_TEST_REALLOC_STRESS)
  11910. # define ONLY_IF_REALLOC_STRESS(X) (X)
  11911. #elif !defined(NDEBUG)
  11912. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  11913. #else
  11914. # define ONLY_IF_REALLOC_STRESS(X) (0)
  11915. #endif
  11916. /*
  11917. ** Declarations used for tracing the operating system interfaces.
  11918. */
  11919. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  11920. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  11921. extern int sqlite3OSTrace;
  11922. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  11923. # define SQLITE_HAVE_OS_TRACE
  11924. #else
  11925. # define OSTRACE(X)
  11926. # undef SQLITE_HAVE_OS_TRACE
  11927. #endif
  11928. /*
  11929. ** Is the sqlite3ErrName() function needed in the build? Currently,
  11930. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  11931. ** OSTRACE is enabled), and by several "test*.c" files (which are
  11932. ** compiled using SQLITE_TEST).
  11933. */
  11934. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  11935. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  11936. # define SQLITE_NEED_ERR_NAME
  11937. #else
  11938. # undef SQLITE_NEED_ERR_NAME
  11939. #endif
  11940. /*
  11941. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  11942. */
  11943. #ifdef SQLITE_OMIT_EXPLAIN
  11944. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  11945. #endif
  11946. /*
  11947. ** Return true (non-zero) if the input is an integer that is too large
  11948. ** to fit in 32-bits. This macro is used inside of various testcase()
  11949. ** macros to verify that we have tested SQLite for large-file support.
  11950. */
  11951. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  11952. /*
  11953. ** The macro unlikely() is a hint that surrounds a boolean
  11954. ** expression that is usually false. Macro likely() surrounds
  11955. ** a boolean expression that is usually true. These hints could,
  11956. ** in theory, be used by the compiler to generate better code, but
  11957. ** currently they are just comments for human readers.
  11958. */
  11959. #define likely(X) (X)
  11960. #define unlikely(X) (X)
  11961. /************** Include hash.h in the middle of sqliteInt.h ******************/
  11962. /************** Begin file hash.h ********************************************/
  11963. /*
  11964. ** 2001 September 22
  11965. **
  11966. ** The author disclaims copyright to this source code. In place of
  11967. ** a legal notice, here is a blessing:
  11968. **
  11969. ** May you do good and not evil.
  11970. ** May you find forgiveness for yourself and forgive others.
  11971. ** May you share freely, never taking more than you give.
  11972. **
  11973. *************************************************************************
  11974. ** This is the header file for the generic hash-table implementation
  11975. ** used in SQLite.
  11976. */
  11977. #ifndef SQLITE_HASH_H
  11978. #define SQLITE_HASH_H
  11979. /* Forward declarations of structures. */
  11980. typedef struct Hash Hash;
  11981. typedef struct HashElem HashElem;
  11982. /* A complete hash table is an instance of the following structure.
  11983. ** The internals of this structure are intended to be opaque -- client
  11984. ** code should not attempt to access or modify the fields of this structure
  11985. ** directly. Change this structure only by using the routines below.
  11986. ** However, some of the "procedures" and "functions" for modifying and
  11987. ** accessing this structure are really macros, so we can't really make
  11988. ** this structure opaque.
  11989. **
  11990. ** All elements of the hash table are on a single doubly-linked list.
  11991. ** Hash.first points to the head of this list.
  11992. **
  11993. ** There are Hash.htsize buckets. Each bucket points to a spot in
  11994. ** the global doubly-linked list. The contents of the bucket are the
  11995. ** element pointed to plus the next _ht.count-1 elements in the list.
  11996. **
  11997. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  11998. ** by a linear search of the global list. For small tables, the
  11999. ** Hash.ht table is never allocated because if there are few elements
  12000. ** in the table, it is faster to do a linear search than to manage
  12001. ** the hash table.
  12002. */
  12003. struct Hash {
  12004. unsigned int htsize; /* Number of buckets in the hash table */
  12005. unsigned int count; /* Number of entries in this table */
  12006. HashElem *first; /* The first element of the array */
  12007. struct _ht { /* the hash table */
  12008. int count; /* Number of entries with this hash */
  12009. HashElem *chain; /* Pointer to first entry with this hash */
  12010. } *ht;
  12011. };
  12012. /* Each element in the hash table is an instance of the following
  12013. ** structure. All elements are stored on a single doubly-linked list.
  12014. **
  12015. ** Again, this structure is intended to be opaque, but it can't really
  12016. ** be opaque because it is used by macros.
  12017. */
  12018. struct HashElem {
  12019. HashElem *next, *prev; /* Next and previous elements in the table */
  12020. void *data; /* Data associated with this element */
  12021. const char *pKey; /* Key associated with this element */
  12022. };
  12023. /*
  12024. ** Access routines. To delete, insert a NULL pointer.
  12025. */
  12026. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  12027. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  12028. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  12029. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  12030. /*
  12031. ** Macros for looping over all elements of a hash table. The idiom is
  12032. ** like this:
  12033. **
  12034. ** Hash h;
  12035. ** HashElem *p;
  12036. ** ...
  12037. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  12038. ** SomeStructure *pData = sqliteHashData(p);
  12039. ** // do something with pData
  12040. ** }
  12041. */
  12042. #define sqliteHashFirst(H) ((H)->first)
  12043. #define sqliteHashNext(E) ((E)->next)
  12044. #define sqliteHashData(E) ((E)->data)
  12045. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  12046. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  12047. /*
  12048. ** Number of entries in a hash table
  12049. */
  12050. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  12051. #endif /* SQLITE_HASH_H */
  12052. /************** End of hash.h ************************************************/
  12053. /************** Continuing where we left off in sqliteInt.h ******************/
  12054. /************** Include parse.h in the middle of sqliteInt.h *****************/
  12055. /************** Begin file parse.h *******************************************/
  12056. #define TK_SEMI 1
  12057. #define TK_EXPLAIN 2
  12058. #define TK_QUERY 3
  12059. #define TK_PLAN 4
  12060. #define TK_BEGIN 5
  12061. #define TK_TRANSACTION 6
  12062. #define TK_DEFERRED 7
  12063. #define TK_IMMEDIATE 8
  12064. #define TK_EXCLUSIVE 9
  12065. #define TK_COMMIT 10
  12066. #define TK_END 11
  12067. #define TK_ROLLBACK 12
  12068. #define TK_SAVEPOINT 13
  12069. #define TK_RELEASE 14
  12070. #define TK_TO 15
  12071. #define TK_TABLE 16
  12072. #define TK_CREATE 17
  12073. #define TK_IF 18
  12074. #define TK_NOT 19
  12075. #define TK_EXISTS 20
  12076. #define TK_TEMP 21
  12077. #define TK_LP 22
  12078. #define TK_RP 23
  12079. #define TK_AS 24
  12080. #define TK_WITHOUT 25
  12081. #define TK_COMMA 26
  12082. #define TK_ABORT 27
  12083. #define TK_ACTION 28
  12084. #define TK_AFTER 29
  12085. #define TK_ANALYZE 30
  12086. #define TK_ASC 31
  12087. #define TK_ATTACH 32
  12088. #define TK_BEFORE 33
  12089. #define TK_BY 34
  12090. #define TK_CASCADE 35
  12091. #define TK_CAST 36
  12092. #define TK_CONFLICT 37
  12093. #define TK_DATABASE 38
  12094. #define TK_DESC 39
  12095. #define TK_DETACH 40
  12096. #define TK_EACH 41
  12097. #define TK_FAIL 42
  12098. #define TK_OR 43
  12099. #define TK_AND 44
  12100. #define TK_IS 45
  12101. #define TK_MATCH 46
  12102. #define TK_LIKE_KW 47
  12103. #define TK_BETWEEN 48
  12104. #define TK_IN 49
  12105. #define TK_ISNULL 50
  12106. #define TK_NOTNULL 51
  12107. #define TK_NE 52
  12108. #define TK_EQ 53
  12109. #define TK_GT 54
  12110. #define TK_LE 55
  12111. #define TK_LT 56
  12112. #define TK_GE 57
  12113. #define TK_ESCAPE 58
  12114. #define TK_ID 59
  12115. #define TK_COLUMNKW 60
  12116. #define TK_FOR 61
  12117. #define TK_IGNORE 62
  12118. #define TK_INITIALLY 63
  12119. #define TK_INSTEAD 64
  12120. #define TK_NO 65
  12121. #define TK_KEY 66
  12122. #define TK_OF 67
  12123. #define TK_OFFSET 68
  12124. #define TK_PRAGMA 69
  12125. #define TK_RAISE 70
  12126. #define TK_RECURSIVE 71
  12127. #define TK_REPLACE 72
  12128. #define TK_RESTRICT 73
  12129. #define TK_ROW 74
  12130. #define TK_TRIGGER 75
  12131. #define TK_VACUUM 76
  12132. #define TK_VIEW 77
  12133. #define TK_VIRTUAL 78
  12134. #define TK_WITH 79
  12135. #define TK_REINDEX 80
  12136. #define TK_RENAME 81
  12137. #define TK_CTIME_KW 82
  12138. #define TK_ANY 83
  12139. #define TK_BITAND 84
  12140. #define TK_BITOR 85
  12141. #define TK_LSHIFT 86
  12142. #define TK_RSHIFT 87
  12143. #define TK_PLUS 88
  12144. #define TK_MINUS 89
  12145. #define TK_STAR 90
  12146. #define TK_SLASH 91
  12147. #define TK_REM 92
  12148. #define TK_CONCAT 93
  12149. #define TK_COLLATE 94
  12150. #define TK_BITNOT 95
  12151. #define TK_INDEXED 96
  12152. #define TK_STRING 97
  12153. #define TK_JOIN_KW 98
  12154. #define TK_CONSTRAINT 99
  12155. #define TK_DEFAULT 100
  12156. #define TK_NULL 101
  12157. #define TK_PRIMARY 102
  12158. #define TK_UNIQUE 103
  12159. #define TK_CHECK 104
  12160. #define TK_REFERENCES 105
  12161. #define TK_AUTOINCR 106
  12162. #define TK_ON 107
  12163. #define TK_INSERT 108
  12164. #define TK_DELETE 109
  12165. #define TK_UPDATE 110
  12166. #define TK_SET 111
  12167. #define TK_DEFERRABLE 112
  12168. #define TK_FOREIGN 113
  12169. #define TK_DROP 114
  12170. #define TK_UNION 115
  12171. #define TK_ALL 116
  12172. #define TK_EXCEPT 117
  12173. #define TK_INTERSECT 118
  12174. #define TK_SELECT 119
  12175. #define TK_VALUES 120
  12176. #define TK_DISTINCT 121
  12177. #define TK_DOT 122
  12178. #define TK_FROM 123
  12179. #define TK_JOIN 124
  12180. #define TK_USING 125
  12181. #define TK_ORDER 126
  12182. #define TK_GROUP 127
  12183. #define TK_HAVING 128
  12184. #define TK_LIMIT 129
  12185. #define TK_WHERE 130
  12186. #define TK_INTO 131
  12187. #define TK_FLOAT 132
  12188. #define TK_BLOB 133
  12189. #define TK_INTEGER 134
  12190. #define TK_VARIABLE 135
  12191. #define TK_CASE 136
  12192. #define TK_WHEN 137
  12193. #define TK_THEN 138
  12194. #define TK_ELSE 139
  12195. #define TK_INDEX 140
  12196. #define TK_ALTER 141
  12197. #define TK_ADD 142
  12198. #define TK_ISNOT 143
  12199. #define TK_FUNCTION 144
  12200. #define TK_COLUMN 145
  12201. #define TK_AGG_FUNCTION 146
  12202. #define TK_AGG_COLUMN 147
  12203. #define TK_UMINUS 148
  12204. #define TK_UPLUS 149
  12205. #define TK_REGISTER 150
  12206. #define TK_VECTOR 151
  12207. #define TK_SELECT_COLUMN 152
  12208. #define TK_IF_NULL_ROW 153
  12209. #define TK_ASTERISK 154
  12210. #define TK_SPAN 155
  12211. #define TK_END_OF_FILE 156
  12212. #define TK_UNCLOSED_STRING 157
  12213. #define TK_SPACE 158
  12214. #define TK_ILLEGAL 159
  12215. /* The token codes above must all fit in 8 bits */
  12216. #define TKFLG_MASK 0xff
  12217. /* Flags that can be added to a token code when it is not
  12218. ** being stored in a u8: */
  12219. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  12220. /************** End of parse.h ***********************************************/
  12221. /************** Continuing where we left off in sqliteInt.h ******************/
  12222. #include <stdio.h>
  12223. #include <stdlib.h>
  12224. #include <string.h>
  12225. #include <assert.h>
  12226. #include <stddef.h>
  12227. /*
  12228. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  12229. ** This allows better measurements of where memcpy() is used when running
  12230. ** cachegrind. But this macro version of memcpy() is very slow so it
  12231. ** should not be used in production. This is a performance measurement
  12232. ** hack only.
  12233. */
  12234. #ifdef SQLITE_INLINE_MEMCPY
  12235. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  12236. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  12237. #endif
  12238. /*
  12239. ** If compiling for a processor that lacks floating point support,
  12240. ** substitute integer for floating-point
  12241. */
  12242. #ifdef SQLITE_OMIT_FLOATING_POINT
  12243. # define double sqlite_int64
  12244. # define float sqlite_int64
  12245. # define LONGDOUBLE_TYPE sqlite_int64
  12246. # ifndef SQLITE_BIG_DBL
  12247. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  12248. # endif
  12249. # define SQLITE_OMIT_DATETIME_FUNCS 1
  12250. # define SQLITE_OMIT_TRACE 1
  12251. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12252. # undef SQLITE_HAVE_ISNAN
  12253. #endif
  12254. #ifndef SQLITE_BIG_DBL
  12255. # define SQLITE_BIG_DBL (1e99)
  12256. #endif
  12257. /*
  12258. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  12259. ** afterward. Having this macro allows us to cause the C compiler
  12260. ** to omit code used by TEMP tables without messy #ifndef statements.
  12261. */
  12262. #ifdef SQLITE_OMIT_TEMPDB
  12263. #define OMIT_TEMPDB 1
  12264. #else
  12265. #define OMIT_TEMPDB 0
  12266. #endif
  12267. /*
  12268. ** The "file format" number is an integer that is incremented whenever
  12269. ** the VDBE-level file format changes. The following macros define the
  12270. ** the default file format for new databases and the maximum file format
  12271. ** that the library can read.
  12272. */
  12273. #define SQLITE_MAX_FILE_FORMAT 4
  12274. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  12275. # define SQLITE_DEFAULT_FILE_FORMAT 4
  12276. #endif
  12277. /*
  12278. ** Determine whether triggers are recursive by default. This can be
  12279. ** changed at run-time using a pragma.
  12280. */
  12281. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  12282. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  12283. #endif
  12284. /*
  12285. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  12286. ** on the command-line
  12287. */
  12288. #ifndef SQLITE_TEMP_STORE
  12289. # define SQLITE_TEMP_STORE 1
  12290. #endif
  12291. /*
  12292. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  12293. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  12294. ** to zero.
  12295. */
  12296. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  12297. # undef SQLITE_MAX_WORKER_THREADS
  12298. # define SQLITE_MAX_WORKER_THREADS 0
  12299. #endif
  12300. #ifndef SQLITE_MAX_WORKER_THREADS
  12301. # define SQLITE_MAX_WORKER_THREADS 8
  12302. #endif
  12303. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  12304. # define SQLITE_DEFAULT_WORKER_THREADS 0
  12305. #endif
  12306. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  12307. # undef SQLITE_MAX_WORKER_THREADS
  12308. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  12309. #endif
  12310. /*
  12311. ** The default initial allocation for the pagecache when using separate
  12312. ** pagecaches for each database connection. A positive number is the
  12313. ** number of pages. A negative number N translations means that a buffer
  12314. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  12315. **
  12316. ** The default value of "20" was choosen to minimize the run-time of the
  12317. ** speedtest1 test program with options: --shrink-memory --reprepare
  12318. */
  12319. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  12320. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  12321. #endif
  12322. /*
  12323. ** The compile-time options SQLITE_MMAP_READWRITE and
  12324. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  12325. ** You must choose one or the other (or neither) but not both.
  12326. */
  12327. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  12328. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  12329. #endif
  12330. /*
  12331. ** GCC does not define the offsetof() macro so we'll have to do it
  12332. ** ourselves.
  12333. */
  12334. #ifndef offsetof
  12335. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  12336. #endif
  12337. /*
  12338. ** Macros to compute minimum and maximum of two numbers.
  12339. */
  12340. #ifndef MIN
  12341. # define MIN(A,B) ((A)<(B)?(A):(B))
  12342. #endif
  12343. #ifndef MAX
  12344. # define MAX(A,B) ((A)>(B)?(A):(B))
  12345. #endif
  12346. /*
  12347. ** Swap two objects of type TYPE.
  12348. */
  12349. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  12350. /*
  12351. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  12352. ** not, there are still machines out there that use EBCDIC.)
  12353. */
  12354. #if 'A' == '\301'
  12355. # define SQLITE_EBCDIC 1
  12356. #else
  12357. # define SQLITE_ASCII 1
  12358. #endif
  12359. /*
  12360. ** Integers of known sizes. These typedefs might change for architectures
  12361. ** where the sizes very. Preprocessor macros are available so that the
  12362. ** types can be conveniently redefined at compile-type. Like this:
  12363. **
  12364. ** cc '-DUINTPTR_TYPE=long long int' ...
  12365. */
  12366. #ifndef UINT32_TYPE
  12367. # ifdef HAVE_UINT32_T
  12368. # define UINT32_TYPE uint32_t
  12369. # else
  12370. # define UINT32_TYPE unsigned int
  12371. # endif
  12372. #endif
  12373. #ifndef UINT16_TYPE
  12374. # ifdef HAVE_UINT16_T
  12375. # define UINT16_TYPE uint16_t
  12376. # else
  12377. # define UINT16_TYPE unsigned short int
  12378. # endif
  12379. #endif
  12380. #ifndef INT16_TYPE
  12381. # ifdef HAVE_INT16_T
  12382. # define INT16_TYPE int16_t
  12383. # else
  12384. # define INT16_TYPE short int
  12385. # endif
  12386. #endif
  12387. #ifndef UINT8_TYPE
  12388. # ifdef HAVE_UINT8_T
  12389. # define UINT8_TYPE uint8_t
  12390. # else
  12391. # define UINT8_TYPE unsigned char
  12392. # endif
  12393. #endif
  12394. #ifndef INT8_TYPE
  12395. # ifdef HAVE_INT8_T
  12396. # define INT8_TYPE int8_t
  12397. # else
  12398. # define INT8_TYPE signed char
  12399. # endif
  12400. #endif
  12401. #ifndef LONGDOUBLE_TYPE
  12402. # define LONGDOUBLE_TYPE long double
  12403. #endif
  12404. typedef sqlite_int64 i64; /* 8-byte signed integer */
  12405. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  12406. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  12407. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  12408. typedef INT16_TYPE i16; /* 2-byte signed integer */
  12409. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  12410. typedef INT8_TYPE i8; /* 1-byte signed integer */
  12411. /*
  12412. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  12413. ** that can be stored in a u32 without loss of data. The value
  12414. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  12415. ** have to specify the value in the less intuitive manner shown:
  12416. */
  12417. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  12418. /*
  12419. ** The datatype used to store estimates of the number of rows in a
  12420. ** table or index. This is an unsigned integer type. For 99.9% of
  12421. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  12422. ** can be used at compile-time if desired.
  12423. */
  12424. #ifdef SQLITE_64BIT_STATS
  12425. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  12426. #else
  12427. typedef u32 tRowcnt; /* 32-bit is the default */
  12428. #endif
  12429. /*
  12430. ** Estimated quantities used for query planning are stored as 16-bit
  12431. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  12432. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  12433. ** But the allowed values are "grainy". Not every value is representable.
  12434. ** For example, quantities 16 and 17 are both represented by a LogEst
  12435. ** of 40. However, since LogEst quantities are suppose to be estimates,
  12436. ** not exact values, this imprecision is not a problem.
  12437. **
  12438. ** "LogEst" is short for "Logarithmic Estimate".
  12439. **
  12440. ** Examples:
  12441. ** 1 -> 0 20 -> 43 10000 -> 132
  12442. ** 2 -> 10 25 -> 46 25000 -> 146
  12443. ** 3 -> 16 100 -> 66 1000000 -> 199
  12444. ** 4 -> 20 1000 -> 99 1048576 -> 200
  12445. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  12446. **
  12447. ** The LogEst can be negative to indicate fractional values.
  12448. ** Examples:
  12449. **
  12450. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  12451. */
  12452. typedef INT16_TYPE LogEst;
  12453. /*
  12454. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  12455. */
  12456. #ifndef SQLITE_PTRSIZE
  12457. # if defined(__SIZEOF_POINTER__)
  12458. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  12459. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  12460. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  12461. # define SQLITE_PTRSIZE 4
  12462. # else
  12463. # define SQLITE_PTRSIZE 8
  12464. # endif
  12465. #endif
  12466. /* The uptr type is an unsigned integer large enough to hold a pointer
  12467. */
  12468. #if defined(HAVE_STDINT_H)
  12469. typedef uintptr_t uptr;
  12470. #elif SQLITE_PTRSIZE==4
  12471. typedef u32 uptr;
  12472. #else
  12473. typedef u64 uptr;
  12474. #endif
  12475. /*
  12476. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  12477. ** something between S (inclusive) and E (exclusive).
  12478. **
  12479. ** In other words, S is a buffer and E is a pointer to the first byte after
  12480. ** the end of buffer S. This macro returns true if P points to something
  12481. ** contained within the buffer S.
  12482. */
  12483. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  12484. /*
  12485. ** Macros to determine whether the machine is big or little endian,
  12486. ** and whether or not that determination is run-time or compile-time.
  12487. **
  12488. ** For best performance, an attempt is made to guess at the byte-order
  12489. ** using C-preprocessor macros. If that is unsuccessful, or if
  12490. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  12491. ** at run-time.
  12492. */
  12493. #ifndef SQLITE_BYTEORDER
  12494. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  12495. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  12496. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  12497. defined(__arm__)
  12498. # define SQLITE_BYTEORDER 1234
  12499. # elif defined(sparc) || defined(__ppc__)
  12500. # define SQLITE_BYTEORDER 4321
  12501. # else
  12502. # define SQLITE_BYTEORDER 0
  12503. # endif
  12504. #endif
  12505. #if SQLITE_BYTEORDER==4321
  12506. # define SQLITE_BIGENDIAN 1
  12507. # define SQLITE_LITTLEENDIAN 0
  12508. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  12509. #elif SQLITE_BYTEORDER==1234
  12510. # define SQLITE_BIGENDIAN 0
  12511. # define SQLITE_LITTLEENDIAN 1
  12512. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  12513. #else
  12514. # ifdef SQLITE_AMALGAMATION
  12515. const int sqlite3one = 1;
  12516. # else
  12517. extern const int sqlite3one;
  12518. # endif
  12519. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  12520. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  12521. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  12522. #endif
  12523. /*
  12524. ** Constants for the largest and smallest possible 64-bit signed integers.
  12525. ** These macros are designed to work correctly on both 32-bit and 64-bit
  12526. ** compilers.
  12527. */
  12528. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  12529. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  12530. /*
  12531. ** Round up a number to the next larger multiple of 8. This is used
  12532. ** to force 8-byte alignment on 64-bit architectures.
  12533. */
  12534. #define ROUND8(x) (((x)+7)&~7)
  12535. /*
  12536. ** Round down to the nearest multiple of 8
  12537. */
  12538. #define ROUNDDOWN8(x) ((x)&~7)
  12539. /*
  12540. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  12541. ** macro is used only within assert() to verify that the code gets
  12542. ** all alignment restrictions correct.
  12543. **
  12544. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  12545. ** underlying malloc() implementation might return us 4-byte aligned
  12546. ** pointers. In that case, only verify 4-byte alignment.
  12547. */
  12548. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12549. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  12550. #else
  12551. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  12552. #endif
  12553. /*
  12554. ** Disable MMAP on platforms where it is known to not work
  12555. */
  12556. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  12557. # undef SQLITE_MAX_MMAP_SIZE
  12558. # define SQLITE_MAX_MMAP_SIZE 0
  12559. #endif
  12560. /*
  12561. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  12562. */
  12563. #ifdef __APPLE__
  12564. # include <TargetConditionals.h>
  12565. #endif
  12566. #ifndef SQLITE_MAX_MMAP_SIZE
  12567. # if defined(__linux__) \
  12568. || defined(_WIN32) \
  12569. || (defined(__APPLE__) && defined(__MACH__)) \
  12570. || defined(__sun) \
  12571. || defined(__FreeBSD__) \
  12572. || defined(__DragonFly__)
  12573. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  12574. # else
  12575. # define SQLITE_MAX_MMAP_SIZE 0
  12576. # endif
  12577. #endif
  12578. /*
  12579. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  12580. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  12581. ** not exceed the maximum mmap size.
  12582. */
  12583. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  12584. # define SQLITE_DEFAULT_MMAP_SIZE 0
  12585. #endif
  12586. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  12587. # undef SQLITE_DEFAULT_MMAP_SIZE
  12588. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  12589. #endif
  12590. /*
  12591. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  12592. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  12593. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  12594. */
  12595. #ifdef SQLITE_ENABLE_STAT4
  12596. # undef SQLITE_ENABLE_STAT3
  12597. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  12598. #elif SQLITE_ENABLE_STAT3
  12599. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  12600. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  12601. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  12602. #endif
  12603. /*
  12604. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  12605. ** the Select query generator tracing logic is turned on.
  12606. */
  12607. #if defined(SQLITE_ENABLE_SELECTTRACE)
  12608. # define SELECTTRACE_ENABLED 1
  12609. #else
  12610. # define SELECTTRACE_ENABLED 0
  12611. #endif
  12612. /*
  12613. ** An instance of the following structure is used to store the busy-handler
  12614. ** callback for a given sqlite handle.
  12615. **
  12616. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  12617. ** callback for the database handle. Each pager opened via the sqlite
  12618. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  12619. ** callback is currently invoked only from within pager.c.
  12620. */
  12621. typedef struct BusyHandler BusyHandler;
  12622. struct BusyHandler {
  12623. int (*xFunc)(void *,int); /* The busy callback */
  12624. void *pArg; /* First arg to busy callback */
  12625. int nBusy; /* Incremented with each busy call */
  12626. };
  12627. /*
  12628. ** Name of the master database table. The master database table
  12629. ** is a special table that holds the names and attributes of all
  12630. ** user tables and indices.
  12631. */
  12632. #define MASTER_NAME "sqlite_master"
  12633. #define TEMP_MASTER_NAME "sqlite_temp_master"
  12634. /*
  12635. ** The root-page of the master database table.
  12636. */
  12637. #define MASTER_ROOT 1
  12638. /*
  12639. ** The name of the schema table.
  12640. */
  12641. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  12642. /*
  12643. ** A convenience macro that returns the number of elements in
  12644. ** an array.
  12645. */
  12646. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  12647. /*
  12648. ** Determine if the argument is a power of two
  12649. */
  12650. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  12651. /*
  12652. ** The following value as a destructor means to use sqlite3DbFree().
  12653. ** The sqlite3DbFree() routine requires two parameters instead of the
  12654. ** one parameter that destructors normally want. So we have to introduce
  12655. ** this magic value that the code knows to handle differently. Any
  12656. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  12657. ** and SQLITE_TRANSIENT.
  12658. */
  12659. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  12660. /*
  12661. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  12662. ** not support Writable Static Data (WSD) such as global and static variables.
  12663. ** All variables must either be on the stack or dynamically allocated from
  12664. ** the heap. When WSD is unsupported, the variable declarations scattered
  12665. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  12666. ** macro is used for this purpose. And instead of referencing the variable
  12667. ** directly, we use its constant as a key to lookup the run-time allocated
  12668. ** buffer that holds real variable. The constant is also the initializer
  12669. ** for the run-time allocated buffer.
  12670. **
  12671. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  12672. ** macros become no-ops and have zero performance impact.
  12673. */
  12674. #ifdef SQLITE_OMIT_WSD
  12675. #define SQLITE_WSD const
  12676. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  12677. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  12678. SQLITE_API int sqlite3_wsd_init(int N, int J);
  12679. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  12680. #else
  12681. #define SQLITE_WSD
  12682. #define GLOBAL(t,v) v
  12683. #define sqlite3GlobalConfig sqlite3Config
  12684. #endif
  12685. /*
  12686. ** The following macros are used to suppress compiler warnings and to
  12687. ** make it clear to human readers when a function parameter is deliberately
  12688. ** left unused within the body of a function. This usually happens when
  12689. ** a function is called via a function pointer. For example the
  12690. ** implementation of an SQL aggregate step callback may not use the
  12691. ** parameter indicating the number of arguments passed to the aggregate,
  12692. ** if it knows that this is enforced elsewhere.
  12693. **
  12694. ** When a function parameter is not used at all within the body of a function,
  12695. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  12696. ** However, these macros may also be used to suppress warnings related to
  12697. ** parameters that may or may not be used depending on compilation options.
  12698. ** For example those parameters only used in assert() statements. In these
  12699. ** cases the parameters are named as per the usual conventions.
  12700. */
  12701. #define UNUSED_PARAMETER(x) (void)(x)
  12702. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  12703. /*
  12704. ** Forward references to structures
  12705. */
  12706. typedef struct AggInfo AggInfo;
  12707. typedef struct AuthContext AuthContext;
  12708. typedef struct AutoincInfo AutoincInfo;
  12709. typedef struct Bitvec Bitvec;
  12710. typedef struct CollSeq CollSeq;
  12711. typedef struct Column Column;
  12712. typedef struct Db Db;
  12713. typedef struct Schema Schema;
  12714. typedef struct Expr Expr;
  12715. typedef struct ExprList ExprList;
  12716. typedef struct ExprSpan ExprSpan;
  12717. typedef struct FKey FKey;
  12718. typedef struct FuncDestructor FuncDestructor;
  12719. typedef struct FuncDef FuncDef;
  12720. typedef struct FuncDefHash FuncDefHash;
  12721. typedef struct IdList IdList;
  12722. typedef struct Index Index;
  12723. typedef struct IndexSample IndexSample;
  12724. typedef struct KeyClass KeyClass;
  12725. typedef struct KeyInfo KeyInfo;
  12726. typedef struct Lookaside Lookaside;
  12727. typedef struct LookasideSlot LookasideSlot;
  12728. typedef struct Module Module;
  12729. typedef struct NameContext NameContext;
  12730. typedef struct Parse Parse;
  12731. typedef struct PreUpdate PreUpdate;
  12732. typedef struct PrintfArguments PrintfArguments;
  12733. typedef struct RowSet RowSet;
  12734. typedef struct Savepoint Savepoint;
  12735. typedef struct Select Select;
  12736. typedef struct SQLiteThread SQLiteThread;
  12737. typedef struct SelectDest SelectDest;
  12738. typedef struct SrcList SrcList;
  12739. typedef struct StrAccum StrAccum;
  12740. typedef struct Table Table;
  12741. typedef struct TableLock TableLock;
  12742. typedef struct Token Token;
  12743. typedef struct TreeView TreeView;
  12744. typedef struct Trigger Trigger;
  12745. typedef struct TriggerPrg TriggerPrg;
  12746. typedef struct TriggerStep TriggerStep;
  12747. typedef struct UnpackedRecord UnpackedRecord;
  12748. typedef struct VTable VTable;
  12749. typedef struct VtabCtx VtabCtx;
  12750. typedef struct Walker Walker;
  12751. typedef struct WhereInfo WhereInfo;
  12752. typedef struct With With;
  12753. /* A VList object records a mapping between parameters/variables/wildcards
  12754. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  12755. ** variable number associated with that parameter. See the format description
  12756. ** on the sqlite3VListAdd() routine for more information. A VList is really
  12757. ** just an array of integers.
  12758. */
  12759. typedef int VList;
  12760. /*
  12761. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  12762. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  12763. ** pointer types (i.e. FuncDef) defined above.
  12764. */
  12765. /************** Include btree.h in the middle of sqliteInt.h *****************/
  12766. /************** Begin file btree.h *******************************************/
  12767. /*
  12768. ** 2001 September 15
  12769. **
  12770. ** The author disclaims copyright to this source code. In place of
  12771. ** a legal notice, here is a blessing:
  12772. **
  12773. ** May you do good and not evil.
  12774. ** May you find forgiveness for yourself and forgive others.
  12775. ** May you share freely, never taking more than you give.
  12776. **
  12777. *************************************************************************
  12778. ** This header file defines the interface that the sqlite B-Tree file
  12779. ** subsystem. See comments in the source code for a detailed description
  12780. ** of what each interface routine does.
  12781. */
  12782. #ifndef SQLITE_BTREE_H
  12783. #define SQLITE_BTREE_H
  12784. /* TODO: This definition is just included so other modules compile. It
  12785. ** needs to be revisited.
  12786. */
  12787. #define SQLITE_N_BTREE_META 16
  12788. /*
  12789. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  12790. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  12791. */
  12792. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  12793. #define SQLITE_DEFAULT_AUTOVACUUM 0
  12794. #endif
  12795. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  12796. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  12797. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  12798. /*
  12799. ** Forward declarations of structure
  12800. */
  12801. typedef struct Btree Btree;
  12802. typedef struct BtCursor BtCursor;
  12803. typedef struct BtShared BtShared;
  12804. typedef struct BtreePayload BtreePayload;
  12805. SQLITE_PRIVATE int sqlite3BtreeOpen(
  12806. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  12807. const char *zFilename, /* Name of database file to open */
  12808. sqlite3 *db, /* Associated database connection */
  12809. Btree **ppBtree, /* Return open Btree* here */
  12810. int flags, /* Flags */
  12811. int vfsFlags /* Flags passed through to VFS open */
  12812. );
  12813. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  12814. ** following values.
  12815. **
  12816. ** NOTE: These values must match the corresponding PAGER_ values in
  12817. ** pager.h.
  12818. */
  12819. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  12820. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  12821. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  12822. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  12823. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  12824. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  12825. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  12826. #if SQLITE_MAX_MMAP_SIZE>0
  12827. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  12828. #endif
  12829. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  12830. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  12831. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  12832. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  12833. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  12834. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  12835. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  12836. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  12837. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  12838. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  12839. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  12840. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  12841. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  12842. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  12843. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  12844. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  12845. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  12846. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  12847. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  12848. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  12849. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  12850. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  12851. #ifndef SQLITE_OMIT_SHARED_CACHE
  12852. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  12853. #endif
  12854. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  12855. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  12856. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  12857. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  12858. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  12859. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  12860. ** of the flags shown below.
  12861. **
  12862. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  12863. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  12864. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  12865. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  12866. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  12867. ** indices.)
  12868. */
  12869. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  12870. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  12871. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  12872. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  12873. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  12874. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  12875. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  12876. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  12877. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  12878. /*
  12879. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  12880. ** should be one of the following values. The integer values are assigned
  12881. ** to constants so that the offset of the corresponding field in an
  12882. ** SQLite database header may be found using the following formula:
  12883. **
  12884. ** offset = 36 + (idx * 4)
  12885. **
  12886. ** For example, the free-page-count field is located at byte offset 36 of
  12887. ** the database file header. The incr-vacuum-flag field is located at
  12888. ** byte offset 64 (== 36+4*7).
  12889. **
  12890. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  12891. ** It is a read-only number computed by the pager. But we merge it with
  12892. ** the header value access routines since its access pattern is the same.
  12893. ** Call it a "virtual meta value".
  12894. */
  12895. #define BTREE_FREE_PAGE_COUNT 0
  12896. #define BTREE_SCHEMA_VERSION 1
  12897. #define BTREE_FILE_FORMAT 2
  12898. #define BTREE_DEFAULT_CACHE_SIZE 3
  12899. #define BTREE_LARGEST_ROOT_PAGE 4
  12900. #define BTREE_TEXT_ENCODING 5
  12901. #define BTREE_USER_VERSION 6
  12902. #define BTREE_INCR_VACUUM 7
  12903. #define BTREE_APPLICATION_ID 8
  12904. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  12905. /*
  12906. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  12907. ** interface.
  12908. **
  12909. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  12910. **
  12911. ** The first argument is an Expr* (which is guaranteed to be constant for
  12912. ** the lifetime of the cursor) that defines constraints on which rows
  12913. ** might be fetched with this cursor. The Expr* tree may contain
  12914. ** TK_REGISTER nodes that refer to values stored in the array of registers
  12915. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  12916. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  12917. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  12918. ** column of the b-tree of the cursor. The Expr tree will not contain
  12919. ** any function calls nor subqueries nor references to b-trees other than
  12920. ** the cursor being hinted.
  12921. **
  12922. ** The design of the _RANGE hint is aid b-tree implementations that try
  12923. ** to prefetch content from remote machines - to provide those
  12924. ** implementations with limits on what needs to be prefetched and thereby
  12925. ** reduce network bandwidth.
  12926. **
  12927. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  12928. ** standard SQLite. The other hints are provided for extentions that use
  12929. ** the SQLite parser and code generator but substitute their own storage
  12930. ** engine.
  12931. */
  12932. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  12933. /*
  12934. ** Values that may be OR'd together to form the argument to the
  12935. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  12936. **
  12937. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  12938. ** to be filled with content that is already in sorted order.
  12939. **
  12940. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  12941. ** OP_SeekLE opcodes for a range search, but where the range of entries
  12942. ** selected will all have the same key. In other words, the cursor will
  12943. ** be used only for equality key searches.
  12944. **
  12945. */
  12946. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  12947. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  12948. /*
  12949. ** Flags passed as the third argument to sqlite3BtreeCursor().
  12950. **
  12951. ** For read-only cursors the wrFlag argument is always zero. For read-write
  12952. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  12953. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  12954. ** only be used by SQLite for the following:
  12955. **
  12956. ** * to seek to and then delete specific entries, and/or
  12957. **
  12958. ** * to read values that will be used to create keys that other
  12959. ** BTREE_FORDELETE cursors will seek to and delete.
  12960. **
  12961. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  12962. ** by this, the native b-tree engine of SQLite, but it is available to
  12963. ** alternative storage engines that might be substituted in place of this
  12964. ** b-tree system. For alternative storage engines in which a delete of
  12965. ** the main table row automatically deletes corresponding index rows,
  12966. ** the FORDELETE flag hint allows those alternative storage engines to
  12967. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  12968. ** and DELETE operations as no-ops, and any READ operation against a
  12969. ** FORDELETE cursor may return a null row: 0x01 0x00.
  12970. */
  12971. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  12972. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  12973. SQLITE_PRIVATE int sqlite3BtreeCursor(
  12974. Btree*, /* BTree containing table to open */
  12975. int iTable, /* Index of root page */
  12976. int wrFlag, /* 1 for writing. 0 for read-only */
  12977. struct KeyInfo*, /* First argument to compare function */
  12978. BtCursor *pCursor /* Space to write cursor structure */
  12979. );
  12980. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  12981. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  12982. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  12983. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  12984. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  12985. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  12986. #endif
  12987. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  12988. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  12989. BtCursor*,
  12990. UnpackedRecord *pUnKey,
  12991. i64 intKey,
  12992. int bias,
  12993. int *pRes
  12994. );
  12995. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  12996. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  12997. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  12998. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  12999. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  13000. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  13001. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  13002. /* An instance of the BtreePayload object describes the content of a single
  13003. ** entry in either an index or table btree.
  13004. **
  13005. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  13006. ** an arbitrary key and no data. These btrees have pKey,nKey set to their
  13007. ** key and pData,nData,nZero set to zero.
  13008. **
  13009. ** Table btrees (used for rowid tables) contain an integer rowid used as
  13010. ** the key and passed in the nKey field. The pKey field is zero.
  13011. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  13012. ** are appended to the end of the content when constructing the entry.
  13013. **
  13014. ** This object is used to pass information into sqlite3BtreeInsert(). The
  13015. ** same information used to be passed as five separate parameters. But placing
  13016. ** the information into this object helps to keep the interface more
  13017. ** organized and understandable, and it also helps the resulting code to
  13018. ** run a little faster by using fewer registers for parameter passing.
  13019. */
  13020. struct BtreePayload {
  13021. const void *pKey; /* Key content for indexes. NULL for tables */
  13022. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  13023. const void *pData; /* Data for tables. NULL for indexes */
  13024. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  13025. u16 nMem; /* Number of aMem[] value. Might be zero */
  13026. int nData; /* Size of pData. 0 if none. */
  13027. int nZero; /* Extra zero data appended after pData,nData */
  13028. };
  13029. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  13030. int flags, int seekResult);
  13031. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  13032. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  13033. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  13034. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  13035. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  13036. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  13037. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  13038. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  13039. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  13040. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  13041. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  13042. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  13043. #ifndef SQLITE_OMIT_INCRBLOB
  13044. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  13045. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  13046. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  13047. #endif
  13048. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  13049. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  13050. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  13051. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  13052. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  13053. #ifndef NDEBUG
  13054. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  13055. #endif
  13056. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  13057. #ifndef SQLITE_OMIT_BTREECOUNT
  13058. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  13059. #endif
  13060. #ifdef SQLITE_TEST
  13061. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  13062. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  13063. #endif
  13064. #ifndef SQLITE_OMIT_WAL
  13065. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  13066. #endif
  13067. /*
  13068. ** If we are not using shared cache, then there is no need to
  13069. ** use mutexes to access the BtShared structures. So make the
  13070. ** Enter and Leave procedures no-ops.
  13071. */
  13072. #ifndef SQLITE_OMIT_SHARED_CACHE
  13073. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  13074. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  13075. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  13076. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  13077. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  13078. #else
  13079. # define sqlite3BtreeEnter(X)
  13080. # define sqlite3BtreeEnterAll(X)
  13081. # define sqlite3BtreeSharable(X) 0
  13082. # define sqlite3BtreeEnterCursor(X)
  13083. # define sqlite3BtreeConnectionCount(X) 1
  13084. #endif
  13085. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  13086. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  13087. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  13088. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  13089. #ifndef NDEBUG
  13090. /* These routines are used inside assert() statements only. */
  13091. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  13092. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  13093. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  13094. #endif
  13095. #else
  13096. # define sqlite3BtreeLeave(X)
  13097. # define sqlite3BtreeLeaveCursor(X)
  13098. # define sqlite3BtreeLeaveAll(X)
  13099. # define sqlite3BtreeHoldsMutex(X) 1
  13100. # define sqlite3BtreeHoldsAllMutexes(X) 1
  13101. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  13102. #endif
  13103. #endif /* SQLITE_BTREE_H */
  13104. /************** End of btree.h ***********************************************/
  13105. /************** Continuing where we left off in sqliteInt.h ******************/
  13106. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  13107. /************** Begin file vdbe.h ********************************************/
  13108. /*
  13109. ** 2001 September 15
  13110. **
  13111. ** The author disclaims copyright to this source code. In place of
  13112. ** a legal notice, here is a blessing:
  13113. **
  13114. ** May you do good and not evil.
  13115. ** May you find forgiveness for yourself and forgive others.
  13116. ** May you share freely, never taking more than you give.
  13117. **
  13118. *************************************************************************
  13119. ** Header file for the Virtual DataBase Engine (VDBE)
  13120. **
  13121. ** This header defines the interface to the virtual database engine
  13122. ** or VDBE. The VDBE implements an abstract machine that runs a
  13123. ** simple program to access and modify the underlying database.
  13124. */
  13125. #ifndef SQLITE_VDBE_H
  13126. #define SQLITE_VDBE_H
  13127. /* #include <stdio.h> */
  13128. /*
  13129. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  13130. ** in the source file sqliteVdbe.c are allowed to see the insides
  13131. ** of this structure.
  13132. */
  13133. typedef struct Vdbe Vdbe;
  13134. /*
  13135. ** The names of the following types declared in vdbeInt.h are required
  13136. ** for the VdbeOp definition.
  13137. */
  13138. typedef struct sqlite3_value Mem;
  13139. typedef struct SubProgram SubProgram;
  13140. /*
  13141. ** A single instruction of the virtual machine has an opcode
  13142. ** and as many as three operands. The instruction is recorded
  13143. ** as an instance of the following structure:
  13144. */
  13145. struct VdbeOp {
  13146. u8 opcode; /* What operation to perform */
  13147. signed char p4type; /* One of the P4_xxx constants for p4 */
  13148. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  13149. int p1; /* First operand */
  13150. int p2; /* Second parameter (often the jump destination) */
  13151. int p3; /* The third parameter */
  13152. union p4union { /* fourth parameter */
  13153. int i; /* Integer value if p4type==P4_INT32 */
  13154. void *p; /* Generic pointer */
  13155. char *z; /* Pointer to data for string (char array) types */
  13156. i64 *pI64; /* Used when p4type is P4_INT64 */
  13157. double *pReal; /* Used when p4type is P4_REAL */
  13158. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  13159. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  13160. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  13161. Mem *pMem; /* Used when p4type is P4_MEM */
  13162. VTable *pVtab; /* Used when p4type is P4_VTAB */
  13163. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  13164. int *ai; /* Used when p4type is P4_INTARRAY */
  13165. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  13166. Table *pTab; /* Used when p4type is P4_TABLE */
  13167. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13168. Expr *pExpr; /* Used when p4type is P4_EXPR */
  13169. #endif
  13170. int (*xAdvance)(BtCursor *, int);
  13171. } p4;
  13172. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13173. char *zComment; /* Comment to improve readability */
  13174. #endif
  13175. #ifdef VDBE_PROFILE
  13176. u32 cnt; /* Number of times this instruction was executed */
  13177. u64 cycles; /* Total time spent executing this instruction */
  13178. #endif
  13179. #ifdef SQLITE_VDBE_COVERAGE
  13180. int iSrcLine; /* Source-code line that generated this opcode */
  13181. #endif
  13182. };
  13183. typedef struct VdbeOp VdbeOp;
  13184. /*
  13185. ** A sub-routine used to implement a trigger program.
  13186. */
  13187. struct SubProgram {
  13188. VdbeOp *aOp; /* Array of opcodes for sub-program */
  13189. int nOp; /* Elements in aOp[] */
  13190. int nMem; /* Number of memory cells required */
  13191. int nCsr; /* Number of cursors required */
  13192. u8 *aOnce; /* Array of OP_Once flags */
  13193. void *token; /* id that may be used to recursive triggers */
  13194. SubProgram *pNext; /* Next sub-program already visited */
  13195. };
  13196. /*
  13197. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  13198. ** it takes up less space.
  13199. */
  13200. struct VdbeOpList {
  13201. u8 opcode; /* What operation to perform */
  13202. signed char p1; /* First operand */
  13203. signed char p2; /* Second parameter (often the jump destination) */
  13204. signed char p3; /* Third parameter */
  13205. };
  13206. typedef struct VdbeOpList VdbeOpList;
  13207. /*
  13208. ** Allowed values of VdbeOp.p4type
  13209. */
  13210. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  13211. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  13212. #define P4_STATIC (-1) /* Pointer to a static string */
  13213. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  13214. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  13215. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  13216. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  13217. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  13218. /* Above do not own any resources. Must free those below */
  13219. #define P4_FREE_IF_LE (-7)
  13220. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  13221. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  13222. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  13223. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  13224. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  13225. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  13226. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  13227. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  13228. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  13229. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  13230. /* Error message codes for OP_Halt */
  13231. #define P5_ConstraintNotNull 1
  13232. #define P5_ConstraintUnique 2
  13233. #define P5_ConstraintCheck 3
  13234. #define P5_ConstraintFK 4
  13235. /*
  13236. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  13237. ** number of columns of data returned by the statement.
  13238. */
  13239. #define COLNAME_NAME 0
  13240. #define COLNAME_DECLTYPE 1
  13241. #define COLNAME_DATABASE 2
  13242. #define COLNAME_TABLE 3
  13243. #define COLNAME_COLUMN 4
  13244. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  13245. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  13246. #else
  13247. # ifdef SQLITE_OMIT_DECLTYPE
  13248. # define COLNAME_N 1 /* Store only the name */
  13249. # else
  13250. # define COLNAME_N 2 /* Store the name and decltype */
  13251. # endif
  13252. #endif
  13253. /*
  13254. ** The following macro converts a relative address in the p2 field
  13255. ** of a VdbeOp structure into a negative number so that
  13256. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  13257. ** the macro again restores the address.
  13258. */
  13259. #define ADDR(X) (-1-(X))
  13260. /*
  13261. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  13262. ** header file that defines a number for each opcode used by the VDBE.
  13263. */
  13264. /************** Include opcodes.h in the middle of vdbe.h ********************/
  13265. /************** Begin file opcodes.h *****************************************/
  13266. /* Automatically generated. Do not edit */
  13267. /* See the tool/mkopcodeh.tcl script for details */
  13268. #define OP_Savepoint 0
  13269. #define OP_AutoCommit 1
  13270. #define OP_Transaction 2
  13271. #define OP_SorterNext 3 /* jump */
  13272. #define OP_PrevIfOpen 4 /* jump */
  13273. #define OP_NextIfOpen 5 /* jump */
  13274. #define OP_Prev 6 /* jump */
  13275. #define OP_Next 7 /* jump */
  13276. #define OP_Checkpoint 8
  13277. #define OP_JournalMode 9
  13278. #define OP_Vacuum 10
  13279. #define OP_VFilter 11 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  13280. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  13281. #define OP_Goto 13 /* jump */
  13282. #define OP_Gosub 14 /* jump */
  13283. #define OP_InitCoroutine 15 /* jump */
  13284. #define OP_Yield 16 /* jump */
  13285. #define OP_MustBeInt 17 /* jump */
  13286. #define OP_Jump 18 /* jump */
  13287. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  13288. #define OP_Once 20 /* jump */
  13289. #define OP_If 21 /* jump */
  13290. #define OP_IfNot 22 /* jump */
  13291. #define OP_IfNullRow 23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  13292. #define OP_SeekLT 24 /* jump, synopsis: key=r[P3@P4] */
  13293. #define OP_SeekLE 25 /* jump, synopsis: key=r[P3@P4] */
  13294. #define OP_SeekGE 26 /* jump, synopsis: key=r[P3@P4] */
  13295. #define OP_SeekGT 27 /* jump, synopsis: key=r[P3@P4] */
  13296. #define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
  13297. #define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
  13298. #define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
  13299. #define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
  13300. #define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
  13301. #define OP_Last 33 /* jump */
  13302. #define OP_IfSmaller 34 /* jump */
  13303. #define OP_SorterSort 35 /* jump */
  13304. #define OP_Sort 36 /* jump */
  13305. #define OP_Rewind 37 /* jump */
  13306. #define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
  13307. #define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
  13308. #define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
  13309. #define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
  13310. #define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
  13311. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  13312. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  13313. #define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  13314. #define OP_Program 46 /* jump */
  13315. #define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  13316. #define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  13317. #define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  13318. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  13319. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  13320. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  13321. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  13322. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  13323. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  13324. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  13325. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  13326. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  13327. #define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  13328. #define OP_IncrVacuum 60 /* jump */
  13329. #define OP_VNext 61 /* jump */
  13330. #define OP_Init 62 /* jump, synopsis: Start at P2 */
  13331. #define OP_Return 63
  13332. #define OP_EndCoroutine 64
  13333. #define OP_HaltIfNull 65 /* synopsis: if r[P3]=null halt */
  13334. #define OP_Halt 66
  13335. #define OP_Integer 67 /* synopsis: r[P2]=P1 */
  13336. #define OP_Int64 68 /* synopsis: r[P2]=P4 */
  13337. #define OP_String 69 /* synopsis: r[P2]='P4' (len=P1) */
  13338. #define OP_Null 70 /* synopsis: r[P2..P3]=NULL */
  13339. #define OP_SoftNull 71 /* synopsis: r[P1]=NULL */
  13340. #define OP_Blob 72 /* synopsis: r[P2]=P4 (len=P1) */
  13341. #define OP_Variable 73 /* synopsis: r[P2]=parameter(P1,P4) */
  13342. #define OP_Move 74 /* synopsis: r[P2@P3]=r[P1@P3] */
  13343. #define OP_Copy 75 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  13344. #define OP_SCopy 76 /* synopsis: r[P2]=r[P1] */
  13345. #define OP_IntCopy 77 /* synopsis: r[P2]=r[P1] */
  13346. #define OP_ResultRow 78 /* synopsis: output=r[P1@P2] */
  13347. #define OP_CollSeq 79
  13348. #define OP_AddImm 80 /* synopsis: r[P1]=r[P1]+P2 */
  13349. #define OP_RealAffinity 81
  13350. #define OP_Cast 82 /* synopsis: affinity(r[P1]) */
  13351. #define OP_Permutation 83
  13352. #define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  13353. #define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  13354. #define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  13355. #define OP_ShiftRight 87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  13356. #define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  13357. #define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  13358. #define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  13359. #define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  13360. #define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  13361. #define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  13362. #define OP_Compare 94 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  13363. #define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  13364. #define OP_Column 96 /* synopsis: r[P3]=PX */
  13365. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  13366. #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */
  13367. #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  13368. #define OP_Count 100 /* synopsis: r[P2]=count() */
  13369. #define OP_ReadCookie 101
  13370. #define OP_SetCookie 102
  13371. #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */
  13372. #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */
  13373. #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */
  13374. #define OP_OpenDup 106
  13375. #define OP_OpenAutoindex 107 /* synopsis: nColumn=P2 */
  13376. #define OP_OpenEphemeral 108 /* synopsis: nColumn=P2 */
  13377. #define OP_SorterOpen 109
  13378. #define OP_SequenceTest 110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  13379. #define OP_OpenPseudo 111 /* synopsis: P3 columns in r[P2] */
  13380. #define OP_Close 112
  13381. #define OP_ColumnsUsed 113
  13382. #define OP_Sequence 114 /* synopsis: r[P2]=cursor[P1].ctr++ */
  13383. #define OP_NewRowid 115 /* synopsis: r[P2]=rowid */
  13384. #define OP_Insert 116 /* synopsis: intkey=r[P3] data=r[P2] */
  13385. #define OP_InsertInt 117 /* synopsis: intkey=P3 data=r[P2] */
  13386. #define OP_Delete 118
  13387. #define OP_ResetCount 119
  13388. #define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  13389. #define OP_SorterData 121 /* synopsis: r[P2]=data */
  13390. #define OP_RowData 122 /* synopsis: r[P2]=data */
  13391. #define OP_Rowid 123 /* synopsis: r[P2]=rowid */
  13392. #define OP_NullRow 124
  13393. #define OP_SeekEnd 125
  13394. #define OP_SorterInsert 126 /* synopsis: key=r[P2] */
  13395. #define OP_IdxInsert 127 /* synopsis: key=r[P2] */
  13396. #define OP_IdxDelete 128 /* synopsis: key=r[P2@P3] */
  13397. #define OP_DeferredSeek 129 /* synopsis: Move P3 to P1.rowid if needed */
  13398. #define OP_IdxRowid 130 /* synopsis: r[P2]=rowid */
  13399. #define OP_Destroy 131
  13400. #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  13401. #define OP_Clear 133
  13402. #define OP_ResetSorter 134
  13403. #define OP_CreateBtree 135 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  13404. #define OP_SqlExec 136
  13405. #define OP_ParseSchema 137
  13406. #define OP_LoadAnalysis 138
  13407. #define OP_DropTable 139
  13408. #define OP_DropIndex 140
  13409. #define OP_DropTrigger 141
  13410. #define OP_IntegrityCk 142
  13411. #define OP_RowSetAdd 143 /* synopsis: rowset(P1)=r[P2] */
  13412. #define OP_Param 144
  13413. #define OP_FkCounter 145 /* synopsis: fkctr[P1]+=P2 */
  13414. #define OP_MemMax 146 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  13415. #define OP_OffsetLimit 147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  13416. #define OP_AggStep0 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  13417. #define OP_AggStep 149 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  13418. #define OP_AggFinal 150 /* synopsis: accum=r[P1] N=P2 */
  13419. #define OP_Expire 151
  13420. #define OP_TableLock 152 /* synopsis: iDb=P1 root=P2 write=P3 */
  13421. #define OP_VBegin 153
  13422. #define OP_VCreate 154
  13423. #define OP_VDestroy 155
  13424. #define OP_VOpen 156
  13425. #define OP_VColumn 157 /* synopsis: r[P3]=vcolumn(P2) */
  13426. #define OP_VRename 158
  13427. #define OP_Pagecount 159
  13428. #define OP_MaxPgcnt 160
  13429. #define OP_PureFunc0 161
  13430. #define OP_Function0 162 /* synopsis: r[P3]=func(r[P2@P5]) */
  13431. #define OP_PureFunc 163
  13432. #define OP_Function 164 /* synopsis: r[P3]=func(r[P2@P5]) */
  13433. #define OP_CursorHint 165
  13434. #define OP_Noop 166
  13435. #define OP_Explain 167
  13436. /* Properties such as "out2" or "jump" that are specified in
  13437. ** comments following the "case" for each opcode in the vdbe.c
  13438. ** are encoded into bitvectors as follows:
  13439. */
  13440. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  13441. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  13442. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  13443. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  13444. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  13445. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  13446. #define OPFLG_INITIALIZER {\
  13447. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  13448. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
  13449. /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
  13450. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  13451. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  13452. /* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
  13453. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  13454. /* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
  13455. /* 64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
  13456. /* 72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  13457. /* 80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\
  13458. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
  13459. /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  13460. /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13461. /* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
  13462. /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x04,\
  13463. /* 128 */ 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x10,\
  13464. /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\
  13465. /* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
  13466. /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
  13467. /* 160 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13468. }
  13469. /* The sqlite3P2Values() routine is able to run faster if it knows
  13470. ** the value of the largest JUMP opcode. The smaller the maximum
  13471. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  13472. ** generated this include file strives to group all JUMP opcodes
  13473. ** together near the beginning of the list.
  13474. */
  13475. #define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
  13476. /************** End of opcodes.h *********************************************/
  13477. /************** Continuing where we left off in vdbe.h ***********************/
  13478. /*
  13479. ** Additional non-public SQLITE_PREPARE_* flags
  13480. */
  13481. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  13482. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  13483. /*
  13484. ** Prototypes for the VDBE interface. See comments on the implementation
  13485. ** for a description of what each of these routines does.
  13486. */
  13487. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  13488. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  13489. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  13490. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  13491. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  13492. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  13493. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  13494. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  13495. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  13496. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  13497. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  13498. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  13499. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  13500. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  13501. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  13502. #else
  13503. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  13504. # define sqlite3VdbeVerifyNoResultRow(A)
  13505. #endif
  13506. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  13507. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  13508. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  13509. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  13510. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  13511. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  13512. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  13513. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  13514. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  13515. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  13516. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  13517. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  13518. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  13519. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  13520. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  13521. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  13522. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  13523. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  13524. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  13525. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  13526. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  13527. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  13528. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  13529. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  13530. #ifdef SQLITE_DEBUG
  13531. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  13532. #endif
  13533. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  13534. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  13535. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  13536. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  13537. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  13538. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  13539. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  13540. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  13541. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  13542. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  13543. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  13544. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  13545. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  13546. #ifndef SQLITE_OMIT_TRACE
  13547. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  13548. #endif
  13549. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13550. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  13551. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  13552. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  13553. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  13554. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  13555. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  13556. #ifndef SQLITE_OMIT_TRIGGER
  13557. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  13558. #endif
  13559. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  13560. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  13561. ** each VDBE opcode.
  13562. **
  13563. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  13564. ** comments in VDBE programs that show key decision points in the code
  13565. ** generator.
  13566. */
  13567. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13568. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  13569. # define VdbeComment(X) sqlite3VdbeComment X
  13570. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  13571. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  13572. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  13573. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  13574. # else
  13575. # define VdbeModuleComment(X)
  13576. # endif
  13577. #else
  13578. # define VdbeComment(X)
  13579. # define VdbeNoopComment(X)
  13580. # define VdbeModuleComment(X)
  13581. #endif
  13582. /*
  13583. ** The VdbeCoverage macros are used to set a coverage testing point
  13584. ** for VDBE branch instructions. The coverage testing points are line
  13585. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  13586. ** only works with an amalagmation build. That's ok since a VDBE branch
  13587. ** coverage build designed for testing the test suite only. No application
  13588. ** should ever ship with VDBE branch coverage measuring turned on.
  13589. **
  13590. ** VdbeCoverage(v) // Mark the previously coded instruction
  13591. ** // as a branch
  13592. **
  13593. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  13594. **
  13595. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  13596. **
  13597. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  13598. **
  13599. ** Every VDBE branch operation must be tagged with one of the macros above.
  13600. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  13601. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  13602. ** routine in vdbe.c, alerting the developer to the missed tag.
  13603. */
  13604. #ifdef SQLITE_VDBE_COVERAGE
  13605. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  13606. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  13607. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  13608. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  13609. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  13610. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  13611. #else
  13612. # define VdbeCoverage(v)
  13613. # define VdbeCoverageIf(v,x)
  13614. # define VdbeCoverageAlwaysTaken(v)
  13615. # define VdbeCoverageNeverTaken(v)
  13616. # define VDBE_OFFSET_LINENO(x) 0
  13617. #endif
  13618. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  13619. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  13620. #else
  13621. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  13622. #endif
  13623. #endif /* SQLITE_VDBE_H */
  13624. /************** End of vdbe.h ************************************************/
  13625. /************** Continuing where we left off in sqliteInt.h ******************/
  13626. /************** Include pager.h in the middle of sqliteInt.h *****************/
  13627. /************** Begin file pager.h *******************************************/
  13628. /*
  13629. ** 2001 September 15
  13630. **
  13631. ** The author disclaims copyright to this source code. In place of
  13632. ** a legal notice, here is a blessing:
  13633. **
  13634. ** May you do good and not evil.
  13635. ** May you find forgiveness for yourself and forgive others.
  13636. ** May you share freely, never taking more than you give.
  13637. **
  13638. *************************************************************************
  13639. ** This header file defines the interface that the sqlite page cache
  13640. ** subsystem. The page cache subsystem reads and writes a file a page
  13641. ** at a time and provides a journal for rollback.
  13642. */
  13643. #ifndef SQLITE_PAGER_H
  13644. #define SQLITE_PAGER_H
  13645. /*
  13646. ** Default maximum size for persistent journal files. A negative
  13647. ** value means no limit. This value may be overridden using the
  13648. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  13649. */
  13650. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  13651. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  13652. #endif
  13653. /*
  13654. ** The type used to represent a page number. The first page in a file
  13655. ** is called page 1. 0 is used to represent "not a page".
  13656. */
  13657. typedef u32 Pgno;
  13658. /*
  13659. ** Each open file is managed by a separate instance of the "Pager" structure.
  13660. */
  13661. typedef struct Pager Pager;
  13662. /*
  13663. ** Handle type for pages.
  13664. */
  13665. typedef struct PgHdr DbPage;
  13666. /*
  13667. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  13668. ** reserved for working around a windows/posix incompatibility). It is
  13669. ** used in the journal to signify that the remainder of the journal file
  13670. ** is devoted to storing a master journal name - there are no more pages to
  13671. ** roll back. See comments for function writeMasterJournal() in pager.c
  13672. ** for details.
  13673. */
  13674. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  13675. /*
  13676. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  13677. **
  13678. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  13679. */
  13680. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  13681. #define PAGER_MEMORY 0x0002 /* In-memory database */
  13682. /*
  13683. ** Valid values for the second argument to sqlite3PagerLockingMode().
  13684. */
  13685. #define PAGER_LOCKINGMODE_QUERY -1
  13686. #define PAGER_LOCKINGMODE_NORMAL 0
  13687. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  13688. /*
  13689. ** Numeric constants that encode the journalmode.
  13690. **
  13691. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  13692. ** are exposed in the API via the "PRAGMA journal_mode" command and
  13693. ** therefore cannot be changed without a compatibility break.
  13694. */
  13695. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  13696. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  13697. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  13698. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  13699. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  13700. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  13701. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  13702. /*
  13703. ** Flags that make up the mask passed to sqlite3PagerGet().
  13704. */
  13705. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  13706. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  13707. /*
  13708. ** Flags for sqlite3PagerSetFlags()
  13709. **
  13710. ** Value constraints (enforced via assert()):
  13711. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  13712. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  13713. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  13714. */
  13715. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  13716. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  13717. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  13718. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  13719. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  13720. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  13721. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  13722. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  13723. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  13724. /*
  13725. ** The remainder of this file contains the declarations of the functions
  13726. ** that make up the Pager sub-system API. See source code comments for
  13727. ** a detailed description of each routine.
  13728. */
  13729. /* Open and close a Pager connection. */
  13730. SQLITE_PRIVATE int sqlite3PagerOpen(
  13731. sqlite3_vfs*,
  13732. Pager **ppPager,
  13733. const char*,
  13734. int,
  13735. int,
  13736. int,
  13737. void(*)(DbPage*)
  13738. );
  13739. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  13740. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  13741. /* Functions used to configure a Pager object. */
  13742. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  13743. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  13744. #ifdef SQLITE_HAS_CODEC
  13745. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  13746. #endif
  13747. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  13748. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  13749. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  13750. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  13751. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  13752. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  13753. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  13754. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  13755. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  13756. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  13757. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  13758. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  13759. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  13760. /* Functions used to obtain and release page references. */
  13761. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  13762. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  13763. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  13764. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  13765. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  13766. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  13767. /* Operations on page references. */
  13768. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  13769. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  13770. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  13771. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  13772. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  13773. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  13774. /* Functions used to manage pager transactions and savepoints. */
  13775. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  13776. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  13777. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  13778. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  13779. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  13780. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  13781. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  13782. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  13783. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  13784. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  13785. #ifndef SQLITE_OMIT_WAL
  13786. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  13787. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  13788. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  13789. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  13790. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  13791. # ifdef SQLITE_DIRECT_OVERFLOW_READ
  13792. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
  13793. # endif
  13794. # ifdef SQLITE_ENABLE_SNAPSHOT
  13795. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  13796. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  13797. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  13798. # endif
  13799. #else
  13800. # define sqlite3PagerUseWal(x,y) 0
  13801. #endif
  13802. #ifdef SQLITE_ENABLE_ZIPVFS
  13803. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  13804. #endif
  13805. /* Functions used to query pager state and configuration. */
  13806. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  13807. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  13808. #ifdef SQLITE_DEBUG
  13809. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  13810. #endif
  13811. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  13812. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  13813. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  13814. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  13815. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  13816. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  13817. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  13818. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  13819. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  13820. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  13821. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  13822. /* Functions used to truncate the database file. */
  13823. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  13824. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  13825. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  13826. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  13827. #endif
  13828. /* Functions to support testing and debugging. */
  13829. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  13830. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  13831. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  13832. #endif
  13833. #ifdef SQLITE_TEST
  13834. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  13835. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  13836. void disable_simulated_io_errors(void);
  13837. void enable_simulated_io_errors(void);
  13838. #else
  13839. # define disable_simulated_io_errors()
  13840. # define enable_simulated_io_errors()
  13841. #endif
  13842. #endif /* SQLITE_PAGER_H */
  13843. /************** End of pager.h ***********************************************/
  13844. /************** Continuing where we left off in sqliteInt.h ******************/
  13845. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  13846. /************** Begin file pcache.h ******************************************/
  13847. /*
  13848. ** 2008 August 05
  13849. **
  13850. ** The author disclaims copyright to this source code. In place of
  13851. ** a legal notice, here is a blessing:
  13852. **
  13853. ** May you do good and not evil.
  13854. ** May you find forgiveness for yourself and forgive others.
  13855. ** May you share freely, never taking more than you give.
  13856. **
  13857. *************************************************************************
  13858. ** This header file defines the interface that the sqlite page cache
  13859. ** subsystem.
  13860. */
  13861. #ifndef _PCACHE_H_
  13862. typedef struct PgHdr PgHdr;
  13863. typedef struct PCache PCache;
  13864. /*
  13865. ** Every page in the cache is controlled by an instance of the following
  13866. ** structure.
  13867. */
  13868. struct PgHdr {
  13869. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  13870. void *pData; /* Page data */
  13871. void *pExtra; /* Extra content */
  13872. PCache *pCache; /* PRIVATE: Cache that owns this page */
  13873. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  13874. Pager *pPager; /* The pager this page is part of */
  13875. Pgno pgno; /* Page number for this page */
  13876. #ifdef SQLITE_CHECK_PAGES
  13877. u32 pageHash; /* Hash of page content */
  13878. #endif
  13879. u16 flags; /* PGHDR flags defined below */
  13880. /**********************************************************************
  13881. ** Elements above, except pCache, are public. All that follow are
  13882. ** private to pcache.c and should not be accessed by other modules.
  13883. ** pCache is grouped with the public elements for efficiency.
  13884. */
  13885. i16 nRef; /* Number of users of this page */
  13886. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  13887. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  13888. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  13889. ** PgHdr object is not dirty */
  13890. };
  13891. /* Bit values for PgHdr.flags */
  13892. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  13893. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  13894. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  13895. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  13896. ** writing this page to the database */
  13897. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  13898. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  13899. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  13900. /* Initialize and shutdown the page cache subsystem */
  13901. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  13902. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  13903. /* Page cache buffer management:
  13904. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  13905. */
  13906. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  13907. /* Create a new pager cache.
  13908. ** Under memory stress, invoke xStress to try to make pages clean.
  13909. ** Only clean and unpinned pages can be reclaimed.
  13910. */
  13911. SQLITE_PRIVATE int sqlite3PcacheOpen(
  13912. int szPage, /* Size of every page */
  13913. int szExtra, /* Extra space associated with each page */
  13914. int bPurgeable, /* True if pages are on backing store */
  13915. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  13916. void *pStress, /* Argument to xStress */
  13917. PCache *pToInit /* Preallocated space for the PCache */
  13918. );
  13919. /* Modify the page-size after the cache has been created. */
  13920. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  13921. /* Return the size in bytes of a PCache object. Used to preallocate
  13922. ** storage space.
  13923. */
  13924. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  13925. /* One release per successful fetch. Page is pinned until released.
  13926. ** Reference counted.
  13927. */
  13928. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  13929. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  13930. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  13931. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  13932. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  13933. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  13934. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  13935. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  13936. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  13937. /* Change a page number. Used by incr-vacuum. */
  13938. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  13939. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  13940. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  13941. /* Get a list of all dirty pages in the cache, sorted by page number */
  13942. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  13943. /* Reset and close the cache object */
  13944. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  13945. /* Clear flags from pages of the page cache */
  13946. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  13947. /* Discard the contents of the cache */
  13948. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  13949. /* Return the total number of outstanding page references */
  13950. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  13951. /* Increment the reference count of an existing page */
  13952. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  13953. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  13954. /* Return the total number of pages stored in the cache */
  13955. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  13956. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  13957. /* Iterate through all dirty pages currently stored in the cache. This
  13958. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  13959. ** library is built.
  13960. */
  13961. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  13962. #endif
  13963. #if defined(SQLITE_DEBUG)
  13964. /* Check invariants on a PgHdr object */
  13965. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  13966. #endif
  13967. /* Set and get the suggested cache-size for the specified pager-cache.
  13968. **
  13969. ** If no global maximum is configured, then the system attempts to limit
  13970. ** the total number of pages cached by purgeable pager-caches to the sum
  13971. ** of the suggested cache-sizes.
  13972. */
  13973. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  13974. #ifdef SQLITE_TEST
  13975. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  13976. #endif
  13977. /* Set or get the suggested spill-size for the specified pager-cache.
  13978. **
  13979. ** The spill-size is the minimum number of pages in cache before the cache
  13980. ** will attempt to spill dirty pages by calling xStress.
  13981. */
  13982. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  13983. /* Free up as much memory as possible from the page cache */
  13984. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  13985. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  13986. /* Try to return memory used by the pcache module to the main memory heap */
  13987. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  13988. #endif
  13989. #ifdef SQLITE_TEST
  13990. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  13991. #endif
  13992. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  13993. /* Return the header size */
  13994. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  13995. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  13996. /* Number of dirty pages as a percentage of the configured cache size */
  13997. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  13998. #endif /* _PCACHE_H_ */
  13999. /************** End of pcache.h **********************************************/
  14000. /************** Continuing where we left off in sqliteInt.h ******************/
  14001. /************** Include os.h in the middle of sqliteInt.h ********************/
  14002. /************** Begin file os.h **********************************************/
  14003. /*
  14004. ** 2001 September 16
  14005. **
  14006. ** The author disclaims copyright to this source code. In place of
  14007. ** a legal notice, here is a blessing:
  14008. **
  14009. ** May you do good and not evil.
  14010. ** May you find forgiveness for yourself and forgive others.
  14011. ** May you share freely, never taking more than you give.
  14012. **
  14013. ******************************************************************************
  14014. **
  14015. ** This header file (together with is companion C source-code file
  14016. ** "os.c") attempt to abstract the underlying operating system so that
  14017. ** the SQLite library will work on both POSIX and windows systems.
  14018. **
  14019. ** This header file is #include-ed by sqliteInt.h and thus ends up
  14020. ** being included by every source file.
  14021. */
  14022. #ifndef _SQLITE_OS_H_
  14023. #define _SQLITE_OS_H_
  14024. /*
  14025. ** Attempt to automatically detect the operating system and setup the
  14026. ** necessary pre-processor macros for it.
  14027. */
  14028. /************** Include os_setup.h in the middle of os.h *********************/
  14029. /************** Begin file os_setup.h ****************************************/
  14030. /*
  14031. ** 2013 November 25
  14032. **
  14033. ** The author disclaims copyright to this source code. In place of
  14034. ** a legal notice, here is a blessing:
  14035. **
  14036. ** May you do good and not evil.
  14037. ** May you find forgiveness for yourself and forgive others.
  14038. ** May you share freely, never taking more than you give.
  14039. **
  14040. ******************************************************************************
  14041. **
  14042. ** This file contains pre-processor directives related to operating system
  14043. ** detection and/or setup.
  14044. */
  14045. #ifndef SQLITE_OS_SETUP_H
  14046. #define SQLITE_OS_SETUP_H
  14047. /*
  14048. ** Figure out if we are dealing with Unix, Windows, or some other operating
  14049. ** system.
  14050. **
  14051. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  14052. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  14053. ** the three will be 1. The other two will be 0.
  14054. */
  14055. #if defined(SQLITE_OS_OTHER)
  14056. # if SQLITE_OS_OTHER==1
  14057. # undef SQLITE_OS_UNIX
  14058. # define SQLITE_OS_UNIX 0
  14059. # undef SQLITE_OS_WIN
  14060. # define SQLITE_OS_WIN 0
  14061. # else
  14062. # undef SQLITE_OS_OTHER
  14063. # endif
  14064. #endif
  14065. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  14066. # define SQLITE_OS_OTHER 0
  14067. # ifndef SQLITE_OS_WIN
  14068. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  14069. defined(__MINGW32__) || defined(__BORLANDC__)
  14070. # define SQLITE_OS_WIN 1
  14071. # define SQLITE_OS_UNIX 0
  14072. # else
  14073. # define SQLITE_OS_WIN 0
  14074. # define SQLITE_OS_UNIX 1
  14075. # endif
  14076. # else
  14077. # define SQLITE_OS_UNIX 0
  14078. # endif
  14079. #else
  14080. # ifndef SQLITE_OS_WIN
  14081. # define SQLITE_OS_WIN 0
  14082. # endif
  14083. #endif
  14084. #endif /* SQLITE_OS_SETUP_H */
  14085. /************** End of os_setup.h ********************************************/
  14086. /************** Continuing where we left off in os.h *************************/
  14087. /* If the SET_FULLSYNC macro is not defined above, then make it
  14088. ** a no-op
  14089. */
  14090. #ifndef SET_FULLSYNC
  14091. # define SET_FULLSYNC(x,y)
  14092. #endif
  14093. /*
  14094. ** The default size of a disk sector
  14095. */
  14096. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  14097. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  14098. #endif
  14099. /*
  14100. ** Temporary files are named starting with this prefix followed by 16 random
  14101. ** alphanumeric characters, and no file extension. They are stored in the
  14102. ** OS's standard temporary file directory, and are deleted prior to exit.
  14103. ** If sqlite is being embedded in another program, you may wish to change the
  14104. ** prefix to reflect your program's name, so that if your program exits
  14105. ** prematurely, old temporary files can be easily identified. This can be done
  14106. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  14107. **
  14108. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  14109. ** Mcafee started using SQLite in their anti-virus product and it
  14110. ** started putting files with the "sqlite" name in the c:/temp folder.
  14111. ** This annoyed many windows users. Those users would then do a
  14112. ** Google search for "sqlite", find the telephone numbers of the
  14113. ** developers and call to wake them up at night and complain.
  14114. ** For this reason, the default name prefix is changed to be "sqlite"
  14115. ** spelled backwards. So the temp files are still identified, but
  14116. ** anybody smart enough to figure out the code is also likely smart
  14117. ** enough to know that calling the developer will not help get rid
  14118. ** of the file.
  14119. */
  14120. #ifndef SQLITE_TEMP_FILE_PREFIX
  14121. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  14122. #endif
  14123. /*
  14124. ** The following values may be passed as the second argument to
  14125. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  14126. **
  14127. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  14128. ** RESERVED: A single process may hold a RESERVED lock on a file at
  14129. ** any time. Other processes may hold and obtain new SHARED locks.
  14130. ** PENDING: A single process may hold a PENDING lock on a file at
  14131. ** any one time. Existing SHARED locks may persist, but no new
  14132. ** SHARED locks may be obtained by other processes.
  14133. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  14134. **
  14135. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  14136. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  14137. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  14138. ** sqlite3OsLock().
  14139. */
  14140. #define NO_LOCK 0
  14141. #define SHARED_LOCK 1
  14142. #define RESERVED_LOCK 2
  14143. #define PENDING_LOCK 3
  14144. #define EXCLUSIVE_LOCK 4
  14145. /*
  14146. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  14147. **
  14148. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  14149. ** those functions are not available. So we use only LockFile() and
  14150. ** UnlockFile().
  14151. **
  14152. ** LockFile() prevents not just writing but also reading by other processes.
  14153. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  14154. ** byte out of a specific range of bytes. The lock byte is obtained at
  14155. ** random so two separate readers can probably access the file at the
  14156. ** same time, unless they are unlucky and choose the same lock byte.
  14157. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  14158. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  14159. ** a single byte of the file that is designated as the reserved lock byte.
  14160. ** A PENDING_LOCK is obtained by locking a designated byte different from
  14161. ** the RESERVED_LOCK byte.
  14162. **
  14163. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  14164. ** which means we can use reader/writer locks. When reader/writer locks
  14165. ** are used, the lock is placed on the same range of bytes that is used
  14166. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  14167. ** will support two or more Win95 readers or two or more WinNT readers.
  14168. ** But a single Win95 reader will lock out all WinNT readers and a single
  14169. ** WinNT reader will lock out all other Win95 readers.
  14170. **
  14171. ** The following #defines specify the range of bytes used for locking.
  14172. ** SHARED_SIZE is the number of bytes available in the pool from which
  14173. ** a random byte is selected for a shared lock. The pool of bytes for
  14174. ** shared locks begins at SHARED_FIRST.
  14175. **
  14176. ** The same locking strategy and
  14177. ** byte ranges are used for Unix. This leaves open the possibility of having
  14178. ** clients on win95, winNT, and unix all talking to the same shared file
  14179. ** and all locking correctly. To do so would require that samba (or whatever
  14180. ** tool is being used for file sharing) implements locks correctly between
  14181. ** windows and unix. I'm guessing that isn't likely to happen, but by
  14182. ** using the same locking range we are at least open to the possibility.
  14183. **
  14184. ** Locking in windows is manditory. For this reason, we cannot store
  14185. ** actual data in the bytes used for locking. The pager never allocates
  14186. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  14187. ** that all locks will fit on a single page even at the minimum page size.
  14188. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  14189. ** is set high so that we don't have to allocate an unused page except
  14190. ** for very large databases. But one should test the page skipping logic
  14191. ** by setting PENDING_BYTE low and running the entire regression suite.
  14192. **
  14193. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  14194. ** file format. Depending on how it is changed, you might not notice
  14195. ** the incompatibility right away, even running a full regression test.
  14196. ** The default location of PENDING_BYTE is the first byte past the
  14197. ** 1GB boundary.
  14198. **
  14199. */
  14200. #ifdef SQLITE_OMIT_WSD
  14201. # define PENDING_BYTE (0x40000000)
  14202. #else
  14203. # define PENDING_BYTE sqlite3PendingByte
  14204. #endif
  14205. #define RESERVED_BYTE (PENDING_BYTE+1)
  14206. #define SHARED_FIRST (PENDING_BYTE+2)
  14207. #define SHARED_SIZE 510
  14208. /*
  14209. ** Wrapper around OS specific sqlite3_os_init() function.
  14210. */
  14211. SQLITE_PRIVATE int sqlite3OsInit(void);
  14212. /*
  14213. ** Functions for accessing sqlite3_file methods
  14214. */
  14215. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  14216. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  14217. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  14218. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  14219. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  14220. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  14221. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  14222. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  14223. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  14224. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  14225. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  14226. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  14227. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  14228. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  14229. #ifndef SQLITE_OMIT_WAL
  14230. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  14231. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  14232. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  14233. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  14234. #endif /* SQLITE_OMIT_WAL */
  14235. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  14236. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  14237. /*
  14238. ** Functions for accessing sqlite3_vfs methods
  14239. */
  14240. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  14241. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  14242. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  14243. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  14244. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14245. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  14246. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  14247. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  14248. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  14249. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14250. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  14251. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  14252. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  14253. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  14254. /*
  14255. ** Convenience functions for opening and closing files using
  14256. ** sqlite3_malloc() to obtain space for the file-handle structure.
  14257. */
  14258. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  14259. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  14260. #endif /* _SQLITE_OS_H_ */
  14261. /************** End of os.h **************************************************/
  14262. /************** Continuing where we left off in sqliteInt.h ******************/
  14263. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  14264. /************** Begin file mutex.h *******************************************/
  14265. /*
  14266. ** 2007 August 28
  14267. **
  14268. ** The author disclaims copyright to this source code. In place of
  14269. ** a legal notice, here is a blessing:
  14270. **
  14271. ** May you do good and not evil.
  14272. ** May you find forgiveness for yourself and forgive others.
  14273. ** May you share freely, never taking more than you give.
  14274. **
  14275. *************************************************************************
  14276. **
  14277. ** This file contains the common header for all mutex implementations.
  14278. ** The sqliteInt.h header #includes this file so that it is available
  14279. ** to all source files. We break it out in an effort to keep the code
  14280. ** better organized.
  14281. **
  14282. ** NOTE: source files should *not* #include this header file directly.
  14283. ** Source files should #include the sqliteInt.h file and let that file
  14284. ** include this one indirectly.
  14285. */
  14286. /*
  14287. ** Figure out what version of the code to use. The choices are
  14288. **
  14289. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  14290. ** mutexes implementation cannot be overridden
  14291. ** at start-time.
  14292. **
  14293. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  14294. ** mutual exclusion is provided. But this
  14295. ** implementation can be overridden at
  14296. ** start-time.
  14297. **
  14298. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  14299. **
  14300. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  14301. */
  14302. #if !SQLITE_THREADSAFE
  14303. # define SQLITE_MUTEX_OMIT
  14304. #endif
  14305. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  14306. # if SQLITE_OS_UNIX
  14307. # define SQLITE_MUTEX_PTHREADS
  14308. # elif SQLITE_OS_WIN
  14309. # define SQLITE_MUTEX_W32
  14310. # else
  14311. # define SQLITE_MUTEX_NOOP
  14312. # endif
  14313. #endif
  14314. #ifdef SQLITE_MUTEX_OMIT
  14315. /*
  14316. ** If this is a no-op implementation, implement everything as macros.
  14317. */
  14318. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  14319. #define sqlite3_mutex_free(X)
  14320. #define sqlite3_mutex_enter(X)
  14321. #define sqlite3_mutex_try(X) SQLITE_OK
  14322. #define sqlite3_mutex_leave(X)
  14323. #define sqlite3_mutex_held(X) ((void)(X),1)
  14324. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  14325. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  14326. #define sqlite3MutexInit() SQLITE_OK
  14327. #define sqlite3MutexEnd()
  14328. #define MUTEX_LOGIC(X)
  14329. #else
  14330. #define MUTEX_LOGIC(X) X
  14331. #endif /* defined(SQLITE_MUTEX_OMIT) */
  14332. /************** End of mutex.h ***********************************************/
  14333. /************** Continuing where we left off in sqliteInt.h ******************/
  14334. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  14335. ** synchronous setting to EXTRA. It is no longer supported.
  14336. */
  14337. #ifdef SQLITE_EXTRA_DURABLE
  14338. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  14339. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  14340. #endif
  14341. /*
  14342. ** Default synchronous levels.
  14343. **
  14344. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  14345. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  14346. **
  14347. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  14348. ** OFF 1 0
  14349. ** NORMAL 2 1
  14350. ** FULL 3 2
  14351. ** EXTRA 4 3
  14352. **
  14353. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  14354. ** In other words, the zero-based numbers are used for all external interfaces
  14355. ** and the one-based values are used internally.
  14356. */
  14357. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  14358. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  14359. #endif
  14360. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  14361. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  14362. #endif
  14363. /*
  14364. ** Each database file to be accessed by the system is an instance
  14365. ** of the following structure. There are normally two of these structures
  14366. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  14367. ** aDb[1] is the database file used to hold temporary tables. Additional
  14368. ** databases may be attached.
  14369. */
  14370. struct Db {
  14371. char *zDbSName; /* Name of this database. (schema name, not filename) */
  14372. Btree *pBt; /* The B*Tree structure for this database file */
  14373. u8 safety_level; /* How aggressive at syncing data to disk */
  14374. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  14375. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  14376. };
  14377. /*
  14378. ** An instance of the following structure stores a database schema.
  14379. **
  14380. ** Most Schema objects are associated with a Btree. The exception is
  14381. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  14382. ** In shared cache mode, a single Schema object can be shared by multiple
  14383. ** Btrees that refer to the same underlying BtShared object.
  14384. **
  14385. ** Schema objects are automatically deallocated when the last Btree that
  14386. ** references them is destroyed. The TEMP Schema is manually freed by
  14387. ** sqlite3_close().
  14388. *
  14389. ** A thread must be holding a mutex on the corresponding Btree in order
  14390. ** to access Schema content. This implies that the thread must also be
  14391. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  14392. ** For a TEMP Schema, only the connection mutex is required.
  14393. */
  14394. struct Schema {
  14395. int schema_cookie; /* Database schema version number for this file */
  14396. int iGeneration; /* Generation counter. Incremented with each change */
  14397. Hash tblHash; /* All tables indexed by name */
  14398. Hash idxHash; /* All (named) indices indexed by name */
  14399. Hash trigHash; /* All triggers indexed by name */
  14400. Hash fkeyHash; /* All foreign keys by referenced table name */
  14401. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  14402. u8 file_format; /* Schema format version for this file */
  14403. u8 enc; /* Text encoding used by this database */
  14404. u16 schemaFlags; /* Flags associated with this schema */
  14405. int cache_size; /* Number of pages to use in the cache */
  14406. };
  14407. /*
  14408. ** These macros can be used to test, set, or clear bits in the
  14409. ** Db.pSchema->flags field.
  14410. */
  14411. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  14412. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  14413. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  14414. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  14415. /*
  14416. ** Allowed values for the DB.pSchema->flags field.
  14417. **
  14418. ** The DB_SchemaLoaded flag is set after the database schema has been
  14419. ** read into internal hash tables.
  14420. **
  14421. ** DB_UnresetViews means that one or more views have column names that
  14422. ** have been filled out. If the schema changes, these column names might
  14423. ** changes and so the view will need to be reset.
  14424. */
  14425. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  14426. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  14427. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  14428. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  14429. /*
  14430. ** The number of different kinds of things that can be limited
  14431. ** using the sqlite3_limit() interface.
  14432. */
  14433. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  14434. /*
  14435. ** Lookaside malloc is a set of fixed-size buffers that can be used
  14436. ** to satisfy small transient memory allocation requests for objects
  14437. ** associated with a particular database connection. The use of
  14438. ** lookaside malloc provides a significant performance enhancement
  14439. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  14440. ** SQL statements.
  14441. **
  14442. ** The Lookaside structure holds configuration information about the
  14443. ** lookaside malloc subsystem. Each available memory allocation in
  14444. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  14445. ** objects.
  14446. **
  14447. ** Lookaside allocations are only allowed for objects that are associated
  14448. ** with a particular database connection. Hence, schema information cannot
  14449. ** be stored in lookaside because in shared cache mode the schema information
  14450. ** is shared by multiple database connections. Therefore, while parsing
  14451. ** schema information, the Lookaside.bEnabled flag is cleared so that
  14452. ** lookaside allocations are not used to construct the schema objects.
  14453. */
  14454. struct Lookaside {
  14455. u32 bDisable; /* Only operate the lookaside when zero */
  14456. u16 sz; /* Size of each buffer in bytes */
  14457. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  14458. u32 nSlot; /* Number of lookaside slots allocated */
  14459. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  14460. LookasideSlot *pInit; /* List of buffers not previously used */
  14461. LookasideSlot *pFree; /* List of available buffers */
  14462. void *pStart; /* First byte of available memory space */
  14463. void *pEnd; /* First byte past end of available space */
  14464. };
  14465. struct LookasideSlot {
  14466. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  14467. };
  14468. /*
  14469. ** A hash table for built-in function definitions. (Application-defined
  14470. ** functions use a regular table table from hash.h.)
  14471. **
  14472. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  14473. ** Collisions are on the FuncDef.u.pHash chain.
  14474. */
  14475. #define SQLITE_FUNC_HASH_SZ 23
  14476. struct FuncDefHash {
  14477. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  14478. };
  14479. #ifdef SQLITE_USER_AUTHENTICATION
  14480. /*
  14481. ** Information held in the "sqlite3" database connection object and used
  14482. ** to manage user authentication.
  14483. */
  14484. typedef struct sqlite3_userauth sqlite3_userauth;
  14485. struct sqlite3_userauth {
  14486. u8 authLevel; /* Current authentication level */
  14487. int nAuthPW; /* Size of the zAuthPW in bytes */
  14488. char *zAuthPW; /* Password used to authenticate */
  14489. char *zAuthUser; /* User name used to authenticate */
  14490. };
  14491. /* Allowed values for sqlite3_userauth.authLevel */
  14492. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  14493. #define UAUTH_Fail 1 /* User authentication failed */
  14494. #define UAUTH_User 2 /* Authenticated as a normal user */
  14495. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  14496. /* Functions used only by user authorization logic */
  14497. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  14498. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  14499. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  14500. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  14501. #endif /* SQLITE_USER_AUTHENTICATION */
  14502. /*
  14503. ** typedef for the authorization callback function.
  14504. */
  14505. #ifdef SQLITE_USER_AUTHENTICATION
  14506. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  14507. const char*, const char*);
  14508. #else
  14509. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  14510. const char*);
  14511. #endif
  14512. #ifndef SQLITE_OMIT_DEPRECATED
  14513. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  14514. ** in the style of sqlite3_trace()
  14515. */
  14516. #define SQLITE_TRACE_LEGACY 0x80
  14517. #else
  14518. #define SQLITE_TRACE_LEGACY 0
  14519. #endif /* SQLITE_OMIT_DEPRECATED */
  14520. /*
  14521. ** Each database connection is an instance of the following structure.
  14522. */
  14523. struct sqlite3 {
  14524. sqlite3_vfs *pVfs; /* OS Interface */
  14525. struct Vdbe *pVdbe; /* List of active virtual machines */
  14526. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  14527. sqlite3_mutex *mutex; /* Connection mutex */
  14528. Db *aDb; /* All backends */
  14529. int nDb; /* Number of backends currently in use */
  14530. u32 mDbFlags; /* flags recording internal state */
  14531. u32 flags; /* flags settable by pragmas. See below */
  14532. i64 lastRowid; /* ROWID of most recent insert (see above) */
  14533. i64 szMmap; /* Default mmap_size setting */
  14534. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  14535. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  14536. int errCode; /* Most recent error code (SQLITE_*) */
  14537. int errMask; /* & result codes with this before returning */
  14538. int iSysErrno; /* Errno value from last system error */
  14539. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  14540. u8 enc; /* Text encoding */
  14541. u8 autoCommit; /* The auto-commit flag. */
  14542. u8 temp_store; /* 1: file 2: memory 0: default */
  14543. u8 mallocFailed; /* True if we have seen a malloc failure */
  14544. u8 bBenignMalloc; /* Do not require OOMs if true */
  14545. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  14546. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  14547. u8 suppressErr; /* Do not issue error messages if true */
  14548. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  14549. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  14550. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  14551. u8 skipBtreeMutex; /* True if no shared-cache backends */
  14552. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  14553. int nextPagesize; /* Pagesize after VACUUM if >0 */
  14554. u32 magic; /* Magic number for detect library misuse */
  14555. int nChange; /* Value returned by sqlite3_changes() */
  14556. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  14557. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  14558. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  14559. struct sqlite3InitInfo { /* Information used during initialization */
  14560. int newTnum; /* Rootpage of table being initialized */
  14561. u8 iDb; /* Which db file is being initialized */
  14562. u8 busy; /* TRUE if currently initializing */
  14563. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  14564. u8 imposterTable; /* Building an imposter table */
  14565. } init;
  14566. int nVdbeActive; /* Number of VDBEs currently running */
  14567. int nVdbeRead; /* Number of active VDBEs that read or write */
  14568. int nVdbeWrite; /* Number of active VDBEs that read and write */
  14569. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  14570. int nVDestroy; /* Number of active OP_VDestroy operations */
  14571. int nExtension; /* Number of loaded extensions */
  14572. void **aExtension; /* Array of shared library handles */
  14573. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  14574. void *pTraceArg; /* Argument to the trace function */
  14575. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  14576. void *pProfileArg; /* Argument to profile function */
  14577. void *pCommitArg; /* Argument to xCommitCallback() */
  14578. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  14579. void *pRollbackArg; /* Argument to xRollbackCallback() */
  14580. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  14581. void *pUpdateArg;
  14582. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  14583. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  14584. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  14585. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  14586. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  14587. );
  14588. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  14589. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  14590. #ifndef SQLITE_OMIT_WAL
  14591. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  14592. void *pWalArg;
  14593. #endif
  14594. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  14595. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  14596. void *pCollNeededArg;
  14597. sqlite3_value *pErr; /* Most recent error message */
  14598. union {
  14599. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  14600. double notUsed1; /* Spacer */
  14601. } u1;
  14602. Lookaside lookaside; /* Lookaside malloc configuration */
  14603. #ifndef SQLITE_OMIT_AUTHORIZATION
  14604. sqlite3_xauth xAuth; /* Access authorization function */
  14605. void *pAuthArg; /* 1st argument to the access auth function */
  14606. #endif
  14607. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  14608. int (*xProgress)(void *); /* The progress callback */
  14609. void *pProgressArg; /* Argument to the progress callback */
  14610. unsigned nProgressOps; /* Number of opcodes for progress callback */
  14611. #endif
  14612. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14613. int nVTrans; /* Allocated size of aVTrans */
  14614. Hash aModule; /* populated by sqlite3_create_module() */
  14615. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  14616. VTable **aVTrans; /* Virtual tables with open transactions */
  14617. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  14618. #endif
  14619. Hash aFunc; /* Hash table of connection functions */
  14620. Hash aCollSeq; /* All collating sequences */
  14621. BusyHandler busyHandler; /* Busy callback */
  14622. Db aDbStatic[2]; /* Static space for the 2 default backends */
  14623. Savepoint *pSavepoint; /* List of active savepoints */
  14624. int busyTimeout; /* Busy handler timeout, in msec */
  14625. int nSavepoint; /* Number of non-transaction savepoints */
  14626. int nStatement; /* Number of nested statement-transactions */
  14627. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  14628. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  14629. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  14630. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  14631. /* The following variables are all protected by the STATIC_MASTER
  14632. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  14633. **
  14634. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  14635. ** unlock so that it can proceed.
  14636. **
  14637. ** When X.pBlockingConnection==Y, that means that something that X tried
  14638. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  14639. ** held by Y.
  14640. */
  14641. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  14642. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  14643. void *pUnlockArg; /* Argument to xUnlockNotify */
  14644. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  14645. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  14646. #endif
  14647. #ifdef SQLITE_USER_AUTHENTICATION
  14648. sqlite3_userauth auth; /* User authentication information */
  14649. #endif
  14650. };
  14651. /*
  14652. ** A macro to discover the encoding of a database.
  14653. */
  14654. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  14655. #define ENC(db) ((db)->enc)
  14656. /*
  14657. ** Possible values for the sqlite3.flags.
  14658. **
  14659. ** Value constraints (enforced via assert()):
  14660. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  14661. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  14662. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  14663. */
  14664. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  14665. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  14666. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  14667. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  14668. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  14669. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  14670. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  14671. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  14672. /* DELETE, or UPDATE and return */
  14673. /* the count using a callback. */
  14674. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  14675. /* result set is empty */
  14676. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  14677. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  14678. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  14679. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  14680. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  14681. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  14682. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  14683. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  14684. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  14685. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  14686. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  14687. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  14688. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  14689. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  14690. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee */
  14691. /* Flags used only if debugging */
  14692. #ifdef SQLITE_DEBUG
  14693. #define SQLITE_SqlTrace 0x08000000 /* Debug print SQL as it executes */
  14694. #define SQLITE_VdbeListing 0x10000000 /* Debug listings of VDBE programs */
  14695. #define SQLITE_VdbeTrace 0x20000000 /* True to trace VDBE execution */
  14696. #define SQLITE_VdbeAddopTrace 0x40000000 /* Trace sqlite3VdbeAddOp() calls */
  14697. #define SQLITE_VdbeEQP 0x80000000 /* Debug EXPLAIN QUERY PLAN */
  14698. #endif
  14699. /*
  14700. ** Allowed values for sqlite3.mDbFlags
  14701. */
  14702. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  14703. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  14704. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  14705. /*
  14706. ** Bits of the sqlite3.dbOptFlags field that are used by the
  14707. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  14708. ** selectively disable various optimizations.
  14709. */
  14710. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  14711. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  14712. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  14713. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  14714. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  14715. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  14716. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  14717. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  14718. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  14719. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  14720. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  14721. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  14722. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  14723. #define SQLITE_AllOpts 0xffff /* All optimizations */
  14724. /*
  14725. ** Macros for testing whether or not optimizations are enabled or disabled.
  14726. */
  14727. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  14728. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  14729. /*
  14730. ** Return true if it OK to factor constant expressions into the initialization
  14731. ** code. The argument is a Parse object for the code generator.
  14732. */
  14733. #define ConstFactorOk(P) ((P)->okConstFactor)
  14734. /*
  14735. ** Possible values for the sqlite.magic field.
  14736. ** The numbers are obtained at random and have no special meaning, other
  14737. ** than being distinct from one another.
  14738. */
  14739. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  14740. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  14741. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  14742. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  14743. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  14744. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  14745. /*
  14746. ** Each SQL function is defined by an instance of the following
  14747. ** structure. For global built-in functions (ex: substr(), max(), count())
  14748. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  14749. ** For per-connection application-defined functions, a pointer to this
  14750. ** structure is held in the db->aHash hash table.
  14751. **
  14752. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  14753. ** field is used by per-connection app-def functions.
  14754. */
  14755. struct FuncDef {
  14756. i8 nArg; /* Number of arguments. -1 means unlimited */
  14757. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  14758. void *pUserData; /* User data parameter */
  14759. FuncDef *pNext; /* Next function with same name */
  14760. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  14761. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  14762. const char *zName; /* SQL name of the function. */
  14763. union {
  14764. FuncDef *pHash; /* Next with a different name but the same hash */
  14765. FuncDestructor *pDestructor; /* Reference counted destructor function */
  14766. } u;
  14767. };
  14768. /*
  14769. ** This structure encapsulates a user-function destructor callback (as
  14770. ** configured using create_function_v2()) and a reference counter. When
  14771. ** create_function_v2() is called to create a function with a destructor,
  14772. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  14773. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  14774. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  14775. ** member of each of the new FuncDef objects is set to point to the allocated
  14776. ** FuncDestructor.
  14777. **
  14778. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  14779. ** count on this object is decremented. When it reaches 0, the destructor
  14780. ** is invoked and the FuncDestructor structure freed.
  14781. */
  14782. struct FuncDestructor {
  14783. int nRef;
  14784. void (*xDestroy)(void *);
  14785. void *pUserData;
  14786. };
  14787. /*
  14788. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  14789. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  14790. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  14791. ** are assert() statements in the code to verify this.
  14792. **
  14793. ** Value constraints (enforced via assert()):
  14794. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  14795. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  14796. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  14797. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  14798. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  14799. */
  14800. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  14801. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  14802. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  14803. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  14804. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  14805. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  14806. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  14807. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  14808. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  14809. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  14810. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  14811. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  14812. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  14813. ** single query - might change over time */
  14814. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  14815. /*
  14816. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  14817. ** used to create the initializers for the FuncDef structures.
  14818. **
  14819. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  14820. ** Used to create a scalar function definition of a function zName
  14821. ** implemented by C function xFunc that accepts nArg arguments. The
  14822. ** value passed as iArg is cast to a (void*) and made available
  14823. ** as the user-data (sqlite3_user_data()) for the function. If
  14824. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  14825. **
  14826. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  14827. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  14828. **
  14829. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  14830. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  14831. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  14832. ** and functions like sqlite_version() that can change, but not during
  14833. ** a single query. The iArg is ignored. The user-data is always set
  14834. ** to a NULL pointer. The bNC parameter is not used.
  14835. **
  14836. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  14837. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  14838. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  14839. ** ignored and the user-data for these functions is set to an
  14840. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  14841. **
  14842. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  14843. ** Used to create an aggregate function definition implemented by
  14844. ** the C functions xStep and xFinal. The first four parameters
  14845. ** are interpreted in the same way as the first 4 parameters to
  14846. ** FUNCTION().
  14847. **
  14848. ** LIKEFUNC(zName, nArg, pArg, flags)
  14849. ** Used to create a scalar function definition of a function zName
  14850. ** that accepts nArg arguments and is implemented by a call to C
  14851. ** function likeFunc. Argument pArg is cast to a (void *) and made
  14852. ** available as the function user-data (sqlite3_user_data()). The
  14853. ** FuncDef.flags variable is set to the value passed as the flags
  14854. ** parameter.
  14855. */
  14856. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  14857. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  14858. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  14859. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  14860. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  14861. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  14862. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  14863. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  14864. 0, 0, xFunc, 0, #zName, {0} }
  14865. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  14866. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  14867. (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
  14868. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  14869. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  14870. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  14871. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  14872. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  14873. pArg, 0, xFunc, 0, #zName, }
  14874. #define LIKEFUNC(zName, nArg, arg, flags) \
  14875. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  14876. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  14877. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  14878. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  14879. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  14880. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  14881. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  14882. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  14883. /*
  14884. ** All current savepoints are stored in a linked list starting at
  14885. ** sqlite3.pSavepoint. The first element in the list is the most recently
  14886. ** opened savepoint. Savepoints are added to the list by the vdbe
  14887. ** OP_Savepoint instruction.
  14888. */
  14889. struct Savepoint {
  14890. char *zName; /* Savepoint name (nul-terminated) */
  14891. i64 nDeferredCons; /* Number of deferred fk violations */
  14892. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  14893. Savepoint *pNext; /* Parent savepoint (if any) */
  14894. };
  14895. /*
  14896. ** The following are used as the second parameter to sqlite3Savepoint(),
  14897. ** and as the P1 argument to the OP_Savepoint instruction.
  14898. */
  14899. #define SAVEPOINT_BEGIN 0
  14900. #define SAVEPOINT_RELEASE 1
  14901. #define SAVEPOINT_ROLLBACK 2
  14902. /*
  14903. ** Each SQLite module (virtual table definition) is defined by an
  14904. ** instance of the following structure, stored in the sqlite3.aModule
  14905. ** hash table.
  14906. */
  14907. struct Module {
  14908. const sqlite3_module *pModule; /* Callback pointers */
  14909. const char *zName; /* Name passed to create_module() */
  14910. void *pAux; /* pAux passed to create_module() */
  14911. void (*xDestroy)(void *); /* Module destructor function */
  14912. Table *pEpoTab; /* Eponymous table for this module */
  14913. };
  14914. /*
  14915. ** information about each column of an SQL table is held in an instance
  14916. ** of this structure.
  14917. */
  14918. struct Column {
  14919. char *zName; /* Name of this column, \000, then the type */
  14920. Expr *pDflt; /* Default value of this column */
  14921. char *zColl; /* Collating sequence. If NULL, use the default */
  14922. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  14923. char affinity; /* One of the SQLITE_AFF_... values */
  14924. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  14925. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  14926. };
  14927. /* Allowed values for Column.colFlags:
  14928. */
  14929. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  14930. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  14931. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  14932. /*
  14933. ** A "Collating Sequence" is defined by an instance of the following
  14934. ** structure. Conceptually, a collating sequence consists of a name and
  14935. ** a comparison routine that defines the order of that sequence.
  14936. **
  14937. ** If CollSeq.xCmp is NULL, it means that the
  14938. ** collating sequence is undefined. Indices built on an undefined
  14939. ** collating sequence may not be read or written.
  14940. */
  14941. struct CollSeq {
  14942. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  14943. u8 enc; /* Text encoding handled by xCmp() */
  14944. void *pUser; /* First argument to xCmp() */
  14945. int (*xCmp)(void*,int, const void*, int, const void*);
  14946. void (*xDel)(void*); /* Destructor for pUser */
  14947. };
  14948. /*
  14949. ** A sort order can be either ASC or DESC.
  14950. */
  14951. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  14952. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  14953. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  14954. /*
  14955. ** Column affinity types.
  14956. **
  14957. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  14958. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  14959. ** the speed a little by numbering the values consecutively.
  14960. **
  14961. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  14962. ** when multiple affinity types are concatenated into a string and
  14963. ** used as the P4 operand, they will be more readable.
  14964. **
  14965. ** Note also that the numeric types are grouped together so that testing
  14966. ** for a numeric type is a single comparison. And the BLOB type is first.
  14967. */
  14968. #define SQLITE_AFF_BLOB 'A'
  14969. #define SQLITE_AFF_TEXT 'B'
  14970. #define SQLITE_AFF_NUMERIC 'C'
  14971. #define SQLITE_AFF_INTEGER 'D'
  14972. #define SQLITE_AFF_REAL 'E'
  14973. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  14974. /*
  14975. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  14976. ** affinity value.
  14977. */
  14978. #define SQLITE_AFF_MASK 0x47
  14979. /*
  14980. ** Additional bit values that can be ORed with an affinity without
  14981. ** changing the affinity.
  14982. **
  14983. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  14984. ** It causes an assert() to fire if either operand to a comparison
  14985. ** operator is NULL. It is added to certain comparison operators to
  14986. ** prove that the operands are always NOT NULL.
  14987. */
  14988. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  14989. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  14990. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  14991. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  14992. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  14993. /*
  14994. ** An object of this type is created for each virtual table present in
  14995. ** the database schema.
  14996. **
  14997. ** If the database schema is shared, then there is one instance of this
  14998. ** structure for each database connection (sqlite3*) that uses the shared
  14999. ** schema. This is because each database connection requires its own unique
  15000. ** instance of the sqlite3_vtab* handle used to access the virtual table
  15001. ** implementation. sqlite3_vtab* handles can not be shared between
  15002. ** database connections, even when the rest of the in-memory database
  15003. ** schema is shared, as the implementation often stores the database
  15004. ** connection handle passed to it via the xConnect() or xCreate() method
  15005. ** during initialization internally. This database connection handle may
  15006. ** then be used by the virtual table implementation to access real tables
  15007. ** within the database. So that they appear as part of the callers
  15008. ** transaction, these accesses need to be made via the same database
  15009. ** connection as that used to execute SQL operations on the virtual table.
  15010. **
  15011. ** All VTable objects that correspond to a single table in a shared
  15012. ** database schema are initially stored in a linked-list pointed to by
  15013. ** the Table.pVTable member variable of the corresponding Table object.
  15014. ** When an sqlite3_prepare() operation is required to access the virtual
  15015. ** table, it searches the list for the VTable that corresponds to the
  15016. ** database connection doing the preparing so as to use the correct
  15017. ** sqlite3_vtab* handle in the compiled query.
  15018. **
  15019. ** When an in-memory Table object is deleted (for example when the
  15020. ** schema is being reloaded for some reason), the VTable objects are not
  15021. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  15022. ** immediately. Instead, they are moved from the Table.pVTable list to
  15023. ** another linked list headed by the sqlite3.pDisconnect member of the
  15024. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  15025. ** next time a statement is prepared using said sqlite3*. This is done
  15026. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  15027. ** Refer to comments above function sqlite3VtabUnlockList() for an
  15028. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  15029. ** list without holding the corresponding sqlite3.mutex mutex.
  15030. **
  15031. ** The memory for objects of this type is always allocated by
  15032. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  15033. ** the first argument.
  15034. */
  15035. struct VTable {
  15036. sqlite3 *db; /* Database connection associated with this table */
  15037. Module *pMod; /* Pointer to module implementation */
  15038. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  15039. int nRef; /* Number of pointers to this structure */
  15040. u8 bConstraint; /* True if constraints are supported */
  15041. int iSavepoint; /* Depth of the SAVEPOINT stack */
  15042. VTable *pNext; /* Next in linked list (see above) */
  15043. };
  15044. /*
  15045. ** The schema for each SQL table and view is represented in memory
  15046. ** by an instance of the following structure.
  15047. */
  15048. struct Table {
  15049. char *zName; /* Name of the table or view */
  15050. Column *aCol; /* Information about each column */
  15051. Index *pIndex; /* List of SQL indexes on this table. */
  15052. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  15053. FKey *pFKey; /* Linked list of all foreign keys in this table */
  15054. char *zColAff; /* String defining the affinity of each column */
  15055. ExprList *pCheck; /* All CHECK constraints */
  15056. /* ... also used as column name list in a VIEW */
  15057. int tnum; /* Root BTree page for this table */
  15058. u32 nTabRef; /* Number of pointers to this Table */
  15059. u32 tabFlags; /* Mask of TF_* values */
  15060. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  15061. i16 nCol; /* Number of columns in this table */
  15062. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  15063. LogEst szTabRow; /* Estimated size of each table row in bytes */
  15064. #ifdef SQLITE_ENABLE_COSTMULT
  15065. LogEst costMult; /* Cost multiplier for using this table */
  15066. #endif
  15067. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  15068. #ifndef SQLITE_OMIT_ALTERTABLE
  15069. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  15070. #endif
  15071. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15072. int nModuleArg; /* Number of arguments to the module */
  15073. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  15074. VTable *pVTable; /* List of VTable objects. */
  15075. #endif
  15076. Trigger *pTrigger; /* List of triggers stored in pSchema */
  15077. Schema *pSchema; /* Schema that contains this table */
  15078. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  15079. };
  15080. /*
  15081. ** Allowed values for Table.tabFlags.
  15082. **
  15083. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  15084. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  15085. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  15086. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  15087. ** special handling during INSERT processing.
  15088. */
  15089. #define TF_Readonly 0x0001 /* Read-only system table */
  15090. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  15091. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  15092. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  15093. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  15094. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  15095. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  15096. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  15097. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  15098. ** Index.aiRowLogEst[] values */
  15099. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  15100. /*
  15101. ** Test to see whether or not a table is a virtual table. This is
  15102. ** done as a macro so that it will be optimized out when virtual
  15103. ** table support is omitted from the build.
  15104. */
  15105. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15106. # define IsVirtual(X) ((X)->nModuleArg)
  15107. #else
  15108. # define IsVirtual(X) 0
  15109. #endif
  15110. /*
  15111. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  15112. ** only works for non-virtual tables (ordinary tables and views) and is
  15113. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  15114. ** IsHiddenColumn() macro is general purpose.
  15115. */
  15116. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  15117. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15118. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15119. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  15120. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15121. # define IsOrdinaryHiddenColumn(X) 0
  15122. #else
  15123. # define IsHiddenColumn(X) 0
  15124. # define IsOrdinaryHiddenColumn(X) 0
  15125. #endif
  15126. /* Does the table have a rowid */
  15127. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  15128. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  15129. /*
  15130. ** Each foreign key constraint is an instance of the following structure.
  15131. **
  15132. ** A foreign key is associated with two tables. The "from" table is
  15133. ** the table that contains the REFERENCES clause that creates the foreign
  15134. ** key. The "to" table is the table that is named in the REFERENCES clause.
  15135. ** Consider this example:
  15136. **
  15137. ** CREATE TABLE ex1(
  15138. ** a INTEGER PRIMARY KEY,
  15139. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  15140. ** );
  15141. **
  15142. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  15143. ** Equivalent names:
  15144. **
  15145. ** from-table == child-table
  15146. ** to-table == parent-table
  15147. **
  15148. ** Each REFERENCES clause generates an instance of the following structure
  15149. ** which is attached to the from-table. The to-table need not exist when
  15150. ** the from-table is created. The existence of the to-table is not checked.
  15151. **
  15152. ** The list of all parents for child Table X is held at X.pFKey.
  15153. **
  15154. ** A list of all children for a table named Z (which might not even exist)
  15155. ** is held in Schema.fkeyHash with a hash key of Z.
  15156. */
  15157. struct FKey {
  15158. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  15159. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  15160. char *zTo; /* Name of table that the key points to (aka: Parent) */
  15161. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  15162. FKey *pPrevTo; /* Previous with the same zTo */
  15163. int nCol; /* Number of columns in this key */
  15164. /* EV: R-30323-21917 */
  15165. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  15166. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  15167. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  15168. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  15169. int iFrom; /* Index of column in pFrom */
  15170. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  15171. } aCol[1]; /* One entry for each of nCol columns */
  15172. };
  15173. /*
  15174. ** SQLite supports many different ways to resolve a constraint
  15175. ** error. ROLLBACK processing means that a constraint violation
  15176. ** causes the operation in process to fail and for the current transaction
  15177. ** to be rolled back. ABORT processing means the operation in process
  15178. ** fails and any prior changes from that one operation are backed out,
  15179. ** but the transaction is not rolled back. FAIL processing means that
  15180. ** the operation in progress stops and returns an error code. But prior
  15181. ** changes due to the same operation are not backed out and no rollback
  15182. ** occurs. IGNORE means that the particular row that caused the constraint
  15183. ** error is not inserted or updated. Processing continues and no error
  15184. ** is returned. REPLACE means that preexisting database rows that caused
  15185. ** a UNIQUE constraint violation are removed so that the new insert or
  15186. ** update can proceed. Processing continues and no error is reported.
  15187. **
  15188. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  15189. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  15190. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  15191. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  15192. ** referenced table row is propagated into the row that holds the
  15193. ** foreign key.
  15194. **
  15195. ** The following symbolic values are used to record which type
  15196. ** of action to take.
  15197. */
  15198. #define OE_None 0 /* There is no constraint to check */
  15199. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  15200. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  15201. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  15202. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  15203. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  15204. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  15205. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  15206. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  15207. #define OE_Cascade 9 /* Cascade the changes */
  15208. #define OE_Default 10 /* Do whatever the default action is */
  15209. /*
  15210. ** An instance of the following structure is passed as the first
  15211. ** argument to sqlite3VdbeKeyCompare and is used to control the
  15212. ** comparison of the two index keys.
  15213. **
  15214. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  15215. ** are nField slots for the columns of an index then one extra slot
  15216. ** for the rowid at the end.
  15217. */
  15218. struct KeyInfo {
  15219. u32 nRef; /* Number of references to this KeyInfo object */
  15220. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  15221. u16 nKeyField; /* Number of key columns in the index */
  15222. u16 nAllField; /* Total columns, including key plus others */
  15223. sqlite3 *db; /* The database connection */
  15224. u8 *aSortOrder; /* Sort order for each column. */
  15225. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  15226. };
  15227. /*
  15228. ** This object holds a record which has been parsed out into individual
  15229. ** fields, for the purposes of doing a comparison.
  15230. **
  15231. ** A record is an object that contains one or more fields of data.
  15232. ** Records are used to store the content of a table row and to store
  15233. ** the key of an index. A blob encoding of a record is created by
  15234. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  15235. ** OP_Column opcode.
  15236. **
  15237. ** An instance of this object serves as a "key" for doing a search on
  15238. ** an index b+tree. The goal of the search is to find the entry that
  15239. ** is closed to the key described by this object. This object might hold
  15240. ** just a prefix of the key. The number of fields is given by
  15241. ** pKeyInfo->nField.
  15242. **
  15243. ** The r1 and r2 fields are the values to return if this key is less than
  15244. ** or greater than a key in the btree, respectively. These are normally
  15245. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  15246. ** is in DESC order.
  15247. **
  15248. ** The key comparison functions actually return default_rc when they find
  15249. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  15250. ** multiple entries in the b-tree with the same key (when only looking
  15251. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  15252. ** cause the search to find the last match, or +1 to cause the search to
  15253. ** find the first match.
  15254. **
  15255. ** The key comparison functions will set eqSeen to true if they ever
  15256. ** get and equal results when comparing this structure to a b-tree record.
  15257. ** When default_rc!=0, the search might end up on the record immediately
  15258. ** before the first match or immediately after the last match. The
  15259. ** eqSeen field will indicate whether or not an exact match exists in the
  15260. ** b-tree.
  15261. */
  15262. struct UnpackedRecord {
  15263. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  15264. Mem *aMem; /* Values */
  15265. u16 nField; /* Number of entries in apMem[] */
  15266. i8 default_rc; /* Comparison result if keys are equal */
  15267. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  15268. i8 r1; /* Value to return if (lhs < rhs) */
  15269. i8 r2; /* Value to return if (lhs > rhs) */
  15270. u8 eqSeen; /* True if an equality comparison has been seen */
  15271. };
  15272. /*
  15273. ** Each SQL index is represented in memory by an
  15274. ** instance of the following structure.
  15275. **
  15276. ** The columns of the table that are to be indexed are described
  15277. ** by the aiColumn[] field of this structure. For example, suppose
  15278. ** we have the following table and index:
  15279. **
  15280. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  15281. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  15282. **
  15283. ** In the Table structure describing Ex1, nCol==3 because there are
  15284. ** three columns in the table. In the Index structure describing
  15285. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  15286. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  15287. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  15288. ** The second column to be indexed (c1) has an index of 0 in
  15289. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  15290. **
  15291. ** The Index.onError field determines whether or not the indexed columns
  15292. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  15293. ** it means this is not a unique index. Otherwise it is a unique index
  15294. ** and the value of Index.onError indicate the which conflict resolution
  15295. ** algorithm to employ whenever an attempt is made to insert a non-unique
  15296. ** element.
  15297. **
  15298. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  15299. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  15300. ** table as part of parsing an existing database schema), transient instances
  15301. ** of this structure may be created. In this case the Index.tnum variable is
  15302. ** used to store the address of a VDBE instruction, not a database page
  15303. ** number (it cannot - the database page is not allocated until the VDBE
  15304. ** program is executed). See convertToWithoutRowidTable() for details.
  15305. */
  15306. struct Index {
  15307. char *zName; /* Name of this index */
  15308. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  15309. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  15310. Table *pTable; /* The SQL table being indexed */
  15311. char *zColAff; /* String defining the affinity of each column */
  15312. Index *pNext; /* The next index associated with the same table */
  15313. Schema *pSchema; /* Schema containing this index */
  15314. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  15315. const char **azColl; /* Array of collation sequence names for index */
  15316. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  15317. ExprList *aColExpr; /* Column expressions */
  15318. int tnum; /* DB Page containing root of this index */
  15319. LogEst szIdxRow; /* Estimated average row size in bytes */
  15320. u16 nKeyCol; /* Number of columns forming the key */
  15321. u16 nColumn; /* Number of columns stored in the index */
  15322. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  15323. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  15324. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  15325. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  15326. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  15327. unsigned isCovering:1; /* True if this is a covering index */
  15328. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  15329. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  15330. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  15331. int nSample; /* Number of elements in aSample[] */
  15332. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  15333. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  15334. IndexSample *aSample; /* Samples of the left-most key */
  15335. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  15336. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  15337. #endif
  15338. };
  15339. /*
  15340. ** Allowed values for Index.idxType
  15341. */
  15342. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  15343. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  15344. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  15345. /* Return true if index X is a PRIMARY KEY index */
  15346. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  15347. /* Return true if index X is a UNIQUE index */
  15348. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  15349. /* The Index.aiColumn[] values are normally positive integer. But
  15350. ** there are some negative values that have special meaning:
  15351. */
  15352. #define XN_ROWID (-1) /* Indexed column is the rowid */
  15353. #define XN_EXPR (-2) /* Indexed column is an expression */
  15354. /*
  15355. ** Each sample stored in the sqlite_stat3 table is represented in memory
  15356. ** using a structure of this type. See documentation at the top of the
  15357. ** analyze.c source file for additional information.
  15358. */
  15359. struct IndexSample {
  15360. void *p; /* Pointer to sampled record */
  15361. int n; /* Size of record in bytes */
  15362. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  15363. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  15364. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  15365. };
  15366. /*
  15367. ** Each token coming out of the lexer is an instance of
  15368. ** this structure. Tokens are also used as part of an expression.
  15369. **
  15370. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  15371. ** may contain random values. Do not make any assumptions about Token.dyn
  15372. ** and Token.n when Token.z==0.
  15373. */
  15374. struct Token {
  15375. const char *z; /* Text of the token. Not NULL-terminated! */
  15376. unsigned int n; /* Number of characters in this token */
  15377. };
  15378. /*
  15379. ** An instance of this structure contains information needed to generate
  15380. ** code for a SELECT that contains aggregate functions.
  15381. **
  15382. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  15383. ** pointer to this structure. The Expr.iColumn field is the index in
  15384. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  15385. ** code for that node.
  15386. **
  15387. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  15388. ** original Select structure that describes the SELECT statement. These
  15389. ** fields do not need to be freed when deallocating the AggInfo structure.
  15390. */
  15391. struct AggInfo {
  15392. u8 directMode; /* Direct rendering mode means take data directly
  15393. ** from source tables rather than from accumulators */
  15394. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  15395. ** than the source table */
  15396. int sortingIdx; /* Cursor number of the sorting index */
  15397. int sortingIdxPTab; /* Cursor number of pseudo-table */
  15398. int nSortingColumn; /* Number of columns in the sorting index */
  15399. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  15400. ExprList *pGroupBy; /* The group by clause */
  15401. struct AggInfo_col { /* For each column used in source tables */
  15402. Table *pTab; /* Source table */
  15403. int iTable; /* Cursor number of the source table */
  15404. int iColumn; /* Column number within the source table */
  15405. int iSorterColumn; /* Column number in the sorting index */
  15406. int iMem; /* Memory location that acts as accumulator */
  15407. Expr *pExpr; /* The original expression */
  15408. } *aCol;
  15409. int nColumn; /* Number of used entries in aCol[] */
  15410. int nAccumulator; /* Number of columns that show through to the output.
  15411. ** Additional columns are used only as parameters to
  15412. ** aggregate functions */
  15413. struct AggInfo_func { /* For each aggregate function */
  15414. Expr *pExpr; /* Expression encoding the function */
  15415. FuncDef *pFunc; /* The aggregate function implementation */
  15416. int iMem; /* Memory location that acts as accumulator */
  15417. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  15418. } *aFunc;
  15419. int nFunc; /* Number of entries in aFunc[] */
  15420. };
  15421. /*
  15422. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  15423. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  15424. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  15425. ** it uses less memory in the Expr object, which is a big memory user
  15426. ** in systems with lots of prepared statements. And few applications
  15427. ** need more than about 10 or 20 variables. But some extreme users want
  15428. ** to have prepared statements with over 32767 variables, and for them
  15429. ** the option is available (at compile-time).
  15430. */
  15431. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  15432. typedef i16 ynVar;
  15433. #else
  15434. typedef int ynVar;
  15435. #endif
  15436. /*
  15437. ** Each node of an expression in the parse tree is an instance
  15438. ** of this structure.
  15439. **
  15440. ** Expr.op is the opcode. The integer parser token codes are reused
  15441. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  15442. ** code representing the ">=" operator. This same integer code is reused
  15443. ** to represent the greater-than-or-equal-to operator in the expression
  15444. ** tree.
  15445. **
  15446. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  15447. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  15448. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  15449. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  15450. ** then Expr.token contains the name of the function.
  15451. **
  15452. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  15453. ** binary operator. Either or both may be NULL.
  15454. **
  15455. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  15456. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  15457. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  15458. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  15459. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  15460. ** valid.
  15461. **
  15462. ** An expression of the form ID or ID.ID refers to a column in a table.
  15463. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  15464. ** the integer cursor number of a VDBE cursor pointing to that table and
  15465. ** Expr.iColumn is the column number for the specific column. If the
  15466. ** expression is used as a result in an aggregate SELECT, then the
  15467. ** value is also stored in the Expr.iAgg column in the aggregate so that
  15468. ** it can be accessed after all aggregates are computed.
  15469. **
  15470. ** If the expression is an unbound variable marker (a question mark
  15471. ** character '?' in the original SQL) then the Expr.iTable holds the index
  15472. ** number for that variable.
  15473. **
  15474. ** If the expression is a subquery then Expr.iColumn holds an integer
  15475. ** register number containing the result of the subquery. If the
  15476. ** subquery gives a constant result, then iTable is -1. If the subquery
  15477. ** gives a different answer at different times during statement processing
  15478. ** then iTable is the address of a subroutine that computes the subquery.
  15479. **
  15480. ** If the Expr is of type OP_Column, and the table it is selecting from
  15481. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  15482. ** corresponding table definition.
  15483. **
  15484. ** ALLOCATION NOTES:
  15485. **
  15486. ** Expr objects can use a lot of memory space in database schema. To
  15487. ** help reduce memory requirements, sometimes an Expr object will be
  15488. ** truncated. And to reduce the number of memory allocations, sometimes
  15489. ** two or more Expr objects will be stored in a single memory allocation,
  15490. ** together with Expr.zToken strings.
  15491. **
  15492. ** If the EP_Reduced and EP_TokenOnly flags are set when
  15493. ** an Expr object is truncated. When EP_Reduced is set, then all
  15494. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  15495. ** are contained within the same memory allocation. Note, however, that
  15496. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  15497. ** allocated, regardless of whether or not EP_Reduced is set.
  15498. */
  15499. struct Expr {
  15500. u8 op; /* Operation performed by this node */
  15501. char affinity; /* The affinity of the column or 0 if not a column */
  15502. u32 flags; /* Various flags. EP_* See below */
  15503. union {
  15504. char *zToken; /* Token value. Zero terminated and dequoted */
  15505. int iValue; /* Non-negative integer value if EP_IntValue */
  15506. } u;
  15507. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  15508. ** space is allocated for the fields below this point. An attempt to
  15509. ** access them will result in a segfault or malfunction.
  15510. *********************************************************************/
  15511. Expr *pLeft; /* Left subnode */
  15512. Expr *pRight; /* Right subnode */
  15513. union {
  15514. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  15515. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  15516. } x;
  15517. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  15518. ** space is allocated for the fields below this point. An attempt to
  15519. ** access them will result in a segfault or malfunction.
  15520. *********************************************************************/
  15521. #if SQLITE_MAX_EXPR_DEPTH>0
  15522. int nHeight; /* Height of the tree headed by this node */
  15523. #endif
  15524. int iTable; /* TK_COLUMN: cursor number of table holding column
  15525. ** TK_REGISTER: register number
  15526. ** TK_TRIGGER: 1 -> new, 0 -> old
  15527. ** EP_Unlikely: 134217728 times likelihood
  15528. ** TK_SELECT: 1st register of result vector */
  15529. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  15530. ** TK_VARIABLE: variable number (always >= 1).
  15531. ** TK_SELECT_COLUMN: column of the result vector */
  15532. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  15533. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  15534. u8 op2; /* TK_REGISTER: original value of Expr.op
  15535. ** TK_COLUMN: the value of p5 for OP_Column
  15536. ** TK_AGG_FUNCTION: nesting depth */
  15537. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  15538. Table *pTab; /* Table for TK_COLUMN expressions. Can be NULL
  15539. ** for a column of an index on an expression */
  15540. };
  15541. /*
  15542. ** The following are the meanings of bits in the Expr.flags field.
  15543. */
  15544. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  15545. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  15546. /* 0x000004 // available for use */
  15547. /* 0x000008 // available for use */
  15548. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  15549. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  15550. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  15551. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  15552. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  15553. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  15554. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  15555. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  15556. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  15557. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  15558. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  15559. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  15560. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  15561. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  15562. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  15563. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  15564. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  15565. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  15566. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  15567. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  15568. /*
  15569. ** Combinations of two or more EP_* flags
  15570. */
  15571. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  15572. /*
  15573. ** These macros can be used to test, set, or clear bits in the
  15574. ** Expr.flags field.
  15575. */
  15576. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  15577. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  15578. #define ExprSetProperty(E,P) (E)->flags|=(P)
  15579. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  15580. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  15581. ** and Accreditation only. It works like ExprSetProperty() during VVA
  15582. ** processes but is a no-op for delivery.
  15583. */
  15584. #ifdef SQLITE_DEBUG
  15585. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  15586. #else
  15587. # define ExprSetVVAProperty(E,P)
  15588. #endif
  15589. /*
  15590. ** Macros to determine the number of bytes required by a normal Expr
  15591. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  15592. ** and an Expr struct with the EP_TokenOnly flag set.
  15593. */
  15594. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  15595. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  15596. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  15597. /*
  15598. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  15599. ** above sqlite3ExprDup() for details.
  15600. */
  15601. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  15602. /*
  15603. ** A list of expressions. Each expression may optionally have a
  15604. ** name. An expr/name combination can be used in several ways, such
  15605. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  15606. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  15607. ** also be used as the argument to a function, in which case the a.zName
  15608. ** field is not used.
  15609. **
  15610. ** By default the Expr.zSpan field holds a human-readable description of
  15611. ** the expression that is used in the generation of error messages and
  15612. ** column labels. In this case, Expr.zSpan is typically the text of a
  15613. ** column expression as it exists in a SELECT statement. However, if
  15614. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  15615. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  15616. ** form is used for name resolution with nested FROM clauses.
  15617. */
  15618. struct ExprList {
  15619. int nExpr; /* Number of expressions on the list */
  15620. struct ExprList_item { /* For each expression in the list */
  15621. Expr *pExpr; /* The parse tree for this expression */
  15622. char *zName; /* Token associated with this expression */
  15623. char *zSpan; /* Original text of the expression */
  15624. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  15625. unsigned done :1; /* A flag to indicate when processing is finished */
  15626. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  15627. unsigned reusable :1; /* Constant expression is reusable */
  15628. union {
  15629. struct {
  15630. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  15631. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  15632. } x;
  15633. int iConstExprReg; /* Register in which Expr value is cached */
  15634. } u;
  15635. } a[1]; /* One slot for each expression in the list */
  15636. };
  15637. /*
  15638. ** An instance of this structure is used by the parser to record both
  15639. ** the parse tree for an expression and the span of input text for an
  15640. ** expression.
  15641. */
  15642. struct ExprSpan {
  15643. Expr *pExpr; /* The expression parse tree */
  15644. const char *zStart; /* First character of input text */
  15645. const char *zEnd; /* One character past the end of input text */
  15646. };
  15647. /*
  15648. ** An instance of this structure can hold a simple list of identifiers,
  15649. ** such as the list "a,b,c" in the following statements:
  15650. **
  15651. ** INSERT INTO t(a,b,c) VALUES ...;
  15652. ** CREATE INDEX idx ON t(a,b,c);
  15653. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  15654. **
  15655. ** The IdList.a.idx field is used when the IdList represents the list of
  15656. ** column names after a table name in an INSERT statement. In the statement
  15657. **
  15658. ** INSERT INTO t(a,b,c) ...
  15659. **
  15660. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  15661. */
  15662. struct IdList {
  15663. struct IdList_item {
  15664. char *zName; /* Name of the identifier */
  15665. int idx; /* Index in some Table.aCol[] of a column named zName */
  15666. } *a;
  15667. int nId; /* Number of identifiers on the list */
  15668. };
  15669. /*
  15670. ** The bitmask datatype defined below is used for various optimizations.
  15671. **
  15672. ** Changing this from a 64-bit to a 32-bit type limits the number of
  15673. ** tables in a join to 32 instead of 64. But it also reduces the size
  15674. ** of the library by 738 bytes on ix86.
  15675. */
  15676. #ifdef SQLITE_BITMASK_TYPE
  15677. typedef SQLITE_BITMASK_TYPE Bitmask;
  15678. #else
  15679. typedef u64 Bitmask;
  15680. #endif
  15681. /*
  15682. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  15683. */
  15684. #define BMS ((int)(sizeof(Bitmask)*8))
  15685. /*
  15686. ** A bit in a Bitmask
  15687. */
  15688. #define MASKBIT(n) (((Bitmask)1)<<(n))
  15689. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  15690. #define ALLBITS ((Bitmask)-1)
  15691. /*
  15692. ** The following structure describes the FROM clause of a SELECT statement.
  15693. ** Each table or subquery in the FROM clause is a separate element of
  15694. ** the SrcList.a[] array.
  15695. **
  15696. ** With the addition of multiple database support, the following structure
  15697. ** can also be used to describe a particular table such as the table that
  15698. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  15699. ** such a table must be a simple name: ID. But in SQLite, the table can
  15700. ** now be identified by a database name, a dot, then the table name: ID.ID.
  15701. **
  15702. ** The jointype starts out showing the join type between the current table
  15703. ** and the next table on the list. The parser builds the list this way.
  15704. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  15705. ** jointype expresses the join between the table and the previous table.
  15706. **
  15707. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  15708. ** contains more than 63 columns and the 64-th or later column is used.
  15709. */
  15710. struct SrcList {
  15711. int nSrc; /* Number of tables or subqueries in the FROM clause */
  15712. u32 nAlloc; /* Number of entries allocated in a[] below */
  15713. struct SrcList_item {
  15714. Schema *pSchema; /* Schema to which this item is fixed */
  15715. char *zDatabase; /* Name of database holding this table */
  15716. char *zName; /* Name of the table */
  15717. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  15718. Table *pTab; /* An SQL table corresponding to zName */
  15719. Select *pSelect; /* A SELECT statement used in place of a table name */
  15720. int addrFillSub; /* Address of subroutine to manifest a subquery */
  15721. int regReturn; /* Register holding return address of addrFillSub */
  15722. int regResult; /* Registers holding results of a co-routine */
  15723. struct {
  15724. u8 jointype; /* Type of join between this table and the previous */
  15725. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  15726. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  15727. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  15728. unsigned isCorrelated :1; /* True if sub-query is correlated */
  15729. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  15730. unsigned isRecursive :1; /* True for recursive reference in WITH */
  15731. } fg;
  15732. #ifndef SQLITE_OMIT_EXPLAIN
  15733. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  15734. #endif
  15735. int iCursor; /* The VDBE cursor number used to access this table */
  15736. Expr *pOn; /* The ON clause of a join */
  15737. IdList *pUsing; /* The USING clause of a join */
  15738. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  15739. union {
  15740. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  15741. ExprList *pFuncArg; /* Arguments to table-valued-function */
  15742. } u1;
  15743. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  15744. } a[1]; /* One entry for each identifier on the list */
  15745. };
  15746. /*
  15747. ** Permitted values of the SrcList.a.jointype field
  15748. */
  15749. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  15750. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  15751. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  15752. #define JT_LEFT 0x0008 /* Left outer join */
  15753. #define JT_RIGHT 0x0010 /* Right outer join */
  15754. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  15755. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  15756. /*
  15757. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  15758. ** and the WhereInfo.wctrlFlags member.
  15759. **
  15760. ** Value constraints (enforced via assert()):
  15761. ** WHERE_USE_LIMIT == SF_FixedLimit
  15762. */
  15763. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  15764. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  15765. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  15766. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  15767. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  15768. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  15769. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  15770. ** the OR optimization */
  15771. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  15772. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  15773. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  15774. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  15775. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  15776. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  15777. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  15778. /* 0x2000 not currently used */
  15779. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  15780. /* 0x8000 not currently used */
  15781. /* Allowed return values from sqlite3WhereIsDistinct()
  15782. */
  15783. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  15784. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  15785. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  15786. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  15787. /*
  15788. ** A NameContext defines a context in which to resolve table and column
  15789. ** names. The context consists of a list of tables (the pSrcList) field and
  15790. ** a list of named expression (pEList). The named expression list may
  15791. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  15792. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  15793. ** pEList corresponds to the result set of a SELECT and is NULL for
  15794. ** other statements.
  15795. **
  15796. ** NameContexts can be nested. When resolving names, the inner-most
  15797. ** context is searched first. If no match is found, the next outer
  15798. ** context is checked. If there is still no match, the next context
  15799. ** is checked. This process continues until either a match is found
  15800. ** or all contexts are check. When a match is found, the nRef member of
  15801. ** the context containing the match is incremented.
  15802. **
  15803. ** Each subquery gets a new NameContext. The pNext field points to the
  15804. ** NameContext in the parent query. Thus the process of scanning the
  15805. ** NameContext list corresponds to searching through successively outer
  15806. ** subqueries looking for a match.
  15807. */
  15808. struct NameContext {
  15809. Parse *pParse; /* The parser */
  15810. SrcList *pSrcList; /* One or more tables used to resolve names */
  15811. ExprList *pEList; /* Optional list of result-set columns */
  15812. AggInfo *pAggInfo; /* Information about aggregates at this level */
  15813. NameContext *pNext; /* Next outer name context. NULL for outermost */
  15814. int nRef; /* Number of names resolved by this context */
  15815. int nErr; /* Number of errors encountered while resolving names */
  15816. u16 ncFlags; /* Zero or more NC_* flags defined below */
  15817. };
  15818. /*
  15819. ** Allowed values for the NameContext, ncFlags field.
  15820. **
  15821. ** Value constraints (all checked via assert()):
  15822. ** NC_HasAgg == SF_HasAgg
  15823. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  15824. **
  15825. */
  15826. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  15827. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  15828. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  15829. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  15830. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  15831. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  15832. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  15833. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  15834. /*
  15835. ** An instance of the following structure contains all information
  15836. ** needed to generate code for a single SELECT statement.
  15837. **
  15838. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  15839. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  15840. ** limit and nOffset to the value of the offset (or 0 if there is not
  15841. ** offset). But later on, nLimit and nOffset become the memory locations
  15842. ** in the VDBE that record the limit and offset counters.
  15843. **
  15844. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  15845. ** These addresses must be stored so that we can go back and fill in
  15846. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  15847. ** the number of columns in P2 can be computed at the same time
  15848. ** as the OP_OpenEphm instruction is coded because not
  15849. ** enough information about the compound query is known at that point.
  15850. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  15851. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  15852. ** sequences for the ORDER BY clause.
  15853. */
  15854. struct Select {
  15855. ExprList *pEList; /* The fields of the result */
  15856. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  15857. LogEst nSelectRow; /* Estimated number of result rows */
  15858. u32 selFlags; /* Various SF_* values */
  15859. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  15860. #if SELECTTRACE_ENABLED
  15861. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  15862. #endif
  15863. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  15864. SrcList *pSrc; /* The FROM clause */
  15865. Expr *pWhere; /* The WHERE clause */
  15866. ExprList *pGroupBy; /* The GROUP BY clause */
  15867. Expr *pHaving; /* The HAVING clause */
  15868. ExprList *pOrderBy; /* The ORDER BY clause */
  15869. Select *pPrior; /* Prior select in a compound select statement */
  15870. Select *pNext; /* Next select to the left in a compound */
  15871. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  15872. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  15873. With *pWith; /* WITH clause attached to this select. Or NULL. */
  15874. };
  15875. /*
  15876. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  15877. ** "Select Flag".
  15878. **
  15879. ** Value constraints (all checked via assert())
  15880. ** SF_HasAgg == NC_HasAgg
  15881. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  15882. ** SF_FixedLimit == WHERE_USE_LIMIT
  15883. */
  15884. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  15885. #define SF_All 0x00002 /* Includes the ALL keyword */
  15886. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  15887. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  15888. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  15889. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  15890. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  15891. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  15892. #define SF_Compound 0x00100 /* Part of a compound query */
  15893. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  15894. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  15895. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  15896. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  15897. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  15898. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  15899. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  15900. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  15901. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  15902. /*
  15903. ** The results of a SELECT can be distributed in several ways, as defined
  15904. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  15905. ** Type".
  15906. **
  15907. ** SRT_Union Store results as a key in a temporary index
  15908. ** identified by pDest->iSDParm.
  15909. **
  15910. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  15911. **
  15912. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  15913. ** set is not empty.
  15914. **
  15915. ** SRT_Discard Throw the results away. This is used by SELECT
  15916. ** statements within triggers whose only purpose is
  15917. ** the side-effects of functions.
  15918. **
  15919. ** All of the above are free to ignore their ORDER BY clause. Those that
  15920. ** follow must honor the ORDER BY clause.
  15921. **
  15922. ** SRT_Output Generate a row of output (using the OP_ResultRow
  15923. ** opcode) for each row in the result set.
  15924. **
  15925. ** SRT_Mem Only valid if the result is a single column.
  15926. ** Store the first column of the first result row
  15927. ** in register pDest->iSDParm then abandon the rest
  15928. ** of the query. This destination implies "LIMIT 1".
  15929. **
  15930. ** SRT_Set The result must be a single column. Store each
  15931. ** row of result as the key in table pDest->iSDParm.
  15932. ** Apply the affinity pDest->affSdst before storing
  15933. ** results. Used to implement "IN (SELECT ...)".
  15934. **
  15935. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  15936. ** the result there. The cursor is left open after
  15937. ** returning. This is like SRT_Table except that
  15938. ** this destination uses OP_OpenEphemeral to create
  15939. ** the table first.
  15940. **
  15941. ** SRT_Coroutine Generate a co-routine that returns a new row of
  15942. ** results each time it is invoked. The entry point
  15943. ** of the co-routine is stored in register pDest->iSDParm
  15944. ** and the result row is stored in pDest->nDest registers
  15945. ** starting with pDest->iSdst.
  15946. **
  15947. ** SRT_Table Store results in temporary table pDest->iSDParm.
  15948. ** SRT_Fifo This is like SRT_EphemTab except that the table
  15949. ** is assumed to already be open. SRT_Fifo has
  15950. ** the additional property of being able to ignore
  15951. ** the ORDER BY clause.
  15952. **
  15953. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  15954. ** But also use temporary table pDest->iSDParm+1 as
  15955. ** a record of all prior results and ignore any duplicate
  15956. ** rows. Name means: "Distinct Fifo".
  15957. **
  15958. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  15959. ** an index). Append a sequence number so that all entries
  15960. ** are distinct.
  15961. **
  15962. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  15963. ** the same record has never been stored before. The
  15964. ** index at pDest->iSDParm+1 hold all prior stores.
  15965. */
  15966. #define SRT_Union 1 /* Store result as keys in an index */
  15967. #define SRT_Except 2 /* Remove result from a UNION index */
  15968. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  15969. #define SRT_Discard 4 /* Do not save the results anywhere */
  15970. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  15971. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  15972. #define SRT_Queue 7 /* Store result in an queue */
  15973. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  15974. /* The ORDER BY clause is ignored for all of the above */
  15975. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  15976. #define SRT_Output 9 /* Output each row of result */
  15977. #define SRT_Mem 10 /* Store result in a memory cell */
  15978. #define SRT_Set 11 /* Store results as keys in an index */
  15979. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  15980. #define SRT_Coroutine 13 /* Generate a single row of result */
  15981. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  15982. /*
  15983. ** An instance of this object describes where to put of the results of
  15984. ** a SELECT statement.
  15985. */
  15986. struct SelectDest {
  15987. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  15988. int iSDParm; /* A parameter used by the eDest disposal method */
  15989. int iSdst; /* Base register where results are written */
  15990. int nSdst; /* Number of registers allocated */
  15991. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  15992. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  15993. };
  15994. /*
  15995. ** During code generation of statements that do inserts into AUTOINCREMENT
  15996. ** tables, the following information is attached to the Table.u.autoInc.p
  15997. ** pointer of each autoincrement table to record some side information that
  15998. ** the code generator needs. We have to keep per-table autoincrement
  15999. ** information in case inserts are done within triggers. Triggers do not
  16000. ** normally coordinate their activities, but we do need to coordinate the
  16001. ** loading and saving of autoincrement information.
  16002. */
  16003. struct AutoincInfo {
  16004. AutoincInfo *pNext; /* Next info block in a list of them all */
  16005. Table *pTab; /* Table this info block refers to */
  16006. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  16007. int regCtr; /* Memory register holding the rowid counter */
  16008. };
  16009. /*
  16010. ** Size of the column cache
  16011. */
  16012. #ifndef SQLITE_N_COLCACHE
  16013. # define SQLITE_N_COLCACHE 10
  16014. #endif
  16015. /*
  16016. ** At least one instance of the following structure is created for each
  16017. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  16018. ** statement. All such objects are stored in the linked list headed at
  16019. ** Parse.pTriggerPrg and deleted once statement compilation has been
  16020. ** completed.
  16021. **
  16022. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  16023. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  16024. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  16025. ** The Parse.pTriggerPrg list never contains two entries with the same
  16026. ** values for both pTrigger and orconf.
  16027. **
  16028. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  16029. ** accessed (or set to 0 for triggers fired as a result of INSERT
  16030. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  16031. ** a mask of new.* columns used by the program.
  16032. */
  16033. struct TriggerPrg {
  16034. Trigger *pTrigger; /* Trigger this program was coded from */
  16035. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  16036. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  16037. int orconf; /* Default ON CONFLICT policy */
  16038. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  16039. };
  16040. /*
  16041. ** The yDbMask datatype for the bitmask of all attached databases.
  16042. */
  16043. #if SQLITE_MAX_ATTACHED>30
  16044. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  16045. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  16046. # define DbMaskZero(M) memset((M),0,sizeof(M))
  16047. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  16048. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  16049. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  16050. #else
  16051. typedef unsigned int yDbMask;
  16052. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  16053. # define DbMaskZero(M) (M)=0
  16054. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  16055. # define DbMaskAllZero(M) (M)==0
  16056. # define DbMaskNonZero(M) (M)!=0
  16057. #endif
  16058. /*
  16059. ** An SQL parser context. A copy of this structure is passed through
  16060. ** the parser and down into all the parser action routine in order to
  16061. ** carry around information that is global to the entire parse.
  16062. **
  16063. ** The structure is divided into two parts. When the parser and code
  16064. ** generate call themselves recursively, the first part of the structure
  16065. ** is constant but the second part is reset at the beginning and end of
  16066. ** each recursion.
  16067. **
  16068. ** The nTableLock and aTableLock variables are only used if the shared-cache
  16069. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  16070. ** used to store the set of table-locks required by the statement being
  16071. ** compiled. Function sqlite3TableLock() is used to add entries to the
  16072. ** list.
  16073. */
  16074. struct Parse {
  16075. sqlite3 *db; /* The main database structure */
  16076. char *zErrMsg; /* An error message */
  16077. Vdbe *pVdbe; /* An engine for executing database bytecode */
  16078. int rc; /* Return code from execution */
  16079. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  16080. u8 checkSchema; /* Causes schema cookie check after an error */
  16081. u8 nested; /* Number of nested calls to the parser/code generator */
  16082. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  16083. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  16084. u8 mayAbort; /* True if statement may throw an ABORT exception */
  16085. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  16086. u8 okConstFactor; /* OK to factor out constants */
  16087. u8 disableLookaside; /* Number of times lookaside has been disabled */
  16088. u8 nColCache; /* Number of entries in aColCache[] */
  16089. int nRangeReg; /* Size of the temporary register block */
  16090. int iRangeReg; /* First register in temporary register block */
  16091. int nErr; /* Number of errors seen */
  16092. int nTab; /* Number of previously allocated VDBE cursors */
  16093. int nMem; /* Number of memory cells used so far */
  16094. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  16095. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  16096. int iSelfTab; /* Table for associated with an index on expr, or negative
  16097. ** of the base register during check-constraint eval */
  16098. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  16099. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  16100. int nLabel; /* Number of labels used */
  16101. int *aLabel; /* Space to hold the labels */
  16102. ExprList *pConstExpr;/* Constant expressions */
  16103. Token constraintName;/* Name of the constraint currently being parsed */
  16104. yDbMask writeMask; /* Start a write transaction on these databases */
  16105. yDbMask cookieMask; /* Bitmask of schema verified databases */
  16106. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  16107. int regRoot; /* Register holding root page number for new objects */
  16108. int nMaxArg; /* Max args passed to user function by sub-program */
  16109. #if SELECTTRACE_ENABLED
  16110. int nSelect; /* Number of SELECT statements seen */
  16111. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  16112. #endif
  16113. #ifndef SQLITE_OMIT_SHARED_CACHE
  16114. int nTableLock; /* Number of locks in aTableLock */
  16115. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  16116. #endif
  16117. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  16118. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  16119. Table *pTriggerTab; /* Table triggers are being coded for */
  16120. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  16121. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  16122. u32 oldmask; /* Mask of old.* columns referenced */
  16123. u32 newmask; /* Mask of new.* columns referenced */
  16124. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  16125. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  16126. u8 disableTriggers; /* True to disable triggers */
  16127. /**************************************************************************
  16128. ** Fields above must be initialized to zero. The fields that follow,
  16129. ** down to the beginning of the recursive section, do not need to be
  16130. ** initialized as they will be set before being used. The boundary is
  16131. ** determined by offsetof(Parse,aColCache).
  16132. **************************************************************************/
  16133. struct yColCache {
  16134. int iTable; /* Table cursor number */
  16135. i16 iColumn; /* Table column number */
  16136. u8 tempReg; /* iReg is a temp register that needs to be freed */
  16137. int iLevel; /* Nesting level */
  16138. int iReg; /* Reg with value of this column. 0 means none. */
  16139. int lru; /* Least recently used entry has the smallest value */
  16140. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  16141. int aTempReg[8]; /* Holding area for temporary registers */
  16142. Token sNameToken; /* Token with unqualified schema object name */
  16143. /************************************************************************
  16144. ** Above is constant between recursions. Below is reset before and after
  16145. ** each recursion. The boundary between these two regions is determined
  16146. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  16147. ** first field in the recursive region.
  16148. ************************************************************************/
  16149. Token sLastToken; /* The last token parsed */
  16150. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  16151. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  16152. u8 explain; /* True if the EXPLAIN flag is found on the query */
  16153. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16154. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  16155. int nVtabLock; /* Number of virtual tables to lock */
  16156. #endif
  16157. int nHeight; /* Expression tree height of current sub-select */
  16158. #ifndef SQLITE_OMIT_EXPLAIN
  16159. int iSelectId; /* ID of current select for EXPLAIN output */
  16160. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  16161. #endif
  16162. VList *pVList; /* Mapping between variable names and numbers */
  16163. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  16164. const char *zTail; /* All SQL text past the last semicolon parsed */
  16165. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  16166. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  16167. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  16168. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16169. Token sArg; /* Complete text of a module argument */
  16170. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  16171. #endif
  16172. Table *pZombieTab; /* List of Table objects to delete after code gen */
  16173. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  16174. With *pWith; /* Current WITH clause, or NULL */
  16175. With *pWithToFree; /* Free this WITH object at the end of the parse */
  16176. };
  16177. /*
  16178. ** Sizes and pointers of various parts of the Parse object.
  16179. */
  16180. #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
  16181. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  16182. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  16183. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  16184. /*
  16185. ** Return true if currently inside an sqlite3_declare_vtab() call.
  16186. */
  16187. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16188. #define IN_DECLARE_VTAB 0
  16189. #else
  16190. #define IN_DECLARE_VTAB (pParse->declareVtab)
  16191. #endif
  16192. /*
  16193. ** An instance of the following structure can be declared on a stack and used
  16194. ** to save the Parse.zAuthContext value so that it can be restored later.
  16195. */
  16196. struct AuthContext {
  16197. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  16198. Parse *pParse; /* The Parse structure */
  16199. };
  16200. /*
  16201. ** Bitfield flags for P5 value in various opcodes.
  16202. **
  16203. ** Value constraints (enforced via assert()):
  16204. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  16205. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  16206. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  16207. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  16208. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  16209. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  16210. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  16211. */
  16212. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  16213. /* Also used in P2 (not P5) of OP_Delete */
  16214. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  16215. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  16216. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  16217. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  16218. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  16219. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  16220. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  16221. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  16222. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  16223. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  16224. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  16225. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  16226. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  16227. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  16228. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  16229. /*
  16230. * Each trigger present in the database schema is stored as an instance of
  16231. * struct Trigger.
  16232. *
  16233. * Pointers to instances of struct Trigger are stored in two ways.
  16234. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  16235. * database). This allows Trigger structures to be retrieved by name.
  16236. * 2. All triggers associated with a single table form a linked list, using the
  16237. * pNext member of struct Trigger. A pointer to the first element of the
  16238. * linked list is stored as the "pTrigger" member of the associated
  16239. * struct Table.
  16240. *
  16241. * The "step_list" member points to the first element of a linked list
  16242. * containing the SQL statements specified as the trigger program.
  16243. */
  16244. struct Trigger {
  16245. char *zName; /* The name of the trigger */
  16246. char *table; /* The table or view to which the trigger applies */
  16247. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  16248. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  16249. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  16250. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  16251. the <column-list> is stored here */
  16252. Schema *pSchema; /* Schema containing the trigger */
  16253. Schema *pTabSchema; /* Schema containing the table */
  16254. TriggerStep *step_list; /* Link list of trigger program steps */
  16255. Trigger *pNext; /* Next trigger associated with the table */
  16256. };
  16257. /*
  16258. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  16259. ** determine which.
  16260. **
  16261. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  16262. ** In that cases, the constants below can be ORed together.
  16263. */
  16264. #define TRIGGER_BEFORE 1
  16265. #define TRIGGER_AFTER 2
  16266. /*
  16267. * An instance of struct TriggerStep is used to store a single SQL statement
  16268. * that is a part of a trigger-program.
  16269. *
  16270. * Instances of struct TriggerStep are stored in a singly linked list (linked
  16271. * using the "pNext" member) referenced by the "step_list" member of the
  16272. * associated struct Trigger instance. The first element of the linked list is
  16273. * the first step of the trigger-program.
  16274. *
  16275. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  16276. * "SELECT" statement. The meanings of the other members is determined by the
  16277. * value of "op" as follows:
  16278. *
  16279. * (op == TK_INSERT)
  16280. * orconf -> stores the ON CONFLICT algorithm
  16281. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  16282. * this stores a pointer to the SELECT statement. Otherwise NULL.
  16283. * zTarget -> Dequoted name of the table to insert into.
  16284. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  16285. * this stores values to be inserted. Otherwise NULL.
  16286. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  16287. * statement, then this stores the column-names to be
  16288. * inserted into.
  16289. *
  16290. * (op == TK_DELETE)
  16291. * zTarget -> Dequoted name of the table to delete from.
  16292. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  16293. * Otherwise NULL.
  16294. *
  16295. * (op == TK_UPDATE)
  16296. * zTarget -> Dequoted name of the table to update.
  16297. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  16298. * Otherwise NULL.
  16299. * pExprList -> A list of the columns to update and the expressions to update
  16300. * them to. See sqlite3Update() documentation of "pChanges"
  16301. * argument.
  16302. *
  16303. */
  16304. struct TriggerStep {
  16305. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  16306. u8 orconf; /* OE_Rollback etc. */
  16307. Trigger *pTrig; /* The trigger that this step is a part of */
  16308. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  16309. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  16310. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  16311. ExprList *pExprList; /* SET clause for UPDATE. */
  16312. IdList *pIdList; /* Column names for INSERT */
  16313. TriggerStep *pNext; /* Next in the link-list */
  16314. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  16315. };
  16316. /*
  16317. ** The following structure contains information used by the sqliteFix...
  16318. ** routines as they walk the parse tree to make database references
  16319. ** explicit.
  16320. */
  16321. typedef struct DbFixer DbFixer;
  16322. struct DbFixer {
  16323. Parse *pParse; /* The parsing context. Error messages written here */
  16324. Schema *pSchema; /* Fix items to this schema */
  16325. int bVarOnly; /* Check for variable references only */
  16326. const char *zDb; /* Make sure all objects are contained in this database */
  16327. const char *zType; /* Type of the container - used for error messages */
  16328. const Token *pName; /* Name of the container - used for error messages */
  16329. };
  16330. /*
  16331. ** An objected used to accumulate the text of a string where we
  16332. ** do not necessarily know how big the string will be in the end.
  16333. */
  16334. struct StrAccum {
  16335. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  16336. char *zText; /* The string collected so far */
  16337. u32 nAlloc; /* Amount of space allocated in zText */
  16338. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  16339. u32 nChar; /* Length of the string so far */
  16340. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  16341. u8 printfFlags; /* SQLITE_PRINTF flags below */
  16342. };
  16343. #define STRACCUM_NOMEM 1
  16344. #define STRACCUM_TOOBIG 2
  16345. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  16346. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  16347. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  16348. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  16349. /*
  16350. ** A pointer to this structure is used to communicate information
  16351. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  16352. */
  16353. typedef struct {
  16354. sqlite3 *db; /* The database being initialized */
  16355. char **pzErrMsg; /* Error message stored here */
  16356. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  16357. int rc; /* Result code stored here */
  16358. } InitData;
  16359. /*
  16360. ** Structure containing global configuration data for the SQLite library.
  16361. **
  16362. ** This structure also contains some state information.
  16363. */
  16364. struct Sqlite3Config {
  16365. int bMemstat; /* True to enable memory status */
  16366. int bCoreMutex; /* True to enable core mutexing */
  16367. int bFullMutex; /* True to enable full mutexing */
  16368. int bOpenUri; /* True to interpret filenames as URIs */
  16369. int bUseCis; /* Use covering indices for full-scans */
  16370. int bSmallMalloc; /* Avoid large memory allocations if true */
  16371. int mxStrlen; /* Maximum string length */
  16372. int neverCorrupt; /* Database is always well-formed */
  16373. int szLookaside; /* Default lookaside buffer size */
  16374. int nLookaside; /* Default lookaside buffer count */
  16375. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  16376. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  16377. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  16378. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  16379. void *pHeap; /* Heap storage space */
  16380. int nHeap; /* Size of pHeap[] */
  16381. int mnReq, mxReq; /* Min and max heap requests sizes */
  16382. sqlite3_int64 szMmap; /* mmap() space per open file */
  16383. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  16384. void *pPage; /* Page cache memory */
  16385. int szPage; /* Size of each page in pPage[] */
  16386. int nPage; /* Number of pages in pPage[] */
  16387. int mxParserStack; /* maximum depth of the parser stack */
  16388. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  16389. u32 szPma; /* Maximum Sorter PMA size */
  16390. /* The above might be initialized to non-zero. The following need to always
  16391. ** initially be zero, however. */
  16392. int isInit; /* True after initialization has finished */
  16393. int inProgress; /* True while initialization in progress */
  16394. int isMutexInit; /* True after mutexes are initialized */
  16395. int isMallocInit; /* True after malloc is initialized */
  16396. int isPCacheInit; /* True after malloc is initialized */
  16397. int nRefInitMutex; /* Number of users of pInitMutex */
  16398. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  16399. void (*xLog)(void*,int,const char*); /* Function for logging */
  16400. void *pLogArg; /* First argument to xLog() */
  16401. #ifdef SQLITE_ENABLE_SQLLOG
  16402. void(*xSqllog)(void*,sqlite3*,const char*, int);
  16403. void *pSqllogArg;
  16404. #endif
  16405. #ifdef SQLITE_VDBE_COVERAGE
  16406. /* The following callback (if not NULL) is invoked on every VDBE branch
  16407. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  16408. */
  16409. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  16410. void *pVdbeBranchArg; /* 1st argument */
  16411. #endif
  16412. #ifndef SQLITE_UNTESTABLE
  16413. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  16414. #endif
  16415. int bLocaltimeFault; /* True to fail localtime() calls */
  16416. int iOnceResetThreshold; /* When to reset OP_Once counters */
  16417. };
  16418. /*
  16419. ** This macro is used inside of assert() statements to indicate that
  16420. ** the assert is only valid on a well-formed database. Instead of:
  16421. **
  16422. ** assert( X );
  16423. **
  16424. ** One writes:
  16425. **
  16426. ** assert( X || CORRUPT_DB );
  16427. **
  16428. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  16429. ** that the database is definitely corrupt, only that it might be corrupt.
  16430. ** For most test cases, CORRUPT_DB is set to false using a special
  16431. ** sqlite3_test_control(). This enables assert() statements to prove
  16432. ** things that are always true for well-formed databases.
  16433. */
  16434. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  16435. /*
  16436. ** Context pointer passed down through the tree-walk.
  16437. */
  16438. struct Walker {
  16439. Parse *pParse; /* Parser context. */
  16440. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  16441. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  16442. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  16443. int walkerDepth; /* Number of subqueries */
  16444. u8 eCode; /* A small processing code */
  16445. union { /* Extra data for callback */
  16446. NameContext *pNC; /* Naming context */
  16447. int n; /* A counter */
  16448. int iCur; /* A cursor number */
  16449. SrcList *pSrcList; /* FROM clause */
  16450. struct SrcCount *pSrcCount; /* Counting column references */
  16451. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  16452. int *aiCol; /* array of column indexes */
  16453. struct IdxCover *pIdxCover; /* Check for index coverage */
  16454. struct IdxExprTrans *pIdxTrans; /* Convert indexed expr to column */
  16455. ExprList *pGroupBy; /* GROUP BY clause */
  16456. struct HavingToWhereCtx *pHavingCtx; /* HAVING to WHERE clause ctx */
  16457. } u;
  16458. };
  16459. /* Forward declarations */
  16460. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  16461. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  16462. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  16463. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  16464. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  16465. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  16466. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  16467. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  16468. #ifdef SQLITE_DEBUG
  16469. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  16470. #endif
  16471. /*
  16472. ** Return code from the parse-tree walking primitives and their
  16473. ** callbacks.
  16474. */
  16475. #define WRC_Continue 0 /* Continue down into children */
  16476. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  16477. #define WRC_Abort 2 /* Abandon the tree walk */
  16478. /*
  16479. ** An instance of this structure represents a set of one or more CTEs
  16480. ** (common table expressions) created by a single WITH clause.
  16481. */
  16482. struct With {
  16483. int nCte; /* Number of CTEs in the WITH clause */
  16484. With *pOuter; /* Containing WITH clause, or NULL */
  16485. struct Cte { /* For each CTE in the WITH clause.... */
  16486. char *zName; /* Name of this CTE */
  16487. ExprList *pCols; /* List of explicit column names, or NULL */
  16488. Select *pSelect; /* The definition of this CTE */
  16489. const char *zCteErr; /* Error message for circular references */
  16490. } a[1];
  16491. };
  16492. #ifdef SQLITE_DEBUG
  16493. /*
  16494. ** An instance of the TreeView object is used for printing the content of
  16495. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  16496. */
  16497. struct TreeView {
  16498. int iLevel; /* Which level of the tree we are on */
  16499. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  16500. };
  16501. #endif /* SQLITE_DEBUG */
  16502. /*
  16503. ** Assuming zIn points to the first byte of a UTF-8 character,
  16504. ** advance zIn to point to the first byte of the next UTF-8 character.
  16505. */
  16506. #define SQLITE_SKIP_UTF8(zIn) { \
  16507. if( (*(zIn++))>=0xc0 ){ \
  16508. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  16509. } \
  16510. }
  16511. /*
  16512. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  16513. ** the same name but without the _BKPT suffix. These macros invoke
  16514. ** routines that report the line-number on which the error originated
  16515. ** using sqlite3_log(). The routines also provide a convenient place
  16516. ** to set a debugger breakpoint.
  16517. */
  16518. SQLITE_PRIVATE int sqlite3CorruptError(int);
  16519. SQLITE_PRIVATE int sqlite3MisuseError(int);
  16520. SQLITE_PRIVATE int sqlite3CantopenError(int);
  16521. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  16522. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  16523. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  16524. #ifdef SQLITE_DEBUG
  16525. SQLITE_PRIVATE int sqlite3NomemError(int);
  16526. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  16527. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  16528. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  16529. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  16530. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  16531. #else
  16532. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  16533. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  16534. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  16535. #endif
  16536. /*
  16537. ** FTS3 and FTS4 both require virtual table support
  16538. */
  16539. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  16540. # undef SQLITE_ENABLE_FTS3
  16541. # undef SQLITE_ENABLE_FTS4
  16542. #endif
  16543. /*
  16544. ** FTS4 is really an extension for FTS3. It is enabled using the
  16545. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  16546. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  16547. */
  16548. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  16549. # define SQLITE_ENABLE_FTS3 1
  16550. #endif
  16551. /*
  16552. ** The ctype.h header is needed for non-ASCII systems. It is also
  16553. ** needed by FTS3 when FTS3 is included in the amalgamation.
  16554. */
  16555. #if !defined(SQLITE_ASCII) || \
  16556. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  16557. # include <ctype.h>
  16558. #endif
  16559. /*
  16560. ** The following macros mimic the standard library functions toupper(),
  16561. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  16562. ** sqlite versions only work for ASCII characters, regardless of locale.
  16563. */
  16564. #ifdef SQLITE_ASCII
  16565. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  16566. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  16567. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  16568. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  16569. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  16570. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  16571. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  16572. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  16573. #else
  16574. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  16575. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  16576. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  16577. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  16578. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  16579. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  16580. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  16581. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  16582. #endif
  16583. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  16584. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  16585. #endif
  16586. /*
  16587. ** Internal function prototypes
  16588. */
  16589. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  16590. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  16591. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  16592. #define sqlite3StrNICmp sqlite3_strnicmp
  16593. SQLITE_PRIVATE int sqlite3MallocInit(void);
  16594. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  16595. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  16596. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  16597. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  16598. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  16599. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  16600. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  16601. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  16602. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  16603. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  16604. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  16605. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  16606. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  16607. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  16608. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  16609. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  16610. SQLITE_PRIVATE void sqlite3PageFree(void*);
  16611. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  16612. #ifndef SQLITE_UNTESTABLE
  16613. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  16614. #endif
  16615. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  16616. /*
  16617. ** On systems with ample stack space and that support alloca(), make
  16618. ** use of alloca() to obtain space for large automatic objects. By default,
  16619. ** obtain space from malloc().
  16620. **
  16621. ** The alloca() routine never returns NULL. This will cause code paths
  16622. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  16623. */
  16624. #ifdef SQLITE_USE_ALLOCA
  16625. # define sqlite3StackAllocRaw(D,N) alloca(N)
  16626. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  16627. # define sqlite3StackFree(D,P)
  16628. #else
  16629. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  16630. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  16631. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  16632. #endif
  16633. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  16634. ** are, disable MEMSYS3
  16635. */
  16636. #ifdef SQLITE_ENABLE_MEMSYS5
  16637. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  16638. #undef SQLITE_ENABLE_MEMSYS3
  16639. #endif
  16640. #ifdef SQLITE_ENABLE_MEMSYS3
  16641. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  16642. #endif
  16643. #ifndef SQLITE_MUTEX_OMIT
  16644. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  16645. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  16646. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  16647. SQLITE_PRIVATE int sqlite3MutexInit(void);
  16648. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  16649. #endif
  16650. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  16651. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  16652. #else
  16653. # define sqlite3MemoryBarrier()
  16654. #endif
  16655. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  16656. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  16657. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  16658. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  16659. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  16660. /* Access to mutexes used by sqlite3_status() */
  16661. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  16662. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  16663. #ifndef SQLITE_OMIT_FLOATING_POINT
  16664. SQLITE_PRIVATE int sqlite3IsNaN(double);
  16665. #else
  16666. # define sqlite3IsNaN(X) 0
  16667. #endif
  16668. /*
  16669. ** An instance of the following structure holds information about SQL
  16670. ** functions arguments that are the parameters to the printf() function.
  16671. */
  16672. struct PrintfArguments {
  16673. int nArg; /* Total number of arguments */
  16674. int nUsed; /* Number of arguments used so far */
  16675. sqlite3_value **apArg; /* The argument values */
  16676. };
  16677. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
  16678. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  16679. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  16680. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  16681. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  16682. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  16683. #endif
  16684. #if defined(SQLITE_TEST)
  16685. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  16686. #endif
  16687. #if defined(SQLITE_DEBUG)
  16688. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  16689. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  16690. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  16691. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  16692. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  16693. #endif
  16694. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  16695. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  16696. SQLITE_PRIVATE void sqlite3Dequote(char*);
  16697. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  16698. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  16699. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  16700. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  16701. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  16702. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  16703. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  16704. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  16705. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  16706. #ifdef SQLITE_DEBUG
  16707. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  16708. #endif
  16709. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  16710. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  16711. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  16712. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  16713. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  16714. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  16715. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  16716. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  16717. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  16718. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  16719. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  16720. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  16721. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  16722. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  16723. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  16724. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  16725. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  16726. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  16727. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  16728. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16729. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  16730. #endif
  16731. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  16732. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  16733. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  16734. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  16735. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  16736. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  16737. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  16738. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  16739. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  16740. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  16741. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  16742. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  16743. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  16744. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  16745. #else
  16746. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  16747. #endif
  16748. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  16749. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  16750. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  16751. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  16752. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  16753. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  16754. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  16755. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  16756. sqlite3_vfs**,char**,char **);
  16757. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  16758. #ifdef SQLITE_UNTESTABLE
  16759. # define sqlite3FaultSim(X) SQLITE_OK
  16760. #else
  16761. SQLITE_PRIVATE int sqlite3FaultSim(int);
  16762. #endif
  16763. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  16764. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  16765. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  16766. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  16767. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  16768. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  16769. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  16770. #ifndef SQLITE_UNTESTABLE
  16771. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  16772. #endif
  16773. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  16774. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  16775. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  16776. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  16777. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  16778. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  16779. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  16780. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  16781. #else
  16782. # define sqlite3ViewGetColumnNames(A,B) 0
  16783. #endif
  16784. #if SQLITE_MAX_ATTACHED>30
  16785. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  16786. #endif
  16787. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  16788. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  16789. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  16790. #ifndef SQLITE_OMIT_AUTOINCREMENT
  16791. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  16792. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  16793. #else
  16794. # define sqlite3AutoincrementBegin(X)
  16795. # define sqlite3AutoincrementEnd(X)
  16796. #endif
  16797. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  16798. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  16799. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  16800. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  16801. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  16802. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  16803. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  16804. Token*, Select*, Expr*, IdList*);
  16805. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  16806. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  16807. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  16808. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  16809. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  16810. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  16811. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  16812. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  16813. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  16814. Expr*, int, int, u8);
  16815. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  16816. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  16817. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  16818. Expr*,ExprList*,u32,Expr*,Expr*);
  16819. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  16820. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  16821. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  16822. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  16823. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  16824. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  16825. #endif
  16826. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  16827. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  16828. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  16829. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  16830. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  16831. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  16832. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  16833. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
  16834. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  16835. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  16836. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  16837. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  16838. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  16839. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  16840. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  16841. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  16842. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  16843. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  16844. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  16845. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  16846. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  16847. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  16848. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  16849. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  16850. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  16851. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  16852. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  16853. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  16854. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  16855. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  16856. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  16857. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  16858. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  16859. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  16860. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  16861. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  16862. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  16863. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  16864. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  16865. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  16866. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  16867. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  16868. #define LOCATE_VIEW 0x01
  16869. #define LOCATE_NOERR 0x02
  16870. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  16871. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  16872. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  16873. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  16874. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  16875. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  16876. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  16877. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  16878. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  16879. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  16880. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  16881. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  16882. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  16883. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  16884. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  16885. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  16886. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  16887. #ifndef SQLITE_UNTESTABLE
  16888. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  16889. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  16890. #endif
  16891. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  16892. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  16893. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  16894. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  16895. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  16896. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  16897. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  16898. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  16899. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  16900. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  16901. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  16902. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  16903. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  16904. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  16905. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  16906. #endif
  16907. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  16908. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  16909. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  16910. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  16911. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  16912. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  16913. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  16914. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  16915. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  16916. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  16917. u8,u8,int,int*,int*);
  16918. #ifdef SQLITE_ENABLE_NULL_TRIM
  16919. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  16920. #else
  16921. # define sqlite3SetMakeRecordP5(A,B)
  16922. #endif
  16923. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  16924. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  16925. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  16926. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  16927. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  16928. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  16929. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  16930. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  16931. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  16932. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  16933. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  16934. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  16935. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  16936. #if SELECTTRACE_ENABLED
  16937. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  16938. #else
  16939. # define sqlite3SelectSetName(A,B)
  16940. #endif
  16941. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  16942. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  16943. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  16944. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  16945. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  16946. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  16947. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  16948. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  16949. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  16950. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  16951. #endif
  16952. #ifndef SQLITE_OMIT_TRIGGER
  16953. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  16954. Expr*,int, int);
  16955. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  16956. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  16957. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  16958. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  16959. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  16960. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  16961. int, int, int);
  16962. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  16963. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  16964. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  16965. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  16966. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  16967. Select*,u8);
  16968. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  16969. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  16970. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  16971. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  16972. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  16973. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  16974. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  16975. #else
  16976. # define sqlite3TriggersExist(B,C,D,E,F) 0
  16977. # define sqlite3DeleteTrigger(A,B)
  16978. # define sqlite3DropTriggerPtr(A,B)
  16979. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  16980. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  16981. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  16982. # define sqlite3TriggerList(X, Y) 0
  16983. # define sqlite3ParseToplevel(p) p
  16984. # define sqlite3IsToplevel(p) 1
  16985. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  16986. #endif
  16987. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  16988. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  16989. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  16990. #ifndef SQLITE_OMIT_AUTHORIZATION
  16991. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  16992. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  16993. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  16994. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  16995. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  16996. #else
  16997. # define sqlite3AuthRead(a,b,c,d)
  16998. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  16999. # define sqlite3AuthContextPush(a,b,c)
  17000. # define sqlite3AuthContextPop(a) ((void)(a))
  17001. #endif
  17002. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  17003. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  17004. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  17005. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  17006. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  17007. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  17008. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  17009. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  17010. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  17011. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  17012. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  17013. #ifndef SQLITE_OMIT_UTF16
  17014. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  17015. #endif
  17016. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  17017. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  17018. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  17019. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  17020. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17021. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  17022. #endif
  17023. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  17024. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  17025. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  17026. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  17027. #endif
  17028. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  17029. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  17030. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  17031. /*
  17032. ** Routines to read and write variable-length integers. These used to
  17033. ** be defined locally, but now we use the varint routines in the util.c
  17034. ** file.
  17035. */
  17036. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  17037. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  17038. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  17039. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  17040. /*
  17041. ** The common case is for a varint to be a single byte. They following
  17042. ** macros handle the common case without a procedure call, but then call
  17043. ** the procedure for larger varints.
  17044. */
  17045. #define getVarint32(A,B) \
  17046. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  17047. #define putVarint32(A,B) \
  17048. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  17049. sqlite3PutVarint((A),(B)))
  17050. #define getVarint sqlite3GetVarint
  17051. #define putVarint sqlite3PutVarint
  17052. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  17053. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  17054. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  17055. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  17056. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  17057. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  17058. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  17059. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  17060. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  17061. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  17062. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  17063. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  17064. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  17065. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  17066. #if defined(SQLITE_NEED_ERR_NAME)
  17067. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  17068. #endif
  17069. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  17070. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  17071. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  17072. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  17073. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  17074. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  17075. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  17076. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  17077. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  17078. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  17079. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  17080. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  17081. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  17082. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  17083. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  17084. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  17085. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  17086. #ifdef SQLITE_ENABLE_8_3_NAMES
  17087. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  17088. #else
  17089. # define sqlite3FileSuffix3(X,Y)
  17090. #endif
  17091. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  17092. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  17093. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  17094. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  17095. void(*)(void*));
  17096. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  17097. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  17098. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  17099. #ifndef SQLITE_OMIT_UTF16
  17100. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  17101. #endif
  17102. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  17103. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  17104. #ifndef SQLITE_AMALGAMATION
  17105. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  17106. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  17107. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  17108. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  17109. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  17110. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  17111. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  17112. #ifndef SQLITE_OMIT_WSD
  17113. SQLITE_PRIVATE int sqlite3PendingByte;
  17114. #endif
  17115. #endif
  17116. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  17117. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  17118. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  17119. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  17120. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  17121. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  17122. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  17123. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  17124. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  17125. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  17126. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  17127. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  17128. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  17129. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  17130. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  17131. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  17132. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  17133. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  17134. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  17135. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  17136. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  17137. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  17138. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  17139. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  17140. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  17141. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  17142. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  17143. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  17144. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  17145. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  17146. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  17147. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  17148. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  17149. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  17150. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  17151. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  17152. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  17153. #ifdef SQLITE_DEBUG
  17154. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  17155. #endif
  17156. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  17157. void (*)(sqlite3_context*,int,sqlite3_value **),
  17158. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  17159. FuncDestructor *pDestructor
  17160. );
  17161. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  17162. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  17163. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  17164. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  17165. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  17166. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  17167. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  17168. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  17169. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  17170. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  17171. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  17172. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  17173. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  17174. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  17175. #ifndef SQLITE_OMIT_SUBQUERY
  17176. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  17177. #else
  17178. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  17179. #endif
  17180. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  17181. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  17182. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  17183. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  17184. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  17185. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  17186. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  17187. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  17188. #endif
  17189. /*
  17190. ** The interface to the LEMON-generated parser
  17191. */
  17192. #ifndef SQLITE_AMALGAMATION
  17193. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  17194. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  17195. #endif
  17196. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  17197. #ifdef YYTRACKMAXSTACKDEPTH
  17198. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  17199. #endif
  17200. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  17201. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  17202. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  17203. #else
  17204. # define sqlite3CloseExtensions(X)
  17205. #endif
  17206. #ifndef SQLITE_OMIT_SHARED_CACHE
  17207. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  17208. #else
  17209. #define sqlite3TableLock(v,w,x,y,z)
  17210. #endif
  17211. #ifdef SQLITE_TEST
  17212. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  17213. #endif
  17214. #ifdef SQLITE_OMIT_VIRTUALTABLE
  17215. # define sqlite3VtabClear(Y)
  17216. # define sqlite3VtabSync(X,Y) SQLITE_OK
  17217. # define sqlite3VtabRollback(X)
  17218. # define sqlite3VtabCommit(X)
  17219. # define sqlite3VtabInSync(db) 0
  17220. # define sqlite3VtabLock(X)
  17221. # define sqlite3VtabUnlock(X)
  17222. # define sqlite3VtabUnlockList(X)
  17223. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  17224. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  17225. #else
  17226. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  17227. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  17228. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  17229. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  17230. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  17231. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  17232. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  17233. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  17234. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  17235. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  17236. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  17237. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  17238. sqlite3*,
  17239. const char*,
  17240. const sqlite3_module*,
  17241. void*,
  17242. void(*)(void*)
  17243. );
  17244. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  17245. #endif
  17246. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  17247. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  17248. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  17249. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  17250. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  17251. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  17252. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  17253. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  17254. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  17255. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  17256. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  17257. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  17258. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  17259. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  17260. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  17261. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  17262. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  17263. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  17264. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  17265. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  17266. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  17267. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  17268. #ifndef SQLITE_OMIT_WAL
  17269. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  17270. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  17271. #endif
  17272. #ifndef SQLITE_OMIT_CTE
  17273. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  17274. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  17275. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  17276. #else
  17277. #define sqlite3WithPush(x,y,z)
  17278. #define sqlite3WithDelete(x,y)
  17279. #endif
  17280. /* Declarations for functions in fkey.c. All of these are replaced by
  17281. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  17282. ** key functionality is available. If OMIT_TRIGGER is defined but
  17283. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  17284. ** this case foreign keys are parsed, but no other functionality is
  17285. ** provided (enforcement of FK constraints requires the triggers sub-system).
  17286. */
  17287. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  17288. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  17289. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  17290. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  17291. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  17292. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  17293. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  17294. #else
  17295. #define sqlite3FkActions(a,b,c,d,e,f)
  17296. #define sqlite3FkCheck(a,b,c,d,e,f)
  17297. #define sqlite3FkDropTable(a,b,c)
  17298. #define sqlite3FkOldmask(a,b) 0
  17299. #define sqlite3FkRequired(a,b,c,d) 0
  17300. #define sqlite3FkReferences(a) 0
  17301. #endif
  17302. #ifndef SQLITE_OMIT_FOREIGN_KEY
  17303. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  17304. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  17305. #else
  17306. #define sqlite3FkDelete(a,b)
  17307. #define sqlite3FkLocateIndex(a,b,c,d,e)
  17308. #endif
  17309. /*
  17310. ** Available fault injectors. Should be numbered beginning with 0.
  17311. */
  17312. #define SQLITE_FAULTINJECTOR_MALLOC 0
  17313. #define SQLITE_FAULTINJECTOR_COUNT 1
  17314. /*
  17315. ** The interface to the code in fault.c used for identifying "benign"
  17316. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  17317. ** is not defined.
  17318. */
  17319. #ifndef SQLITE_UNTESTABLE
  17320. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  17321. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  17322. #else
  17323. #define sqlite3BeginBenignMalloc()
  17324. #define sqlite3EndBenignMalloc()
  17325. #endif
  17326. /*
  17327. ** Allowed return values from sqlite3FindInIndex()
  17328. */
  17329. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  17330. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  17331. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  17332. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  17333. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  17334. /*
  17335. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  17336. */
  17337. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  17338. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  17339. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  17340. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  17341. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  17342. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  17343. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  17344. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  17345. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  17346. #endif
  17347. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  17348. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  17349. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  17350. #if SQLITE_MAX_EXPR_DEPTH>0
  17351. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  17352. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  17353. #else
  17354. #define sqlite3SelectExprHeight(x) 0
  17355. #define sqlite3ExprCheckHeight(x,y)
  17356. #endif
  17357. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  17358. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  17359. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  17360. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  17361. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  17362. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  17363. #else
  17364. #define sqlite3ConnectionBlocked(x,y)
  17365. #define sqlite3ConnectionUnlocked(x)
  17366. #define sqlite3ConnectionClosed(x)
  17367. #endif
  17368. #ifdef SQLITE_DEBUG
  17369. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  17370. #endif
  17371. /*
  17372. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  17373. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  17374. ** print I/O tracing messages.
  17375. */
  17376. #ifdef SQLITE_ENABLE_IOTRACE
  17377. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  17378. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  17379. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  17380. #else
  17381. # define IOTRACE(A)
  17382. # define sqlite3VdbeIOTraceSql(X)
  17383. #endif
  17384. /*
  17385. ** These routines are available for the mem2.c debugging memory allocator
  17386. ** only. They are used to verify that different "types" of memory
  17387. ** allocations are properly tracked by the system.
  17388. **
  17389. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  17390. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  17391. ** a single bit set.
  17392. **
  17393. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  17394. ** argument match the type set by the previous sqlite3MemdebugSetType().
  17395. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  17396. **
  17397. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  17398. ** argument match the type set by the previous sqlite3MemdebugSetType().
  17399. **
  17400. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  17401. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  17402. ** it might have been allocated by lookaside, except the allocation was
  17403. ** too large or lookaside was already full. It is important to verify
  17404. ** that allocations that might have been satisfied by lookaside are not
  17405. ** passed back to non-lookaside free() routines. Asserts such as the
  17406. ** example above are placed on the non-lookaside free() routines to verify
  17407. ** this constraint.
  17408. **
  17409. ** All of this is no-op for a production build. It only comes into
  17410. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  17411. */
  17412. #ifdef SQLITE_MEMDEBUG
  17413. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  17414. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  17415. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  17416. #else
  17417. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  17418. # define sqlite3MemdebugHasType(X,Y) 1
  17419. # define sqlite3MemdebugNoType(X,Y) 1
  17420. #endif
  17421. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  17422. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  17423. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  17424. /*
  17425. ** Threading interface
  17426. */
  17427. #if SQLITE_MAX_WORKER_THREADS>0
  17428. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  17429. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  17430. #endif
  17431. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  17432. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  17433. #endif
  17434. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  17435. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  17436. #endif
  17437. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  17438. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  17439. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  17440. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  17441. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  17442. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  17443. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  17444. #endif
  17445. #endif /* SQLITEINT_H */
  17446. /************** End of sqliteInt.h *******************************************/
  17447. /************** Begin file global.c ******************************************/
  17448. /*
  17449. ** 2008 June 13
  17450. **
  17451. ** The author disclaims copyright to this source code. In place of
  17452. ** a legal notice, here is a blessing:
  17453. **
  17454. ** May you do good and not evil.
  17455. ** May you find forgiveness for yourself and forgive others.
  17456. ** May you share freely, never taking more than you give.
  17457. **
  17458. *************************************************************************
  17459. **
  17460. ** This file contains definitions of global variables and constants.
  17461. */
  17462. /* #include "sqliteInt.h" */
  17463. /* An array to map all upper-case characters into their corresponding
  17464. ** lower-case character.
  17465. **
  17466. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  17467. ** handle case conversions for the UTF character set since the tables
  17468. ** involved are nearly as big or bigger than SQLite itself.
  17469. */
  17470. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  17471. #ifdef SQLITE_ASCII
  17472. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  17473. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  17474. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  17475. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  17476. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  17477. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  17478. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  17479. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  17480. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  17481. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  17482. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  17483. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  17484. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  17485. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  17486. 252,253,254,255
  17487. #endif
  17488. #ifdef SQLITE_EBCDIC
  17489. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  17490. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  17491. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  17492. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  17493. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  17494. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  17495. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  17496. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  17497. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  17498. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  17499. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  17500. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  17501. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  17502. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  17503. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  17504. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  17505. #endif
  17506. };
  17507. /*
  17508. ** The following 256 byte lookup table is used to support SQLites built-in
  17509. ** equivalents to the following standard library functions:
  17510. **
  17511. ** isspace() 0x01
  17512. ** isalpha() 0x02
  17513. ** isdigit() 0x04
  17514. ** isalnum() 0x06
  17515. ** isxdigit() 0x08
  17516. ** toupper() 0x20
  17517. ** SQLite identifier character 0x40
  17518. ** Quote character 0x80
  17519. **
  17520. ** Bit 0x20 is set if the mapped character requires translation to upper
  17521. ** case. i.e. if the character is a lower-case ASCII character.
  17522. ** If x is a lower-case ASCII character, then its upper-case equivalent
  17523. ** is (x - 0x20). Therefore toupper() can be implemented as:
  17524. **
  17525. ** (x & ~(map[x]&0x20))
  17526. **
  17527. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  17528. ** array. tolower() is used more often than toupper() by SQLite.
  17529. **
  17530. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  17531. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  17532. ** non-ASCII UTF character. Hence the test for whether or not a character is
  17533. ** part of an identifier is 0x46.
  17534. */
  17535. #ifdef SQLITE_ASCII
  17536. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  17537. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  17538. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  17539. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  17540. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  17541. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  17542. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  17543. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  17544. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  17545. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  17546. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  17547. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  17548. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  17549. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  17550. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  17551. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  17552. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  17553. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  17554. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  17555. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  17556. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  17557. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  17558. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  17559. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  17560. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  17561. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  17562. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  17563. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  17564. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  17565. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  17566. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  17567. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  17568. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  17569. };
  17570. #endif
  17571. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  17572. ** compatibility for legacy applications, the URI filename capability is
  17573. ** disabled by default.
  17574. **
  17575. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  17576. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  17577. **
  17578. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  17579. ** disabled. The default value may be changed by compiling with the
  17580. ** SQLITE_USE_URI symbol defined.
  17581. **
  17582. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  17583. ** enabled.
  17584. */
  17585. #ifndef SQLITE_USE_URI
  17586. # ifdef SQLITE_HAS_CODEC
  17587. # define SQLITE_USE_URI 1
  17588. # else
  17589. # define SQLITE_USE_URI 0
  17590. # endif
  17591. #endif
  17592. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  17593. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  17594. ** that compile-time option is omitted.
  17595. */
  17596. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  17597. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  17598. #endif
  17599. /* The minimum PMA size is set to this value multiplied by the database
  17600. ** page size in bytes.
  17601. */
  17602. #ifndef SQLITE_SORTER_PMASZ
  17603. # define SQLITE_SORTER_PMASZ 250
  17604. #endif
  17605. /* Statement journals spill to disk when their size exceeds the following
  17606. ** threshold (in bytes). 0 means that statement journals are created and
  17607. ** written to disk immediately (the default behavior for SQLite versions
  17608. ** before 3.12.0). -1 means always keep the entire statement journal in
  17609. ** memory. (The statement journal is also always held entirely in memory
  17610. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  17611. ** setting.)
  17612. */
  17613. #ifndef SQLITE_STMTJRNL_SPILL
  17614. # define SQLITE_STMTJRNL_SPILL (64*1024)
  17615. #endif
  17616. /*
  17617. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  17618. ** number of bytes in each lookaside slot (should be a multiple of 8)
  17619. ** and N is the number of slots. The lookaside-configuration can be
  17620. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  17621. ** or at run-time for an individual database connection using
  17622. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  17623. */
  17624. #ifndef SQLITE_DEFAULT_LOOKASIDE
  17625. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  17626. #endif
  17627. /*
  17628. ** The following singleton contains the global configuration for
  17629. ** the SQLite library.
  17630. */
  17631. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  17632. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  17633. 1, /* bCoreMutex */
  17634. SQLITE_THREADSAFE==1, /* bFullMutex */
  17635. SQLITE_USE_URI, /* bOpenUri */
  17636. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  17637. 0, /* bSmallMalloc */
  17638. 0x7ffffffe, /* mxStrlen */
  17639. 0, /* neverCorrupt */
  17640. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  17641. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  17642. {0,0,0,0,0,0,0,0}, /* m */
  17643. {0,0,0,0,0,0,0,0,0}, /* mutex */
  17644. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  17645. (void*)0, /* pHeap */
  17646. 0, /* nHeap */
  17647. 0, 0, /* mnHeap, mxHeap */
  17648. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  17649. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  17650. (void*)0, /* pPage */
  17651. 0, /* szPage */
  17652. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  17653. 0, /* mxParserStack */
  17654. 0, /* sharedCacheEnabled */
  17655. SQLITE_SORTER_PMASZ, /* szPma */
  17656. /* All the rest should always be initialized to zero */
  17657. 0, /* isInit */
  17658. 0, /* inProgress */
  17659. 0, /* isMutexInit */
  17660. 0, /* isMallocInit */
  17661. 0, /* isPCacheInit */
  17662. 0, /* nRefInitMutex */
  17663. 0, /* pInitMutex */
  17664. 0, /* xLog */
  17665. 0, /* pLogArg */
  17666. #ifdef SQLITE_ENABLE_SQLLOG
  17667. 0, /* xSqllog */
  17668. 0, /* pSqllogArg */
  17669. #endif
  17670. #ifdef SQLITE_VDBE_COVERAGE
  17671. 0, /* xVdbeBranch */
  17672. 0, /* pVbeBranchArg */
  17673. #endif
  17674. #ifndef SQLITE_UNTESTABLE
  17675. 0, /* xTestCallback */
  17676. #endif
  17677. 0, /* bLocaltimeFault */
  17678. 0x7ffffffe /* iOnceResetThreshold */
  17679. };
  17680. /*
  17681. ** Hash table for global functions - functions common to all
  17682. ** database connections. After initialization, this table is
  17683. ** read-only.
  17684. */
  17685. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  17686. /*
  17687. ** Constant tokens for values 0 and 1.
  17688. */
  17689. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  17690. { "0", 1 },
  17691. { "1", 1 }
  17692. };
  17693. /*
  17694. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  17695. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  17696. ** the database page that contains the pending byte. It never attempts
  17697. ** to read or write that page. The pending byte page is set aside
  17698. ** for use by the VFS layers as space for managing file locks.
  17699. **
  17700. ** During testing, it is often desirable to move the pending byte to
  17701. ** a different position in the file. This allows code that has to
  17702. ** deal with the pending byte to run on files that are much smaller
  17703. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  17704. ** move the pending byte.
  17705. **
  17706. ** IMPORTANT: Changing the pending byte to any value other than
  17707. ** 0x40000000 results in an incompatible database file format!
  17708. ** Changing the pending byte during operation will result in undefined
  17709. ** and incorrect behavior.
  17710. */
  17711. #ifndef SQLITE_OMIT_WSD
  17712. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  17713. #endif
  17714. /* #include "opcodes.h" */
  17715. /*
  17716. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  17717. ** created by mkopcodeh.awk during compilation. Data is obtained
  17718. ** from the comments following the "case OP_xxxx:" statements in
  17719. ** the vdbe.c file.
  17720. */
  17721. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  17722. /*
  17723. ** Name of the default collating sequence
  17724. */
  17725. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  17726. /************** End of global.c **********************************************/
  17727. /************** Begin file status.c ******************************************/
  17728. /*
  17729. ** 2008 June 18
  17730. **
  17731. ** The author disclaims copyright to this source code. In place of
  17732. ** a legal notice, here is a blessing:
  17733. **
  17734. ** May you do good and not evil.
  17735. ** May you find forgiveness for yourself and forgive others.
  17736. ** May you share freely, never taking more than you give.
  17737. **
  17738. *************************************************************************
  17739. **
  17740. ** This module implements the sqlite3_status() interface and related
  17741. ** functionality.
  17742. */
  17743. /* #include "sqliteInt.h" */
  17744. /************** Include vdbeInt.h in the middle of status.c ******************/
  17745. /************** Begin file vdbeInt.h *****************************************/
  17746. /*
  17747. ** 2003 September 6
  17748. **
  17749. ** The author disclaims copyright to this source code. In place of
  17750. ** a legal notice, here is a blessing:
  17751. **
  17752. ** May you do good and not evil.
  17753. ** May you find forgiveness for yourself and forgive others.
  17754. ** May you share freely, never taking more than you give.
  17755. **
  17756. *************************************************************************
  17757. ** This is the header file for information that is private to the
  17758. ** VDBE. This information used to all be at the top of the single
  17759. ** source code file "vdbe.c". When that file became too big (over
  17760. ** 6000 lines long) it was split up into several smaller files and
  17761. ** this header information was factored out.
  17762. */
  17763. #ifndef SQLITE_VDBEINT_H
  17764. #define SQLITE_VDBEINT_H
  17765. /*
  17766. ** The maximum number of times that a statement will try to reparse
  17767. ** itself before giving up and returning SQLITE_SCHEMA.
  17768. */
  17769. #ifndef SQLITE_MAX_SCHEMA_RETRY
  17770. # define SQLITE_MAX_SCHEMA_RETRY 50
  17771. #endif
  17772. /*
  17773. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  17774. ** "explain" P4 display logic is enabled.
  17775. */
  17776. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  17777. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  17778. # define VDBE_DISPLAY_P4 1
  17779. #else
  17780. # define VDBE_DISPLAY_P4 0
  17781. #endif
  17782. /*
  17783. ** SQL is translated into a sequence of instructions to be
  17784. ** executed by a virtual machine. Each instruction is an instance
  17785. ** of the following structure.
  17786. */
  17787. typedef struct VdbeOp Op;
  17788. /*
  17789. ** Boolean values
  17790. */
  17791. typedef unsigned Bool;
  17792. /* Opaque type used by code in vdbesort.c */
  17793. typedef struct VdbeSorter VdbeSorter;
  17794. /* Elements of the linked list at Vdbe.pAuxData */
  17795. typedef struct AuxData AuxData;
  17796. /* Types of VDBE cursors */
  17797. #define CURTYPE_BTREE 0
  17798. #define CURTYPE_SORTER 1
  17799. #define CURTYPE_VTAB 2
  17800. #define CURTYPE_PSEUDO 3
  17801. /*
  17802. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  17803. **
  17804. ** * A b-tree cursor
  17805. ** - In the main database or in an ephemeral database
  17806. ** - On either an index or a table
  17807. ** * A sorter
  17808. ** * A virtual table
  17809. ** * A one-row "pseudotable" stored in a single register
  17810. */
  17811. typedef struct VdbeCursor VdbeCursor;
  17812. struct VdbeCursor {
  17813. u8 eCurType; /* One of the CURTYPE_* values above */
  17814. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  17815. u8 nullRow; /* True if pointing to a row with no data */
  17816. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  17817. u8 isTable; /* True for rowid tables. False for indexes */
  17818. #ifdef SQLITE_DEBUG
  17819. u8 seekOp; /* Most recent seek operation on this cursor */
  17820. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  17821. #endif
  17822. Bool isEphemeral:1; /* True for an ephemeral table */
  17823. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  17824. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  17825. Btree *pBtx; /* Separate file holding temporary table */
  17826. i64 seqCount; /* Sequence counter */
  17827. int *aAltMap; /* Mapping from table to index column numbers */
  17828. /* Cached OP_Column parse information is only valid if cacheStatus matches
  17829. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  17830. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  17831. ** the cache is out of date. */
  17832. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  17833. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  17834. ** if there have been no prior seeks on the cursor. */
  17835. /* seekResult does not distinguish between "no seeks have ever occurred
  17836. ** on this cursor" and "the most recent seek was an exact match".
  17837. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  17838. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  17839. ** The fields that follow are uninitialized, and must be individually
  17840. ** initialized prior to first use. */
  17841. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  17842. union {
  17843. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  17844. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  17845. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  17846. } uc;
  17847. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  17848. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  17849. Pgno pgnoRoot; /* Root page of the open btree cursor */
  17850. i16 nField; /* Number of fields in the header */
  17851. u16 nHdrParsed; /* Number of header fields parsed so far */
  17852. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  17853. u32 *aOffset; /* Pointer to aType[nField] */
  17854. const u8 *aRow; /* Data for the current row, if all on one page */
  17855. u32 payloadSize; /* Total number of bytes in the record */
  17856. u32 szRow; /* Byte available in aRow */
  17857. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  17858. u64 maskUsed; /* Mask of columns used by this cursor */
  17859. #endif
  17860. /* 2*nField extra array elements allocated for aType[], beyond the one
  17861. ** static element declared in the structure. nField total array slots for
  17862. ** aType[] and nField+1 array slots for aOffset[] */
  17863. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  17864. };
  17865. /*
  17866. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  17867. */
  17868. #define CACHE_STALE 0
  17869. /*
  17870. ** When a sub-program is executed (OP_Program), a structure of this type
  17871. ** is allocated to store the current value of the program counter, as
  17872. ** well as the current memory cell array and various other frame specific
  17873. ** values stored in the Vdbe struct. When the sub-program is finished,
  17874. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  17875. ** restoring the state of the VM to as it was before the sub-program
  17876. ** began executing.
  17877. **
  17878. ** The memory for a VdbeFrame object is allocated and managed by a memory
  17879. ** cell in the parent (calling) frame. When the memory cell is deleted or
  17880. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  17881. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  17882. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  17883. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  17884. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  17885. ** child frame are released.
  17886. **
  17887. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  17888. ** set to NULL if the currently executing frame is the main program.
  17889. */
  17890. typedef struct VdbeFrame VdbeFrame;
  17891. struct VdbeFrame {
  17892. Vdbe *v; /* VM this frame belongs to */
  17893. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  17894. Op *aOp; /* Program instructions for parent frame */
  17895. i64 *anExec; /* Event counters from parent frame */
  17896. Mem *aMem; /* Array of memory cells for parent frame */
  17897. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  17898. u8 *aOnce; /* Bitmask used by OP_Once */
  17899. void *token; /* Copy of SubProgram.token */
  17900. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  17901. AuxData *pAuxData; /* Linked list of auxdata allocations */
  17902. int nCursor; /* Number of entries in apCsr */
  17903. int pc; /* Program Counter in parent (calling) frame */
  17904. int nOp; /* Size of aOp array */
  17905. int nMem; /* Number of entries in aMem */
  17906. int nChildMem; /* Number of memory cells for child frame */
  17907. int nChildCsr; /* Number of cursors for child frame */
  17908. int nChange; /* Statement changes (Vdbe.nChange) */
  17909. int nDbChange; /* Value of db->nChange */
  17910. };
  17911. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  17912. /*
  17913. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  17914. ** structures. Each Mem struct may cache multiple representations (string,
  17915. ** integer etc.) of the same value.
  17916. */
  17917. struct sqlite3_value {
  17918. union MemValue {
  17919. double r; /* Real value used when MEM_Real is set in flags */
  17920. i64 i; /* Integer value used when MEM_Int is set in flags */
  17921. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  17922. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  17923. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  17924. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  17925. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  17926. } u;
  17927. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  17928. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  17929. u8 eSubtype; /* Subtype for this value */
  17930. int n; /* Number of characters in string value, excluding '\0' */
  17931. char *z; /* String or BLOB value */
  17932. /* ShallowCopy only needs to copy the information above */
  17933. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  17934. int szMalloc; /* Size of the zMalloc allocation */
  17935. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  17936. sqlite3 *db; /* The associated database connection */
  17937. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  17938. #ifdef SQLITE_DEBUG
  17939. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  17940. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  17941. #endif
  17942. };
  17943. /*
  17944. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  17945. ** follows.
  17946. */
  17947. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  17948. /* One or more of the following flags are set to indicate the validOK
  17949. ** representations of the value stored in the Mem struct.
  17950. **
  17951. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  17952. ** For a pointer type created using sqlite3_bind_pointer() or
  17953. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  17954. **
  17955. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  17956. ** Usually this is encoded in the same unicode encoding as the main
  17957. ** database (see below for exceptions). If the MEM_Term flag is also
  17958. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  17959. ** flags may coexist with the MEM_Str flag.
  17960. */
  17961. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  17962. #define MEM_Str 0x0002 /* Value is a string */
  17963. #define MEM_Int 0x0004 /* Value is an integer */
  17964. #define MEM_Real 0x0008 /* Value is a real number */
  17965. #define MEM_Blob 0x0010 /* Value is a BLOB */
  17966. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  17967. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  17968. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  17969. #define MEM_Undefined 0x0080 /* Value is undefined */
  17970. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  17971. #define MEM_TypeMask 0xc1ff /* Mask of type bits */
  17972. /* Whenever Mem contains a valid string or blob representation, one of
  17973. ** the following flags must be set to determine the memory management
  17974. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  17975. ** string is \000 or \u0000 terminated
  17976. */
  17977. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  17978. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  17979. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  17980. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  17981. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  17982. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  17983. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  17984. #ifdef SQLITE_OMIT_INCRBLOB
  17985. #undef MEM_Zero
  17986. #define MEM_Zero 0x0000
  17987. #endif
  17988. /* Return TRUE if Mem X contains dynamically allocated content - anything
  17989. ** that needs to be deallocated to avoid a leak.
  17990. */
  17991. #define VdbeMemDynamic(X) \
  17992. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  17993. /*
  17994. ** Clear any existing type flags from a Mem and replace them with f
  17995. */
  17996. #define MemSetTypeFlag(p, f) \
  17997. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  17998. /*
  17999. ** Return true if a memory cell is not marked as invalid. This macro
  18000. ** is for use inside assert() statements only.
  18001. */
  18002. #ifdef SQLITE_DEBUG
  18003. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  18004. #endif
  18005. /*
  18006. ** Each auxiliary data pointer stored by a user defined function
  18007. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  18008. ** of this structure. All such structures associated with a single VM
  18009. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  18010. ** when the VM is halted (if not before).
  18011. */
  18012. struct AuxData {
  18013. int iAuxOp; /* Instruction number of OP_Function opcode */
  18014. int iAuxArg; /* Index of function argument. */
  18015. void *pAux; /* Aux data pointer */
  18016. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  18017. AuxData *pNextAux; /* Next element in list */
  18018. };
  18019. /*
  18020. ** The "context" argument for an installable function. A pointer to an
  18021. ** instance of this structure is the first argument to the routines used
  18022. ** implement the SQL functions.
  18023. **
  18024. ** There is a typedef for this structure in sqlite.h. So all routines,
  18025. ** even the public interface to SQLite, can use a pointer to this structure.
  18026. ** But this file is the only place where the internal details of this
  18027. ** structure are known.
  18028. **
  18029. ** This structure is defined inside of vdbeInt.h because it uses substructures
  18030. ** (Mem) which are only defined there.
  18031. */
  18032. struct sqlite3_context {
  18033. Mem *pOut; /* The return value is stored here */
  18034. FuncDef *pFunc; /* Pointer to function information */
  18035. Mem *pMem; /* Memory cell used to store aggregate context */
  18036. Vdbe *pVdbe; /* The VM that owns this context */
  18037. int iOp; /* Instruction number of OP_Function */
  18038. int isError; /* Error code returned by the function. */
  18039. u8 skipFlag; /* Skip accumulator loading if true */
  18040. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  18041. u8 argc; /* Number of arguments */
  18042. sqlite3_value *argv[1]; /* Argument set */
  18043. };
  18044. /* A bitfield type for use inside of structures. Always follow with :N where
  18045. ** N is the number of bits.
  18046. */
  18047. typedef unsigned bft; /* Bit Field Type */
  18048. typedef struct ScanStatus ScanStatus;
  18049. struct ScanStatus {
  18050. int addrExplain; /* OP_Explain for loop */
  18051. int addrLoop; /* Address of "loops" counter */
  18052. int addrVisit; /* Address of "rows visited" counter */
  18053. int iSelectID; /* The "Select-ID" for this loop */
  18054. LogEst nEst; /* Estimated output rows per loop */
  18055. char *zName; /* Name of table or index */
  18056. };
  18057. /*
  18058. ** An instance of the virtual machine. This structure contains the complete
  18059. ** state of the virtual machine.
  18060. **
  18061. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  18062. ** is really a pointer to an instance of this structure.
  18063. */
  18064. struct Vdbe {
  18065. sqlite3 *db; /* The database connection that owns this statement */
  18066. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  18067. Parse *pParse; /* Parsing context used to create this Vdbe */
  18068. ynVar nVar; /* Number of entries in aVar[] */
  18069. u32 magic; /* Magic number for sanity checking */
  18070. int nMem; /* Number of memory locations currently allocated */
  18071. int nCursor; /* Number of slots in apCsr[] */
  18072. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  18073. int pc; /* The program counter */
  18074. int rc; /* Value to return */
  18075. int nChange; /* Number of db changes made since last reset */
  18076. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  18077. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  18078. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  18079. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  18080. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  18081. /* When allocating a new Vdbe object, all of the fields below should be
  18082. ** initialized to zero or NULL */
  18083. Op *aOp; /* Space to hold the virtual machine's program */
  18084. Mem *aMem; /* The memory locations */
  18085. Mem **apArg; /* Arguments to currently executing user function */
  18086. Mem *aColName; /* Column names to return */
  18087. Mem *pResultSet; /* Pointer to an array of results */
  18088. char *zErrMsg; /* Error message written here */
  18089. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  18090. Mem *aVar; /* Values for the OP_Variable opcode. */
  18091. VList *pVList; /* Name of variables */
  18092. #ifndef SQLITE_OMIT_TRACE
  18093. i64 startTime; /* Time when query started - used for profiling */
  18094. #endif
  18095. int nOp; /* Number of instructions in the program */
  18096. #ifdef SQLITE_DEBUG
  18097. int rcApp; /* errcode set by sqlite3_result_error_code() */
  18098. #endif
  18099. u16 nResColumn; /* Number of columns in one row of the result set */
  18100. u8 errorAction; /* Recovery action to do in case of an error */
  18101. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  18102. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  18103. bft expired:1; /* True if the VM needs to be recompiled */
  18104. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  18105. bft explain:2; /* True if EXPLAIN present on SQL command */
  18106. bft changeCntOn:1; /* True to update the change-counter */
  18107. bft runOnlyOnce:1; /* Automatically expire on reset */
  18108. bft usesStmtJournal:1; /* True if uses a statement journal */
  18109. bft readOnly:1; /* True for statements that do not write */
  18110. bft bIsReader:1; /* True for statements that read */
  18111. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  18112. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  18113. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  18114. char *zSql; /* Text of the SQL statement that generated this */
  18115. void *pFree; /* Free this when deleting the vdbe */
  18116. VdbeFrame *pFrame; /* Parent frame */
  18117. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  18118. int nFrame; /* Number of frames in pFrame list */
  18119. u32 expmask; /* Binding to these vars invalidates VM */
  18120. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  18121. AuxData *pAuxData; /* Linked list of auxdata allocations */
  18122. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  18123. i64 *anExec; /* Number of times each op has been executed */
  18124. int nScan; /* Entries in aScan[] */
  18125. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  18126. #endif
  18127. };
  18128. /*
  18129. ** The following are allowed values for Vdbe.magic
  18130. */
  18131. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  18132. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  18133. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  18134. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  18135. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  18136. /*
  18137. ** Structure used to store the context required by the
  18138. ** sqlite3_preupdate_*() API functions.
  18139. */
  18140. struct PreUpdate {
  18141. Vdbe *v;
  18142. VdbeCursor *pCsr; /* Cursor to read old values from */
  18143. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  18144. u8 *aRecord; /* old.* database record */
  18145. KeyInfo keyinfo;
  18146. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  18147. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  18148. int iNewReg; /* Register for new.* values */
  18149. i64 iKey1; /* First key value passed to hook */
  18150. i64 iKey2; /* Second key value passed to hook */
  18151. Mem *aNew; /* Array of new.* values */
  18152. Table *pTab; /* Schema object being upated */
  18153. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  18154. };
  18155. /*
  18156. ** Function prototypes
  18157. */
  18158. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  18159. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  18160. void sqliteVdbePopStack(Vdbe*,int);
  18161. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  18162. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  18163. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  18164. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  18165. #endif
  18166. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  18167. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  18168. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  18169. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  18170. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  18171. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  18172. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  18173. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  18174. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  18175. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  18176. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  18177. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  18178. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  18179. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  18180. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  18181. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  18182. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  18183. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  18184. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  18185. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  18186. #ifdef SQLITE_OMIT_FLOATING_POINT
  18187. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  18188. #else
  18189. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  18190. #endif
  18191. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  18192. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  18193. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  18194. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  18195. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  18196. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  18197. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  18198. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  18199. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  18200. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  18201. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  18202. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  18203. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  18204. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  18205. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  18206. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  18207. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  18208. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  18209. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  18210. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  18211. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  18212. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  18213. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  18214. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  18215. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  18216. #endif
  18217. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  18218. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  18219. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  18220. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  18221. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  18222. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  18223. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  18224. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  18225. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  18226. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  18227. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  18228. #else
  18229. # define sqlite3VdbeEnter(X)
  18230. #endif
  18231. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  18232. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  18233. #else
  18234. # define sqlite3VdbeLeave(X)
  18235. #endif
  18236. #ifdef SQLITE_DEBUG
  18237. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  18238. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  18239. #endif
  18240. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18241. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  18242. #else
  18243. # define sqlite3VdbeCheckFk(p,i) 0
  18244. #endif
  18245. #ifdef SQLITE_DEBUG
  18246. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  18247. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  18248. #endif
  18249. #ifndef SQLITE_OMIT_UTF16
  18250. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  18251. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  18252. #endif
  18253. #ifndef SQLITE_OMIT_INCRBLOB
  18254. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  18255. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  18256. #else
  18257. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  18258. #define ExpandBlob(P) SQLITE_OK
  18259. #endif
  18260. #endif /* !defined(SQLITE_VDBEINT_H) */
  18261. /************** End of vdbeInt.h *********************************************/
  18262. /************** Continuing where we left off in status.c *********************/
  18263. /*
  18264. ** Variables in which to record status information.
  18265. */
  18266. #if SQLITE_PTRSIZE>4
  18267. typedef sqlite3_int64 sqlite3StatValueType;
  18268. #else
  18269. typedef u32 sqlite3StatValueType;
  18270. #endif
  18271. typedef struct sqlite3StatType sqlite3StatType;
  18272. static SQLITE_WSD struct sqlite3StatType {
  18273. sqlite3StatValueType nowValue[10]; /* Current value */
  18274. sqlite3StatValueType mxValue[10]; /* Maximum value */
  18275. } sqlite3Stat = { {0,}, {0,} };
  18276. /*
  18277. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  18278. ** mutex, or by the pcache1 mutex. The following array determines which.
  18279. */
  18280. static const char statMutex[] = {
  18281. 0, /* SQLITE_STATUS_MEMORY_USED */
  18282. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  18283. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  18284. 0, /* SQLITE_STATUS_SCRATCH_USED */
  18285. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  18286. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  18287. 0, /* SQLITE_STATUS_PARSER_STACK */
  18288. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  18289. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  18290. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  18291. };
  18292. /* The "wsdStat" macro will resolve to the status information
  18293. ** state vector. If writable static data is unsupported on the target,
  18294. ** we have to locate the state vector at run-time. In the more common
  18295. ** case where writable static data is supported, wsdStat can refer directly
  18296. ** to the "sqlite3Stat" state vector declared above.
  18297. */
  18298. #ifdef SQLITE_OMIT_WSD
  18299. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  18300. # define wsdStat x[0]
  18301. #else
  18302. # define wsdStatInit
  18303. # define wsdStat sqlite3Stat
  18304. #endif
  18305. /*
  18306. ** Return the current value of a status parameter. The caller must
  18307. ** be holding the appropriate mutex.
  18308. */
  18309. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  18310. wsdStatInit;
  18311. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18312. assert( op>=0 && op<ArraySize(statMutex) );
  18313. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18314. : sqlite3MallocMutex()) );
  18315. return wsdStat.nowValue[op];
  18316. }
  18317. /*
  18318. ** Add N to the value of a status record. The caller must hold the
  18319. ** appropriate mutex. (Locking is checked by assert()).
  18320. **
  18321. ** The StatusUp() routine can accept positive or negative values for N.
  18322. ** The value of N is added to the current status value and the high-water
  18323. ** mark is adjusted if necessary.
  18324. **
  18325. ** The StatusDown() routine lowers the current value by N. The highwater
  18326. ** mark is unchanged. N must be non-negative for StatusDown().
  18327. */
  18328. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  18329. wsdStatInit;
  18330. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18331. assert( op>=0 && op<ArraySize(statMutex) );
  18332. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18333. : sqlite3MallocMutex()) );
  18334. wsdStat.nowValue[op] += N;
  18335. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  18336. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  18337. }
  18338. }
  18339. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  18340. wsdStatInit;
  18341. assert( N>=0 );
  18342. assert( op>=0 && op<ArraySize(statMutex) );
  18343. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18344. : sqlite3MallocMutex()) );
  18345. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18346. wsdStat.nowValue[op] -= N;
  18347. }
  18348. /*
  18349. ** Adjust the highwater mark if necessary.
  18350. ** The caller must hold the appropriate mutex.
  18351. */
  18352. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  18353. sqlite3StatValueType newValue;
  18354. wsdStatInit;
  18355. assert( X>=0 );
  18356. newValue = (sqlite3StatValueType)X;
  18357. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18358. assert( op>=0 && op<ArraySize(statMutex) );
  18359. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18360. : sqlite3MallocMutex()) );
  18361. assert( op==SQLITE_STATUS_MALLOC_SIZE
  18362. || op==SQLITE_STATUS_PAGECACHE_SIZE
  18363. || op==SQLITE_STATUS_PARSER_STACK );
  18364. if( newValue>wsdStat.mxValue[op] ){
  18365. wsdStat.mxValue[op] = newValue;
  18366. }
  18367. }
  18368. /*
  18369. ** Query status information.
  18370. */
  18371. SQLITE_API int sqlite3_status64(
  18372. int op,
  18373. sqlite3_int64 *pCurrent,
  18374. sqlite3_int64 *pHighwater,
  18375. int resetFlag
  18376. ){
  18377. sqlite3_mutex *pMutex;
  18378. wsdStatInit;
  18379. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  18380. return SQLITE_MISUSE_BKPT;
  18381. }
  18382. #ifdef SQLITE_ENABLE_API_ARMOR
  18383. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  18384. #endif
  18385. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  18386. sqlite3_mutex_enter(pMutex);
  18387. *pCurrent = wsdStat.nowValue[op];
  18388. *pHighwater = wsdStat.mxValue[op];
  18389. if( resetFlag ){
  18390. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  18391. }
  18392. sqlite3_mutex_leave(pMutex);
  18393. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  18394. return SQLITE_OK;
  18395. }
  18396. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  18397. sqlite3_int64 iCur = 0, iHwtr = 0;
  18398. int rc;
  18399. #ifdef SQLITE_ENABLE_API_ARMOR
  18400. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  18401. #endif
  18402. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  18403. if( rc==0 ){
  18404. *pCurrent = (int)iCur;
  18405. *pHighwater = (int)iHwtr;
  18406. }
  18407. return rc;
  18408. }
  18409. /*
  18410. ** Return the number of LookasideSlot elements on the linked list
  18411. */
  18412. static u32 countLookasideSlots(LookasideSlot *p){
  18413. u32 cnt = 0;
  18414. while( p ){
  18415. p = p->pNext;
  18416. cnt++;
  18417. }
  18418. return cnt;
  18419. }
  18420. /*
  18421. ** Count the number of slots of lookaside memory that are outstanding
  18422. */
  18423. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  18424. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  18425. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  18426. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  18427. return db->lookaside.nSlot - (nInit+nFree);
  18428. }
  18429. /*
  18430. ** Query status information for a single database connection
  18431. */
  18432. SQLITE_API int sqlite3_db_status(
  18433. sqlite3 *db, /* The database connection whose status is desired */
  18434. int op, /* Status verb */
  18435. int *pCurrent, /* Write current value here */
  18436. int *pHighwater, /* Write high-water mark here */
  18437. int resetFlag /* Reset high-water mark if true */
  18438. ){
  18439. int rc = SQLITE_OK; /* Return code */
  18440. #ifdef SQLITE_ENABLE_API_ARMOR
  18441. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  18442. return SQLITE_MISUSE_BKPT;
  18443. }
  18444. #endif
  18445. sqlite3_mutex_enter(db->mutex);
  18446. switch( op ){
  18447. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  18448. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  18449. if( resetFlag ){
  18450. LookasideSlot *p = db->lookaside.pFree;
  18451. if( p ){
  18452. while( p->pNext ) p = p->pNext;
  18453. p->pNext = db->lookaside.pInit;
  18454. db->lookaside.pInit = db->lookaside.pFree;
  18455. db->lookaside.pFree = 0;
  18456. }
  18457. }
  18458. break;
  18459. }
  18460. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  18461. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  18462. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  18463. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  18464. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  18465. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  18466. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  18467. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  18468. *pCurrent = 0;
  18469. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  18470. if( resetFlag ){
  18471. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  18472. }
  18473. break;
  18474. }
  18475. /*
  18476. ** Return an approximation for the amount of memory currently used
  18477. ** by all pagers associated with the given database connection. The
  18478. ** highwater mark is meaningless and is returned as zero.
  18479. */
  18480. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  18481. case SQLITE_DBSTATUS_CACHE_USED: {
  18482. int totalUsed = 0;
  18483. int i;
  18484. sqlite3BtreeEnterAll(db);
  18485. for(i=0; i<db->nDb; i++){
  18486. Btree *pBt = db->aDb[i].pBt;
  18487. if( pBt ){
  18488. Pager *pPager = sqlite3BtreePager(pBt);
  18489. int nByte = sqlite3PagerMemUsed(pPager);
  18490. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  18491. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  18492. }
  18493. totalUsed += nByte;
  18494. }
  18495. }
  18496. sqlite3BtreeLeaveAll(db);
  18497. *pCurrent = totalUsed;
  18498. *pHighwater = 0;
  18499. break;
  18500. }
  18501. /*
  18502. ** *pCurrent gets an accurate estimate of the amount of memory used
  18503. ** to store the schema for all databases (main, temp, and any ATTACHed
  18504. ** databases. *pHighwater is set to zero.
  18505. */
  18506. case SQLITE_DBSTATUS_SCHEMA_USED: {
  18507. int i; /* Used to iterate through schemas */
  18508. int nByte = 0; /* Used to accumulate return value */
  18509. sqlite3BtreeEnterAll(db);
  18510. db->pnBytesFreed = &nByte;
  18511. for(i=0; i<db->nDb; i++){
  18512. Schema *pSchema = db->aDb[i].pSchema;
  18513. if( ALWAYS(pSchema!=0) ){
  18514. HashElem *p;
  18515. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  18516. pSchema->tblHash.count
  18517. + pSchema->trigHash.count
  18518. + pSchema->idxHash.count
  18519. + pSchema->fkeyHash.count
  18520. );
  18521. nByte += sqlite3_msize(pSchema->tblHash.ht);
  18522. nByte += sqlite3_msize(pSchema->trigHash.ht);
  18523. nByte += sqlite3_msize(pSchema->idxHash.ht);
  18524. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  18525. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  18526. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  18527. }
  18528. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  18529. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  18530. }
  18531. }
  18532. }
  18533. db->pnBytesFreed = 0;
  18534. sqlite3BtreeLeaveAll(db);
  18535. *pHighwater = 0;
  18536. *pCurrent = nByte;
  18537. break;
  18538. }
  18539. /*
  18540. ** *pCurrent gets an accurate estimate of the amount of memory used
  18541. ** to store all prepared statements.
  18542. ** *pHighwater is set to zero.
  18543. */
  18544. case SQLITE_DBSTATUS_STMT_USED: {
  18545. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  18546. int nByte = 0; /* Used to accumulate return value */
  18547. db->pnBytesFreed = &nByte;
  18548. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  18549. sqlite3VdbeClearObject(db, pVdbe);
  18550. sqlite3DbFree(db, pVdbe);
  18551. }
  18552. db->pnBytesFreed = 0;
  18553. *pHighwater = 0; /* IMP: R-64479-57858 */
  18554. *pCurrent = nByte;
  18555. break;
  18556. }
  18557. /*
  18558. ** Set *pCurrent to the total cache hits or misses encountered by all
  18559. ** pagers the database handle is connected to. *pHighwater is always set
  18560. ** to zero.
  18561. */
  18562. case SQLITE_DBSTATUS_CACHE_HIT:
  18563. case SQLITE_DBSTATUS_CACHE_MISS:
  18564. case SQLITE_DBSTATUS_CACHE_WRITE:{
  18565. int i;
  18566. int nRet = 0;
  18567. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  18568. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  18569. for(i=0; i<db->nDb; i++){
  18570. if( db->aDb[i].pBt ){
  18571. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  18572. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  18573. }
  18574. }
  18575. *pHighwater = 0; /* IMP: R-42420-56072 */
  18576. /* IMP: R-54100-20147 */
  18577. /* IMP: R-29431-39229 */
  18578. *pCurrent = nRet;
  18579. break;
  18580. }
  18581. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  18582. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  18583. ** have been satisfied. The *pHighwater is always set to zero.
  18584. */
  18585. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  18586. *pHighwater = 0; /* IMP: R-11967-56545 */
  18587. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  18588. break;
  18589. }
  18590. default: {
  18591. rc = SQLITE_ERROR;
  18592. }
  18593. }
  18594. sqlite3_mutex_leave(db->mutex);
  18595. return rc;
  18596. }
  18597. /************** End of status.c **********************************************/
  18598. /************** Begin file date.c ********************************************/
  18599. /*
  18600. ** 2003 October 31
  18601. **
  18602. ** The author disclaims copyright to this source code. In place of
  18603. ** a legal notice, here is a blessing:
  18604. **
  18605. ** May you do good and not evil.
  18606. ** May you find forgiveness for yourself and forgive others.
  18607. ** May you share freely, never taking more than you give.
  18608. **
  18609. *************************************************************************
  18610. ** This file contains the C functions that implement date and time
  18611. ** functions for SQLite.
  18612. **
  18613. ** There is only one exported symbol in this file - the function
  18614. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  18615. ** All other code has file scope.
  18616. **
  18617. ** SQLite processes all times and dates as julian day numbers. The
  18618. ** dates and times are stored as the number of days since noon
  18619. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  18620. ** calendar system.
  18621. **
  18622. ** 1970-01-01 00:00:00 is JD 2440587.5
  18623. ** 2000-01-01 00:00:00 is JD 2451544.5
  18624. **
  18625. ** This implementation requires years to be expressed as a 4-digit number
  18626. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  18627. ** be represented, even though julian day numbers allow a much wider
  18628. ** range of dates.
  18629. **
  18630. ** The Gregorian calendar system is used for all dates and times,
  18631. ** even those that predate the Gregorian calendar. Historians usually
  18632. ** use the julian calendar for dates prior to 1582-10-15 and for some
  18633. ** dates afterwards, depending on locale. Beware of this difference.
  18634. **
  18635. ** The conversion algorithms are implemented based on descriptions
  18636. ** in the following text:
  18637. **
  18638. ** Jean Meeus
  18639. ** Astronomical Algorithms, 2nd Edition, 1998
  18640. ** ISBM 0-943396-61-1
  18641. ** Willmann-Bell, Inc
  18642. ** Richmond, Virginia (USA)
  18643. */
  18644. /* #include "sqliteInt.h" */
  18645. /* #include <stdlib.h> */
  18646. /* #include <assert.h> */
  18647. #include <time.h>
  18648. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  18649. /*
  18650. ** The MSVC CRT on Windows CE may not have a localtime() function.
  18651. ** So declare a substitute. The substitute function itself is
  18652. ** defined in "os_win.c".
  18653. */
  18654. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  18655. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  18656. struct tm *__cdecl localtime(const time_t *);
  18657. #endif
  18658. /*
  18659. ** A structure for holding a single date and time.
  18660. */
  18661. typedef struct DateTime DateTime;
  18662. struct DateTime {
  18663. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  18664. int Y, M, D; /* Year, month, and day */
  18665. int h, m; /* Hour and minutes */
  18666. int tz; /* Timezone offset in minutes */
  18667. double s; /* Seconds */
  18668. char validJD; /* True (1) if iJD is valid */
  18669. char rawS; /* Raw numeric value stored in s */
  18670. char validYMD; /* True (1) if Y,M,D are valid */
  18671. char validHMS; /* True (1) if h,m,s are valid */
  18672. char validTZ; /* True (1) if tz is valid */
  18673. char tzSet; /* Timezone was set explicitly */
  18674. char isError; /* An overflow has occurred */
  18675. };
  18676. /*
  18677. ** Convert zDate into one or more integers according to the conversion
  18678. ** specifier zFormat.
  18679. **
  18680. ** zFormat[] contains 4 characters for each integer converted, except for
  18681. ** the last integer which is specified by three characters. The meaning
  18682. ** of a four-character format specifiers ABCD is:
  18683. **
  18684. ** A: number of digits to convert. Always "2" or "4".
  18685. ** B: minimum value. Always "0" or "1".
  18686. ** C: maximum value, decoded as:
  18687. ** a: 12
  18688. ** b: 14
  18689. ** c: 24
  18690. ** d: 31
  18691. ** e: 59
  18692. ** f: 9999
  18693. ** D: the separator character, or \000 to indicate this is the
  18694. ** last number to convert.
  18695. **
  18696. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  18697. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  18698. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  18699. ** the 2-digit day which is the last integer in the set.
  18700. **
  18701. ** The function returns the number of successful conversions.
  18702. */
  18703. static int getDigits(const char *zDate, const char *zFormat, ...){
  18704. /* The aMx[] array translates the 3rd character of each format
  18705. ** spec into a max size: a b c d e f */
  18706. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  18707. va_list ap;
  18708. int cnt = 0;
  18709. char nextC;
  18710. va_start(ap, zFormat);
  18711. do{
  18712. char N = zFormat[0] - '0';
  18713. char min = zFormat[1] - '0';
  18714. int val = 0;
  18715. u16 max;
  18716. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  18717. max = aMx[zFormat[2] - 'a'];
  18718. nextC = zFormat[3];
  18719. val = 0;
  18720. while( N-- ){
  18721. if( !sqlite3Isdigit(*zDate) ){
  18722. goto end_getDigits;
  18723. }
  18724. val = val*10 + *zDate - '0';
  18725. zDate++;
  18726. }
  18727. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  18728. goto end_getDigits;
  18729. }
  18730. *va_arg(ap,int*) = val;
  18731. zDate++;
  18732. cnt++;
  18733. zFormat += 4;
  18734. }while( nextC );
  18735. end_getDigits:
  18736. va_end(ap);
  18737. return cnt;
  18738. }
  18739. /*
  18740. ** Parse a timezone extension on the end of a date-time.
  18741. ** The extension is of the form:
  18742. **
  18743. ** (+/-)HH:MM
  18744. **
  18745. ** Or the "zulu" notation:
  18746. **
  18747. ** Z
  18748. **
  18749. ** If the parse is successful, write the number of minutes
  18750. ** of change in p->tz and return 0. If a parser error occurs,
  18751. ** return non-zero.
  18752. **
  18753. ** A missing specifier is not considered an error.
  18754. */
  18755. static int parseTimezone(const char *zDate, DateTime *p){
  18756. int sgn = 0;
  18757. int nHr, nMn;
  18758. int c;
  18759. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18760. p->tz = 0;
  18761. c = *zDate;
  18762. if( c=='-' ){
  18763. sgn = -1;
  18764. }else if( c=='+' ){
  18765. sgn = +1;
  18766. }else if( c=='Z' || c=='z' ){
  18767. zDate++;
  18768. goto zulu_time;
  18769. }else{
  18770. return c!=0;
  18771. }
  18772. zDate++;
  18773. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  18774. return 1;
  18775. }
  18776. zDate += 5;
  18777. p->tz = sgn*(nMn + nHr*60);
  18778. zulu_time:
  18779. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18780. p->tzSet = 1;
  18781. return *zDate!=0;
  18782. }
  18783. /*
  18784. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  18785. ** The HH, MM, and SS must each be exactly 2 digits. The
  18786. ** fractional seconds FFFF can be one or more digits.
  18787. **
  18788. ** Return 1 if there is a parsing error and 0 on success.
  18789. */
  18790. static int parseHhMmSs(const char *zDate, DateTime *p){
  18791. int h, m, s;
  18792. double ms = 0.0;
  18793. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  18794. return 1;
  18795. }
  18796. zDate += 5;
  18797. if( *zDate==':' ){
  18798. zDate++;
  18799. if( getDigits(zDate, "20e", &s)!=1 ){
  18800. return 1;
  18801. }
  18802. zDate += 2;
  18803. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  18804. double rScale = 1.0;
  18805. zDate++;
  18806. while( sqlite3Isdigit(*zDate) ){
  18807. ms = ms*10.0 + *zDate - '0';
  18808. rScale *= 10.0;
  18809. zDate++;
  18810. }
  18811. ms /= rScale;
  18812. }
  18813. }else{
  18814. s = 0;
  18815. }
  18816. p->validJD = 0;
  18817. p->rawS = 0;
  18818. p->validHMS = 1;
  18819. p->h = h;
  18820. p->m = m;
  18821. p->s = s + ms;
  18822. if( parseTimezone(zDate, p) ) return 1;
  18823. p->validTZ = (p->tz!=0)?1:0;
  18824. return 0;
  18825. }
  18826. /*
  18827. ** Put the DateTime object into its error state.
  18828. */
  18829. static void datetimeError(DateTime *p){
  18830. memset(p, 0, sizeof(*p));
  18831. p->isError = 1;
  18832. }
  18833. /*
  18834. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  18835. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  18836. **
  18837. ** Reference: Meeus page 61
  18838. */
  18839. static void computeJD(DateTime *p){
  18840. int Y, M, D, A, B, X1, X2;
  18841. if( p->validJD ) return;
  18842. if( p->validYMD ){
  18843. Y = p->Y;
  18844. M = p->M;
  18845. D = p->D;
  18846. }else{
  18847. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  18848. M = 1;
  18849. D = 1;
  18850. }
  18851. if( Y<-4713 || Y>9999 || p->rawS ){
  18852. datetimeError(p);
  18853. return;
  18854. }
  18855. if( M<=2 ){
  18856. Y--;
  18857. M += 12;
  18858. }
  18859. A = Y/100;
  18860. B = 2 - A + (A/4);
  18861. X1 = 36525*(Y+4716)/100;
  18862. X2 = 306001*(M+1)/10000;
  18863. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  18864. p->validJD = 1;
  18865. if( p->validHMS ){
  18866. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  18867. if( p->validTZ ){
  18868. p->iJD -= p->tz*60000;
  18869. p->validYMD = 0;
  18870. p->validHMS = 0;
  18871. p->validTZ = 0;
  18872. }
  18873. }
  18874. }
  18875. /*
  18876. ** Parse dates of the form
  18877. **
  18878. ** YYYY-MM-DD HH:MM:SS.FFF
  18879. ** YYYY-MM-DD HH:MM:SS
  18880. ** YYYY-MM-DD HH:MM
  18881. ** YYYY-MM-DD
  18882. **
  18883. ** Write the result into the DateTime structure and return 0
  18884. ** on success and 1 if the input string is not a well-formed
  18885. ** date.
  18886. */
  18887. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  18888. int Y, M, D, neg;
  18889. if( zDate[0]=='-' ){
  18890. zDate++;
  18891. neg = 1;
  18892. }else{
  18893. neg = 0;
  18894. }
  18895. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  18896. return 1;
  18897. }
  18898. zDate += 10;
  18899. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  18900. if( parseHhMmSs(zDate, p)==0 ){
  18901. /* We got the time */
  18902. }else if( *zDate==0 ){
  18903. p->validHMS = 0;
  18904. }else{
  18905. return 1;
  18906. }
  18907. p->validJD = 0;
  18908. p->validYMD = 1;
  18909. p->Y = neg ? -Y : Y;
  18910. p->M = M;
  18911. p->D = D;
  18912. if( p->validTZ ){
  18913. computeJD(p);
  18914. }
  18915. return 0;
  18916. }
  18917. /*
  18918. ** Set the time to the current time reported by the VFS.
  18919. **
  18920. ** Return the number of errors.
  18921. */
  18922. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  18923. p->iJD = sqlite3StmtCurrentTime(context);
  18924. if( p->iJD>0 ){
  18925. p->validJD = 1;
  18926. return 0;
  18927. }else{
  18928. return 1;
  18929. }
  18930. }
  18931. /*
  18932. ** Input "r" is a numeric quantity which might be a julian day number,
  18933. ** or the number of seconds since 1970. If the value if r is within
  18934. ** range of a julian day number, install it as such and set validJD.
  18935. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  18936. */
  18937. static void setRawDateNumber(DateTime *p, double r){
  18938. p->s = r;
  18939. p->rawS = 1;
  18940. if( r>=0.0 && r<5373484.5 ){
  18941. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  18942. p->validJD = 1;
  18943. }
  18944. }
  18945. /*
  18946. ** Attempt to parse the given string into a julian day number. Return
  18947. ** the number of errors.
  18948. **
  18949. ** The following are acceptable forms for the input string:
  18950. **
  18951. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  18952. ** DDDD.DD
  18953. ** now
  18954. **
  18955. ** In the first form, the +/-HH:MM is always optional. The fractional
  18956. ** seconds extension (the ".FFF") is optional. The seconds portion
  18957. ** (":SS.FFF") is option. The year and date can be omitted as long
  18958. ** as there is a time string. The time string can be omitted as long
  18959. ** as there is a year and date.
  18960. */
  18961. static int parseDateOrTime(
  18962. sqlite3_context *context,
  18963. const char *zDate,
  18964. DateTime *p
  18965. ){
  18966. double r;
  18967. if( parseYyyyMmDd(zDate,p)==0 ){
  18968. return 0;
  18969. }else if( parseHhMmSs(zDate, p)==0 ){
  18970. return 0;
  18971. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  18972. return setDateTimeToCurrent(context, p);
  18973. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  18974. setRawDateNumber(p, r);
  18975. return 0;
  18976. }
  18977. return 1;
  18978. }
  18979. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  18980. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  18981. ** for DateTime.iJD.
  18982. **
  18983. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  18984. ** such a large integer literal, so we have to encode it.
  18985. */
  18986. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  18987. /*
  18988. ** Return TRUE if the given julian day number is within range.
  18989. **
  18990. ** The input is the JulianDay times 86400000.
  18991. */
  18992. static int validJulianDay(sqlite3_int64 iJD){
  18993. return iJD>=0 && iJD<=INT_464269060799999;
  18994. }
  18995. /*
  18996. ** Compute the Year, Month, and Day from the julian day number.
  18997. */
  18998. static void computeYMD(DateTime *p){
  18999. int Z, A, B, C, D, E, X1;
  19000. if( p->validYMD ) return;
  19001. if( !p->validJD ){
  19002. p->Y = 2000;
  19003. p->M = 1;
  19004. p->D = 1;
  19005. }else if( !validJulianDay(p->iJD) ){
  19006. datetimeError(p);
  19007. return;
  19008. }else{
  19009. Z = (int)((p->iJD + 43200000)/86400000);
  19010. A = (int)((Z - 1867216.25)/36524.25);
  19011. A = Z + 1 + A - (A/4);
  19012. B = A + 1524;
  19013. C = (int)((B - 122.1)/365.25);
  19014. D = (36525*(C&32767))/100;
  19015. E = (int)((B-D)/30.6001);
  19016. X1 = (int)(30.6001*E);
  19017. p->D = B - D - X1;
  19018. p->M = E<14 ? E-1 : E-13;
  19019. p->Y = p->M>2 ? C - 4716 : C - 4715;
  19020. }
  19021. p->validYMD = 1;
  19022. }
  19023. /*
  19024. ** Compute the Hour, Minute, and Seconds from the julian day number.
  19025. */
  19026. static void computeHMS(DateTime *p){
  19027. int s;
  19028. if( p->validHMS ) return;
  19029. computeJD(p);
  19030. s = (int)((p->iJD + 43200000) % 86400000);
  19031. p->s = s/1000.0;
  19032. s = (int)p->s;
  19033. p->s -= s;
  19034. p->h = s/3600;
  19035. s -= p->h*3600;
  19036. p->m = s/60;
  19037. p->s += s - p->m*60;
  19038. p->rawS = 0;
  19039. p->validHMS = 1;
  19040. }
  19041. /*
  19042. ** Compute both YMD and HMS
  19043. */
  19044. static void computeYMD_HMS(DateTime *p){
  19045. computeYMD(p);
  19046. computeHMS(p);
  19047. }
  19048. /*
  19049. ** Clear the YMD and HMS and the TZ
  19050. */
  19051. static void clearYMD_HMS_TZ(DateTime *p){
  19052. p->validYMD = 0;
  19053. p->validHMS = 0;
  19054. p->validTZ = 0;
  19055. }
  19056. #ifndef SQLITE_OMIT_LOCALTIME
  19057. /*
  19058. ** On recent Windows platforms, the localtime_s() function is available
  19059. ** as part of the "Secure CRT". It is essentially equivalent to
  19060. ** localtime_r() available under most POSIX platforms, except that the
  19061. ** order of the parameters is reversed.
  19062. **
  19063. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  19064. **
  19065. ** If the user has not indicated to use localtime_r() or localtime_s()
  19066. ** already, check for an MSVC build environment that provides
  19067. ** localtime_s().
  19068. */
  19069. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  19070. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  19071. #undef HAVE_LOCALTIME_S
  19072. #define HAVE_LOCALTIME_S 1
  19073. #endif
  19074. /*
  19075. ** The following routine implements the rough equivalent of localtime_r()
  19076. ** using whatever operating-system specific localtime facility that
  19077. ** is available. This routine returns 0 on success and
  19078. ** non-zero on any kind of error.
  19079. **
  19080. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  19081. ** routine will always fail.
  19082. **
  19083. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  19084. ** library function localtime_r() is used to assist in the calculation of
  19085. ** local time.
  19086. */
  19087. static int osLocaltime(time_t *t, struct tm *pTm){
  19088. int rc;
  19089. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  19090. struct tm *pX;
  19091. #if SQLITE_THREADSAFE>0
  19092. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19093. #endif
  19094. sqlite3_mutex_enter(mutex);
  19095. pX = localtime(t);
  19096. #ifndef SQLITE_UNTESTABLE
  19097. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  19098. #endif
  19099. if( pX ) *pTm = *pX;
  19100. sqlite3_mutex_leave(mutex);
  19101. rc = pX==0;
  19102. #else
  19103. #ifndef SQLITE_UNTESTABLE
  19104. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  19105. #endif
  19106. #if HAVE_LOCALTIME_R
  19107. rc = localtime_r(t, pTm)==0;
  19108. #else
  19109. rc = localtime_s(pTm, t);
  19110. #endif /* HAVE_LOCALTIME_R */
  19111. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  19112. return rc;
  19113. }
  19114. #endif /* SQLITE_OMIT_LOCALTIME */
  19115. #ifndef SQLITE_OMIT_LOCALTIME
  19116. /*
  19117. ** Compute the difference (in milliseconds) between localtime and UTC
  19118. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  19119. ** return this value and set *pRc to SQLITE_OK.
  19120. **
  19121. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  19122. ** is undefined in this case.
  19123. */
  19124. static sqlite3_int64 localtimeOffset(
  19125. DateTime *p, /* Date at which to calculate offset */
  19126. sqlite3_context *pCtx, /* Write error here if one occurs */
  19127. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  19128. ){
  19129. DateTime x, y;
  19130. time_t t;
  19131. struct tm sLocal;
  19132. /* Initialize the contents of sLocal to avoid a compiler warning. */
  19133. memset(&sLocal, 0, sizeof(sLocal));
  19134. x = *p;
  19135. computeYMD_HMS(&x);
  19136. if( x.Y<1971 || x.Y>=2038 ){
  19137. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  19138. ** works for years between 1970 and 2037. For dates outside this range,
  19139. ** SQLite attempts to map the year into an equivalent year within this
  19140. ** range, do the calculation, then map the year back.
  19141. */
  19142. x.Y = 2000;
  19143. x.M = 1;
  19144. x.D = 1;
  19145. x.h = 0;
  19146. x.m = 0;
  19147. x.s = 0.0;
  19148. } else {
  19149. int s = (int)(x.s + 0.5);
  19150. x.s = s;
  19151. }
  19152. x.tz = 0;
  19153. x.validJD = 0;
  19154. computeJD(&x);
  19155. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  19156. if( osLocaltime(&t, &sLocal) ){
  19157. sqlite3_result_error(pCtx, "local time unavailable", -1);
  19158. *pRc = SQLITE_ERROR;
  19159. return 0;
  19160. }
  19161. y.Y = sLocal.tm_year + 1900;
  19162. y.M = sLocal.tm_mon + 1;
  19163. y.D = sLocal.tm_mday;
  19164. y.h = sLocal.tm_hour;
  19165. y.m = sLocal.tm_min;
  19166. y.s = sLocal.tm_sec;
  19167. y.validYMD = 1;
  19168. y.validHMS = 1;
  19169. y.validJD = 0;
  19170. y.rawS = 0;
  19171. y.validTZ = 0;
  19172. y.isError = 0;
  19173. computeJD(&y);
  19174. *pRc = SQLITE_OK;
  19175. return y.iJD - x.iJD;
  19176. }
  19177. #endif /* SQLITE_OMIT_LOCALTIME */
  19178. /*
  19179. ** The following table defines various date transformations of the form
  19180. **
  19181. ** 'NNN days'
  19182. **
  19183. ** Where NNN is an arbitrary floating-point number and "days" can be one
  19184. ** of several units of time.
  19185. */
  19186. static const struct {
  19187. u8 eType; /* Transformation type code */
  19188. u8 nName; /* Length of th name */
  19189. char *zName; /* Name of the transformation */
  19190. double rLimit; /* Maximum NNN value for this transform */
  19191. double rXform; /* Constant used for this transform */
  19192. } aXformType[] = {
  19193. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  19194. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  19195. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  19196. { 0, 3, "day", 5373485.0, 86400000.0 },
  19197. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  19198. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  19199. };
  19200. /*
  19201. ** Process a modifier to a date-time stamp. The modifiers are
  19202. ** as follows:
  19203. **
  19204. ** NNN days
  19205. ** NNN hours
  19206. ** NNN minutes
  19207. ** NNN.NNNN seconds
  19208. ** NNN months
  19209. ** NNN years
  19210. ** start of month
  19211. ** start of year
  19212. ** start of week
  19213. ** start of day
  19214. ** weekday N
  19215. ** unixepoch
  19216. ** localtime
  19217. ** utc
  19218. **
  19219. ** Return 0 on success and 1 if there is any kind of error. If the error
  19220. ** is in a system call (i.e. localtime()), then an error message is written
  19221. ** to context pCtx. If the error is an unrecognized modifier, no error is
  19222. ** written to pCtx.
  19223. */
  19224. static int parseModifier(
  19225. sqlite3_context *pCtx, /* Function context */
  19226. const char *z, /* The text of the modifier */
  19227. int n, /* Length of zMod in bytes */
  19228. DateTime *p /* The date/time value to be modified */
  19229. ){
  19230. int rc = 1;
  19231. double r;
  19232. switch(sqlite3UpperToLower[(u8)z[0]] ){
  19233. #ifndef SQLITE_OMIT_LOCALTIME
  19234. case 'l': {
  19235. /* localtime
  19236. **
  19237. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  19238. ** show local time.
  19239. */
  19240. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  19241. computeJD(p);
  19242. p->iJD += localtimeOffset(p, pCtx, &rc);
  19243. clearYMD_HMS_TZ(p);
  19244. }
  19245. break;
  19246. }
  19247. #endif
  19248. case 'u': {
  19249. /*
  19250. ** unixepoch
  19251. **
  19252. ** Treat the current value of p->s as the number of
  19253. ** seconds since 1970. Convert to a real julian day number.
  19254. */
  19255. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  19256. r = p->s*1000.0 + 210866760000000.0;
  19257. if( r>=0.0 && r<464269060800000.0 ){
  19258. clearYMD_HMS_TZ(p);
  19259. p->iJD = (sqlite3_int64)r;
  19260. p->validJD = 1;
  19261. p->rawS = 0;
  19262. rc = 0;
  19263. }
  19264. }
  19265. #ifndef SQLITE_OMIT_LOCALTIME
  19266. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  19267. if( p->tzSet==0 ){
  19268. sqlite3_int64 c1;
  19269. computeJD(p);
  19270. c1 = localtimeOffset(p, pCtx, &rc);
  19271. if( rc==SQLITE_OK ){
  19272. p->iJD -= c1;
  19273. clearYMD_HMS_TZ(p);
  19274. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  19275. }
  19276. p->tzSet = 1;
  19277. }else{
  19278. rc = SQLITE_OK;
  19279. }
  19280. }
  19281. #endif
  19282. break;
  19283. }
  19284. case 'w': {
  19285. /*
  19286. ** weekday N
  19287. **
  19288. ** Move the date to the same time on the next occurrence of
  19289. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  19290. ** date is already on the appropriate weekday, this is a no-op.
  19291. */
  19292. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  19293. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  19294. && (n=(int)r)==r && n>=0 && r<7 ){
  19295. sqlite3_int64 Z;
  19296. computeYMD_HMS(p);
  19297. p->validTZ = 0;
  19298. p->validJD = 0;
  19299. computeJD(p);
  19300. Z = ((p->iJD + 129600000)/86400000) % 7;
  19301. if( Z>n ) Z -= 7;
  19302. p->iJD += (n - Z)*86400000;
  19303. clearYMD_HMS_TZ(p);
  19304. rc = 0;
  19305. }
  19306. break;
  19307. }
  19308. case 's': {
  19309. /*
  19310. ** start of TTTTT
  19311. **
  19312. ** Move the date backwards to the beginning of the current day,
  19313. ** or month or year.
  19314. */
  19315. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  19316. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  19317. z += 9;
  19318. computeYMD(p);
  19319. p->validHMS = 1;
  19320. p->h = p->m = 0;
  19321. p->s = 0.0;
  19322. p->rawS = 0;
  19323. p->validTZ = 0;
  19324. p->validJD = 0;
  19325. if( sqlite3_stricmp(z,"month")==0 ){
  19326. p->D = 1;
  19327. rc = 0;
  19328. }else if( sqlite3_stricmp(z,"year")==0 ){
  19329. p->M = 1;
  19330. p->D = 1;
  19331. rc = 0;
  19332. }else if( sqlite3_stricmp(z,"day")==0 ){
  19333. rc = 0;
  19334. }
  19335. break;
  19336. }
  19337. case '+':
  19338. case '-':
  19339. case '0':
  19340. case '1':
  19341. case '2':
  19342. case '3':
  19343. case '4':
  19344. case '5':
  19345. case '6':
  19346. case '7':
  19347. case '8':
  19348. case '9': {
  19349. double rRounder;
  19350. int i;
  19351. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  19352. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  19353. rc = 1;
  19354. break;
  19355. }
  19356. if( z[n]==':' ){
  19357. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  19358. ** specified number of hours, minutes, seconds, and fractional seconds
  19359. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  19360. ** omitted.
  19361. */
  19362. const char *z2 = z;
  19363. DateTime tx;
  19364. sqlite3_int64 day;
  19365. if( !sqlite3Isdigit(*z2) ) z2++;
  19366. memset(&tx, 0, sizeof(tx));
  19367. if( parseHhMmSs(z2, &tx) ) break;
  19368. computeJD(&tx);
  19369. tx.iJD -= 43200000;
  19370. day = tx.iJD/86400000;
  19371. tx.iJD -= day*86400000;
  19372. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  19373. computeJD(p);
  19374. clearYMD_HMS_TZ(p);
  19375. p->iJD += tx.iJD;
  19376. rc = 0;
  19377. break;
  19378. }
  19379. /* If control reaches this point, it means the transformation is
  19380. ** one of the forms like "+NNN days". */
  19381. z += n;
  19382. while( sqlite3Isspace(*z) ) z++;
  19383. n = sqlite3Strlen30(z);
  19384. if( n>10 || n<3 ) break;
  19385. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  19386. computeJD(p);
  19387. rc = 1;
  19388. rRounder = r<0 ? -0.5 : +0.5;
  19389. for(i=0; i<ArraySize(aXformType); i++){
  19390. if( aXformType[i].nName==n
  19391. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  19392. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  19393. ){
  19394. switch( aXformType[i].eType ){
  19395. case 1: { /* Special processing to add months */
  19396. int x;
  19397. computeYMD_HMS(p);
  19398. p->M += (int)r;
  19399. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  19400. p->Y += x;
  19401. p->M -= x*12;
  19402. p->validJD = 0;
  19403. r -= (int)r;
  19404. break;
  19405. }
  19406. case 2: { /* Special processing to add years */
  19407. int y = (int)r;
  19408. computeYMD_HMS(p);
  19409. p->Y += y;
  19410. p->validJD = 0;
  19411. r -= (int)r;
  19412. break;
  19413. }
  19414. }
  19415. computeJD(p);
  19416. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  19417. rc = 0;
  19418. break;
  19419. }
  19420. }
  19421. clearYMD_HMS_TZ(p);
  19422. break;
  19423. }
  19424. default: {
  19425. break;
  19426. }
  19427. }
  19428. return rc;
  19429. }
  19430. /*
  19431. ** Process time function arguments. argv[0] is a date-time stamp.
  19432. ** argv[1] and following are modifiers. Parse them all and write
  19433. ** the resulting time into the DateTime structure p. Return 0
  19434. ** on success and 1 if there are any errors.
  19435. **
  19436. ** If there are zero parameters (if even argv[0] is undefined)
  19437. ** then assume a default value of "now" for argv[0].
  19438. */
  19439. static int isDate(
  19440. sqlite3_context *context,
  19441. int argc,
  19442. sqlite3_value **argv,
  19443. DateTime *p
  19444. ){
  19445. int i, n;
  19446. const unsigned char *z;
  19447. int eType;
  19448. memset(p, 0, sizeof(*p));
  19449. if( argc==0 ){
  19450. return setDateTimeToCurrent(context, p);
  19451. }
  19452. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  19453. || eType==SQLITE_INTEGER ){
  19454. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  19455. }else{
  19456. z = sqlite3_value_text(argv[0]);
  19457. if( !z || parseDateOrTime(context, (char*)z, p) ){
  19458. return 1;
  19459. }
  19460. }
  19461. for(i=1; i<argc; i++){
  19462. z = sqlite3_value_text(argv[i]);
  19463. n = sqlite3_value_bytes(argv[i]);
  19464. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  19465. }
  19466. computeJD(p);
  19467. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  19468. return 0;
  19469. }
  19470. /*
  19471. ** The following routines implement the various date and time functions
  19472. ** of SQLite.
  19473. */
  19474. /*
  19475. ** julianday( TIMESTRING, MOD, MOD, ...)
  19476. **
  19477. ** Return the julian day number of the date specified in the arguments
  19478. */
  19479. static void juliandayFunc(
  19480. sqlite3_context *context,
  19481. int argc,
  19482. sqlite3_value **argv
  19483. ){
  19484. DateTime x;
  19485. if( isDate(context, argc, argv, &x)==0 ){
  19486. computeJD(&x);
  19487. sqlite3_result_double(context, x.iJD/86400000.0);
  19488. }
  19489. }
  19490. /*
  19491. ** datetime( TIMESTRING, MOD, MOD, ...)
  19492. **
  19493. ** Return YYYY-MM-DD HH:MM:SS
  19494. */
  19495. static void datetimeFunc(
  19496. sqlite3_context *context,
  19497. int argc,
  19498. sqlite3_value **argv
  19499. ){
  19500. DateTime x;
  19501. if( isDate(context, argc, argv, &x)==0 ){
  19502. char zBuf[100];
  19503. computeYMD_HMS(&x);
  19504. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  19505. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  19506. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19507. }
  19508. }
  19509. /*
  19510. ** time( TIMESTRING, MOD, MOD, ...)
  19511. **
  19512. ** Return HH:MM:SS
  19513. */
  19514. static void timeFunc(
  19515. sqlite3_context *context,
  19516. int argc,
  19517. sqlite3_value **argv
  19518. ){
  19519. DateTime x;
  19520. if( isDate(context, argc, argv, &x)==0 ){
  19521. char zBuf[100];
  19522. computeHMS(&x);
  19523. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  19524. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19525. }
  19526. }
  19527. /*
  19528. ** date( TIMESTRING, MOD, MOD, ...)
  19529. **
  19530. ** Return YYYY-MM-DD
  19531. */
  19532. static void dateFunc(
  19533. sqlite3_context *context,
  19534. int argc,
  19535. sqlite3_value **argv
  19536. ){
  19537. DateTime x;
  19538. if( isDate(context, argc, argv, &x)==0 ){
  19539. char zBuf[100];
  19540. computeYMD(&x);
  19541. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  19542. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19543. }
  19544. }
  19545. /*
  19546. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  19547. **
  19548. ** Return a string described by FORMAT. Conversions as follows:
  19549. **
  19550. ** %d day of month
  19551. ** %f ** fractional seconds SS.SSS
  19552. ** %H hour 00-24
  19553. ** %j day of year 000-366
  19554. ** %J ** julian day number
  19555. ** %m month 01-12
  19556. ** %M minute 00-59
  19557. ** %s seconds since 1970-01-01
  19558. ** %S seconds 00-59
  19559. ** %w day of week 0-6 sunday==0
  19560. ** %W week of year 00-53
  19561. ** %Y year 0000-9999
  19562. ** %% %
  19563. */
  19564. static void strftimeFunc(
  19565. sqlite3_context *context,
  19566. int argc,
  19567. sqlite3_value **argv
  19568. ){
  19569. DateTime x;
  19570. u64 n;
  19571. size_t i,j;
  19572. char *z;
  19573. sqlite3 *db;
  19574. const char *zFmt;
  19575. char zBuf[100];
  19576. if( argc==0 ) return;
  19577. zFmt = (const char*)sqlite3_value_text(argv[0]);
  19578. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  19579. db = sqlite3_context_db_handle(context);
  19580. for(i=0, n=1; zFmt[i]; i++, n++){
  19581. if( zFmt[i]=='%' ){
  19582. switch( zFmt[i+1] ){
  19583. case 'd':
  19584. case 'H':
  19585. case 'm':
  19586. case 'M':
  19587. case 'S':
  19588. case 'W':
  19589. n++;
  19590. /* fall thru */
  19591. case 'w':
  19592. case '%':
  19593. break;
  19594. case 'f':
  19595. n += 8;
  19596. break;
  19597. case 'j':
  19598. n += 3;
  19599. break;
  19600. case 'Y':
  19601. n += 8;
  19602. break;
  19603. case 's':
  19604. case 'J':
  19605. n += 50;
  19606. break;
  19607. default:
  19608. return; /* ERROR. return a NULL */
  19609. }
  19610. i++;
  19611. }
  19612. }
  19613. testcase( n==sizeof(zBuf)-1 );
  19614. testcase( n==sizeof(zBuf) );
  19615. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  19616. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  19617. if( n<sizeof(zBuf) ){
  19618. z = zBuf;
  19619. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  19620. sqlite3_result_error_toobig(context);
  19621. return;
  19622. }else{
  19623. z = sqlite3DbMallocRawNN(db, (int)n);
  19624. if( z==0 ){
  19625. sqlite3_result_error_nomem(context);
  19626. return;
  19627. }
  19628. }
  19629. computeJD(&x);
  19630. computeYMD_HMS(&x);
  19631. for(i=j=0; zFmt[i]; i++){
  19632. if( zFmt[i]!='%' ){
  19633. z[j++] = zFmt[i];
  19634. }else{
  19635. i++;
  19636. switch( zFmt[i] ){
  19637. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  19638. case 'f': {
  19639. double s = x.s;
  19640. if( s>59.999 ) s = 59.999;
  19641. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  19642. j += sqlite3Strlen30(&z[j]);
  19643. break;
  19644. }
  19645. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  19646. case 'W': /* Fall thru */
  19647. case 'j': {
  19648. int nDay; /* Number of days since 1st day of year */
  19649. DateTime y = x;
  19650. y.validJD = 0;
  19651. y.M = 1;
  19652. y.D = 1;
  19653. computeJD(&y);
  19654. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  19655. if( zFmt[i]=='W' ){
  19656. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  19657. wd = (int)(((x.iJD+43200000)/86400000)%7);
  19658. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  19659. j += 2;
  19660. }else{
  19661. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  19662. j += 3;
  19663. }
  19664. break;
  19665. }
  19666. case 'J': {
  19667. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  19668. j+=sqlite3Strlen30(&z[j]);
  19669. break;
  19670. }
  19671. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  19672. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  19673. case 's': {
  19674. sqlite3_snprintf(30,&z[j],"%lld",
  19675. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  19676. j += sqlite3Strlen30(&z[j]);
  19677. break;
  19678. }
  19679. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  19680. case 'w': {
  19681. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  19682. break;
  19683. }
  19684. case 'Y': {
  19685. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  19686. break;
  19687. }
  19688. default: z[j++] = '%'; break;
  19689. }
  19690. }
  19691. }
  19692. z[j] = 0;
  19693. sqlite3_result_text(context, z, -1,
  19694. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  19695. }
  19696. /*
  19697. ** current_time()
  19698. **
  19699. ** This function returns the same value as time('now').
  19700. */
  19701. static void ctimeFunc(
  19702. sqlite3_context *context,
  19703. int NotUsed,
  19704. sqlite3_value **NotUsed2
  19705. ){
  19706. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19707. timeFunc(context, 0, 0);
  19708. }
  19709. /*
  19710. ** current_date()
  19711. **
  19712. ** This function returns the same value as date('now').
  19713. */
  19714. static void cdateFunc(
  19715. sqlite3_context *context,
  19716. int NotUsed,
  19717. sqlite3_value **NotUsed2
  19718. ){
  19719. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19720. dateFunc(context, 0, 0);
  19721. }
  19722. /*
  19723. ** current_timestamp()
  19724. **
  19725. ** This function returns the same value as datetime('now').
  19726. */
  19727. static void ctimestampFunc(
  19728. sqlite3_context *context,
  19729. int NotUsed,
  19730. sqlite3_value **NotUsed2
  19731. ){
  19732. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19733. datetimeFunc(context, 0, 0);
  19734. }
  19735. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  19736. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  19737. /*
  19738. ** If the library is compiled to omit the full-scale date and time
  19739. ** handling (to get a smaller binary), the following minimal version
  19740. ** of the functions current_time(), current_date() and current_timestamp()
  19741. ** are included instead. This is to support column declarations that
  19742. ** include "DEFAULT CURRENT_TIME" etc.
  19743. **
  19744. ** This function uses the C-library functions time(), gmtime()
  19745. ** and strftime(). The format string to pass to strftime() is supplied
  19746. ** as the user-data for the function.
  19747. */
  19748. static void currentTimeFunc(
  19749. sqlite3_context *context,
  19750. int argc,
  19751. sqlite3_value **argv
  19752. ){
  19753. time_t t;
  19754. char *zFormat = (char *)sqlite3_user_data(context);
  19755. sqlite3_int64 iT;
  19756. struct tm *pTm;
  19757. struct tm sNow;
  19758. char zBuf[20];
  19759. UNUSED_PARAMETER(argc);
  19760. UNUSED_PARAMETER(argv);
  19761. iT = sqlite3StmtCurrentTime(context);
  19762. if( iT<=0 ) return;
  19763. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  19764. #if HAVE_GMTIME_R
  19765. pTm = gmtime_r(&t, &sNow);
  19766. #else
  19767. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19768. pTm = gmtime(&t);
  19769. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  19770. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19771. #endif
  19772. if( pTm ){
  19773. strftime(zBuf, 20, zFormat, &sNow);
  19774. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19775. }
  19776. }
  19777. #endif
  19778. /*
  19779. ** This function registered all of the above C functions as SQL
  19780. ** functions. This should be the only routine in this file with
  19781. ** external linkage.
  19782. */
  19783. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  19784. static FuncDef aDateTimeFuncs[] = {
  19785. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19786. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  19787. PURE_DATE(date, -1, 0, 0, dateFunc ),
  19788. PURE_DATE(time, -1, 0, 0, timeFunc ),
  19789. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  19790. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  19791. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  19792. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  19793. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  19794. #else
  19795. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  19796. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  19797. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  19798. #endif
  19799. };
  19800. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  19801. }
  19802. /************** End of date.c ************************************************/
  19803. /************** Begin file os.c **********************************************/
  19804. /*
  19805. ** 2005 November 29
  19806. **
  19807. ** The author disclaims copyright to this source code. In place of
  19808. ** a legal notice, here is a blessing:
  19809. **
  19810. ** May you do good and not evil.
  19811. ** May you find forgiveness for yourself and forgive others.
  19812. ** May you share freely, never taking more than you give.
  19813. **
  19814. ******************************************************************************
  19815. **
  19816. ** This file contains OS interface code that is common to all
  19817. ** architectures.
  19818. */
  19819. /* #include "sqliteInt.h" */
  19820. /*
  19821. ** If we compile with the SQLITE_TEST macro set, then the following block
  19822. ** of code will give us the ability to simulate a disk I/O error. This
  19823. ** is used for testing the I/O recovery logic.
  19824. */
  19825. #if defined(SQLITE_TEST)
  19826. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19827. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19828. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19829. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19830. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19831. SQLITE_API int sqlite3_diskfull_pending = 0;
  19832. SQLITE_API int sqlite3_diskfull = 0;
  19833. #endif /* defined(SQLITE_TEST) */
  19834. /*
  19835. ** When testing, also keep a count of the number of open files.
  19836. */
  19837. #if defined(SQLITE_TEST)
  19838. SQLITE_API int sqlite3_open_file_count = 0;
  19839. #endif /* defined(SQLITE_TEST) */
  19840. /*
  19841. ** The default SQLite sqlite3_vfs implementations do not allocate
  19842. ** memory (actually, os_unix.c allocates a small amount of memory
  19843. ** from within OsOpen()), but some third-party implementations may.
  19844. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  19845. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  19846. **
  19847. ** The following functions are instrumented for malloc() failure
  19848. ** testing:
  19849. **
  19850. ** sqlite3OsRead()
  19851. ** sqlite3OsWrite()
  19852. ** sqlite3OsSync()
  19853. ** sqlite3OsFileSize()
  19854. ** sqlite3OsLock()
  19855. ** sqlite3OsCheckReservedLock()
  19856. ** sqlite3OsFileControl()
  19857. ** sqlite3OsShmMap()
  19858. ** sqlite3OsOpen()
  19859. ** sqlite3OsDelete()
  19860. ** sqlite3OsAccess()
  19861. ** sqlite3OsFullPathname()
  19862. **
  19863. */
  19864. #if defined(SQLITE_TEST)
  19865. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  19866. #define DO_OS_MALLOC_TEST(x) \
  19867. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  19868. void *pTstAlloc = sqlite3Malloc(10); \
  19869. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  19870. sqlite3_free(pTstAlloc); \
  19871. }
  19872. #else
  19873. #define DO_OS_MALLOC_TEST(x)
  19874. #endif
  19875. /*
  19876. ** The following routines are convenience wrappers around methods
  19877. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  19878. ** of this would be completely automatic if SQLite were coded using
  19879. ** C++ instead of plain old C.
  19880. */
  19881. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  19882. if( pId->pMethods ){
  19883. pId->pMethods->xClose(pId);
  19884. pId->pMethods = 0;
  19885. }
  19886. }
  19887. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  19888. DO_OS_MALLOC_TEST(id);
  19889. return id->pMethods->xRead(id, pBuf, amt, offset);
  19890. }
  19891. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  19892. DO_OS_MALLOC_TEST(id);
  19893. return id->pMethods->xWrite(id, pBuf, amt, offset);
  19894. }
  19895. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  19896. return id->pMethods->xTruncate(id, size);
  19897. }
  19898. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  19899. DO_OS_MALLOC_TEST(id);
  19900. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  19901. }
  19902. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  19903. DO_OS_MALLOC_TEST(id);
  19904. return id->pMethods->xFileSize(id, pSize);
  19905. }
  19906. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  19907. DO_OS_MALLOC_TEST(id);
  19908. return id->pMethods->xLock(id, lockType);
  19909. }
  19910. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  19911. return id->pMethods->xUnlock(id, lockType);
  19912. }
  19913. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  19914. DO_OS_MALLOC_TEST(id);
  19915. return id->pMethods->xCheckReservedLock(id, pResOut);
  19916. }
  19917. /*
  19918. ** Use sqlite3OsFileControl() when we are doing something that might fail
  19919. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  19920. ** when simply tossing information over the wall to the VFS and we do not
  19921. ** really care if the VFS receives and understands the information since it
  19922. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  19923. ** routine has no return value since the return value would be meaningless.
  19924. */
  19925. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  19926. #ifdef SQLITE_TEST
  19927. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  19928. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  19929. ** is using a regular VFS, it is called after the corresponding
  19930. ** transaction has been committed. Injecting a fault at this point
  19931. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  19932. ** but the transaction is committed anyway.
  19933. **
  19934. ** The core must call OsFileControl() though, not OsFileControlHint(),
  19935. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  19936. ** means the commit really has failed and an error should be returned
  19937. ** to the user. */
  19938. DO_OS_MALLOC_TEST(id);
  19939. }
  19940. #endif
  19941. return id->pMethods->xFileControl(id, op, pArg);
  19942. }
  19943. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  19944. (void)id->pMethods->xFileControl(id, op, pArg);
  19945. }
  19946. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  19947. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  19948. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  19949. }
  19950. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  19951. return id->pMethods->xDeviceCharacteristics(id);
  19952. }
  19953. #ifndef SQLITE_OMIT_WAL
  19954. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  19955. return id->pMethods->xShmLock(id, offset, n, flags);
  19956. }
  19957. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  19958. id->pMethods->xShmBarrier(id);
  19959. }
  19960. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  19961. return id->pMethods->xShmUnmap(id, deleteFlag);
  19962. }
  19963. SQLITE_PRIVATE int sqlite3OsShmMap(
  19964. sqlite3_file *id, /* Database file handle */
  19965. int iPage,
  19966. int pgsz,
  19967. int bExtend, /* True to extend file if necessary */
  19968. void volatile **pp /* OUT: Pointer to mapping */
  19969. ){
  19970. DO_OS_MALLOC_TEST(id);
  19971. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  19972. }
  19973. #endif /* SQLITE_OMIT_WAL */
  19974. #if SQLITE_MAX_MMAP_SIZE>0
  19975. /* The real implementation of xFetch and xUnfetch */
  19976. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19977. DO_OS_MALLOC_TEST(id);
  19978. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  19979. }
  19980. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19981. return id->pMethods->xUnfetch(id, iOff, p);
  19982. }
  19983. #else
  19984. /* No-op stubs to use when memory-mapped I/O is disabled */
  19985. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19986. *pp = 0;
  19987. return SQLITE_OK;
  19988. }
  19989. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19990. return SQLITE_OK;
  19991. }
  19992. #endif
  19993. /*
  19994. ** The next group of routines are convenience wrappers around the
  19995. ** VFS methods.
  19996. */
  19997. SQLITE_PRIVATE int sqlite3OsOpen(
  19998. sqlite3_vfs *pVfs,
  19999. const char *zPath,
  20000. sqlite3_file *pFile,
  20001. int flags,
  20002. int *pFlagsOut
  20003. ){
  20004. int rc;
  20005. DO_OS_MALLOC_TEST(0);
  20006. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  20007. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  20008. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  20009. ** reaching the VFS. */
  20010. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  20011. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  20012. return rc;
  20013. }
  20014. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  20015. DO_OS_MALLOC_TEST(0);
  20016. assert( dirSync==0 || dirSync==1 );
  20017. return pVfs->xDelete(pVfs, zPath, dirSync);
  20018. }
  20019. SQLITE_PRIVATE int sqlite3OsAccess(
  20020. sqlite3_vfs *pVfs,
  20021. const char *zPath,
  20022. int flags,
  20023. int *pResOut
  20024. ){
  20025. DO_OS_MALLOC_TEST(0);
  20026. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  20027. }
  20028. SQLITE_PRIVATE int sqlite3OsFullPathname(
  20029. sqlite3_vfs *pVfs,
  20030. const char *zPath,
  20031. int nPathOut,
  20032. char *zPathOut
  20033. ){
  20034. DO_OS_MALLOC_TEST(0);
  20035. zPathOut[0] = 0;
  20036. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  20037. }
  20038. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  20039. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  20040. return pVfs->xDlOpen(pVfs, zPath);
  20041. }
  20042. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20043. pVfs->xDlError(pVfs, nByte, zBufOut);
  20044. }
  20045. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  20046. return pVfs->xDlSym(pVfs, pHdle, zSym);
  20047. }
  20048. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  20049. pVfs->xDlClose(pVfs, pHandle);
  20050. }
  20051. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  20052. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20053. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  20054. }
  20055. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  20056. return pVfs->xSleep(pVfs, nMicro);
  20057. }
  20058. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  20059. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  20060. }
  20061. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  20062. int rc;
  20063. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  20064. ** method to get the current date and time if that method is available
  20065. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  20066. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  20067. ** unavailable.
  20068. */
  20069. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  20070. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  20071. }else{
  20072. double r;
  20073. rc = pVfs->xCurrentTime(pVfs, &r);
  20074. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  20075. }
  20076. return rc;
  20077. }
  20078. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  20079. sqlite3_vfs *pVfs,
  20080. const char *zFile,
  20081. sqlite3_file **ppFile,
  20082. int flags,
  20083. int *pOutFlags
  20084. ){
  20085. int rc;
  20086. sqlite3_file *pFile;
  20087. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  20088. if( pFile ){
  20089. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  20090. if( rc!=SQLITE_OK ){
  20091. sqlite3_free(pFile);
  20092. }else{
  20093. *ppFile = pFile;
  20094. }
  20095. }else{
  20096. rc = SQLITE_NOMEM_BKPT;
  20097. }
  20098. return rc;
  20099. }
  20100. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  20101. assert( pFile );
  20102. sqlite3OsClose(pFile);
  20103. sqlite3_free(pFile);
  20104. }
  20105. /*
  20106. ** This function is a wrapper around the OS specific implementation of
  20107. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  20108. ** ability to simulate a malloc failure, so that the handling of an
  20109. ** error in sqlite3_os_init() by the upper layers can be tested.
  20110. */
  20111. SQLITE_PRIVATE int sqlite3OsInit(void){
  20112. void *p = sqlite3_malloc(10);
  20113. if( p==0 ) return SQLITE_NOMEM_BKPT;
  20114. sqlite3_free(p);
  20115. return sqlite3_os_init();
  20116. }
  20117. /*
  20118. ** The list of all registered VFS implementations.
  20119. */
  20120. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  20121. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  20122. /*
  20123. ** Locate a VFS by name. If no name is given, simply return the
  20124. ** first VFS on the list.
  20125. */
  20126. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  20127. sqlite3_vfs *pVfs = 0;
  20128. #if SQLITE_THREADSAFE
  20129. sqlite3_mutex *mutex;
  20130. #endif
  20131. #ifndef SQLITE_OMIT_AUTOINIT
  20132. int rc = sqlite3_initialize();
  20133. if( rc ) return 0;
  20134. #endif
  20135. #if SQLITE_THREADSAFE
  20136. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20137. #endif
  20138. sqlite3_mutex_enter(mutex);
  20139. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  20140. if( zVfs==0 ) break;
  20141. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  20142. }
  20143. sqlite3_mutex_leave(mutex);
  20144. return pVfs;
  20145. }
  20146. /*
  20147. ** Unlink a VFS from the linked list
  20148. */
  20149. static void vfsUnlink(sqlite3_vfs *pVfs){
  20150. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  20151. if( pVfs==0 ){
  20152. /* No-op */
  20153. }else if( vfsList==pVfs ){
  20154. vfsList = pVfs->pNext;
  20155. }else if( vfsList ){
  20156. sqlite3_vfs *p = vfsList;
  20157. while( p->pNext && p->pNext!=pVfs ){
  20158. p = p->pNext;
  20159. }
  20160. if( p->pNext==pVfs ){
  20161. p->pNext = pVfs->pNext;
  20162. }
  20163. }
  20164. }
  20165. /*
  20166. ** Register a VFS with the system. It is harmless to register the same
  20167. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  20168. ** true.
  20169. */
  20170. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  20171. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  20172. #ifndef SQLITE_OMIT_AUTOINIT
  20173. int rc = sqlite3_initialize();
  20174. if( rc ) return rc;
  20175. #endif
  20176. #ifdef SQLITE_ENABLE_API_ARMOR
  20177. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  20178. #endif
  20179. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  20180. sqlite3_mutex_enter(mutex);
  20181. vfsUnlink(pVfs);
  20182. if( makeDflt || vfsList==0 ){
  20183. pVfs->pNext = vfsList;
  20184. vfsList = pVfs;
  20185. }else{
  20186. pVfs->pNext = vfsList->pNext;
  20187. vfsList->pNext = pVfs;
  20188. }
  20189. assert(vfsList);
  20190. sqlite3_mutex_leave(mutex);
  20191. return SQLITE_OK;
  20192. }
  20193. /*
  20194. ** Unregister a VFS so that it is no longer accessible.
  20195. */
  20196. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  20197. #if SQLITE_THREADSAFE
  20198. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20199. #endif
  20200. sqlite3_mutex_enter(mutex);
  20201. vfsUnlink(pVfs);
  20202. sqlite3_mutex_leave(mutex);
  20203. return SQLITE_OK;
  20204. }
  20205. /************** End of os.c **************************************************/
  20206. /************** Begin file fault.c *******************************************/
  20207. /*
  20208. ** 2008 Jan 22
  20209. **
  20210. ** The author disclaims copyright to this source code. In place of
  20211. ** a legal notice, here is a blessing:
  20212. **
  20213. ** May you do good and not evil.
  20214. ** May you find forgiveness for yourself and forgive others.
  20215. ** May you share freely, never taking more than you give.
  20216. **
  20217. *************************************************************************
  20218. **
  20219. ** This file contains code to support the concept of "benign"
  20220. ** malloc failures (when the xMalloc() or xRealloc() method of the
  20221. ** sqlite3_mem_methods structure fails to allocate a block of memory
  20222. ** and returns 0).
  20223. **
  20224. ** Most malloc failures are non-benign. After they occur, SQLite
  20225. ** abandons the current operation and returns an error code (usually
  20226. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  20227. ** fatal. For example, if a malloc fails while resizing a hash table, this
  20228. ** is completely recoverable simply by not carrying out the resize. The
  20229. ** hash table will continue to function normally. So a malloc failure
  20230. ** during a hash table resize is a benign fault.
  20231. */
  20232. /* #include "sqliteInt.h" */
  20233. #ifndef SQLITE_UNTESTABLE
  20234. /*
  20235. ** Global variables.
  20236. */
  20237. typedef struct BenignMallocHooks BenignMallocHooks;
  20238. static SQLITE_WSD struct BenignMallocHooks {
  20239. void (*xBenignBegin)(void);
  20240. void (*xBenignEnd)(void);
  20241. } sqlite3Hooks = { 0, 0 };
  20242. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  20243. ** structure. If writable static data is unsupported on the target,
  20244. ** we have to locate the state vector at run-time. In the more common
  20245. ** case where writable static data is supported, wsdHooks can refer directly
  20246. ** to the "sqlite3Hooks" state vector declared above.
  20247. */
  20248. #ifdef SQLITE_OMIT_WSD
  20249. # define wsdHooksInit \
  20250. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  20251. # define wsdHooks x[0]
  20252. #else
  20253. # define wsdHooksInit
  20254. # define wsdHooks sqlite3Hooks
  20255. #endif
  20256. /*
  20257. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  20258. ** sqlite3EndBenignMalloc() are called, respectively.
  20259. */
  20260. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  20261. void (*xBenignBegin)(void),
  20262. void (*xBenignEnd)(void)
  20263. ){
  20264. wsdHooksInit;
  20265. wsdHooks.xBenignBegin = xBenignBegin;
  20266. wsdHooks.xBenignEnd = xBenignEnd;
  20267. }
  20268. /*
  20269. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  20270. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  20271. ** indicates that subsequent malloc failures are non-benign.
  20272. */
  20273. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  20274. wsdHooksInit;
  20275. if( wsdHooks.xBenignBegin ){
  20276. wsdHooks.xBenignBegin();
  20277. }
  20278. }
  20279. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  20280. wsdHooksInit;
  20281. if( wsdHooks.xBenignEnd ){
  20282. wsdHooks.xBenignEnd();
  20283. }
  20284. }
  20285. #endif /* #ifndef SQLITE_UNTESTABLE */
  20286. /************** End of fault.c ***********************************************/
  20287. /************** Begin file mem0.c ********************************************/
  20288. /*
  20289. ** 2008 October 28
  20290. **
  20291. ** The author disclaims copyright to this source code. In place of
  20292. ** a legal notice, here is a blessing:
  20293. **
  20294. ** May you do good and not evil.
  20295. ** May you find forgiveness for yourself and forgive others.
  20296. ** May you share freely, never taking more than you give.
  20297. **
  20298. *************************************************************************
  20299. **
  20300. ** This file contains a no-op memory allocation drivers for use when
  20301. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  20302. ** here always fail. SQLite will not operate with these drivers. These
  20303. ** are merely placeholders. Real drivers must be substituted using
  20304. ** sqlite3_config() before SQLite will operate.
  20305. */
  20306. /* #include "sqliteInt.h" */
  20307. /*
  20308. ** This version of the memory allocator is the default. It is
  20309. ** used when no other memory allocator is specified using compile-time
  20310. ** macros.
  20311. */
  20312. #ifdef SQLITE_ZERO_MALLOC
  20313. /*
  20314. ** No-op versions of all memory allocation routines
  20315. */
  20316. static void *sqlite3MemMalloc(int nByte){ return 0; }
  20317. static void sqlite3MemFree(void *pPrior){ return; }
  20318. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  20319. static int sqlite3MemSize(void *pPrior){ return 0; }
  20320. static int sqlite3MemRoundup(int n){ return n; }
  20321. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  20322. static void sqlite3MemShutdown(void *NotUsed){ return; }
  20323. /*
  20324. ** This routine is the only routine in this file with external linkage.
  20325. **
  20326. ** Populate the low-level memory allocation function pointers in
  20327. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20328. */
  20329. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20330. static const sqlite3_mem_methods defaultMethods = {
  20331. sqlite3MemMalloc,
  20332. sqlite3MemFree,
  20333. sqlite3MemRealloc,
  20334. sqlite3MemSize,
  20335. sqlite3MemRoundup,
  20336. sqlite3MemInit,
  20337. sqlite3MemShutdown,
  20338. 0
  20339. };
  20340. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20341. }
  20342. #endif /* SQLITE_ZERO_MALLOC */
  20343. /************** End of mem0.c ************************************************/
  20344. /************** Begin file mem1.c ********************************************/
  20345. /*
  20346. ** 2007 August 14
  20347. **
  20348. ** The author disclaims copyright to this source code. In place of
  20349. ** a legal notice, here is a blessing:
  20350. **
  20351. ** May you do good and not evil.
  20352. ** May you find forgiveness for yourself and forgive others.
  20353. ** May you share freely, never taking more than you give.
  20354. **
  20355. *************************************************************************
  20356. **
  20357. ** This file contains low-level memory allocation drivers for when
  20358. ** SQLite will use the standard C-library malloc/realloc/free interface
  20359. ** to obtain the memory it needs.
  20360. **
  20361. ** This file contains implementations of the low-level memory allocation
  20362. ** routines specified in the sqlite3_mem_methods object. The content of
  20363. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  20364. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  20365. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  20366. ** default configuration is to use memory allocation routines in this
  20367. ** file.
  20368. **
  20369. ** C-preprocessor macro summary:
  20370. **
  20371. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  20372. ** the malloc_usable_size() interface exists
  20373. ** on the target platform. Or, this symbol
  20374. ** can be set manually, if desired.
  20375. ** If an equivalent interface exists by
  20376. ** a different name, using a separate -D
  20377. ** option to rename it.
  20378. **
  20379. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  20380. ** memory allocator. Set this symbol to enable
  20381. ** building on older macs.
  20382. **
  20383. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  20384. ** _msize() on windows systems. This might
  20385. ** be necessary when compiling for Delphi,
  20386. ** for example.
  20387. */
  20388. /* #include "sqliteInt.h" */
  20389. /*
  20390. ** This version of the memory allocator is the default. It is
  20391. ** used when no other memory allocator is specified using compile-time
  20392. ** macros.
  20393. */
  20394. #ifdef SQLITE_SYSTEM_MALLOC
  20395. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  20396. /*
  20397. ** Use the zone allocator available on apple products unless the
  20398. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  20399. */
  20400. #include <sys/sysctl.h>
  20401. #include <malloc/malloc.h>
  20402. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  20403. #include <libkern/OSAtomic.h>
  20404. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  20405. static malloc_zone_t* _sqliteZone_;
  20406. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  20407. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  20408. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  20409. #define SQLITE_MALLOCSIZE(x) \
  20410. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  20411. #else /* if not __APPLE__ */
  20412. /*
  20413. ** Use standard C library malloc and free on non-Apple systems.
  20414. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  20415. */
  20416. #define SQLITE_MALLOC(x) malloc(x)
  20417. #define SQLITE_FREE(x) free(x)
  20418. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  20419. /*
  20420. ** The malloc.h header file is needed for malloc_usable_size() function
  20421. ** on some systems (e.g. Linux).
  20422. */
  20423. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  20424. # define SQLITE_USE_MALLOC_H 1
  20425. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  20426. /*
  20427. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  20428. ** use of _msize() is automatic, but can be disabled by compiling with
  20429. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  20430. ** the malloc.h header file.
  20431. */
  20432. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  20433. # define SQLITE_USE_MALLOC_H
  20434. # define SQLITE_USE_MSIZE
  20435. #endif
  20436. /*
  20437. ** Include the malloc.h header file, if necessary. Also set define macro
  20438. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  20439. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  20440. ** The memory size function can always be overridden manually by defining
  20441. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  20442. */
  20443. #if defined(SQLITE_USE_MALLOC_H)
  20444. # include <malloc.h>
  20445. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  20446. # if !defined(SQLITE_MALLOCSIZE)
  20447. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  20448. # endif
  20449. # elif defined(SQLITE_USE_MSIZE)
  20450. # if !defined(SQLITE_MALLOCSIZE)
  20451. # define SQLITE_MALLOCSIZE _msize
  20452. # endif
  20453. # endif
  20454. #endif /* defined(SQLITE_USE_MALLOC_H) */
  20455. #endif /* __APPLE__ or not __APPLE__ */
  20456. /*
  20457. ** Like malloc(), but remember the size of the allocation
  20458. ** so that we can find it later using sqlite3MemSize().
  20459. **
  20460. ** For this low-level routine, we are guaranteed that nByte>0 because
  20461. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  20462. ** routines.
  20463. */
  20464. static void *sqlite3MemMalloc(int nByte){
  20465. #ifdef SQLITE_MALLOCSIZE
  20466. void *p;
  20467. testcase( ROUND8(nByte)==nByte );
  20468. p = SQLITE_MALLOC( nByte );
  20469. if( p==0 ){
  20470. testcase( sqlite3GlobalConfig.xLog!=0 );
  20471. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  20472. }
  20473. return p;
  20474. #else
  20475. sqlite3_int64 *p;
  20476. assert( nByte>0 );
  20477. testcase( ROUND8(nByte)!=nByte );
  20478. p = SQLITE_MALLOC( nByte+8 );
  20479. if( p ){
  20480. p[0] = nByte;
  20481. p++;
  20482. }else{
  20483. testcase( sqlite3GlobalConfig.xLog!=0 );
  20484. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  20485. }
  20486. return (void *)p;
  20487. #endif
  20488. }
  20489. /*
  20490. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  20491. ** or sqlite3MemRealloc().
  20492. **
  20493. ** For this low-level routine, we already know that pPrior!=0 since
  20494. ** cases where pPrior==0 will have been intecepted and dealt with
  20495. ** by higher-level routines.
  20496. */
  20497. static void sqlite3MemFree(void *pPrior){
  20498. #ifdef SQLITE_MALLOCSIZE
  20499. SQLITE_FREE(pPrior);
  20500. #else
  20501. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  20502. assert( pPrior!=0 );
  20503. p--;
  20504. SQLITE_FREE(p);
  20505. #endif
  20506. }
  20507. /*
  20508. ** Report the allocated size of a prior return from xMalloc()
  20509. ** or xRealloc().
  20510. */
  20511. static int sqlite3MemSize(void *pPrior){
  20512. #ifdef SQLITE_MALLOCSIZE
  20513. assert( pPrior!=0 );
  20514. return (int)SQLITE_MALLOCSIZE(pPrior);
  20515. #else
  20516. sqlite3_int64 *p;
  20517. assert( pPrior!=0 );
  20518. p = (sqlite3_int64*)pPrior;
  20519. p--;
  20520. return (int)p[0];
  20521. #endif
  20522. }
  20523. /*
  20524. ** Like realloc(). Resize an allocation previously obtained from
  20525. ** sqlite3MemMalloc().
  20526. **
  20527. ** For this low-level interface, we know that pPrior!=0. Cases where
  20528. ** pPrior==0 while have been intercepted by higher-level routine and
  20529. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  20530. ** cases where nByte<=0 will have been intercepted by higher-level
  20531. ** routines and redirected to xFree.
  20532. */
  20533. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  20534. #ifdef SQLITE_MALLOCSIZE
  20535. void *p = SQLITE_REALLOC(pPrior, nByte);
  20536. if( p==0 ){
  20537. testcase( sqlite3GlobalConfig.xLog!=0 );
  20538. sqlite3_log(SQLITE_NOMEM,
  20539. "failed memory resize %u to %u bytes",
  20540. SQLITE_MALLOCSIZE(pPrior), nByte);
  20541. }
  20542. return p;
  20543. #else
  20544. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  20545. assert( pPrior!=0 && nByte>0 );
  20546. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  20547. p--;
  20548. p = SQLITE_REALLOC(p, nByte+8 );
  20549. if( p ){
  20550. p[0] = nByte;
  20551. p++;
  20552. }else{
  20553. testcase( sqlite3GlobalConfig.xLog!=0 );
  20554. sqlite3_log(SQLITE_NOMEM,
  20555. "failed memory resize %u to %u bytes",
  20556. sqlite3MemSize(pPrior), nByte);
  20557. }
  20558. return (void*)p;
  20559. #endif
  20560. }
  20561. /*
  20562. ** Round up a request size to the next valid allocation size.
  20563. */
  20564. static int sqlite3MemRoundup(int n){
  20565. return ROUND8(n);
  20566. }
  20567. /*
  20568. ** Initialize this module.
  20569. */
  20570. static int sqlite3MemInit(void *NotUsed){
  20571. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  20572. int cpuCount;
  20573. size_t len;
  20574. if( _sqliteZone_ ){
  20575. return SQLITE_OK;
  20576. }
  20577. len = sizeof(cpuCount);
  20578. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  20579. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  20580. if( cpuCount>1 ){
  20581. /* defer MT decisions to system malloc */
  20582. _sqliteZone_ = malloc_default_zone();
  20583. }else{
  20584. /* only 1 core, use our own zone to contention over global locks,
  20585. ** e.g. we have our own dedicated locks */
  20586. _sqliteZone_ = malloc_create_zone(4096, 0);
  20587. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  20588. }
  20589. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  20590. UNUSED_PARAMETER(NotUsed);
  20591. return SQLITE_OK;
  20592. }
  20593. /*
  20594. ** Deinitialize this module.
  20595. */
  20596. static void sqlite3MemShutdown(void *NotUsed){
  20597. UNUSED_PARAMETER(NotUsed);
  20598. return;
  20599. }
  20600. /*
  20601. ** This routine is the only routine in this file with external linkage.
  20602. **
  20603. ** Populate the low-level memory allocation function pointers in
  20604. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20605. */
  20606. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20607. static const sqlite3_mem_methods defaultMethods = {
  20608. sqlite3MemMalloc,
  20609. sqlite3MemFree,
  20610. sqlite3MemRealloc,
  20611. sqlite3MemSize,
  20612. sqlite3MemRoundup,
  20613. sqlite3MemInit,
  20614. sqlite3MemShutdown,
  20615. 0
  20616. };
  20617. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20618. }
  20619. #endif /* SQLITE_SYSTEM_MALLOC */
  20620. /************** End of mem1.c ************************************************/
  20621. /************** Begin file mem2.c ********************************************/
  20622. /*
  20623. ** 2007 August 15
  20624. **
  20625. ** The author disclaims copyright to this source code. In place of
  20626. ** a legal notice, here is a blessing:
  20627. **
  20628. ** May you do good and not evil.
  20629. ** May you find forgiveness for yourself and forgive others.
  20630. ** May you share freely, never taking more than you give.
  20631. **
  20632. *************************************************************************
  20633. **
  20634. ** This file contains low-level memory allocation drivers for when
  20635. ** SQLite will use the standard C-library malloc/realloc/free interface
  20636. ** to obtain the memory it needs while adding lots of additional debugging
  20637. ** information to each allocation in order to help detect and fix memory
  20638. ** leaks and memory usage errors.
  20639. **
  20640. ** This file contains implementations of the low-level memory allocation
  20641. ** routines specified in the sqlite3_mem_methods object.
  20642. */
  20643. /* #include "sqliteInt.h" */
  20644. /*
  20645. ** This version of the memory allocator is used only if the
  20646. ** SQLITE_MEMDEBUG macro is defined
  20647. */
  20648. #ifdef SQLITE_MEMDEBUG
  20649. /*
  20650. ** The backtrace functionality is only available with GLIBC
  20651. */
  20652. #ifdef __GLIBC__
  20653. extern int backtrace(void**,int);
  20654. extern void backtrace_symbols_fd(void*const*,int,int);
  20655. #else
  20656. # define backtrace(A,B) 1
  20657. # define backtrace_symbols_fd(A,B,C)
  20658. #endif
  20659. /* #include <stdio.h> */
  20660. /*
  20661. ** Each memory allocation looks like this:
  20662. **
  20663. ** ------------------------------------------------------------------------
  20664. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  20665. ** ------------------------------------------------------------------------
  20666. **
  20667. ** The application code sees only a pointer to the allocation. We have
  20668. ** to back up from the allocation pointer to find the MemBlockHdr. The
  20669. ** MemBlockHdr tells us the size of the allocation and the number of
  20670. ** backtrace pointers. There is also a guard word at the end of the
  20671. ** MemBlockHdr.
  20672. */
  20673. struct MemBlockHdr {
  20674. i64 iSize; /* Size of this allocation */
  20675. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  20676. char nBacktrace; /* Number of backtraces on this alloc */
  20677. char nBacktraceSlots; /* Available backtrace slots */
  20678. u8 nTitle; /* Bytes of title; includes '\0' */
  20679. u8 eType; /* Allocation type code */
  20680. int iForeGuard; /* Guard word for sanity */
  20681. };
  20682. /*
  20683. ** Guard words
  20684. */
  20685. #define FOREGUARD 0x80F5E153
  20686. #define REARGUARD 0xE4676B53
  20687. /*
  20688. ** Number of malloc size increments to track.
  20689. */
  20690. #define NCSIZE 1000
  20691. /*
  20692. ** All of the static variables used by this module are collected
  20693. ** into a single structure named "mem". This is to keep the
  20694. ** static variables organized and to reduce namespace pollution
  20695. ** when this module is combined with other in the amalgamation.
  20696. */
  20697. static struct {
  20698. /*
  20699. ** Mutex to control access to the memory allocation subsystem.
  20700. */
  20701. sqlite3_mutex *mutex;
  20702. /*
  20703. ** Head and tail of a linked list of all outstanding allocations
  20704. */
  20705. struct MemBlockHdr *pFirst;
  20706. struct MemBlockHdr *pLast;
  20707. /*
  20708. ** The number of levels of backtrace to save in new allocations.
  20709. */
  20710. int nBacktrace;
  20711. void (*xBacktrace)(int, int, void **);
  20712. /*
  20713. ** Title text to insert in front of each block
  20714. */
  20715. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  20716. char zTitle[100]; /* The title text */
  20717. /*
  20718. ** sqlite3MallocDisallow() increments the following counter.
  20719. ** sqlite3MallocAllow() decrements it.
  20720. */
  20721. int disallow; /* Do not allow memory allocation */
  20722. /*
  20723. ** Gather statistics on the sizes of memory allocations.
  20724. ** nAlloc[i] is the number of allocation attempts of i*8
  20725. ** bytes. i==NCSIZE is the number of allocation attempts for
  20726. ** sizes more than NCSIZE*8 bytes.
  20727. */
  20728. int nAlloc[NCSIZE]; /* Total number of allocations */
  20729. int nCurrent[NCSIZE]; /* Current number of allocations */
  20730. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  20731. } mem;
  20732. /*
  20733. ** Adjust memory usage statistics
  20734. */
  20735. static void adjustStats(int iSize, int increment){
  20736. int i = ROUND8(iSize)/8;
  20737. if( i>NCSIZE-1 ){
  20738. i = NCSIZE - 1;
  20739. }
  20740. if( increment>0 ){
  20741. mem.nAlloc[i]++;
  20742. mem.nCurrent[i]++;
  20743. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  20744. mem.mxCurrent[i] = mem.nCurrent[i];
  20745. }
  20746. }else{
  20747. mem.nCurrent[i]--;
  20748. assert( mem.nCurrent[i]>=0 );
  20749. }
  20750. }
  20751. /*
  20752. ** Given an allocation, find the MemBlockHdr for that allocation.
  20753. **
  20754. ** This routine checks the guards at either end of the allocation and
  20755. ** if they are incorrect it asserts.
  20756. */
  20757. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  20758. struct MemBlockHdr *p;
  20759. int *pInt;
  20760. u8 *pU8;
  20761. int nReserve;
  20762. p = (struct MemBlockHdr*)pAllocation;
  20763. p--;
  20764. assert( p->iForeGuard==(int)FOREGUARD );
  20765. nReserve = ROUND8(p->iSize);
  20766. pInt = (int*)pAllocation;
  20767. pU8 = (u8*)pAllocation;
  20768. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  20769. /* This checks any of the "extra" bytes allocated due
  20770. ** to rounding up to an 8 byte boundary to ensure
  20771. ** they haven't been overwritten.
  20772. */
  20773. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  20774. return p;
  20775. }
  20776. /*
  20777. ** Return the number of bytes currently allocated at address p.
  20778. */
  20779. static int sqlite3MemSize(void *p){
  20780. struct MemBlockHdr *pHdr;
  20781. if( !p ){
  20782. return 0;
  20783. }
  20784. pHdr = sqlite3MemsysGetHeader(p);
  20785. return (int)pHdr->iSize;
  20786. }
  20787. /*
  20788. ** Initialize the memory allocation subsystem.
  20789. */
  20790. static int sqlite3MemInit(void *NotUsed){
  20791. UNUSED_PARAMETER(NotUsed);
  20792. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  20793. if( !sqlite3GlobalConfig.bMemstat ){
  20794. /* If memory status is enabled, then the malloc.c wrapper will already
  20795. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  20796. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20797. }
  20798. return SQLITE_OK;
  20799. }
  20800. /*
  20801. ** Deinitialize the memory allocation subsystem.
  20802. */
  20803. static void sqlite3MemShutdown(void *NotUsed){
  20804. UNUSED_PARAMETER(NotUsed);
  20805. mem.mutex = 0;
  20806. }
  20807. /*
  20808. ** Round up a request size to the next valid allocation size.
  20809. */
  20810. static int sqlite3MemRoundup(int n){
  20811. return ROUND8(n);
  20812. }
  20813. /*
  20814. ** Fill a buffer with pseudo-random bytes. This is used to preset
  20815. ** the content of a new memory allocation to unpredictable values and
  20816. ** to clear the content of a freed allocation to unpredictable values.
  20817. */
  20818. static void randomFill(char *pBuf, int nByte){
  20819. unsigned int x, y, r;
  20820. x = SQLITE_PTR_TO_INT(pBuf);
  20821. y = nByte | 1;
  20822. while( nByte >= 4 ){
  20823. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20824. y = y*1103515245 + 12345;
  20825. r = x ^ y;
  20826. *(int*)pBuf = r;
  20827. pBuf += 4;
  20828. nByte -= 4;
  20829. }
  20830. while( nByte-- > 0 ){
  20831. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20832. y = y*1103515245 + 12345;
  20833. r = x ^ y;
  20834. *(pBuf++) = r & 0xff;
  20835. }
  20836. }
  20837. /*
  20838. ** Allocate nByte bytes of memory.
  20839. */
  20840. static void *sqlite3MemMalloc(int nByte){
  20841. struct MemBlockHdr *pHdr;
  20842. void **pBt;
  20843. char *z;
  20844. int *pInt;
  20845. void *p = 0;
  20846. int totalSize;
  20847. int nReserve;
  20848. sqlite3_mutex_enter(mem.mutex);
  20849. assert( mem.disallow==0 );
  20850. nReserve = ROUND8(nByte);
  20851. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  20852. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  20853. p = malloc(totalSize);
  20854. if( p ){
  20855. z = p;
  20856. pBt = (void**)&z[mem.nTitle];
  20857. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  20858. pHdr->pNext = 0;
  20859. pHdr->pPrev = mem.pLast;
  20860. if( mem.pLast ){
  20861. mem.pLast->pNext = pHdr;
  20862. }else{
  20863. mem.pFirst = pHdr;
  20864. }
  20865. mem.pLast = pHdr;
  20866. pHdr->iForeGuard = FOREGUARD;
  20867. pHdr->eType = MEMTYPE_HEAP;
  20868. pHdr->nBacktraceSlots = mem.nBacktrace;
  20869. pHdr->nTitle = mem.nTitle;
  20870. if( mem.nBacktrace ){
  20871. void *aAddr[40];
  20872. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  20873. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  20874. assert(pBt[0]);
  20875. if( mem.xBacktrace ){
  20876. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  20877. }
  20878. }else{
  20879. pHdr->nBacktrace = 0;
  20880. }
  20881. if( mem.nTitle ){
  20882. memcpy(z, mem.zTitle, mem.nTitle);
  20883. }
  20884. pHdr->iSize = nByte;
  20885. adjustStats(nByte, +1);
  20886. pInt = (int*)&pHdr[1];
  20887. pInt[nReserve/sizeof(int)] = REARGUARD;
  20888. randomFill((char*)pInt, nByte);
  20889. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  20890. p = (void*)pInt;
  20891. }
  20892. sqlite3_mutex_leave(mem.mutex);
  20893. return p;
  20894. }
  20895. /*
  20896. ** Free memory.
  20897. */
  20898. static void sqlite3MemFree(void *pPrior){
  20899. struct MemBlockHdr *pHdr;
  20900. void **pBt;
  20901. char *z;
  20902. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  20903. || mem.mutex!=0 );
  20904. pHdr = sqlite3MemsysGetHeader(pPrior);
  20905. pBt = (void**)pHdr;
  20906. pBt -= pHdr->nBacktraceSlots;
  20907. sqlite3_mutex_enter(mem.mutex);
  20908. if( pHdr->pPrev ){
  20909. assert( pHdr->pPrev->pNext==pHdr );
  20910. pHdr->pPrev->pNext = pHdr->pNext;
  20911. }else{
  20912. assert( mem.pFirst==pHdr );
  20913. mem.pFirst = pHdr->pNext;
  20914. }
  20915. if( pHdr->pNext ){
  20916. assert( pHdr->pNext->pPrev==pHdr );
  20917. pHdr->pNext->pPrev = pHdr->pPrev;
  20918. }else{
  20919. assert( mem.pLast==pHdr );
  20920. mem.pLast = pHdr->pPrev;
  20921. }
  20922. z = (char*)pBt;
  20923. z -= pHdr->nTitle;
  20924. adjustStats((int)pHdr->iSize, -1);
  20925. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  20926. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  20927. free(z);
  20928. sqlite3_mutex_leave(mem.mutex);
  20929. }
  20930. /*
  20931. ** Change the size of an existing memory allocation.
  20932. **
  20933. ** For this debugging implementation, we *always* make a copy of the
  20934. ** allocation into a new place in memory. In this way, if the
  20935. ** higher level code is using pointer to the old allocation, it is
  20936. ** much more likely to break and we are much more liking to find
  20937. ** the error.
  20938. */
  20939. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  20940. struct MemBlockHdr *pOldHdr;
  20941. void *pNew;
  20942. assert( mem.disallow==0 );
  20943. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  20944. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  20945. pNew = sqlite3MemMalloc(nByte);
  20946. if( pNew ){
  20947. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  20948. if( nByte>pOldHdr->iSize ){
  20949. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  20950. }
  20951. sqlite3MemFree(pPrior);
  20952. }
  20953. return pNew;
  20954. }
  20955. /*
  20956. ** Populate the low-level memory allocation function pointers in
  20957. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20958. */
  20959. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20960. static const sqlite3_mem_methods defaultMethods = {
  20961. sqlite3MemMalloc,
  20962. sqlite3MemFree,
  20963. sqlite3MemRealloc,
  20964. sqlite3MemSize,
  20965. sqlite3MemRoundup,
  20966. sqlite3MemInit,
  20967. sqlite3MemShutdown,
  20968. 0
  20969. };
  20970. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20971. }
  20972. /*
  20973. ** Set the "type" of an allocation.
  20974. */
  20975. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  20976. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20977. struct MemBlockHdr *pHdr;
  20978. pHdr = sqlite3MemsysGetHeader(p);
  20979. assert( pHdr->iForeGuard==FOREGUARD );
  20980. pHdr->eType = eType;
  20981. }
  20982. }
  20983. /*
  20984. ** Return TRUE if the mask of type in eType matches the type of the
  20985. ** allocation p. Also return true if p==NULL.
  20986. **
  20987. ** This routine is designed for use within an assert() statement, to
  20988. ** verify the type of an allocation. For example:
  20989. **
  20990. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20991. */
  20992. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  20993. int rc = 1;
  20994. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20995. struct MemBlockHdr *pHdr;
  20996. pHdr = sqlite3MemsysGetHeader(p);
  20997. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  20998. if( (pHdr->eType&eType)==0 ){
  20999. rc = 0;
  21000. }
  21001. }
  21002. return rc;
  21003. }
  21004. /*
  21005. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  21006. ** allocation p. Also return true if p==NULL.
  21007. **
  21008. ** This routine is designed for use within an assert() statement, to
  21009. ** verify the type of an allocation. For example:
  21010. **
  21011. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  21012. */
  21013. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  21014. int rc = 1;
  21015. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21016. struct MemBlockHdr *pHdr;
  21017. pHdr = sqlite3MemsysGetHeader(p);
  21018. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  21019. if( (pHdr->eType&eType)!=0 ){
  21020. rc = 0;
  21021. }
  21022. }
  21023. return rc;
  21024. }
  21025. /*
  21026. ** Set the number of backtrace levels kept for each allocation.
  21027. ** A value of zero turns off backtracing. The number is always rounded
  21028. ** up to a multiple of 2.
  21029. */
  21030. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  21031. if( depth<0 ){ depth = 0; }
  21032. if( depth>20 ){ depth = 20; }
  21033. depth = (depth+1)&0xfe;
  21034. mem.nBacktrace = depth;
  21035. }
  21036. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  21037. mem.xBacktrace = xBacktrace;
  21038. }
  21039. /*
  21040. ** Set the title string for subsequent allocations.
  21041. */
  21042. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  21043. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  21044. sqlite3_mutex_enter(mem.mutex);
  21045. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  21046. memcpy(mem.zTitle, zTitle, n);
  21047. mem.zTitle[n] = 0;
  21048. mem.nTitle = ROUND8(n);
  21049. sqlite3_mutex_leave(mem.mutex);
  21050. }
  21051. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  21052. struct MemBlockHdr *pHdr;
  21053. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21054. void **pBt = (void**)pHdr;
  21055. pBt -= pHdr->nBacktraceSlots;
  21056. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  21057. }
  21058. }
  21059. /*
  21060. ** Open the file indicated and write a log of all unfreed memory
  21061. ** allocations into that log.
  21062. */
  21063. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  21064. FILE *out;
  21065. struct MemBlockHdr *pHdr;
  21066. void **pBt;
  21067. int i;
  21068. out = fopen(zFilename, "w");
  21069. if( out==0 ){
  21070. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21071. zFilename);
  21072. return;
  21073. }
  21074. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21075. char *z = (char*)pHdr;
  21076. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  21077. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  21078. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  21079. if( pHdr->nBacktrace ){
  21080. fflush(out);
  21081. pBt = (void**)pHdr;
  21082. pBt -= pHdr->nBacktraceSlots;
  21083. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  21084. fprintf(out, "\n");
  21085. }
  21086. }
  21087. fprintf(out, "COUNTS:\n");
  21088. for(i=0; i<NCSIZE-1; i++){
  21089. if( mem.nAlloc[i] ){
  21090. fprintf(out, " %5d: %10d %10d %10d\n",
  21091. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  21092. }
  21093. }
  21094. if( mem.nAlloc[NCSIZE-1] ){
  21095. fprintf(out, " %5d: %10d %10d %10d\n",
  21096. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  21097. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  21098. }
  21099. fclose(out);
  21100. }
  21101. /*
  21102. ** Return the number of times sqlite3MemMalloc() has been called.
  21103. */
  21104. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  21105. int i;
  21106. int nTotal = 0;
  21107. for(i=0; i<NCSIZE; i++){
  21108. nTotal += mem.nAlloc[i];
  21109. }
  21110. return nTotal;
  21111. }
  21112. #endif /* SQLITE_MEMDEBUG */
  21113. /************** End of mem2.c ************************************************/
  21114. /************** Begin file mem3.c ********************************************/
  21115. /*
  21116. ** 2007 October 14
  21117. **
  21118. ** The author disclaims copyright to this source code. In place of
  21119. ** a legal notice, here is a blessing:
  21120. **
  21121. ** May you do good and not evil.
  21122. ** May you find forgiveness for yourself and forgive others.
  21123. ** May you share freely, never taking more than you give.
  21124. **
  21125. *************************************************************************
  21126. ** This file contains the C functions that implement a memory
  21127. ** allocation subsystem for use by SQLite.
  21128. **
  21129. ** This version of the memory allocation subsystem omits all
  21130. ** use of malloc(). The SQLite user supplies a block of memory
  21131. ** before calling sqlite3_initialize() from which allocations
  21132. ** are made and returned by the xMalloc() and xRealloc()
  21133. ** implementations. Once sqlite3_initialize() has been called,
  21134. ** the amount of memory available to SQLite is fixed and cannot
  21135. ** be changed.
  21136. **
  21137. ** This version of the memory allocation subsystem is included
  21138. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  21139. */
  21140. /* #include "sqliteInt.h" */
  21141. /*
  21142. ** This version of the memory allocator is only built into the library
  21143. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  21144. ** mean that the library will use a memory-pool by default, just that
  21145. ** it is available. The mempool allocator is activated by calling
  21146. ** sqlite3_config().
  21147. */
  21148. #ifdef SQLITE_ENABLE_MEMSYS3
  21149. /*
  21150. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  21151. */
  21152. #define MX_SMALL 10
  21153. /*
  21154. ** Number of freelist hash slots
  21155. */
  21156. #define N_HASH 61
  21157. /*
  21158. ** A memory allocation (also called a "chunk") consists of two or
  21159. ** more blocks where each block is 8 bytes. The first 8 bytes are
  21160. ** a header that is not returned to the user.
  21161. **
  21162. ** A chunk is two or more blocks that is either checked out or
  21163. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  21164. ** size of the allocation in blocks if the allocation is free.
  21165. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  21166. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  21167. ** is true if the previous chunk is checked out and false if the
  21168. ** previous chunk is free. The u.hdr.prevSize field is the size of
  21169. ** the previous chunk in blocks if the previous chunk is on the
  21170. ** freelist. If the previous chunk is checked out, then
  21171. ** u.hdr.prevSize can be part of the data for that chunk and should
  21172. ** not be read or written.
  21173. **
  21174. ** We often identify a chunk by its index in mem3.aPool[]. When
  21175. ** this is done, the chunk index refers to the second block of
  21176. ** the chunk. In this way, the first chunk has an index of 1.
  21177. ** A chunk index of 0 means "no such chunk" and is the equivalent
  21178. ** of a NULL pointer.
  21179. **
  21180. ** The second block of free chunks is of the form u.list. The
  21181. ** two fields form a double-linked list of chunks of related sizes.
  21182. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  21183. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  21184. **
  21185. ** The second block of a chunk is user data if the chunk is checked
  21186. ** out. If a chunk is checked out, the user data may extend into
  21187. ** the u.hdr.prevSize value of the following chunk.
  21188. */
  21189. typedef struct Mem3Block Mem3Block;
  21190. struct Mem3Block {
  21191. union {
  21192. struct {
  21193. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  21194. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  21195. } hdr;
  21196. struct {
  21197. u32 next; /* Index in mem3.aPool[] of next free chunk */
  21198. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  21199. } list;
  21200. } u;
  21201. };
  21202. /*
  21203. ** All of the static variables used by this module are collected
  21204. ** into a single structure named "mem3". This is to keep the
  21205. ** static variables organized and to reduce namespace pollution
  21206. ** when this module is combined with other in the amalgamation.
  21207. */
  21208. static SQLITE_WSD struct Mem3Global {
  21209. /*
  21210. ** Memory available for allocation. nPool is the size of the array
  21211. ** (in Mem3Blocks) pointed to by aPool less 2.
  21212. */
  21213. u32 nPool;
  21214. Mem3Block *aPool;
  21215. /*
  21216. ** True if we are evaluating an out-of-memory callback.
  21217. */
  21218. int alarmBusy;
  21219. /*
  21220. ** Mutex to control access to the memory allocation subsystem.
  21221. */
  21222. sqlite3_mutex *mutex;
  21223. /*
  21224. ** The minimum amount of free space that we have seen.
  21225. */
  21226. u32 mnMaster;
  21227. /*
  21228. ** iMaster is the index of the master chunk. Most new allocations
  21229. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  21230. ** of the current master. iMaster is 0 if there is not master chunk.
  21231. ** The master chunk is not in either the aiHash[] or aiSmall[].
  21232. */
  21233. u32 iMaster;
  21234. u32 szMaster;
  21235. /*
  21236. ** Array of lists of free blocks according to the block size
  21237. ** for smaller chunks, or a hash on the block size for larger
  21238. ** chunks.
  21239. */
  21240. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  21241. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  21242. } mem3 = { 97535575 };
  21243. #define mem3 GLOBAL(struct Mem3Global, mem3)
  21244. /*
  21245. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  21246. ** on. *pRoot is the list that i is a member of.
  21247. */
  21248. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  21249. u32 next = mem3.aPool[i].u.list.next;
  21250. u32 prev = mem3.aPool[i].u.list.prev;
  21251. assert( sqlite3_mutex_held(mem3.mutex) );
  21252. if( prev==0 ){
  21253. *pRoot = next;
  21254. }else{
  21255. mem3.aPool[prev].u.list.next = next;
  21256. }
  21257. if( next ){
  21258. mem3.aPool[next].u.list.prev = prev;
  21259. }
  21260. mem3.aPool[i].u.list.next = 0;
  21261. mem3.aPool[i].u.list.prev = 0;
  21262. }
  21263. /*
  21264. ** Unlink the chunk at index i from
  21265. ** whatever list is currently a member of.
  21266. */
  21267. static void memsys3Unlink(u32 i){
  21268. u32 size, hash;
  21269. assert( sqlite3_mutex_held(mem3.mutex) );
  21270. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  21271. assert( i>=1 );
  21272. size = mem3.aPool[i-1].u.hdr.size4x/4;
  21273. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  21274. assert( size>=2 );
  21275. if( size <= MX_SMALL ){
  21276. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  21277. }else{
  21278. hash = size % N_HASH;
  21279. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  21280. }
  21281. }
  21282. /*
  21283. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  21284. ** at *pRoot.
  21285. */
  21286. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  21287. assert( sqlite3_mutex_held(mem3.mutex) );
  21288. mem3.aPool[i].u.list.next = *pRoot;
  21289. mem3.aPool[i].u.list.prev = 0;
  21290. if( *pRoot ){
  21291. mem3.aPool[*pRoot].u.list.prev = i;
  21292. }
  21293. *pRoot = i;
  21294. }
  21295. /*
  21296. ** Link the chunk at index i into either the appropriate
  21297. ** small chunk list, or into the large chunk hash table.
  21298. */
  21299. static void memsys3Link(u32 i){
  21300. u32 size, hash;
  21301. assert( sqlite3_mutex_held(mem3.mutex) );
  21302. assert( i>=1 );
  21303. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  21304. size = mem3.aPool[i-1].u.hdr.size4x/4;
  21305. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  21306. assert( size>=2 );
  21307. if( size <= MX_SMALL ){
  21308. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  21309. }else{
  21310. hash = size % N_HASH;
  21311. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  21312. }
  21313. }
  21314. /*
  21315. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  21316. ** will already be held (obtained by code in malloc.c) if
  21317. ** sqlite3GlobalConfig.bMemStat is true.
  21318. */
  21319. static void memsys3Enter(void){
  21320. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  21321. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21322. }
  21323. sqlite3_mutex_enter(mem3.mutex);
  21324. }
  21325. static void memsys3Leave(void){
  21326. sqlite3_mutex_leave(mem3.mutex);
  21327. }
  21328. /*
  21329. ** Called when we are unable to satisfy an allocation of nBytes.
  21330. */
  21331. static void memsys3OutOfMemory(int nByte){
  21332. if( !mem3.alarmBusy ){
  21333. mem3.alarmBusy = 1;
  21334. assert( sqlite3_mutex_held(mem3.mutex) );
  21335. sqlite3_mutex_leave(mem3.mutex);
  21336. sqlite3_release_memory(nByte);
  21337. sqlite3_mutex_enter(mem3.mutex);
  21338. mem3.alarmBusy = 0;
  21339. }
  21340. }
  21341. /*
  21342. ** Chunk i is a free chunk that has been unlinked. Adjust its
  21343. ** size parameters for check-out and return a pointer to the
  21344. ** user portion of the chunk.
  21345. */
  21346. static void *memsys3Checkout(u32 i, u32 nBlock){
  21347. u32 x;
  21348. assert( sqlite3_mutex_held(mem3.mutex) );
  21349. assert( i>=1 );
  21350. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  21351. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  21352. x = mem3.aPool[i-1].u.hdr.size4x;
  21353. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  21354. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  21355. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  21356. return &mem3.aPool[i];
  21357. }
  21358. /*
  21359. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  21360. ** Return a pointer to the new allocation. Or, if the master chunk
  21361. ** is not large enough, return 0.
  21362. */
  21363. static void *memsys3FromMaster(u32 nBlock){
  21364. assert( sqlite3_mutex_held(mem3.mutex) );
  21365. assert( mem3.szMaster>=nBlock );
  21366. if( nBlock>=mem3.szMaster-1 ){
  21367. /* Use the entire master */
  21368. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  21369. mem3.iMaster = 0;
  21370. mem3.szMaster = 0;
  21371. mem3.mnMaster = 0;
  21372. return p;
  21373. }else{
  21374. /* Split the master block. Return the tail. */
  21375. u32 newi, x;
  21376. newi = mem3.iMaster + mem3.szMaster - nBlock;
  21377. assert( newi > mem3.iMaster+1 );
  21378. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  21379. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  21380. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  21381. mem3.szMaster -= nBlock;
  21382. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  21383. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  21384. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  21385. if( mem3.szMaster < mem3.mnMaster ){
  21386. mem3.mnMaster = mem3.szMaster;
  21387. }
  21388. return (void*)&mem3.aPool[newi];
  21389. }
  21390. }
  21391. /*
  21392. ** *pRoot is the head of a list of free chunks of the same size
  21393. ** or same size hash. In other words, *pRoot is an entry in either
  21394. ** mem3.aiSmall[] or mem3.aiHash[].
  21395. **
  21396. ** This routine examines all entries on the given list and tries
  21397. ** to coalesce each entries with adjacent free chunks.
  21398. **
  21399. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  21400. ** the current mem3.iMaster with the new larger chunk. In order for
  21401. ** this mem3.iMaster replacement to work, the master chunk must be
  21402. ** linked into the hash tables. That is not the normal state of
  21403. ** affairs, of course. The calling routine must link the master
  21404. ** chunk before invoking this routine, then must unlink the (possibly
  21405. ** changed) master chunk once this routine has finished.
  21406. */
  21407. static void memsys3Merge(u32 *pRoot){
  21408. u32 iNext, prev, size, i, x;
  21409. assert( sqlite3_mutex_held(mem3.mutex) );
  21410. for(i=*pRoot; i>0; i=iNext){
  21411. iNext = mem3.aPool[i].u.list.next;
  21412. size = mem3.aPool[i-1].u.hdr.size4x;
  21413. assert( (size&1)==0 );
  21414. if( (size&2)==0 ){
  21415. memsys3UnlinkFromList(i, pRoot);
  21416. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  21417. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  21418. if( prev==iNext ){
  21419. iNext = mem3.aPool[prev].u.list.next;
  21420. }
  21421. memsys3Unlink(prev);
  21422. size = i + size/4 - prev;
  21423. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  21424. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  21425. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  21426. memsys3Link(prev);
  21427. i = prev;
  21428. }else{
  21429. size /= 4;
  21430. }
  21431. if( size>mem3.szMaster ){
  21432. mem3.iMaster = i;
  21433. mem3.szMaster = size;
  21434. }
  21435. }
  21436. }
  21437. /*
  21438. ** Return a block of memory of at least nBytes in size.
  21439. ** Return NULL if unable.
  21440. **
  21441. ** This function assumes that the necessary mutexes, if any, are
  21442. ** already held by the caller. Hence "Unsafe".
  21443. */
  21444. static void *memsys3MallocUnsafe(int nByte){
  21445. u32 i;
  21446. u32 nBlock;
  21447. u32 toFree;
  21448. assert( sqlite3_mutex_held(mem3.mutex) );
  21449. assert( sizeof(Mem3Block)==8 );
  21450. if( nByte<=12 ){
  21451. nBlock = 2;
  21452. }else{
  21453. nBlock = (nByte + 11)/8;
  21454. }
  21455. assert( nBlock>=2 );
  21456. /* STEP 1:
  21457. ** Look for an entry of the correct size in either the small
  21458. ** chunk table or in the large chunk hash table. This is
  21459. ** successful most of the time (about 9 times out of 10).
  21460. */
  21461. if( nBlock <= MX_SMALL ){
  21462. i = mem3.aiSmall[nBlock-2];
  21463. if( i>0 ){
  21464. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  21465. return memsys3Checkout(i, nBlock);
  21466. }
  21467. }else{
  21468. int hash = nBlock % N_HASH;
  21469. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  21470. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  21471. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  21472. return memsys3Checkout(i, nBlock);
  21473. }
  21474. }
  21475. }
  21476. /* STEP 2:
  21477. ** Try to satisfy the allocation by carving a piece off of the end
  21478. ** of the master chunk. This step usually works if step 1 fails.
  21479. */
  21480. if( mem3.szMaster>=nBlock ){
  21481. return memsys3FromMaster(nBlock);
  21482. }
  21483. /* STEP 3:
  21484. ** Loop through the entire memory pool. Coalesce adjacent free
  21485. ** chunks. Recompute the master chunk as the largest free chunk.
  21486. ** Then try again to satisfy the allocation by carving a piece off
  21487. ** of the end of the master chunk. This step happens very
  21488. ** rarely (we hope!)
  21489. */
  21490. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  21491. memsys3OutOfMemory(toFree);
  21492. if( mem3.iMaster ){
  21493. memsys3Link(mem3.iMaster);
  21494. mem3.iMaster = 0;
  21495. mem3.szMaster = 0;
  21496. }
  21497. for(i=0; i<N_HASH; i++){
  21498. memsys3Merge(&mem3.aiHash[i]);
  21499. }
  21500. for(i=0; i<MX_SMALL-1; i++){
  21501. memsys3Merge(&mem3.aiSmall[i]);
  21502. }
  21503. if( mem3.szMaster ){
  21504. memsys3Unlink(mem3.iMaster);
  21505. if( mem3.szMaster>=nBlock ){
  21506. return memsys3FromMaster(nBlock);
  21507. }
  21508. }
  21509. }
  21510. /* If none of the above worked, then we fail. */
  21511. return 0;
  21512. }
  21513. /*
  21514. ** Free an outstanding memory allocation.
  21515. **
  21516. ** This function assumes that the necessary mutexes, if any, are
  21517. ** already held by the caller. Hence "Unsafe".
  21518. */
  21519. static void memsys3FreeUnsafe(void *pOld){
  21520. Mem3Block *p = (Mem3Block*)pOld;
  21521. int i;
  21522. u32 size, x;
  21523. assert( sqlite3_mutex_held(mem3.mutex) );
  21524. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  21525. i = p - mem3.aPool;
  21526. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  21527. size = mem3.aPool[i-1].u.hdr.size4x/4;
  21528. assert( i+size<=mem3.nPool+1 );
  21529. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  21530. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  21531. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  21532. memsys3Link(i);
  21533. /* Try to expand the master using the newly freed chunk */
  21534. if( mem3.iMaster ){
  21535. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  21536. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  21537. mem3.iMaster -= size;
  21538. mem3.szMaster += size;
  21539. memsys3Unlink(mem3.iMaster);
  21540. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  21541. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  21542. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  21543. }
  21544. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  21545. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  21546. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  21547. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  21548. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  21549. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  21550. }
  21551. }
  21552. }
  21553. /*
  21554. ** Return the size of an outstanding allocation, in bytes. The
  21555. ** size returned omits the 8-byte header overhead. This only
  21556. ** works for chunks that are currently checked out.
  21557. */
  21558. static int memsys3Size(void *p){
  21559. Mem3Block *pBlock;
  21560. assert( p!=0 );
  21561. pBlock = (Mem3Block*)p;
  21562. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  21563. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  21564. }
  21565. /*
  21566. ** Round up a request size to the next valid allocation size.
  21567. */
  21568. static int memsys3Roundup(int n){
  21569. if( n<=12 ){
  21570. return 12;
  21571. }else{
  21572. return ((n+11)&~7) - 4;
  21573. }
  21574. }
  21575. /*
  21576. ** Allocate nBytes of memory.
  21577. */
  21578. static void *memsys3Malloc(int nBytes){
  21579. sqlite3_int64 *p;
  21580. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  21581. memsys3Enter();
  21582. p = memsys3MallocUnsafe(nBytes);
  21583. memsys3Leave();
  21584. return (void*)p;
  21585. }
  21586. /*
  21587. ** Free memory.
  21588. */
  21589. static void memsys3Free(void *pPrior){
  21590. assert( pPrior );
  21591. memsys3Enter();
  21592. memsys3FreeUnsafe(pPrior);
  21593. memsys3Leave();
  21594. }
  21595. /*
  21596. ** Change the size of an existing memory allocation
  21597. */
  21598. static void *memsys3Realloc(void *pPrior, int nBytes){
  21599. int nOld;
  21600. void *p;
  21601. if( pPrior==0 ){
  21602. return sqlite3_malloc(nBytes);
  21603. }
  21604. if( nBytes<=0 ){
  21605. sqlite3_free(pPrior);
  21606. return 0;
  21607. }
  21608. nOld = memsys3Size(pPrior);
  21609. if( nBytes<=nOld && nBytes>=nOld-128 ){
  21610. return pPrior;
  21611. }
  21612. memsys3Enter();
  21613. p = memsys3MallocUnsafe(nBytes);
  21614. if( p ){
  21615. if( nOld<nBytes ){
  21616. memcpy(p, pPrior, nOld);
  21617. }else{
  21618. memcpy(p, pPrior, nBytes);
  21619. }
  21620. memsys3FreeUnsafe(pPrior);
  21621. }
  21622. memsys3Leave();
  21623. return p;
  21624. }
  21625. /*
  21626. ** Initialize this module.
  21627. */
  21628. static int memsys3Init(void *NotUsed){
  21629. UNUSED_PARAMETER(NotUsed);
  21630. if( !sqlite3GlobalConfig.pHeap ){
  21631. return SQLITE_ERROR;
  21632. }
  21633. /* Store a pointer to the memory block in global structure mem3. */
  21634. assert( sizeof(Mem3Block)==8 );
  21635. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  21636. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  21637. /* Initialize the master block. */
  21638. mem3.szMaster = mem3.nPool;
  21639. mem3.mnMaster = mem3.szMaster;
  21640. mem3.iMaster = 1;
  21641. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  21642. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  21643. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  21644. return SQLITE_OK;
  21645. }
  21646. /*
  21647. ** Deinitialize this module.
  21648. */
  21649. static void memsys3Shutdown(void *NotUsed){
  21650. UNUSED_PARAMETER(NotUsed);
  21651. mem3.mutex = 0;
  21652. return;
  21653. }
  21654. /*
  21655. ** Open the file indicated and write a log of all unfreed memory
  21656. ** allocations into that log.
  21657. */
  21658. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  21659. #ifdef SQLITE_DEBUG
  21660. FILE *out;
  21661. u32 i, j;
  21662. u32 size;
  21663. if( zFilename==0 || zFilename[0]==0 ){
  21664. out = stdout;
  21665. }else{
  21666. out = fopen(zFilename, "w");
  21667. if( out==0 ){
  21668. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21669. zFilename);
  21670. return;
  21671. }
  21672. }
  21673. memsys3Enter();
  21674. fprintf(out, "CHUNKS:\n");
  21675. for(i=1; i<=mem3.nPool; i+=size/4){
  21676. size = mem3.aPool[i-1].u.hdr.size4x;
  21677. if( size/4<=1 ){
  21678. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  21679. assert( 0 );
  21680. break;
  21681. }
  21682. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  21683. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  21684. assert( 0 );
  21685. break;
  21686. }
  21687. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  21688. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  21689. assert( 0 );
  21690. break;
  21691. }
  21692. if( size&1 ){
  21693. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  21694. }else{
  21695. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  21696. i==mem3.iMaster ? " **master**" : "");
  21697. }
  21698. }
  21699. for(i=0; i<MX_SMALL-1; i++){
  21700. if( mem3.aiSmall[i]==0 ) continue;
  21701. fprintf(out, "small(%2d):", i);
  21702. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  21703. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21704. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21705. }
  21706. fprintf(out, "\n");
  21707. }
  21708. for(i=0; i<N_HASH; i++){
  21709. if( mem3.aiHash[i]==0 ) continue;
  21710. fprintf(out, "hash(%2d):", i);
  21711. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  21712. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21713. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21714. }
  21715. fprintf(out, "\n");
  21716. }
  21717. fprintf(out, "master=%d\n", mem3.iMaster);
  21718. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  21719. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  21720. sqlite3_mutex_leave(mem3.mutex);
  21721. if( out==stdout ){
  21722. fflush(stdout);
  21723. }else{
  21724. fclose(out);
  21725. }
  21726. #else
  21727. UNUSED_PARAMETER(zFilename);
  21728. #endif
  21729. }
  21730. /*
  21731. ** This routine is the only routine in this file with external
  21732. ** linkage.
  21733. **
  21734. ** Populate the low-level memory allocation function pointers in
  21735. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  21736. ** arguments specify the block of memory to manage.
  21737. **
  21738. ** This routine is only called by sqlite3_config(), and therefore
  21739. ** is not required to be threadsafe (it is not).
  21740. */
  21741. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  21742. static const sqlite3_mem_methods mempoolMethods = {
  21743. memsys3Malloc,
  21744. memsys3Free,
  21745. memsys3Realloc,
  21746. memsys3Size,
  21747. memsys3Roundup,
  21748. memsys3Init,
  21749. memsys3Shutdown,
  21750. 0
  21751. };
  21752. return &mempoolMethods;
  21753. }
  21754. #endif /* SQLITE_ENABLE_MEMSYS3 */
  21755. /************** End of mem3.c ************************************************/
  21756. /************** Begin file mem5.c ********************************************/
  21757. /*
  21758. ** 2007 October 14
  21759. **
  21760. ** The author disclaims copyright to this source code. In place of
  21761. ** a legal notice, here is a blessing:
  21762. **
  21763. ** May you do good and not evil.
  21764. ** May you find forgiveness for yourself and forgive others.
  21765. ** May you share freely, never taking more than you give.
  21766. **
  21767. *************************************************************************
  21768. ** This file contains the C functions that implement a memory
  21769. ** allocation subsystem for use by SQLite.
  21770. **
  21771. ** This version of the memory allocation subsystem omits all
  21772. ** use of malloc(). The application gives SQLite a block of memory
  21773. ** before calling sqlite3_initialize() from which allocations
  21774. ** are made and returned by the xMalloc() and xRealloc()
  21775. ** implementations. Once sqlite3_initialize() has been called,
  21776. ** the amount of memory available to SQLite is fixed and cannot
  21777. ** be changed.
  21778. **
  21779. ** This version of the memory allocation subsystem is included
  21780. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  21781. **
  21782. ** This memory allocator uses the following algorithm:
  21783. **
  21784. ** 1. All memory allocation sizes are rounded up to a power of 2.
  21785. **
  21786. ** 2. If two adjacent free blocks are the halves of a larger block,
  21787. ** then the two blocks are coalesced into the single larger block.
  21788. **
  21789. ** 3. New memory is allocated from the first available free block.
  21790. **
  21791. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  21792. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  21793. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  21794. **
  21795. ** Let n be the size of the largest allocation divided by the minimum
  21796. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  21797. ** be the maximum amount of memory ever outstanding at one time. Let
  21798. ** N be the total amount of memory available for allocation. Robson
  21799. ** proved that this memory allocator will never breakdown due to
  21800. ** fragmentation as long as the following constraint holds:
  21801. **
  21802. ** N >= M*(1 + log2(n)/2) - n + 1
  21803. **
  21804. ** The sqlite3_status() logic tracks the maximum values of n and M so
  21805. ** that an application can, at any time, verify this constraint.
  21806. */
  21807. /* #include "sqliteInt.h" */
  21808. /*
  21809. ** This version of the memory allocator is used only when
  21810. ** SQLITE_ENABLE_MEMSYS5 is defined.
  21811. */
  21812. #ifdef SQLITE_ENABLE_MEMSYS5
  21813. /*
  21814. ** A minimum allocation is an instance of the following structure.
  21815. ** Larger allocations are an array of these structures where the
  21816. ** size of the array is a power of 2.
  21817. **
  21818. ** The size of this object must be a power of two. That fact is
  21819. ** verified in memsys5Init().
  21820. */
  21821. typedef struct Mem5Link Mem5Link;
  21822. struct Mem5Link {
  21823. int next; /* Index of next free chunk */
  21824. int prev; /* Index of previous free chunk */
  21825. };
  21826. /*
  21827. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  21828. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  21829. ** it is not actually possible to reach this limit.
  21830. */
  21831. #define LOGMAX 30
  21832. /*
  21833. ** Masks used for mem5.aCtrl[] elements.
  21834. */
  21835. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  21836. #define CTRL_FREE 0x20 /* True if not checked out */
  21837. /*
  21838. ** All of the static variables used by this module are collected
  21839. ** into a single structure named "mem5". This is to keep the
  21840. ** static variables organized and to reduce namespace pollution
  21841. ** when this module is combined with other in the amalgamation.
  21842. */
  21843. static SQLITE_WSD struct Mem5Global {
  21844. /*
  21845. ** Memory available for allocation
  21846. */
  21847. int szAtom; /* Smallest possible allocation in bytes */
  21848. int nBlock; /* Number of szAtom sized blocks in zPool */
  21849. u8 *zPool; /* Memory available to be allocated */
  21850. /*
  21851. ** Mutex to control access to the memory allocation subsystem.
  21852. */
  21853. sqlite3_mutex *mutex;
  21854. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21855. /*
  21856. ** Performance statistics
  21857. */
  21858. u64 nAlloc; /* Total number of calls to malloc */
  21859. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  21860. u64 totalExcess; /* Total internal fragmentation */
  21861. u32 currentOut; /* Current checkout, including internal fragmentation */
  21862. u32 currentCount; /* Current number of distinct checkouts */
  21863. u32 maxOut; /* Maximum instantaneous currentOut */
  21864. u32 maxCount; /* Maximum instantaneous currentCount */
  21865. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  21866. #endif
  21867. /*
  21868. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  21869. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  21870. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  21871. */
  21872. int aiFreelist[LOGMAX+1];
  21873. /*
  21874. ** Space for tracking which blocks are checked out and the size
  21875. ** of each block. One byte per block.
  21876. */
  21877. u8 *aCtrl;
  21878. } mem5;
  21879. /*
  21880. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  21881. */
  21882. #define mem5 GLOBAL(struct Mem5Global, mem5)
  21883. /*
  21884. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  21885. ** structures, return a pointer to the idx-th such link.
  21886. */
  21887. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  21888. /*
  21889. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  21890. ** on. It should be found on mem5.aiFreelist[iLogsize].
  21891. */
  21892. static void memsys5Unlink(int i, int iLogsize){
  21893. int next, prev;
  21894. assert( i>=0 && i<mem5.nBlock );
  21895. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21896. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21897. next = MEM5LINK(i)->next;
  21898. prev = MEM5LINK(i)->prev;
  21899. if( prev<0 ){
  21900. mem5.aiFreelist[iLogsize] = next;
  21901. }else{
  21902. MEM5LINK(prev)->next = next;
  21903. }
  21904. if( next>=0 ){
  21905. MEM5LINK(next)->prev = prev;
  21906. }
  21907. }
  21908. /*
  21909. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  21910. ** free list.
  21911. */
  21912. static void memsys5Link(int i, int iLogsize){
  21913. int x;
  21914. assert( sqlite3_mutex_held(mem5.mutex) );
  21915. assert( i>=0 && i<mem5.nBlock );
  21916. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21917. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21918. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  21919. MEM5LINK(i)->prev = -1;
  21920. if( x>=0 ){
  21921. assert( x<mem5.nBlock );
  21922. MEM5LINK(x)->prev = i;
  21923. }
  21924. mem5.aiFreelist[iLogsize] = i;
  21925. }
  21926. /*
  21927. ** Obtain or release the mutex needed to access global data structures.
  21928. */
  21929. static void memsys5Enter(void){
  21930. sqlite3_mutex_enter(mem5.mutex);
  21931. }
  21932. static void memsys5Leave(void){
  21933. sqlite3_mutex_leave(mem5.mutex);
  21934. }
  21935. /*
  21936. ** Return the size of an outstanding allocation, in bytes.
  21937. ** This only works for chunks that are currently checked out.
  21938. */
  21939. static int memsys5Size(void *p){
  21940. int iSize, i;
  21941. assert( p!=0 );
  21942. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  21943. assert( i>=0 && i<mem5.nBlock );
  21944. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  21945. return iSize;
  21946. }
  21947. /*
  21948. ** Return a block of memory of at least nBytes in size.
  21949. ** Return NULL if unable. Return NULL if nBytes==0.
  21950. **
  21951. ** The caller guarantees that nByte is positive.
  21952. **
  21953. ** The caller has obtained a mutex prior to invoking this
  21954. ** routine so there is never any chance that two or more
  21955. ** threads can be in this routine at the same time.
  21956. */
  21957. static void *memsys5MallocUnsafe(int nByte){
  21958. int i; /* Index of a mem5.aPool[] slot */
  21959. int iBin; /* Index into mem5.aiFreelist[] */
  21960. int iFullSz; /* Size of allocation rounded up to power of 2 */
  21961. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  21962. /* nByte must be a positive */
  21963. assert( nByte>0 );
  21964. /* No more than 1GiB per allocation */
  21965. if( nByte > 0x40000000 ) return 0;
  21966. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21967. /* Keep track of the maximum allocation request. Even unfulfilled
  21968. ** requests are counted */
  21969. if( (u32)nByte>mem5.maxRequest ){
  21970. mem5.maxRequest = nByte;
  21971. }
  21972. #endif
  21973. /* Round nByte up to the next valid power of two */
  21974. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  21975. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  21976. ** block. If not, then split a block of the next larger power of
  21977. ** two in order to create a new free block of size iLogsize.
  21978. */
  21979. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  21980. if( iBin>LOGMAX ){
  21981. testcase( sqlite3GlobalConfig.xLog!=0 );
  21982. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  21983. return 0;
  21984. }
  21985. i = mem5.aiFreelist[iBin];
  21986. memsys5Unlink(i, iBin);
  21987. while( iBin>iLogsize ){
  21988. int newSize;
  21989. iBin--;
  21990. newSize = 1 << iBin;
  21991. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  21992. memsys5Link(i+newSize, iBin);
  21993. }
  21994. mem5.aCtrl[i] = iLogsize;
  21995. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21996. /* Update allocator performance statistics. */
  21997. mem5.nAlloc++;
  21998. mem5.totalAlloc += iFullSz;
  21999. mem5.totalExcess += iFullSz - nByte;
  22000. mem5.currentCount++;
  22001. mem5.currentOut += iFullSz;
  22002. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  22003. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  22004. #endif
  22005. #ifdef SQLITE_DEBUG
  22006. /* Make sure the allocated memory does not assume that it is set to zero
  22007. ** or retains a value from a previous allocation */
  22008. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  22009. #endif
  22010. /* Return a pointer to the allocated memory. */
  22011. return (void*)&mem5.zPool[i*mem5.szAtom];
  22012. }
  22013. /*
  22014. ** Free an outstanding memory allocation.
  22015. */
  22016. static void memsys5FreeUnsafe(void *pOld){
  22017. u32 size, iLogsize;
  22018. int iBlock;
  22019. /* Set iBlock to the index of the block pointed to by pOld in
  22020. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  22021. */
  22022. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  22023. /* Check that the pointer pOld points to a valid, non-free block. */
  22024. assert( iBlock>=0 && iBlock<mem5.nBlock );
  22025. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  22026. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  22027. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  22028. size = 1<<iLogsize;
  22029. assert( iBlock+size-1<(u32)mem5.nBlock );
  22030. mem5.aCtrl[iBlock] |= CTRL_FREE;
  22031. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  22032. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22033. assert( mem5.currentCount>0 );
  22034. assert( mem5.currentOut>=(size*mem5.szAtom) );
  22035. mem5.currentCount--;
  22036. mem5.currentOut -= size*mem5.szAtom;
  22037. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  22038. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  22039. #endif
  22040. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22041. while( ALWAYS(iLogsize<LOGMAX) ){
  22042. int iBuddy;
  22043. if( (iBlock>>iLogsize) & 1 ){
  22044. iBuddy = iBlock - size;
  22045. assert( iBuddy>=0 );
  22046. }else{
  22047. iBuddy = iBlock + size;
  22048. if( iBuddy>=mem5.nBlock ) break;
  22049. }
  22050. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  22051. memsys5Unlink(iBuddy, iLogsize);
  22052. iLogsize++;
  22053. if( iBuddy<iBlock ){
  22054. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  22055. mem5.aCtrl[iBlock] = 0;
  22056. iBlock = iBuddy;
  22057. }else{
  22058. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22059. mem5.aCtrl[iBuddy] = 0;
  22060. }
  22061. size *= 2;
  22062. }
  22063. #ifdef SQLITE_DEBUG
  22064. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  22065. ** not used after being freed */
  22066. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  22067. #endif
  22068. memsys5Link(iBlock, iLogsize);
  22069. }
  22070. /*
  22071. ** Allocate nBytes of memory.
  22072. */
  22073. static void *memsys5Malloc(int nBytes){
  22074. sqlite3_int64 *p = 0;
  22075. if( nBytes>0 ){
  22076. memsys5Enter();
  22077. p = memsys5MallocUnsafe(nBytes);
  22078. memsys5Leave();
  22079. }
  22080. return (void*)p;
  22081. }
  22082. /*
  22083. ** Free memory.
  22084. **
  22085. ** The outer layer memory allocator prevents this routine from
  22086. ** being called with pPrior==0.
  22087. */
  22088. static void memsys5Free(void *pPrior){
  22089. assert( pPrior!=0 );
  22090. memsys5Enter();
  22091. memsys5FreeUnsafe(pPrior);
  22092. memsys5Leave();
  22093. }
  22094. /*
  22095. ** Change the size of an existing memory allocation.
  22096. **
  22097. ** The outer layer memory allocator prevents this routine from
  22098. ** being called with pPrior==0.
  22099. **
  22100. ** nBytes is always a value obtained from a prior call to
  22101. ** memsys5Round(). Hence nBytes is always a non-negative power
  22102. ** of two. If nBytes==0 that means that an oversize allocation
  22103. ** (an allocation larger than 0x40000000) was requested and this
  22104. ** routine should return 0 without freeing pPrior.
  22105. */
  22106. static void *memsys5Realloc(void *pPrior, int nBytes){
  22107. int nOld;
  22108. void *p;
  22109. assert( pPrior!=0 );
  22110. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  22111. assert( nBytes>=0 );
  22112. if( nBytes==0 ){
  22113. return 0;
  22114. }
  22115. nOld = memsys5Size(pPrior);
  22116. if( nBytes<=nOld ){
  22117. return pPrior;
  22118. }
  22119. p = memsys5Malloc(nBytes);
  22120. if( p ){
  22121. memcpy(p, pPrior, nOld);
  22122. memsys5Free(pPrior);
  22123. }
  22124. return p;
  22125. }
  22126. /*
  22127. ** Round up a request size to the next valid allocation size. If
  22128. ** the allocation is too large to be handled by this allocation system,
  22129. ** return 0.
  22130. **
  22131. ** All allocations must be a power of two and must be expressed by a
  22132. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  22133. ** or 1073741824 bytes.
  22134. */
  22135. static int memsys5Roundup(int n){
  22136. int iFullSz;
  22137. if( n > 0x40000000 ) return 0;
  22138. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  22139. return iFullSz;
  22140. }
  22141. /*
  22142. ** Return the ceiling of the logarithm base 2 of iValue.
  22143. **
  22144. ** Examples: memsys5Log(1) -> 0
  22145. ** memsys5Log(2) -> 1
  22146. ** memsys5Log(4) -> 2
  22147. ** memsys5Log(5) -> 3
  22148. ** memsys5Log(8) -> 3
  22149. ** memsys5Log(9) -> 4
  22150. */
  22151. static int memsys5Log(int iValue){
  22152. int iLog;
  22153. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  22154. return iLog;
  22155. }
  22156. /*
  22157. ** Initialize the memory allocator.
  22158. **
  22159. ** This routine is not threadsafe. The caller must be holding a mutex
  22160. ** to prevent multiple threads from entering at the same time.
  22161. */
  22162. static int memsys5Init(void *NotUsed){
  22163. int ii; /* Loop counter */
  22164. int nByte; /* Number of bytes of memory available to this allocator */
  22165. u8 *zByte; /* Memory usable by this allocator */
  22166. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  22167. int iOffset; /* An offset into mem5.aCtrl[] */
  22168. UNUSED_PARAMETER(NotUsed);
  22169. /* For the purposes of this routine, disable the mutex */
  22170. mem5.mutex = 0;
  22171. /* The size of a Mem5Link object must be a power of two. Verify that
  22172. ** this is case.
  22173. */
  22174. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  22175. nByte = sqlite3GlobalConfig.nHeap;
  22176. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  22177. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  22178. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  22179. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  22180. mem5.szAtom = (1<<nMinLog);
  22181. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  22182. mem5.szAtom = mem5.szAtom << 1;
  22183. }
  22184. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  22185. mem5.zPool = zByte;
  22186. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  22187. for(ii=0; ii<=LOGMAX; ii++){
  22188. mem5.aiFreelist[ii] = -1;
  22189. }
  22190. iOffset = 0;
  22191. for(ii=LOGMAX; ii>=0; ii--){
  22192. int nAlloc = (1<<ii);
  22193. if( (iOffset+nAlloc)<=mem5.nBlock ){
  22194. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  22195. memsys5Link(iOffset, ii);
  22196. iOffset += nAlloc;
  22197. }
  22198. assert((iOffset+nAlloc)>mem5.nBlock);
  22199. }
  22200. /* If a mutex is required for normal operation, allocate one */
  22201. if( sqlite3GlobalConfig.bMemstat==0 ){
  22202. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22203. }
  22204. return SQLITE_OK;
  22205. }
  22206. /*
  22207. ** Deinitialize this module.
  22208. */
  22209. static void memsys5Shutdown(void *NotUsed){
  22210. UNUSED_PARAMETER(NotUsed);
  22211. mem5.mutex = 0;
  22212. return;
  22213. }
  22214. #ifdef SQLITE_TEST
  22215. /*
  22216. ** Open the file indicated and write a log of all unfreed memory
  22217. ** allocations into that log.
  22218. */
  22219. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  22220. FILE *out;
  22221. int i, j, n;
  22222. int nMinLog;
  22223. if( zFilename==0 || zFilename[0]==0 ){
  22224. out = stdout;
  22225. }else{
  22226. out = fopen(zFilename, "w");
  22227. if( out==0 ){
  22228. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22229. zFilename);
  22230. return;
  22231. }
  22232. }
  22233. memsys5Enter();
  22234. nMinLog = memsys5Log(mem5.szAtom);
  22235. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  22236. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  22237. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  22238. }
  22239. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  22240. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  22241. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  22242. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  22243. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  22244. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  22245. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  22246. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  22247. memsys5Leave();
  22248. if( out==stdout ){
  22249. fflush(stdout);
  22250. }else{
  22251. fclose(out);
  22252. }
  22253. }
  22254. #endif
  22255. /*
  22256. ** This routine is the only routine in this file with external
  22257. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  22258. ** struct populated with the memsys5 methods.
  22259. */
  22260. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  22261. static const sqlite3_mem_methods memsys5Methods = {
  22262. memsys5Malloc,
  22263. memsys5Free,
  22264. memsys5Realloc,
  22265. memsys5Size,
  22266. memsys5Roundup,
  22267. memsys5Init,
  22268. memsys5Shutdown,
  22269. 0
  22270. };
  22271. return &memsys5Methods;
  22272. }
  22273. #endif /* SQLITE_ENABLE_MEMSYS5 */
  22274. /************** End of mem5.c ************************************************/
  22275. /************** Begin file mutex.c *******************************************/
  22276. /*
  22277. ** 2007 August 14
  22278. **
  22279. ** The author disclaims copyright to this source code. In place of
  22280. ** a legal notice, here is a blessing:
  22281. **
  22282. ** May you do good and not evil.
  22283. ** May you find forgiveness for yourself and forgive others.
  22284. ** May you share freely, never taking more than you give.
  22285. **
  22286. *************************************************************************
  22287. ** This file contains the C functions that implement mutexes.
  22288. **
  22289. ** This file contains code that is common across all mutex implementations.
  22290. */
  22291. /* #include "sqliteInt.h" */
  22292. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  22293. /*
  22294. ** For debugging purposes, record when the mutex subsystem is initialized
  22295. ** and uninitialized so that we can assert() if there is an attempt to
  22296. ** allocate a mutex while the system is uninitialized.
  22297. */
  22298. static SQLITE_WSD int mutexIsInit = 0;
  22299. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  22300. #ifndef SQLITE_MUTEX_OMIT
  22301. /*
  22302. ** Initialize the mutex system.
  22303. */
  22304. SQLITE_PRIVATE int sqlite3MutexInit(void){
  22305. int rc = SQLITE_OK;
  22306. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  22307. /* If the xMutexAlloc method has not been set, then the user did not
  22308. ** install a mutex implementation via sqlite3_config() prior to
  22309. ** sqlite3_initialize() being called. This block copies pointers to
  22310. ** the default implementation into the sqlite3GlobalConfig structure.
  22311. */
  22312. sqlite3_mutex_methods const *pFrom;
  22313. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  22314. if( sqlite3GlobalConfig.bCoreMutex ){
  22315. pFrom = sqlite3DefaultMutex();
  22316. }else{
  22317. pFrom = sqlite3NoopMutex();
  22318. }
  22319. pTo->xMutexInit = pFrom->xMutexInit;
  22320. pTo->xMutexEnd = pFrom->xMutexEnd;
  22321. pTo->xMutexFree = pFrom->xMutexFree;
  22322. pTo->xMutexEnter = pFrom->xMutexEnter;
  22323. pTo->xMutexTry = pFrom->xMutexTry;
  22324. pTo->xMutexLeave = pFrom->xMutexLeave;
  22325. pTo->xMutexHeld = pFrom->xMutexHeld;
  22326. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  22327. sqlite3MemoryBarrier();
  22328. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  22329. }
  22330. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  22331. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  22332. #ifdef SQLITE_DEBUG
  22333. GLOBAL(int, mutexIsInit) = 1;
  22334. #endif
  22335. return rc;
  22336. }
  22337. /*
  22338. ** Shutdown the mutex system. This call frees resources allocated by
  22339. ** sqlite3MutexInit().
  22340. */
  22341. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  22342. int rc = SQLITE_OK;
  22343. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  22344. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  22345. }
  22346. #ifdef SQLITE_DEBUG
  22347. GLOBAL(int, mutexIsInit) = 0;
  22348. #endif
  22349. return rc;
  22350. }
  22351. /*
  22352. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  22353. */
  22354. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  22355. #ifndef SQLITE_OMIT_AUTOINIT
  22356. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  22357. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  22358. #endif
  22359. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  22360. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  22361. }
  22362. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  22363. if( !sqlite3GlobalConfig.bCoreMutex ){
  22364. return 0;
  22365. }
  22366. assert( GLOBAL(int, mutexIsInit) );
  22367. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  22368. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  22369. }
  22370. /*
  22371. ** Free a dynamic mutex.
  22372. */
  22373. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  22374. if( p ){
  22375. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  22376. sqlite3GlobalConfig.mutex.xMutexFree(p);
  22377. }
  22378. }
  22379. /*
  22380. ** Obtain the mutex p. If some other thread already has the mutex, block
  22381. ** until it can be obtained.
  22382. */
  22383. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  22384. if( p ){
  22385. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  22386. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  22387. }
  22388. }
  22389. /*
  22390. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  22391. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  22392. */
  22393. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  22394. int rc = SQLITE_OK;
  22395. if( p ){
  22396. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  22397. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  22398. }
  22399. return rc;
  22400. }
  22401. /*
  22402. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  22403. ** entered by the same thread. The behavior is undefined if the mutex
  22404. ** is not currently entered. If a NULL pointer is passed as an argument
  22405. ** this function is a no-op.
  22406. */
  22407. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  22408. if( p ){
  22409. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  22410. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  22411. }
  22412. }
  22413. #ifndef NDEBUG
  22414. /*
  22415. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22416. ** intended for use inside assert() statements.
  22417. */
  22418. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  22419. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  22420. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  22421. }
  22422. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  22423. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  22424. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  22425. }
  22426. #endif
  22427. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  22428. /************** End of mutex.c ***********************************************/
  22429. /************** Begin file mutex_noop.c **************************************/
  22430. /*
  22431. ** 2008 October 07
  22432. **
  22433. ** The author disclaims copyright to this source code. In place of
  22434. ** a legal notice, here is a blessing:
  22435. **
  22436. ** May you do good and not evil.
  22437. ** May you find forgiveness for yourself and forgive others.
  22438. ** May you share freely, never taking more than you give.
  22439. **
  22440. *************************************************************************
  22441. ** This file contains the C functions that implement mutexes.
  22442. **
  22443. ** This implementation in this file does not provide any mutual
  22444. ** exclusion and is thus suitable for use only in applications
  22445. ** that use SQLite in a single thread. The routines defined
  22446. ** here are place-holders. Applications can substitute working
  22447. ** mutex routines at start-time using the
  22448. **
  22449. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  22450. **
  22451. ** interface.
  22452. **
  22453. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  22454. ** that does error checking on mutexes to make sure they are being
  22455. ** called correctly.
  22456. */
  22457. /* #include "sqliteInt.h" */
  22458. #ifndef SQLITE_MUTEX_OMIT
  22459. #ifndef SQLITE_DEBUG
  22460. /*
  22461. ** Stub routines for all mutex methods.
  22462. **
  22463. ** This routines provide no mutual exclusion or error checking.
  22464. */
  22465. static int noopMutexInit(void){ return SQLITE_OK; }
  22466. static int noopMutexEnd(void){ return SQLITE_OK; }
  22467. static sqlite3_mutex *noopMutexAlloc(int id){
  22468. UNUSED_PARAMETER(id);
  22469. return (sqlite3_mutex*)8;
  22470. }
  22471. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  22472. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  22473. static int noopMutexTry(sqlite3_mutex *p){
  22474. UNUSED_PARAMETER(p);
  22475. return SQLITE_OK;
  22476. }
  22477. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  22478. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  22479. static const sqlite3_mutex_methods sMutex = {
  22480. noopMutexInit,
  22481. noopMutexEnd,
  22482. noopMutexAlloc,
  22483. noopMutexFree,
  22484. noopMutexEnter,
  22485. noopMutexTry,
  22486. noopMutexLeave,
  22487. 0,
  22488. 0,
  22489. };
  22490. return &sMutex;
  22491. }
  22492. #endif /* !SQLITE_DEBUG */
  22493. #ifdef SQLITE_DEBUG
  22494. /*
  22495. ** In this implementation, error checking is provided for testing
  22496. ** and debugging purposes. The mutexes still do not provide any
  22497. ** mutual exclusion.
  22498. */
  22499. /*
  22500. ** The mutex object
  22501. */
  22502. typedef struct sqlite3_debug_mutex {
  22503. int id; /* The mutex type */
  22504. int cnt; /* Number of entries without a matching leave */
  22505. } sqlite3_debug_mutex;
  22506. /*
  22507. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22508. ** intended for use inside assert() statements.
  22509. */
  22510. static int debugMutexHeld(sqlite3_mutex *pX){
  22511. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22512. return p==0 || p->cnt>0;
  22513. }
  22514. static int debugMutexNotheld(sqlite3_mutex *pX){
  22515. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22516. return p==0 || p->cnt==0;
  22517. }
  22518. /*
  22519. ** Initialize and deinitialize the mutex subsystem.
  22520. */
  22521. static int debugMutexInit(void){ return SQLITE_OK; }
  22522. static int debugMutexEnd(void){ return SQLITE_OK; }
  22523. /*
  22524. ** The sqlite3_mutex_alloc() routine allocates a new
  22525. ** mutex and returns a pointer to it. If it returns NULL
  22526. ** that means that a mutex could not be allocated.
  22527. */
  22528. static sqlite3_mutex *debugMutexAlloc(int id){
  22529. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  22530. sqlite3_debug_mutex *pNew = 0;
  22531. switch( id ){
  22532. case SQLITE_MUTEX_FAST:
  22533. case SQLITE_MUTEX_RECURSIVE: {
  22534. pNew = sqlite3Malloc(sizeof(*pNew));
  22535. if( pNew ){
  22536. pNew->id = id;
  22537. pNew->cnt = 0;
  22538. }
  22539. break;
  22540. }
  22541. default: {
  22542. #ifdef SQLITE_ENABLE_API_ARMOR
  22543. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  22544. (void)SQLITE_MISUSE_BKPT;
  22545. return 0;
  22546. }
  22547. #endif
  22548. pNew = &aStatic[id-2];
  22549. pNew->id = id;
  22550. break;
  22551. }
  22552. }
  22553. return (sqlite3_mutex*)pNew;
  22554. }
  22555. /*
  22556. ** This routine deallocates a previously allocated mutex.
  22557. */
  22558. static void debugMutexFree(sqlite3_mutex *pX){
  22559. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22560. assert( p->cnt==0 );
  22561. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  22562. sqlite3_free(p);
  22563. }else{
  22564. #ifdef SQLITE_ENABLE_API_ARMOR
  22565. (void)SQLITE_MISUSE_BKPT;
  22566. #endif
  22567. }
  22568. }
  22569. /*
  22570. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22571. ** to enter a mutex. If another thread is already within the mutex,
  22572. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22573. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22574. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22575. ** be entered multiple times by the same thread. In such cases the,
  22576. ** mutex must be exited an equal number of times before another thread
  22577. ** can enter. If the same thread tries to enter any other kind of mutex
  22578. ** more than once, the behavior is undefined.
  22579. */
  22580. static void debugMutexEnter(sqlite3_mutex *pX){
  22581. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22582. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  22583. p->cnt++;
  22584. }
  22585. static int debugMutexTry(sqlite3_mutex *pX){
  22586. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22587. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  22588. p->cnt++;
  22589. return SQLITE_OK;
  22590. }
  22591. /*
  22592. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22593. ** previously entered by the same thread. The behavior
  22594. ** is undefined if the mutex is not currently entered or
  22595. ** is not currently allocated. SQLite will never do either.
  22596. */
  22597. static void debugMutexLeave(sqlite3_mutex *pX){
  22598. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22599. assert( debugMutexHeld(pX) );
  22600. p->cnt--;
  22601. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  22602. }
  22603. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  22604. static const sqlite3_mutex_methods sMutex = {
  22605. debugMutexInit,
  22606. debugMutexEnd,
  22607. debugMutexAlloc,
  22608. debugMutexFree,
  22609. debugMutexEnter,
  22610. debugMutexTry,
  22611. debugMutexLeave,
  22612. debugMutexHeld,
  22613. debugMutexNotheld
  22614. };
  22615. return &sMutex;
  22616. }
  22617. #endif /* SQLITE_DEBUG */
  22618. /*
  22619. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  22620. ** is used regardless of the run-time threadsafety setting.
  22621. */
  22622. #ifdef SQLITE_MUTEX_NOOP
  22623. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22624. return sqlite3NoopMutex();
  22625. }
  22626. #endif /* defined(SQLITE_MUTEX_NOOP) */
  22627. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  22628. /************** End of mutex_noop.c ******************************************/
  22629. /************** Begin file mutex_unix.c **************************************/
  22630. /*
  22631. ** 2007 August 28
  22632. **
  22633. ** The author disclaims copyright to this source code. In place of
  22634. ** a legal notice, here is a blessing:
  22635. **
  22636. ** May you do good and not evil.
  22637. ** May you find forgiveness for yourself and forgive others.
  22638. ** May you share freely, never taking more than you give.
  22639. **
  22640. *************************************************************************
  22641. ** This file contains the C functions that implement mutexes for pthreads
  22642. */
  22643. /* #include "sqliteInt.h" */
  22644. /*
  22645. ** The code in this file is only used if we are compiling threadsafe
  22646. ** under unix with pthreads.
  22647. **
  22648. ** Note that this implementation requires a version of pthreads that
  22649. ** supports recursive mutexes.
  22650. */
  22651. #ifdef SQLITE_MUTEX_PTHREADS
  22652. #include <pthread.h>
  22653. /*
  22654. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  22655. ** are necessary under two condidtions: (1) Debug builds and (2) using
  22656. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  22657. */
  22658. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  22659. # define SQLITE_MUTEX_NREF 1
  22660. #else
  22661. # define SQLITE_MUTEX_NREF 0
  22662. #endif
  22663. /*
  22664. ** Each recursive mutex is an instance of the following structure.
  22665. */
  22666. struct sqlite3_mutex {
  22667. pthread_mutex_t mutex; /* Mutex controlling the lock */
  22668. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22669. int id; /* Mutex type */
  22670. #endif
  22671. #if SQLITE_MUTEX_NREF
  22672. volatile int nRef; /* Number of entrances */
  22673. volatile pthread_t owner; /* Thread that is within this mutex */
  22674. int trace; /* True to trace changes */
  22675. #endif
  22676. };
  22677. #if SQLITE_MUTEX_NREF
  22678. #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
  22679. #elif defined(SQLITE_ENABLE_API_ARMOR)
  22680. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
  22681. #else
  22682. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  22683. #endif
  22684. /*
  22685. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22686. ** intended for use only inside assert() statements. On some platforms,
  22687. ** there might be race conditions that can cause these routines to
  22688. ** deliver incorrect results. In particular, if pthread_equal() is
  22689. ** not an atomic operation, then these routines might delivery
  22690. ** incorrect results. On most platforms, pthread_equal() is a
  22691. ** comparison of two integers and is therefore atomic. But we are
  22692. ** told that HPUX is not such a platform. If so, then these routines
  22693. ** will not always work correctly on HPUX.
  22694. **
  22695. ** On those platforms where pthread_equal() is not atomic, SQLite
  22696. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  22697. ** make sure no assert() statements are evaluated and hence these
  22698. ** routines are never called.
  22699. */
  22700. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  22701. static int pthreadMutexHeld(sqlite3_mutex *p){
  22702. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  22703. }
  22704. static int pthreadMutexNotheld(sqlite3_mutex *p){
  22705. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  22706. }
  22707. #endif
  22708. /*
  22709. ** Try to provide a memory barrier operation, needed for initialization
  22710. ** and also for the implementation of xShmBarrier in the VFS in cases
  22711. ** where SQLite is compiled without mutexes.
  22712. */
  22713. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  22714. #if defined(SQLITE_MEMORY_BARRIER)
  22715. SQLITE_MEMORY_BARRIER;
  22716. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  22717. __sync_synchronize();
  22718. #endif
  22719. }
  22720. /*
  22721. ** Initialize and deinitialize the mutex subsystem.
  22722. */
  22723. static int pthreadMutexInit(void){ return SQLITE_OK; }
  22724. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  22725. /*
  22726. ** The sqlite3_mutex_alloc() routine allocates a new
  22727. ** mutex and returns a pointer to it. If it returns NULL
  22728. ** that means that a mutex could not be allocated. SQLite
  22729. ** will unwind its stack and return an error. The argument
  22730. ** to sqlite3_mutex_alloc() is one of these integer constants:
  22731. **
  22732. ** <ul>
  22733. ** <li> SQLITE_MUTEX_FAST
  22734. ** <li> SQLITE_MUTEX_RECURSIVE
  22735. ** <li> SQLITE_MUTEX_STATIC_MASTER
  22736. ** <li> SQLITE_MUTEX_STATIC_MEM
  22737. ** <li> SQLITE_MUTEX_STATIC_OPEN
  22738. ** <li> SQLITE_MUTEX_STATIC_PRNG
  22739. ** <li> SQLITE_MUTEX_STATIC_LRU
  22740. ** <li> SQLITE_MUTEX_STATIC_PMEM
  22741. ** <li> SQLITE_MUTEX_STATIC_APP1
  22742. ** <li> SQLITE_MUTEX_STATIC_APP2
  22743. ** <li> SQLITE_MUTEX_STATIC_APP3
  22744. ** <li> SQLITE_MUTEX_STATIC_VFS1
  22745. ** <li> SQLITE_MUTEX_STATIC_VFS2
  22746. ** <li> SQLITE_MUTEX_STATIC_VFS3
  22747. ** </ul>
  22748. **
  22749. ** The first two constants cause sqlite3_mutex_alloc() to create
  22750. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  22751. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  22752. ** The mutex implementation does not need to make a distinction
  22753. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  22754. ** not want to. But SQLite will only request a recursive mutex in
  22755. ** cases where it really needs one. If a faster non-recursive mutex
  22756. ** implementation is available on the host platform, the mutex subsystem
  22757. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  22758. **
  22759. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  22760. ** a pointer to a static preexisting mutex. Six static mutexes are
  22761. ** used by the current version of SQLite. Future versions of SQLite
  22762. ** may add additional static mutexes. Static mutexes are for internal
  22763. ** use by SQLite only. Applications that use SQLite mutexes should
  22764. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  22765. ** SQLITE_MUTEX_RECURSIVE.
  22766. **
  22767. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  22768. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  22769. ** returns a different mutex on every call. But for the static
  22770. ** mutex types, the same mutex is returned on every call that has
  22771. ** the same type number.
  22772. */
  22773. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  22774. static sqlite3_mutex staticMutexes[] = {
  22775. SQLITE3_MUTEX_INITIALIZER,
  22776. SQLITE3_MUTEX_INITIALIZER,
  22777. SQLITE3_MUTEX_INITIALIZER,
  22778. SQLITE3_MUTEX_INITIALIZER,
  22779. SQLITE3_MUTEX_INITIALIZER,
  22780. SQLITE3_MUTEX_INITIALIZER,
  22781. SQLITE3_MUTEX_INITIALIZER,
  22782. SQLITE3_MUTEX_INITIALIZER,
  22783. SQLITE3_MUTEX_INITIALIZER,
  22784. SQLITE3_MUTEX_INITIALIZER,
  22785. SQLITE3_MUTEX_INITIALIZER,
  22786. SQLITE3_MUTEX_INITIALIZER
  22787. };
  22788. sqlite3_mutex *p;
  22789. switch( iType ){
  22790. case SQLITE_MUTEX_RECURSIVE: {
  22791. p = sqlite3MallocZero( sizeof(*p) );
  22792. if( p ){
  22793. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22794. /* If recursive mutexes are not available, we will have to
  22795. ** build our own. See below. */
  22796. pthread_mutex_init(&p->mutex, 0);
  22797. #else
  22798. /* Use a recursive mutex if it is available */
  22799. pthread_mutexattr_t recursiveAttr;
  22800. pthread_mutexattr_init(&recursiveAttr);
  22801. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  22802. pthread_mutex_init(&p->mutex, &recursiveAttr);
  22803. pthread_mutexattr_destroy(&recursiveAttr);
  22804. #endif
  22805. }
  22806. break;
  22807. }
  22808. case SQLITE_MUTEX_FAST: {
  22809. p = sqlite3MallocZero( sizeof(*p) );
  22810. if( p ){
  22811. pthread_mutex_init(&p->mutex, 0);
  22812. }
  22813. break;
  22814. }
  22815. default: {
  22816. #ifdef SQLITE_ENABLE_API_ARMOR
  22817. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  22818. (void)SQLITE_MISUSE_BKPT;
  22819. return 0;
  22820. }
  22821. #endif
  22822. p = &staticMutexes[iType-2];
  22823. break;
  22824. }
  22825. }
  22826. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22827. if( p ) p->id = iType;
  22828. #endif
  22829. return p;
  22830. }
  22831. /*
  22832. ** This routine deallocates a previously
  22833. ** allocated mutex. SQLite is careful to deallocate every
  22834. ** mutex that it allocates.
  22835. */
  22836. static void pthreadMutexFree(sqlite3_mutex *p){
  22837. assert( p->nRef==0 );
  22838. #if SQLITE_ENABLE_API_ARMOR
  22839. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  22840. #endif
  22841. {
  22842. pthread_mutex_destroy(&p->mutex);
  22843. sqlite3_free(p);
  22844. }
  22845. #ifdef SQLITE_ENABLE_API_ARMOR
  22846. else{
  22847. (void)SQLITE_MISUSE_BKPT;
  22848. }
  22849. #endif
  22850. }
  22851. /*
  22852. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22853. ** to enter a mutex. If another thread is already within the mutex,
  22854. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22855. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22856. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22857. ** be entered multiple times by the same thread. In such cases the,
  22858. ** mutex must be exited an equal number of times before another thread
  22859. ** can enter. If the same thread tries to enter any other kind of mutex
  22860. ** more than once, the behavior is undefined.
  22861. */
  22862. static void pthreadMutexEnter(sqlite3_mutex *p){
  22863. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22864. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22865. /* If recursive mutexes are not available, then we have to grow
  22866. ** our own. This implementation assumes that pthread_equal()
  22867. ** is atomic - that it cannot be deceived into thinking self
  22868. ** and p->owner are equal if p->owner changes between two values
  22869. ** that are not equal to self while the comparison is taking place.
  22870. ** This implementation also assumes a coherent cache - that
  22871. ** separate processes cannot read different values from the same
  22872. ** address at the same time. If either of these two conditions
  22873. ** are not met, then the mutexes will fail and problems will result.
  22874. */
  22875. {
  22876. pthread_t self = pthread_self();
  22877. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22878. p->nRef++;
  22879. }else{
  22880. pthread_mutex_lock(&p->mutex);
  22881. assert( p->nRef==0 );
  22882. p->owner = self;
  22883. p->nRef = 1;
  22884. }
  22885. }
  22886. #else
  22887. /* Use the built-in recursive mutexes if they are available.
  22888. */
  22889. pthread_mutex_lock(&p->mutex);
  22890. #if SQLITE_MUTEX_NREF
  22891. assert( p->nRef>0 || p->owner==0 );
  22892. p->owner = pthread_self();
  22893. p->nRef++;
  22894. #endif
  22895. #endif
  22896. #ifdef SQLITE_DEBUG
  22897. if( p->trace ){
  22898. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22899. }
  22900. #endif
  22901. }
  22902. static int pthreadMutexTry(sqlite3_mutex *p){
  22903. int rc;
  22904. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22905. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22906. /* If recursive mutexes are not available, then we have to grow
  22907. ** our own. This implementation assumes that pthread_equal()
  22908. ** is atomic - that it cannot be deceived into thinking self
  22909. ** and p->owner are equal if p->owner changes between two values
  22910. ** that are not equal to self while the comparison is taking place.
  22911. ** This implementation also assumes a coherent cache - that
  22912. ** separate processes cannot read different values from the same
  22913. ** address at the same time. If either of these two conditions
  22914. ** are not met, then the mutexes will fail and problems will result.
  22915. */
  22916. {
  22917. pthread_t self = pthread_self();
  22918. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22919. p->nRef++;
  22920. rc = SQLITE_OK;
  22921. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  22922. assert( p->nRef==0 );
  22923. p->owner = self;
  22924. p->nRef = 1;
  22925. rc = SQLITE_OK;
  22926. }else{
  22927. rc = SQLITE_BUSY;
  22928. }
  22929. }
  22930. #else
  22931. /* Use the built-in recursive mutexes if they are available.
  22932. */
  22933. if( pthread_mutex_trylock(&p->mutex)==0 ){
  22934. #if SQLITE_MUTEX_NREF
  22935. p->owner = pthread_self();
  22936. p->nRef++;
  22937. #endif
  22938. rc = SQLITE_OK;
  22939. }else{
  22940. rc = SQLITE_BUSY;
  22941. }
  22942. #endif
  22943. #ifdef SQLITE_DEBUG
  22944. if( rc==SQLITE_OK && p->trace ){
  22945. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22946. }
  22947. #endif
  22948. return rc;
  22949. }
  22950. /*
  22951. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22952. ** previously entered by the same thread. The behavior
  22953. ** is undefined if the mutex is not currently entered or
  22954. ** is not currently allocated. SQLite will never do either.
  22955. */
  22956. static void pthreadMutexLeave(sqlite3_mutex *p){
  22957. assert( pthreadMutexHeld(p) );
  22958. #if SQLITE_MUTEX_NREF
  22959. p->nRef--;
  22960. if( p->nRef==0 ) p->owner = 0;
  22961. #endif
  22962. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  22963. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22964. if( p->nRef==0 ){
  22965. pthread_mutex_unlock(&p->mutex);
  22966. }
  22967. #else
  22968. pthread_mutex_unlock(&p->mutex);
  22969. #endif
  22970. #ifdef SQLITE_DEBUG
  22971. if( p->trace ){
  22972. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22973. }
  22974. #endif
  22975. }
  22976. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22977. static const sqlite3_mutex_methods sMutex = {
  22978. pthreadMutexInit,
  22979. pthreadMutexEnd,
  22980. pthreadMutexAlloc,
  22981. pthreadMutexFree,
  22982. pthreadMutexEnter,
  22983. pthreadMutexTry,
  22984. pthreadMutexLeave,
  22985. #ifdef SQLITE_DEBUG
  22986. pthreadMutexHeld,
  22987. pthreadMutexNotheld
  22988. #else
  22989. 0,
  22990. 0
  22991. #endif
  22992. };
  22993. return &sMutex;
  22994. }
  22995. #endif /* SQLITE_MUTEX_PTHREADS */
  22996. /************** End of mutex_unix.c ******************************************/
  22997. /************** Begin file mutex_w32.c ***************************************/
  22998. /*
  22999. ** 2007 August 14
  23000. **
  23001. ** The author disclaims copyright to this source code. In place of
  23002. ** a legal notice, here is a blessing:
  23003. **
  23004. ** May you do good and not evil.
  23005. ** May you find forgiveness for yourself and forgive others.
  23006. ** May you share freely, never taking more than you give.
  23007. **
  23008. *************************************************************************
  23009. ** This file contains the C functions that implement mutexes for Win32.
  23010. */
  23011. /* #include "sqliteInt.h" */
  23012. #if SQLITE_OS_WIN
  23013. /*
  23014. ** Include code that is common to all os_*.c files
  23015. */
  23016. /************** Include os_common.h in the middle of mutex_w32.c *************/
  23017. /************** Begin file os_common.h ***************************************/
  23018. /*
  23019. ** 2004 May 22
  23020. **
  23021. ** The author disclaims copyright to this source code. In place of
  23022. ** a legal notice, here is a blessing:
  23023. **
  23024. ** May you do good and not evil.
  23025. ** May you find forgiveness for yourself and forgive others.
  23026. ** May you share freely, never taking more than you give.
  23027. **
  23028. ******************************************************************************
  23029. **
  23030. ** This file contains macros and a little bit of code that is common to
  23031. ** all of the platform-specific files (os_*.c) and is #included into those
  23032. ** files.
  23033. **
  23034. ** This file should be #included by the os_*.c files only. It is not a
  23035. ** general purpose header file.
  23036. */
  23037. #ifndef _OS_COMMON_H_
  23038. #define _OS_COMMON_H_
  23039. /*
  23040. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  23041. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  23042. ** switch. The following code should catch this problem at compile-time.
  23043. */
  23044. #ifdef MEMORY_DEBUG
  23045. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  23046. #endif
  23047. /*
  23048. ** Macros for performance tracing. Normally turned off. Only works
  23049. ** on i486 hardware.
  23050. */
  23051. #ifdef SQLITE_PERFORMANCE_TRACE
  23052. /*
  23053. ** hwtime.h contains inline assembler code for implementing
  23054. ** high-performance timing routines.
  23055. */
  23056. /************** Include hwtime.h in the middle of os_common.h ****************/
  23057. /************** Begin file hwtime.h ******************************************/
  23058. /*
  23059. ** 2008 May 27
  23060. **
  23061. ** The author disclaims copyright to this source code. In place of
  23062. ** a legal notice, here is a blessing:
  23063. **
  23064. ** May you do good and not evil.
  23065. ** May you find forgiveness for yourself and forgive others.
  23066. ** May you share freely, never taking more than you give.
  23067. **
  23068. ******************************************************************************
  23069. **
  23070. ** This file contains inline asm code for retrieving "high-performance"
  23071. ** counters for x86 class CPUs.
  23072. */
  23073. #ifndef SQLITE_HWTIME_H
  23074. #define SQLITE_HWTIME_H
  23075. /*
  23076. ** The following routine only works on pentium-class (or newer) processors.
  23077. ** It uses the RDTSC opcode to read the cycle count value out of the
  23078. ** processor and returns that value. This can be used for high-res
  23079. ** profiling.
  23080. */
  23081. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  23082. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  23083. #if defined(__GNUC__)
  23084. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23085. unsigned int lo, hi;
  23086. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  23087. return (sqlite_uint64)hi << 32 | lo;
  23088. }
  23089. #elif defined(_MSC_VER)
  23090. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  23091. __asm {
  23092. rdtsc
  23093. ret ; return value at EDX:EAX
  23094. }
  23095. }
  23096. #endif
  23097. #elif (defined(__GNUC__) && defined(__x86_64__))
  23098. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23099. unsigned long val;
  23100. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  23101. return val;
  23102. }
  23103. #elif (defined(__GNUC__) && defined(__ppc__))
  23104. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23105. unsigned long long retval;
  23106. unsigned long junk;
  23107. __asm__ __volatile__ ("\n\
  23108. 1: mftbu %1\n\
  23109. mftb %L0\n\
  23110. mftbu %0\n\
  23111. cmpw %0,%1\n\
  23112. bne 1b"
  23113. : "=r" (retval), "=r" (junk));
  23114. return retval;
  23115. }
  23116. #else
  23117. #error Need implementation of sqlite3Hwtime() for your platform.
  23118. /*
  23119. ** To compile without implementing sqlite3Hwtime() for your platform,
  23120. ** you can remove the above #error and use the following
  23121. ** stub function. You will lose timing support for many
  23122. ** of the debugging and testing utilities, but it should at
  23123. ** least compile and run.
  23124. */
  23125. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  23126. #endif
  23127. #endif /* !defined(SQLITE_HWTIME_H) */
  23128. /************** End of hwtime.h **********************************************/
  23129. /************** Continuing where we left off in os_common.h ******************/
  23130. static sqlite_uint64 g_start;
  23131. static sqlite_uint64 g_elapsed;
  23132. #define TIMER_START g_start=sqlite3Hwtime()
  23133. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  23134. #define TIMER_ELAPSED g_elapsed
  23135. #else
  23136. #define TIMER_START
  23137. #define TIMER_END
  23138. #define TIMER_ELAPSED ((sqlite_uint64)0)
  23139. #endif
  23140. /*
  23141. ** If we compile with the SQLITE_TEST macro set, then the following block
  23142. ** of code will give us the ability to simulate a disk I/O error. This
  23143. ** is used for testing the I/O recovery logic.
  23144. */
  23145. #if defined(SQLITE_TEST)
  23146. SQLITE_API extern int sqlite3_io_error_hit;
  23147. SQLITE_API extern int sqlite3_io_error_hardhit;
  23148. SQLITE_API extern int sqlite3_io_error_pending;
  23149. SQLITE_API extern int sqlite3_io_error_persist;
  23150. SQLITE_API extern int sqlite3_io_error_benign;
  23151. SQLITE_API extern int sqlite3_diskfull_pending;
  23152. SQLITE_API extern int sqlite3_diskfull;
  23153. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  23154. #define SimulateIOError(CODE) \
  23155. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  23156. || sqlite3_io_error_pending-- == 1 ) \
  23157. { local_ioerr(); CODE; }
  23158. static void local_ioerr(){
  23159. IOTRACE(("IOERR\n"));
  23160. sqlite3_io_error_hit++;
  23161. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  23162. }
  23163. #define SimulateDiskfullError(CODE) \
  23164. if( sqlite3_diskfull_pending ){ \
  23165. if( sqlite3_diskfull_pending == 1 ){ \
  23166. local_ioerr(); \
  23167. sqlite3_diskfull = 1; \
  23168. sqlite3_io_error_hit = 1; \
  23169. CODE; \
  23170. }else{ \
  23171. sqlite3_diskfull_pending--; \
  23172. } \
  23173. }
  23174. #else
  23175. #define SimulateIOErrorBenign(X)
  23176. #define SimulateIOError(A)
  23177. #define SimulateDiskfullError(A)
  23178. #endif /* defined(SQLITE_TEST) */
  23179. /*
  23180. ** When testing, keep a count of the number of open files.
  23181. */
  23182. #if defined(SQLITE_TEST)
  23183. SQLITE_API extern int sqlite3_open_file_count;
  23184. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  23185. #else
  23186. #define OpenCounter(X)
  23187. #endif /* defined(SQLITE_TEST) */
  23188. #endif /* !defined(_OS_COMMON_H_) */
  23189. /************** End of os_common.h *******************************************/
  23190. /************** Continuing where we left off in mutex_w32.c ******************/
  23191. /*
  23192. ** Include the header file for the Windows VFS.
  23193. */
  23194. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  23195. /************** Begin file os_win.h ******************************************/
  23196. /*
  23197. ** 2013 November 25
  23198. **
  23199. ** The author disclaims copyright to this source code. In place of
  23200. ** a legal notice, here is a blessing:
  23201. **
  23202. ** May you do good and not evil.
  23203. ** May you find forgiveness for yourself and forgive others.
  23204. ** May you share freely, never taking more than you give.
  23205. **
  23206. ******************************************************************************
  23207. **
  23208. ** This file contains code that is specific to Windows.
  23209. */
  23210. #ifndef SQLITE_OS_WIN_H
  23211. #define SQLITE_OS_WIN_H
  23212. /*
  23213. ** Include the primary Windows SDK header file.
  23214. */
  23215. #include "windows.h"
  23216. #ifdef __CYGWIN__
  23217. # include <sys/cygwin.h>
  23218. # include <errno.h> /* amalgamator: dontcache */
  23219. #endif
  23220. /*
  23221. ** Determine if we are dealing with Windows NT.
  23222. **
  23223. ** We ought to be able to determine if we are compiling for Windows 9x or
  23224. ** Windows NT using the _WIN32_WINNT macro as follows:
  23225. **
  23226. ** #if defined(_WIN32_WINNT)
  23227. ** # define SQLITE_OS_WINNT 1
  23228. ** #else
  23229. ** # define SQLITE_OS_WINNT 0
  23230. ** #endif
  23231. **
  23232. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  23233. ** it ought to, so the above test does not work. We'll just assume that
  23234. ** everything is Windows NT unless the programmer explicitly says otherwise
  23235. ** by setting SQLITE_OS_WINNT to 0.
  23236. */
  23237. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  23238. # define SQLITE_OS_WINNT 1
  23239. #endif
  23240. /*
  23241. ** Determine if we are dealing with Windows CE - which has a much reduced
  23242. ** API.
  23243. */
  23244. #if defined(_WIN32_WCE)
  23245. # define SQLITE_OS_WINCE 1
  23246. #else
  23247. # define SQLITE_OS_WINCE 0
  23248. #endif
  23249. /*
  23250. ** Determine if we are dealing with WinRT, which provides only a subset of
  23251. ** the full Win32 API.
  23252. */
  23253. #if !defined(SQLITE_OS_WINRT)
  23254. # define SQLITE_OS_WINRT 0
  23255. #endif
  23256. /*
  23257. ** For WinCE, some API function parameters do not appear to be declared as
  23258. ** volatile.
  23259. */
  23260. #if SQLITE_OS_WINCE
  23261. # define SQLITE_WIN32_VOLATILE
  23262. #else
  23263. # define SQLITE_WIN32_VOLATILE volatile
  23264. #endif
  23265. /*
  23266. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  23267. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  23268. */
  23269. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  23270. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  23271. # define SQLITE_OS_WIN_THREADS 1
  23272. #else
  23273. # define SQLITE_OS_WIN_THREADS 0
  23274. #endif
  23275. #endif /* SQLITE_OS_WIN_H */
  23276. /************** End of os_win.h **********************************************/
  23277. /************** Continuing where we left off in mutex_w32.c ******************/
  23278. #endif
  23279. /*
  23280. ** The code in this file is only used if we are compiling multithreaded
  23281. ** on a Win32 system.
  23282. */
  23283. #ifdef SQLITE_MUTEX_W32
  23284. /*
  23285. ** Each recursive mutex is an instance of the following structure.
  23286. */
  23287. struct sqlite3_mutex {
  23288. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  23289. int id; /* Mutex type */
  23290. #ifdef SQLITE_DEBUG
  23291. volatile int nRef; /* Number of enterances */
  23292. volatile DWORD owner; /* Thread holding this mutex */
  23293. volatile int trace; /* True to trace changes */
  23294. #endif
  23295. };
  23296. /*
  23297. ** These are the initializer values used when declaring a "static" mutex
  23298. ** on Win32. It should be noted that all mutexes require initialization
  23299. ** on the Win32 platform.
  23300. */
  23301. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  23302. #ifdef SQLITE_DEBUG
  23303. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  23304. 0L, (DWORD)0, 0 }
  23305. #else
  23306. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  23307. #endif
  23308. #ifdef SQLITE_DEBUG
  23309. /*
  23310. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23311. ** intended for use only inside assert() statements.
  23312. */
  23313. static int winMutexHeld(sqlite3_mutex *p){
  23314. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  23315. }
  23316. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  23317. return p->nRef==0 || p->owner!=tid;
  23318. }
  23319. static int winMutexNotheld(sqlite3_mutex *p){
  23320. DWORD tid = GetCurrentThreadId();
  23321. return winMutexNotheld2(p, tid);
  23322. }
  23323. #endif
  23324. /*
  23325. ** Try to provide a memory barrier operation, needed for initialization
  23326. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  23327. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  23328. */
  23329. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  23330. #if defined(SQLITE_MEMORY_BARRIER)
  23331. SQLITE_MEMORY_BARRIER;
  23332. #elif defined(__GNUC__)
  23333. __sync_synchronize();
  23334. #elif MSVC_VERSION>=1300
  23335. _ReadWriteBarrier();
  23336. #elif defined(MemoryBarrier)
  23337. MemoryBarrier();
  23338. #endif
  23339. }
  23340. /*
  23341. ** Initialize and deinitialize the mutex subsystem.
  23342. */
  23343. static sqlite3_mutex winMutex_staticMutexes[] = {
  23344. SQLITE3_MUTEX_INITIALIZER,
  23345. SQLITE3_MUTEX_INITIALIZER,
  23346. SQLITE3_MUTEX_INITIALIZER,
  23347. SQLITE3_MUTEX_INITIALIZER,
  23348. SQLITE3_MUTEX_INITIALIZER,
  23349. SQLITE3_MUTEX_INITIALIZER,
  23350. SQLITE3_MUTEX_INITIALIZER,
  23351. SQLITE3_MUTEX_INITIALIZER,
  23352. SQLITE3_MUTEX_INITIALIZER,
  23353. SQLITE3_MUTEX_INITIALIZER,
  23354. SQLITE3_MUTEX_INITIALIZER,
  23355. SQLITE3_MUTEX_INITIALIZER
  23356. };
  23357. static int winMutex_isInit = 0;
  23358. static int winMutex_isNt = -1; /* <0 means "need to query" */
  23359. /* As the winMutexInit() and winMutexEnd() functions are called as part
  23360. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  23361. ** "interlocked" magic used here is probably not strictly necessary.
  23362. */
  23363. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  23364. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  23365. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  23366. static int winMutexInit(void){
  23367. /* The first to increment to 1 does actual initialization */
  23368. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  23369. int i;
  23370. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  23371. #if SQLITE_OS_WINRT
  23372. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  23373. #else
  23374. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  23375. #endif
  23376. }
  23377. winMutex_isInit = 1;
  23378. }else{
  23379. /* Another thread is (in the process of) initializing the static
  23380. ** mutexes */
  23381. while( !winMutex_isInit ){
  23382. sqlite3_win32_sleep(1);
  23383. }
  23384. }
  23385. return SQLITE_OK;
  23386. }
  23387. static int winMutexEnd(void){
  23388. /* The first to decrement to 0 does actual shutdown
  23389. ** (which should be the last to shutdown.) */
  23390. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  23391. if( winMutex_isInit==1 ){
  23392. int i;
  23393. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  23394. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  23395. }
  23396. winMutex_isInit = 0;
  23397. }
  23398. }
  23399. return SQLITE_OK;
  23400. }
  23401. /*
  23402. ** The sqlite3_mutex_alloc() routine allocates a new
  23403. ** mutex and returns a pointer to it. If it returns NULL
  23404. ** that means that a mutex could not be allocated. SQLite
  23405. ** will unwind its stack and return an error. The argument
  23406. ** to sqlite3_mutex_alloc() is one of these integer constants:
  23407. **
  23408. ** <ul>
  23409. ** <li> SQLITE_MUTEX_FAST
  23410. ** <li> SQLITE_MUTEX_RECURSIVE
  23411. ** <li> SQLITE_MUTEX_STATIC_MASTER
  23412. ** <li> SQLITE_MUTEX_STATIC_MEM
  23413. ** <li> SQLITE_MUTEX_STATIC_OPEN
  23414. ** <li> SQLITE_MUTEX_STATIC_PRNG
  23415. ** <li> SQLITE_MUTEX_STATIC_LRU
  23416. ** <li> SQLITE_MUTEX_STATIC_PMEM
  23417. ** <li> SQLITE_MUTEX_STATIC_APP1
  23418. ** <li> SQLITE_MUTEX_STATIC_APP2
  23419. ** <li> SQLITE_MUTEX_STATIC_APP3
  23420. ** <li> SQLITE_MUTEX_STATIC_VFS1
  23421. ** <li> SQLITE_MUTEX_STATIC_VFS2
  23422. ** <li> SQLITE_MUTEX_STATIC_VFS3
  23423. ** </ul>
  23424. **
  23425. ** The first two constants cause sqlite3_mutex_alloc() to create
  23426. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  23427. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  23428. ** The mutex implementation does not need to make a distinction
  23429. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  23430. ** not want to. But SQLite will only request a recursive mutex in
  23431. ** cases where it really needs one. If a faster non-recursive mutex
  23432. ** implementation is available on the host platform, the mutex subsystem
  23433. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  23434. **
  23435. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  23436. ** a pointer to a static preexisting mutex. Six static mutexes are
  23437. ** used by the current version of SQLite. Future versions of SQLite
  23438. ** may add additional static mutexes. Static mutexes are for internal
  23439. ** use by SQLite only. Applications that use SQLite mutexes should
  23440. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  23441. ** SQLITE_MUTEX_RECURSIVE.
  23442. **
  23443. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  23444. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  23445. ** returns a different mutex on every call. But for the static
  23446. ** mutex types, the same mutex is returned on every call that has
  23447. ** the same type number.
  23448. */
  23449. static sqlite3_mutex *winMutexAlloc(int iType){
  23450. sqlite3_mutex *p;
  23451. switch( iType ){
  23452. case SQLITE_MUTEX_FAST:
  23453. case SQLITE_MUTEX_RECURSIVE: {
  23454. p = sqlite3MallocZero( sizeof(*p) );
  23455. if( p ){
  23456. p->id = iType;
  23457. #ifdef SQLITE_DEBUG
  23458. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  23459. p->trace = 1;
  23460. #endif
  23461. #endif
  23462. #if SQLITE_OS_WINRT
  23463. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  23464. #else
  23465. InitializeCriticalSection(&p->mutex);
  23466. #endif
  23467. }
  23468. break;
  23469. }
  23470. default: {
  23471. #ifdef SQLITE_ENABLE_API_ARMOR
  23472. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  23473. (void)SQLITE_MISUSE_BKPT;
  23474. return 0;
  23475. }
  23476. #endif
  23477. p = &winMutex_staticMutexes[iType-2];
  23478. p->id = iType;
  23479. #ifdef SQLITE_DEBUG
  23480. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  23481. p->trace = 1;
  23482. #endif
  23483. #endif
  23484. break;
  23485. }
  23486. }
  23487. return p;
  23488. }
  23489. /*
  23490. ** This routine deallocates a previously
  23491. ** allocated mutex. SQLite is careful to deallocate every
  23492. ** mutex that it allocates.
  23493. */
  23494. static void winMutexFree(sqlite3_mutex *p){
  23495. assert( p );
  23496. assert( p->nRef==0 && p->owner==0 );
  23497. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  23498. DeleteCriticalSection(&p->mutex);
  23499. sqlite3_free(p);
  23500. }else{
  23501. #ifdef SQLITE_ENABLE_API_ARMOR
  23502. (void)SQLITE_MISUSE_BKPT;
  23503. #endif
  23504. }
  23505. }
  23506. /*
  23507. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  23508. ** to enter a mutex. If another thread is already within the mutex,
  23509. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  23510. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  23511. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  23512. ** be entered multiple times by the same thread. In such cases the,
  23513. ** mutex must be exited an equal number of times before another thread
  23514. ** can enter. If the same thread tries to enter any other kind of mutex
  23515. ** more than once, the behavior is undefined.
  23516. */
  23517. static void winMutexEnter(sqlite3_mutex *p){
  23518. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23519. DWORD tid = GetCurrentThreadId();
  23520. #endif
  23521. #ifdef SQLITE_DEBUG
  23522. assert( p );
  23523. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  23524. #else
  23525. assert( p );
  23526. #endif
  23527. assert( winMutex_isInit==1 );
  23528. EnterCriticalSection(&p->mutex);
  23529. #ifdef SQLITE_DEBUG
  23530. assert( p->nRef>0 || p->owner==0 );
  23531. p->owner = tid;
  23532. p->nRef++;
  23533. if( p->trace ){
  23534. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  23535. tid, p->id, p, p->trace, p->nRef));
  23536. }
  23537. #endif
  23538. }
  23539. static int winMutexTry(sqlite3_mutex *p){
  23540. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23541. DWORD tid = GetCurrentThreadId();
  23542. #endif
  23543. int rc = SQLITE_BUSY;
  23544. assert( p );
  23545. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  23546. /*
  23547. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  23548. ** is used it is merely an optimization. So it is OK for it to always
  23549. ** fail.
  23550. **
  23551. ** The TryEnterCriticalSection() interface is only available on WinNT.
  23552. ** And some windows compilers complain if you try to use it without
  23553. ** first doing some #defines that prevent SQLite from building on Win98.
  23554. ** For that reason, we will omit this optimization for now. See
  23555. ** ticket #2685.
  23556. */
  23557. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  23558. assert( winMutex_isInit==1 );
  23559. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  23560. if( winMutex_isNt<0 ){
  23561. winMutex_isNt = sqlite3_win32_is_nt();
  23562. }
  23563. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  23564. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  23565. #ifdef SQLITE_DEBUG
  23566. p->owner = tid;
  23567. p->nRef++;
  23568. #endif
  23569. rc = SQLITE_OK;
  23570. }
  23571. #else
  23572. UNUSED_PARAMETER(p);
  23573. #endif
  23574. #ifdef SQLITE_DEBUG
  23575. if( p->trace ){
  23576. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  23577. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  23578. }
  23579. #endif
  23580. return rc;
  23581. }
  23582. /*
  23583. ** The sqlite3_mutex_leave() routine exits a mutex that was
  23584. ** previously entered by the same thread. The behavior
  23585. ** is undefined if the mutex is not currently entered or
  23586. ** is not currently allocated. SQLite will never do either.
  23587. */
  23588. static void winMutexLeave(sqlite3_mutex *p){
  23589. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23590. DWORD tid = GetCurrentThreadId();
  23591. #endif
  23592. assert( p );
  23593. #ifdef SQLITE_DEBUG
  23594. assert( p->nRef>0 );
  23595. assert( p->owner==tid );
  23596. p->nRef--;
  23597. if( p->nRef==0 ) p->owner = 0;
  23598. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  23599. #endif
  23600. assert( winMutex_isInit==1 );
  23601. LeaveCriticalSection(&p->mutex);
  23602. #ifdef SQLITE_DEBUG
  23603. if( p->trace ){
  23604. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  23605. tid, p->id, p, p->trace, p->nRef));
  23606. }
  23607. #endif
  23608. }
  23609. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23610. static const sqlite3_mutex_methods sMutex = {
  23611. winMutexInit,
  23612. winMutexEnd,
  23613. winMutexAlloc,
  23614. winMutexFree,
  23615. winMutexEnter,
  23616. winMutexTry,
  23617. winMutexLeave,
  23618. #ifdef SQLITE_DEBUG
  23619. winMutexHeld,
  23620. winMutexNotheld
  23621. #else
  23622. 0,
  23623. 0
  23624. #endif
  23625. };
  23626. return &sMutex;
  23627. }
  23628. #endif /* SQLITE_MUTEX_W32 */
  23629. /************** End of mutex_w32.c *******************************************/
  23630. /************** Begin file malloc.c ******************************************/
  23631. /*
  23632. ** 2001 September 15
  23633. **
  23634. ** The author disclaims copyright to this source code. In place of
  23635. ** a legal notice, here is a blessing:
  23636. **
  23637. ** May you do good and not evil.
  23638. ** May you find forgiveness for yourself and forgive others.
  23639. ** May you share freely, never taking more than you give.
  23640. **
  23641. *************************************************************************
  23642. **
  23643. ** Memory allocation functions used throughout sqlite.
  23644. */
  23645. /* #include "sqliteInt.h" */
  23646. /* #include <stdarg.h> */
  23647. /*
  23648. ** Attempt to release up to n bytes of non-essential memory currently
  23649. ** held by SQLite. An example of non-essential memory is memory used to
  23650. ** cache database pages that are not currently in use.
  23651. */
  23652. SQLITE_API int sqlite3_release_memory(int n){
  23653. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23654. return sqlite3PcacheReleaseMemory(n);
  23655. #else
  23656. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  23657. ** is a no-op returning zero if SQLite is not compiled with
  23658. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  23659. UNUSED_PARAMETER(n);
  23660. return 0;
  23661. #endif
  23662. }
  23663. /*
  23664. ** State information local to the memory allocation subsystem.
  23665. */
  23666. static SQLITE_WSD struct Mem0Global {
  23667. sqlite3_mutex *mutex; /* Mutex to serialize access */
  23668. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  23669. /*
  23670. ** True if heap is nearly "full" where "full" is defined by the
  23671. ** sqlite3_soft_heap_limit() setting.
  23672. */
  23673. int nearlyFull;
  23674. } mem0 = { 0, 0, 0 };
  23675. #define mem0 GLOBAL(struct Mem0Global, mem0)
  23676. /*
  23677. ** Return the memory allocator mutex. sqlite3_status() needs it.
  23678. */
  23679. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  23680. return mem0.mutex;
  23681. }
  23682. #ifndef SQLITE_OMIT_DEPRECATED
  23683. /*
  23684. ** Deprecated external interface. It used to set an alarm callback
  23685. ** that was invoked when memory usage grew too large. Now it is a
  23686. ** no-op.
  23687. */
  23688. SQLITE_API int sqlite3_memory_alarm(
  23689. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  23690. void *pArg,
  23691. sqlite3_int64 iThreshold
  23692. ){
  23693. (void)xCallback;
  23694. (void)pArg;
  23695. (void)iThreshold;
  23696. return SQLITE_OK;
  23697. }
  23698. #endif
  23699. /*
  23700. ** Set the soft heap-size limit for the library. Passing a zero or
  23701. ** negative value indicates no limit.
  23702. */
  23703. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  23704. sqlite3_int64 priorLimit;
  23705. sqlite3_int64 excess;
  23706. sqlite3_int64 nUsed;
  23707. #ifndef SQLITE_OMIT_AUTOINIT
  23708. int rc = sqlite3_initialize();
  23709. if( rc ) return -1;
  23710. #endif
  23711. sqlite3_mutex_enter(mem0.mutex);
  23712. priorLimit = mem0.alarmThreshold;
  23713. if( n<0 ){
  23714. sqlite3_mutex_leave(mem0.mutex);
  23715. return priorLimit;
  23716. }
  23717. mem0.alarmThreshold = n;
  23718. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23719. mem0.nearlyFull = (n>0 && n<=nUsed);
  23720. sqlite3_mutex_leave(mem0.mutex);
  23721. excess = sqlite3_memory_used() - n;
  23722. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  23723. return priorLimit;
  23724. }
  23725. SQLITE_API void sqlite3_soft_heap_limit(int n){
  23726. if( n<0 ) n = 0;
  23727. sqlite3_soft_heap_limit64(n);
  23728. }
  23729. /*
  23730. ** Initialize the memory allocation subsystem.
  23731. */
  23732. SQLITE_PRIVATE int sqlite3MallocInit(void){
  23733. int rc;
  23734. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  23735. sqlite3MemSetDefault();
  23736. }
  23737. memset(&mem0, 0, sizeof(mem0));
  23738. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23739. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  23740. || sqlite3GlobalConfig.nPage<=0 ){
  23741. sqlite3GlobalConfig.pPage = 0;
  23742. sqlite3GlobalConfig.szPage = 0;
  23743. }
  23744. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  23745. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  23746. return rc;
  23747. }
  23748. /*
  23749. ** Return true if the heap is currently under memory pressure - in other
  23750. ** words if the amount of heap used is close to the limit set by
  23751. ** sqlite3_soft_heap_limit().
  23752. */
  23753. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  23754. return mem0.nearlyFull;
  23755. }
  23756. /*
  23757. ** Deinitialize the memory allocation subsystem.
  23758. */
  23759. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  23760. if( sqlite3GlobalConfig.m.xShutdown ){
  23761. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  23762. }
  23763. memset(&mem0, 0, sizeof(mem0));
  23764. }
  23765. /*
  23766. ** Return the amount of memory currently checked out.
  23767. */
  23768. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  23769. sqlite3_int64 res, mx;
  23770. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  23771. return res;
  23772. }
  23773. /*
  23774. ** Return the maximum amount of memory that has ever been
  23775. ** checked out since either the beginning of this process
  23776. ** or since the most recent reset.
  23777. */
  23778. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  23779. sqlite3_int64 res, mx;
  23780. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  23781. return mx;
  23782. }
  23783. /*
  23784. ** Trigger the alarm
  23785. */
  23786. static void sqlite3MallocAlarm(int nByte){
  23787. if( mem0.alarmThreshold<=0 ) return;
  23788. sqlite3_mutex_leave(mem0.mutex);
  23789. sqlite3_release_memory(nByte);
  23790. sqlite3_mutex_enter(mem0.mutex);
  23791. }
  23792. /*
  23793. ** Do a memory allocation with statistics and alarms. Assume the
  23794. ** lock is already held.
  23795. */
  23796. static void mallocWithAlarm(int n, void **pp){
  23797. void *p;
  23798. int nFull;
  23799. assert( sqlite3_mutex_held(mem0.mutex) );
  23800. assert( n>0 );
  23801. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  23802. ** implementation of malloc_good_size(), which must be called in debug
  23803. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  23804. ** or else a crash results. Hence, do not attempt to optimize out the
  23805. ** following xRoundup() call. */
  23806. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  23807. #ifdef SQLITE_MAX_MEMORY
  23808. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  23809. *pp = 0;
  23810. return;
  23811. }
  23812. #endif
  23813. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  23814. if( mem0.alarmThreshold>0 ){
  23815. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23816. if( nUsed >= mem0.alarmThreshold - nFull ){
  23817. mem0.nearlyFull = 1;
  23818. sqlite3MallocAlarm(nFull);
  23819. }else{
  23820. mem0.nearlyFull = 0;
  23821. }
  23822. }
  23823. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23824. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23825. if( p==0 && mem0.alarmThreshold>0 ){
  23826. sqlite3MallocAlarm(nFull);
  23827. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23828. }
  23829. #endif
  23830. if( p ){
  23831. nFull = sqlite3MallocSize(p);
  23832. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  23833. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  23834. }
  23835. *pp = p;
  23836. }
  23837. /*
  23838. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  23839. ** assumes the memory subsystem has already been initialized.
  23840. */
  23841. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  23842. void *p;
  23843. if( n==0 || n>=0x7fffff00 ){
  23844. /* A memory allocation of a number of bytes which is near the maximum
  23845. ** signed integer value might cause an integer overflow inside of the
  23846. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  23847. ** 255 bytes of overhead. SQLite itself will never use anything near
  23848. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  23849. p = 0;
  23850. }else if( sqlite3GlobalConfig.bMemstat ){
  23851. sqlite3_mutex_enter(mem0.mutex);
  23852. mallocWithAlarm((int)n, &p);
  23853. sqlite3_mutex_leave(mem0.mutex);
  23854. }else{
  23855. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  23856. }
  23857. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  23858. return p;
  23859. }
  23860. /*
  23861. ** This version of the memory allocation is for use by the application.
  23862. ** First make sure the memory subsystem is initialized, then do the
  23863. ** allocation.
  23864. */
  23865. SQLITE_API void *sqlite3_malloc(int n){
  23866. #ifndef SQLITE_OMIT_AUTOINIT
  23867. if( sqlite3_initialize() ) return 0;
  23868. #endif
  23869. return n<=0 ? 0 : sqlite3Malloc(n);
  23870. }
  23871. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  23872. #ifndef SQLITE_OMIT_AUTOINIT
  23873. if( sqlite3_initialize() ) return 0;
  23874. #endif
  23875. return sqlite3Malloc(n);
  23876. }
  23877. /*
  23878. ** TRUE if p is a lookaside memory allocation from db
  23879. */
  23880. #ifndef SQLITE_OMIT_LOOKASIDE
  23881. static int isLookaside(sqlite3 *db, void *p){
  23882. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  23883. }
  23884. #else
  23885. #define isLookaside(A,B) 0
  23886. #endif
  23887. /*
  23888. ** Return the size of a memory allocation previously obtained from
  23889. ** sqlite3Malloc() or sqlite3_malloc().
  23890. */
  23891. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  23892. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23893. return sqlite3GlobalConfig.m.xSize(p);
  23894. }
  23895. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  23896. assert( p!=0 );
  23897. if( db==0 || !isLookaside(db,p) ){
  23898. #ifdef SQLITE_DEBUG
  23899. if( db==0 ){
  23900. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23901. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23902. }else{
  23903. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23904. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23905. }
  23906. #endif
  23907. return sqlite3GlobalConfig.m.xSize(p);
  23908. }else{
  23909. assert( sqlite3_mutex_held(db->mutex) );
  23910. return db->lookaside.sz;
  23911. }
  23912. }
  23913. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  23914. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23915. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23916. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  23917. }
  23918. /*
  23919. ** Free memory previously obtained from sqlite3Malloc().
  23920. */
  23921. SQLITE_API void sqlite3_free(void *p){
  23922. if( p==0 ) return; /* IMP: R-49053-54554 */
  23923. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23924. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23925. if( sqlite3GlobalConfig.bMemstat ){
  23926. sqlite3_mutex_enter(mem0.mutex);
  23927. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  23928. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  23929. sqlite3GlobalConfig.m.xFree(p);
  23930. sqlite3_mutex_leave(mem0.mutex);
  23931. }else{
  23932. sqlite3GlobalConfig.m.xFree(p);
  23933. }
  23934. }
  23935. /*
  23936. ** Add the size of memory allocation "p" to the count in
  23937. ** *db->pnBytesFreed.
  23938. */
  23939. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  23940. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  23941. }
  23942. /*
  23943. ** Free memory that might be associated with a particular database
  23944. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  23945. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  23946. */
  23947. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  23948. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23949. assert( p!=0 );
  23950. if( db ){
  23951. if( db->pnBytesFreed ){
  23952. measureAllocationSize(db, p);
  23953. return;
  23954. }
  23955. if( isLookaside(db, p) ){
  23956. LookasideSlot *pBuf = (LookasideSlot*)p;
  23957. #ifdef SQLITE_DEBUG
  23958. /* Trash all content in the buffer being freed */
  23959. memset(p, 0xaa, db->lookaside.sz);
  23960. #endif
  23961. pBuf->pNext = db->lookaside.pFree;
  23962. db->lookaside.pFree = pBuf;
  23963. return;
  23964. }
  23965. }
  23966. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23967. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23968. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  23969. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23970. sqlite3_free(p);
  23971. }
  23972. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  23973. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23974. if( p ) sqlite3DbFreeNN(db, p);
  23975. }
  23976. /*
  23977. ** Change the size of an existing memory allocation
  23978. */
  23979. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  23980. int nOld, nNew, nDiff;
  23981. void *pNew;
  23982. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  23983. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  23984. if( pOld==0 ){
  23985. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  23986. }
  23987. if( nBytes==0 ){
  23988. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  23989. return 0;
  23990. }
  23991. if( nBytes>=0x7fffff00 ){
  23992. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  23993. return 0;
  23994. }
  23995. nOld = sqlite3MallocSize(pOld);
  23996. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  23997. ** argument to xRealloc is always a value returned by a prior call to
  23998. ** xRoundup. */
  23999. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  24000. if( nOld==nNew ){
  24001. pNew = pOld;
  24002. }else if( sqlite3GlobalConfig.bMemstat ){
  24003. sqlite3_mutex_enter(mem0.mutex);
  24004. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  24005. nDiff = nNew - nOld;
  24006. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  24007. mem0.alarmThreshold-nDiff ){
  24008. sqlite3MallocAlarm(nDiff);
  24009. }
  24010. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24011. if( pNew==0 && mem0.alarmThreshold>0 ){
  24012. sqlite3MallocAlarm((int)nBytes);
  24013. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24014. }
  24015. if( pNew ){
  24016. nNew = sqlite3MallocSize(pNew);
  24017. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  24018. }
  24019. sqlite3_mutex_leave(mem0.mutex);
  24020. }else{
  24021. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24022. }
  24023. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  24024. return pNew;
  24025. }
  24026. /*
  24027. ** The public interface to sqlite3Realloc. Make sure that the memory
  24028. ** subsystem is initialized prior to invoking sqliteRealloc.
  24029. */
  24030. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  24031. #ifndef SQLITE_OMIT_AUTOINIT
  24032. if( sqlite3_initialize() ) return 0;
  24033. #endif
  24034. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  24035. return sqlite3Realloc(pOld, n);
  24036. }
  24037. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  24038. #ifndef SQLITE_OMIT_AUTOINIT
  24039. if( sqlite3_initialize() ) return 0;
  24040. #endif
  24041. return sqlite3Realloc(pOld, n);
  24042. }
  24043. /*
  24044. ** Allocate and zero memory.
  24045. */
  24046. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  24047. void *p = sqlite3Malloc(n);
  24048. if( p ){
  24049. memset(p, 0, (size_t)n);
  24050. }
  24051. return p;
  24052. }
  24053. /*
  24054. ** Allocate and zero memory. If the allocation fails, make
  24055. ** the mallocFailed flag in the connection pointer.
  24056. */
  24057. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  24058. void *p;
  24059. testcase( db==0 );
  24060. p = sqlite3DbMallocRaw(db, n);
  24061. if( p ) memset(p, 0, (size_t)n);
  24062. return p;
  24063. }
  24064. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  24065. ** slower case when the allocation cannot be fulfilled using lookaside.
  24066. */
  24067. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  24068. void *p;
  24069. assert( db!=0 );
  24070. p = sqlite3Malloc(n);
  24071. if( !p ) sqlite3OomFault(db);
  24072. sqlite3MemdebugSetType(p,
  24073. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  24074. return p;
  24075. }
  24076. /*
  24077. ** Allocate memory, either lookaside (if possible) or heap.
  24078. ** If the allocation fails, set the mallocFailed flag in
  24079. ** the connection pointer.
  24080. **
  24081. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  24082. ** failure on the same database connection) then always return 0.
  24083. ** Hence for a particular database connection, once malloc starts
  24084. ** failing, it fails consistently until mallocFailed is reset.
  24085. ** This is an important assumption. There are many places in the
  24086. ** code that do things like this:
  24087. **
  24088. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  24089. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  24090. ** if( b ) a[10] = 9;
  24091. **
  24092. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  24093. ** that all prior mallocs (ex: "a") worked too.
  24094. **
  24095. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  24096. ** not a NULL pointer.
  24097. */
  24098. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  24099. void *p;
  24100. if( db ) return sqlite3DbMallocRawNN(db, n);
  24101. p = sqlite3Malloc(n);
  24102. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24103. return p;
  24104. }
  24105. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  24106. #ifndef SQLITE_OMIT_LOOKASIDE
  24107. LookasideSlot *pBuf;
  24108. assert( db!=0 );
  24109. assert( sqlite3_mutex_held(db->mutex) );
  24110. assert( db->pnBytesFreed==0 );
  24111. if( db->lookaside.bDisable==0 ){
  24112. assert( db->mallocFailed==0 );
  24113. if( n>db->lookaside.sz ){
  24114. db->lookaside.anStat[1]++;
  24115. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  24116. db->lookaside.pFree = pBuf->pNext;
  24117. db->lookaside.anStat[0]++;
  24118. return (void*)pBuf;
  24119. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  24120. db->lookaside.pInit = pBuf->pNext;
  24121. db->lookaside.anStat[0]++;
  24122. return (void*)pBuf;
  24123. }else{
  24124. db->lookaside.anStat[2]++;
  24125. }
  24126. }else if( db->mallocFailed ){
  24127. return 0;
  24128. }
  24129. #else
  24130. assert( db!=0 );
  24131. assert( sqlite3_mutex_held(db->mutex) );
  24132. assert( db->pnBytesFreed==0 );
  24133. if( db->mallocFailed ){
  24134. return 0;
  24135. }
  24136. #endif
  24137. return dbMallocRawFinish(db, n);
  24138. }
  24139. /* Forward declaration */
  24140. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  24141. /*
  24142. ** Resize the block of memory pointed to by p to n bytes. If the
  24143. ** resize fails, set the mallocFailed flag in the connection object.
  24144. */
  24145. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  24146. assert( db!=0 );
  24147. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  24148. assert( sqlite3_mutex_held(db->mutex) );
  24149. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  24150. return dbReallocFinish(db, p, n);
  24151. }
  24152. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  24153. void *pNew = 0;
  24154. assert( db!=0 );
  24155. assert( p!=0 );
  24156. if( db->mallocFailed==0 ){
  24157. if( isLookaside(db, p) ){
  24158. pNew = sqlite3DbMallocRawNN(db, n);
  24159. if( pNew ){
  24160. memcpy(pNew, p, db->lookaside.sz);
  24161. sqlite3DbFree(db, p);
  24162. }
  24163. }else{
  24164. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24165. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24166. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24167. pNew = sqlite3_realloc64(p, n);
  24168. if( !pNew ){
  24169. sqlite3OomFault(db);
  24170. }
  24171. sqlite3MemdebugSetType(pNew,
  24172. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  24173. }
  24174. }
  24175. return pNew;
  24176. }
  24177. /*
  24178. ** Attempt to reallocate p. If the reallocation fails, then free p
  24179. ** and set the mallocFailed flag in the database connection.
  24180. */
  24181. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  24182. void *pNew;
  24183. pNew = sqlite3DbRealloc(db, p, n);
  24184. if( !pNew ){
  24185. sqlite3DbFree(db, p);
  24186. }
  24187. return pNew;
  24188. }
  24189. /*
  24190. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  24191. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  24192. ** is because when memory debugging is turned on, these two functions are
  24193. ** called via macros that record the current file and line number in the
  24194. ** ThreadData structure.
  24195. */
  24196. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  24197. char *zNew;
  24198. size_t n;
  24199. if( z==0 ){
  24200. return 0;
  24201. }
  24202. n = strlen(z) + 1;
  24203. zNew = sqlite3DbMallocRaw(db, n);
  24204. if( zNew ){
  24205. memcpy(zNew, z, n);
  24206. }
  24207. return zNew;
  24208. }
  24209. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  24210. char *zNew;
  24211. assert( db!=0 );
  24212. if( z==0 ){
  24213. return 0;
  24214. }
  24215. assert( (n&0x7fffffff)==n );
  24216. zNew = sqlite3DbMallocRawNN(db, n+1);
  24217. if( zNew ){
  24218. memcpy(zNew, z, (size_t)n);
  24219. zNew[n] = 0;
  24220. }
  24221. return zNew;
  24222. }
  24223. /*
  24224. ** Free any prior content in *pz and replace it with a copy of zNew.
  24225. */
  24226. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  24227. sqlite3DbFree(db, *pz);
  24228. *pz = sqlite3DbStrDup(db, zNew);
  24229. }
  24230. /*
  24231. ** Call this routine to record the fact that an OOM (out-of-memory) error
  24232. ** has happened. This routine will set db->mallocFailed, and also
  24233. ** temporarily disable the lookaside memory allocator and interrupt
  24234. ** any running VDBEs.
  24235. */
  24236. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  24237. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  24238. db->mallocFailed = 1;
  24239. if( db->nVdbeExec>0 ){
  24240. db->u1.isInterrupted = 1;
  24241. }
  24242. db->lookaside.bDisable++;
  24243. }
  24244. }
  24245. /*
  24246. ** This routine reactivates the memory allocator and clears the
  24247. ** db->mallocFailed flag as necessary.
  24248. **
  24249. ** The memory allocator is not restarted if there are running
  24250. ** VDBEs.
  24251. */
  24252. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  24253. if( db->mallocFailed && db->nVdbeExec==0 ){
  24254. db->mallocFailed = 0;
  24255. db->u1.isInterrupted = 0;
  24256. assert( db->lookaside.bDisable>0 );
  24257. db->lookaside.bDisable--;
  24258. }
  24259. }
  24260. /*
  24261. ** Take actions at the end of an API call to indicate an OOM error
  24262. */
  24263. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  24264. sqlite3OomClear(db);
  24265. sqlite3Error(db, SQLITE_NOMEM);
  24266. return SQLITE_NOMEM_BKPT;
  24267. }
  24268. /*
  24269. ** This function must be called before exiting any API function (i.e.
  24270. ** returning control to the user) that has called sqlite3_malloc or
  24271. ** sqlite3_realloc.
  24272. **
  24273. ** The returned value is normally a copy of the second argument to this
  24274. ** function. However, if a malloc() failure has occurred since the previous
  24275. ** invocation SQLITE_NOMEM is returned instead.
  24276. **
  24277. ** If an OOM as occurred, then the connection error-code (the value
  24278. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  24279. */
  24280. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  24281. /* If the db handle must hold the connection handle mutex here.
  24282. ** Otherwise the read (and possible write) of db->mallocFailed
  24283. ** is unsafe, as is the call to sqlite3Error().
  24284. */
  24285. assert( db!=0 );
  24286. assert( sqlite3_mutex_held(db->mutex) );
  24287. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  24288. return apiOomError(db);
  24289. }
  24290. return rc & db->errMask;
  24291. }
  24292. /************** End of malloc.c **********************************************/
  24293. /************** Begin file printf.c ******************************************/
  24294. /*
  24295. ** The "printf" code that follows dates from the 1980's. It is in
  24296. ** the public domain.
  24297. **
  24298. **************************************************************************
  24299. **
  24300. ** This file contains code for a set of "printf"-like routines. These
  24301. ** routines format strings much like the printf() from the standard C
  24302. ** library, though the implementation here has enhancements to support
  24303. ** SQLite.
  24304. */
  24305. /* #include "sqliteInt.h" */
  24306. /*
  24307. ** Conversion types fall into various categories as defined by the
  24308. ** following enumeration.
  24309. */
  24310. #define etRADIX 0 /* non-decimal integer types. %x %o */
  24311. #define etFLOAT 1 /* Floating point. %f */
  24312. #define etEXP 2 /* Exponentional notation. %e and %E */
  24313. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  24314. #define etSIZE 4 /* Return number of characters processed so far. %n */
  24315. #define etSTRING 5 /* Strings. %s */
  24316. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  24317. #define etPERCENT 7 /* Percent symbol. %% */
  24318. #define etCHARX 8 /* Characters. %c */
  24319. /* The rest are extensions, not normally found in printf() */
  24320. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  24321. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  24322. NULL pointers replaced by SQL NULL. %Q */
  24323. #define etTOKEN 11 /* a pointer to a Token structure */
  24324. #define etSRCLIST 12 /* a pointer to a SrcList */
  24325. #define etPOINTER 13 /* The %p conversion */
  24326. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  24327. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  24328. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  24329. #define etINVALID 17 /* Any unrecognized conversion type */
  24330. /*
  24331. ** An "etByte" is an 8-bit unsigned value.
  24332. */
  24333. typedef unsigned char etByte;
  24334. /*
  24335. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  24336. ** by an instance of the following structure
  24337. */
  24338. typedef struct et_info { /* Information about each format field */
  24339. char fmttype; /* The format field code letter */
  24340. etByte base; /* The base for radix conversion */
  24341. etByte flags; /* One or more of FLAG_ constants below */
  24342. etByte type; /* Conversion paradigm */
  24343. etByte charset; /* Offset into aDigits[] of the digits string */
  24344. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  24345. } et_info;
  24346. /*
  24347. ** Allowed values for et_info.flags
  24348. */
  24349. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  24350. #define FLAG_STRING 4 /* Allow infinite precision */
  24351. /*
  24352. ** The following table is searched linearly, so it is good to put the
  24353. ** most frequently used conversion types first.
  24354. */
  24355. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  24356. static const char aPrefix[] = "-x0\000X0";
  24357. static const et_info fmtinfo[] = {
  24358. { 'd', 10, 1, etDECIMAL, 0, 0 },
  24359. { 's', 0, 4, etSTRING, 0, 0 },
  24360. { 'g', 0, 1, etGENERIC, 30, 0 },
  24361. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  24362. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  24363. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  24364. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  24365. { 'c', 0, 0, etCHARX, 0, 0 },
  24366. { 'o', 8, 0, etRADIX, 0, 2 },
  24367. { 'u', 10, 0, etDECIMAL, 0, 0 },
  24368. { 'x', 16, 0, etRADIX, 16, 1 },
  24369. { 'X', 16, 0, etRADIX, 0, 4 },
  24370. #ifndef SQLITE_OMIT_FLOATING_POINT
  24371. { 'f', 0, 1, etFLOAT, 0, 0 },
  24372. { 'e', 0, 1, etEXP, 30, 0 },
  24373. { 'E', 0, 1, etEXP, 14, 0 },
  24374. { 'G', 0, 1, etGENERIC, 14, 0 },
  24375. #endif
  24376. { 'i', 10, 1, etDECIMAL, 0, 0 },
  24377. { 'n', 0, 0, etSIZE, 0, 0 },
  24378. { '%', 0, 0, etPERCENT, 0, 0 },
  24379. { 'p', 16, 0, etPOINTER, 0, 1 },
  24380. /* All the rest are undocumented and are for internal use only */
  24381. { 'T', 0, 0, etTOKEN, 0, 0 },
  24382. { 'S', 0, 0, etSRCLIST, 0, 0 },
  24383. { 'r', 10, 1, etORDINAL, 0, 0 },
  24384. };
  24385. /*
  24386. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  24387. ** conversions will work.
  24388. */
  24389. #ifndef SQLITE_OMIT_FLOATING_POINT
  24390. /*
  24391. ** "*val" is a double such that 0.1 <= *val < 10.0
  24392. ** Return the ascii code for the leading digit of *val, then
  24393. ** multiply "*val" by 10.0 to renormalize.
  24394. **
  24395. ** Example:
  24396. ** input: *val = 3.14159
  24397. ** output: *val = 1.4159 function return = '3'
  24398. **
  24399. ** The counter *cnt is incremented each time. After counter exceeds
  24400. ** 16 (the number of significant digits in a 64-bit float) '0' is
  24401. ** always returned.
  24402. */
  24403. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  24404. int digit;
  24405. LONGDOUBLE_TYPE d;
  24406. if( (*cnt)<=0 ) return '0';
  24407. (*cnt)--;
  24408. digit = (int)*val;
  24409. d = digit;
  24410. digit += '0';
  24411. *val = (*val - d)*10.0;
  24412. return (char)digit;
  24413. }
  24414. #endif /* SQLITE_OMIT_FLOATING_POINT */
  24415. /*
  24416. ** Set the StrAccum object to an error mode.
  24417. */
  24418. static void setStrAccumError(StrAccum *p, u8 eError){
  24419. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  24420. p->accError = eError;
  24421. p->nAlloc = 0;
  24422. }
  24423. /*
  24424. ** Extra argument values from a PrintfArguments object
  24425. */
  24426. static sqlite3_int64 getIntArg(PrintfArguments *p){
  24427. if( p->nArg<=p->nUsed ) return 0;
  24428. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  24429. }
  24430. static double getDoubleArg(PrintfArguments *p){
  24431. if( p->nArg<=p->nUsed ) return 0.0;
  24432. return sqlite3_value_double(p->apArg[p->nUsed++]);
  24433. }
  24434. static char *getTextArg(PrintfArguments *p){
  24435. if( p->nArg<=p->nUsed ) return 0;
  24436. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  24437. }
  24438. /*
  24439. ** On machines with a small stack size, you can redefine the
  24440. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  24441. */
  24442. #ifndef SQLITE_PRINT_BUF_SIZE
  24443. # define SQLITE_PRINT_BUF_SIZE 70
  24444. #endif
  24445. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  24446. /*
  24447. ** Render a string given by "fmt" into the StrAccum object.
  24448. */
  24449. SQLITE_PRIVATE void sqlite3VXPrintf(
  24450. StrAccum *pAccum, /* Accumulate results here */
  24451. const char *fmt, /* Format string */
  24452. va_list ap /* arguments */
  24453. ){
  24454. int c; /* Next character in the format string */
  24455. char *bufpt; /* Pointer to the conversion buffer */
  24456. int precision; /* Precision of the current field */
  24457. int length; /* Length of the field */
  24458. int idx; /* A general purpose loop counter */
  24459. int width; /* Width of the current field */
  24460. etByte flag_leftjustify; /* True if "-" flag is present */
  24461. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  24462. etByte flag_alternateform; /* True if "#" flag is present */
  24463. etByte flag_altform2; /* True if "!" flag is present */
  24464. etByte flag_zeropad; /* True if field width constant starts with zero */
  24465. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  24466. etByte done; /* Loop termination flag */
  24467. etByte cThousand; /* Thousands separator for %d and %u */
  24468. etByte xtype = etINVALID; /* Conversion paradigm */
  24469. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  24470. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  24471. sqlite_uint64 longvalue; /* Value for integer types */
  24472. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  24473. const et_info *infop; /* Pointer to the appropriate info structure */
  24474. char *zOut; /* Rendering buffer */
  24475. int nOut; /* Size of the rendering buffer */
  24476. char *zExtra = 0; /* Malloced memory used by some conversion */
  24477. #ifndef SQLITE_OMIT_FLOATING_POINT
  24478. int exp, e2; /* exponent of real numbers */
  24479. int nsd; /* Number of significant digits returned */
  24480. double rounder; /* Used for rounding floating point values */
  24481. etByte flag_dp; /* True if decimal point should be shown */
  24482. etByte flag_rtz; /* True if trailing zeros should be removed */
  24483. #endif
  24484. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  24485. char buf[etBUFSIZE]; /* Conversion buffer */
  24486. bufpt = 0;
  24487. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  24488. pArgList = va_arg(ap, PrintfArguments*);
  24489. bArgList = 1;
  24490. }else{
  24491. bArgList = 0;
  24492. }
  24493. for(; (c=(*fmt))!=0; ++fmt){
  24494. if( c!='%' ){
  24495. bufpt = (char *)fmt;
  24496. #if HAVE_STRCHRNUL
  24497. fmt = strchrnul(fmt, '%');
  24498. #else
  24499. do{ fmt++; }while( *fmt && *fmt != '%' );
  24500. #endif
  24501. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  24502. if( *fmt==0 ) break;
  24503. }
  24504. if( (c=(*++fmt))==0 ){
  24505. sqlite3StrAccumAppend(pAccum, "%", 1);
  24506. break;
  24507. }
  24508. /* Find out what flags are present */
  24509. flag_leftjustify = flag_prefix = cThousand =
  24510. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  24511. done = 0;
  24512. do{
  24513. switch( c ){
  24514. case '-': flag_leftjustify = 1; break;
  24515. case '+': flag_prefix = '+'; break;
  24516. case ' ': flag_prefix = ' '; break;
  24517. case '#': flag_alternateform = 1; break;
  24518. case '!': flag_altform2 = 1; break;
  24519. case '0': flag_zeropad = 1; break;
  24520. case ',': cThousand = ','; break;
  24521. default: done = 1; break;
  24522. }
  24523. }while( !done && (c=(*++fmt))!=0 );
  24524. /* Get the field width */
  24525. if( c=='*' ){
  24526. if( bArgList ){
  24527. width = (int)getIntArg(pArgList);
  24528. }else{
  24529. width = va_arg(ap,int);
  24530. }
  24531. if( width<0 ){
  24532. flag_leftjustify = 1;
  24533. width = width >= -2147483647 ? -width : 0;
  24534. }
  24535. c = *++fmt;
  24536. }else{
  24537. unsigned wx = 0;
  24538. while( c>='0' && c<='9' ){
  24539. wx = wx*10 + c - '0';
  24540. c = *++fmt;
  24541. }
  24542. testcase( wx>0x7fffffff );
  24543. width = wx & 0x7fffffff;
  24544. }
  24545. assert( width>=0 );
  24546. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24547. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  24548. width = SQLITE_PRINTF_PRECISION_LIMIT;
  24549. }
  24550. #endif
  24551. /* Get the precision */
  24552. if( c=='.' ){
  24553. c = *++fmt;
  24554. if( c=='*' ){
  24555. if( bArgList ){
  24556. precision = (int)getIntArg(pArgList);
  24557. }else{
  24558. precision = va_arg(ap,int);
  24559. }
  24560. c = *++fmt;
  24561. if( precision<0 ){
  24562. precision = precision >= -2147483647 ? -precision : -1;
  24563. }
  24564. }else{
  24565. unsigned px = 0;
  24566. while( c>='0' && c<='9' ){
  24567. px = px*10 + c - '0';
  24568. c = *++fmt;
  24569. }
  24570. testcase( px>0x7fffffff );
  24571. precision = px & 0x7fffffff;
  24572. }
  24573. }else{
  24574. precision = -1;
  24575. }
  24576. assert( precision>=(-1) );
  24577. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24578. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  24579. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  24580. }
  24581. #endif
  24582. /* Get the conversion type modifier */
  24583. if( c=='l' ){
  24584. flag_long = 1;
  24585. c = *++fmt;
  24586. if( c=='l' ){
  24587. flag_long = 2;
  24588. c = *++fmt;
  24589. }
  24590. }else{
  24591. flag_long = 0;
  24592. }
  24593. /* Fetch the info entry for the field */
  24594. infop = &fmtinfo[0];
  24595. xtype = etINVALID;
  24596. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  24597. if( c==fmtinfo[idx].fmttype ){
  24598. infop = &fmtinfo[idx];
  24599. xtype = infop->type;
  24600. break;
  24601. }
  24602. }
  24603. /*
  24604. ** At this point, variables are initialized as follows:
  24605. **
  24606. ** flag_alternateform TRUE if a '#' is present.
  24607. ** flag_altform2 TRUE if a '!' is present.
  24608. ** flag_prefix '+' or ' ' or zero
  24609. ** flag_leftjustify TRUE if a '-' is present or if the
  24610. ** field width was negative.
  24611. ** flag_zeropad TRUE if the width began with 0.
  24612. ** flag_long 1 for "l", 2 for "ll"
  24613. ** width The specified field width. This is
  24614. ** always non-negative. Zero is the default.
  24615. ** precision The specified precision. The default
  24616. ** is -1.
  24617. ** xtype The class of the conversion.
  24618. ** infop Pointer to the appropriate info struct.
  24619. */
  24620. switch( xtype ){
  24621. case etPOINTER:
  24622. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  24623. sizeof(char*)==sizeof(long int) ? 1 : 0;
  24624. /* Fall through into the next case */
  24625. case etORDINAL:
  24626. case etRADIX:
  24627. cThousand = 0;
  24628. /* Fall through into the next case */
  24629. case etDECIMAL:
  24630. if( infop->flags & FLAG_SIGNED ){
  24631. i64 v;
  24632. if( bArgList ){
  24633. v = getIntArg(pArgList);
  24634. }else if( flag_long ){
  24635. if( flag_long==2 ){
  24636. v = va_arg(ap,i64) ;
  24637. }else{
  24638. v = va_arg(ap,long int);
  24639. }
  24640. }else{
  24641. v = va_arg(ap,int);
  24642. }
  24643. if( v<0 ){
  24644. if( v==SMALLEST_INT64 ){
  24645. longvalue = ((u64)1)<<63;
  24646. }else{
  24647. longvalue = -v;
  24648. }
  24649. prefix = '-';
  24650. }else{
  24651. longvalue = v;
  24652. prefix = flag_prefix;
  24653. }
  24654. }else{
  24655. if( bArgList ){
  24656. longvalue = (u64)getIntArg(pArgList);
  24657. }else if( flag_long ){
  24658. if( flag_long==2 ){
  24659. longvalue = va_arg(ap,u64);
  24660. }else{
  24661. longvalue = va_arg(ap,unsigned long int);
  24662. }
  24663. }else{
  24664. longvalue = va_arg(ap,unsigned int);
  24665. }
  24666. prefix = 0;
  24667. }
  24668. if( longvalue==0 ) flag_alternateform = 0;
  24669. if( flag_zeropad && precision<width-(prefix!=0) ){
  24670. precision = width-(prefix!=0);
  24671. }
  24672. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  24673. nOut = etBUFSIZE;
  24674. zOut = buf;
  24675. }else{
  24676. u64 n = (u64)precision + 10 + precision/3;
  24677. zOut = zExtra = sqlite3Malloc( n );
  24678. if( zOut==0 ){
  24679. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24680. return;
  24681. }
  24682. nOut = (int)n;
  24683. }
  24684. bufpt = &zOut[nOut-1];
  24685. if( xtype==etORDINAL ){
  24686. static const char zOrd[] = "thstndrd";
  24687. int x = (int)(longvalue % 10);
  24688. if( x>=4 || (longvalue/10)%10==1 ){
  24689. x = 0;
  24690. }
  24691. *(--bufpt) = zOrd[x*2+1];
  24692. *(--bufpt) = zOrd[x*2];
  24693. }
  24694. {
  24695. const char *cset = &aDigits[infop->charset];
  24696. u8 base = infop->base;
  24697. do{ /* Convert to ascii */
  24698. *(--bufpt) = cset[longvalue%base];
  24699. longvalue = longvalue/base;
  24700. }while( longvalue>0 );
  24701. }
  24702. length = (int)(&zOut[nOut-1]-bufpt);
  24703. while( precision>length ){
  24704. *(--bufpt) = '0'; /* Zero pad */
  24705. length++;
  24706. }
  24707. if( cThousand ){
  24708. int nn = (length - 1)/3; /* Number of "," to insert */
  24709. int ix = (length - 1)%3 + 1;
  24710. bufpt -= nn;
  24711. for(idx=0; nn>0; idx++){
  24712. bufpt[idx] = bufpt[idx+nn];
  24713. ix--;
  24714. if( ix==0 ){
  24715. bufpt[++idx] = cThousand;
  24716. nn--;
  24717. ix = 3;
  24718. }
  24719. }
  24720. }
  24721. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  24722. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  24723. const char *pre;
  24724. char x;
  24725. pre = &aPrefix[infop->prefix];
  24726. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  24727. }
  24728. length = (int)(&zOut[nOut-1]-bufpt);
  24729. break;
  24730. case etFLOAT:
  24731. case etEXP:
  24732. case etGENERIC:
  24733. if( bArgList ){
  24734. realvalue = getDoubleArg(pArgList);
  24735. }else{
  24736. realvalue = va_arg(ap,double);
  24737. }
  24738. #ifdef SQLITE_OMIT_FLOATING_POINT
  24739. length = 0;
  24740. #else
  24741. if( precision<0 ) precision = 6; /* Set default precision */
  24742. if( realvalue<0.0 ){
  24743. realvalue = -realvalue;
  24744. prefix = '-';
  24745. }else{
  24746. prefix = flag_prefix;
  24747. }
  24748. if( xtype==etGENERIC && precision>0 ) precision--;
  24749. testcase( precision>0xfff );
  24750. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  24751. if( xtype==etFLOAT ) realvalue += rounder;
  24752. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  24753. exp = 0;
  24754. if( sqlite3IsNaN((double)realvalue) ){
  24755. bufpt = "NaN";
  24756. length = 3;
  24757. break;
  24758. }
  24759. if( realvalue>0.0 ){
  24760. LONGDOUBLE_TYPE scale = 1.0;
  24761. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  24762. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  24763. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  24764. realvalue /= scale;
  24765. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  24766. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  24767. if( exp>350 ){
  24768. bufpt = buf;
  24769. buf[0] = prefix;
  24770. memcpy(buf+(prefix!=0),"Inf",4);
  24771. length = 3+(prefix!=0);
  24772. break;
  24773. }
  24774. }
  24775. bufpt = buf;
  24776. /*
  24777. ** If the field type is etGENERIC, then convert to either etEXP
  24778. ** or etFLOAT, as appropriate.
  24779. */
  24780. if( xtype!=etFLOAT ){
  24781. realvalue += rounder;
  24782. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  24783. }
  24784. if( xtype==etGENERIC ){
  24785. flag_rtz = !flag_alternateform;
  24786. if( exp<-4 || exp>precision ){
  24787. xtype = etEXP;
  24788. }else{
  24789. precision = precision - exp;
  24790. xtype = etFLOAT;
  24791. }
  24792. }else{
  24793. flag_rtz = flag_altform2;
  24794. }
  24795. if( xtype==etEXP ){
  24796. e2 = 0;
  24797. }else{
  24798. e2 = exp;
  24799. }
  24800. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  24801. bufpt = zExtra
  24802. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  24803. if( bufpt==0 ){
  24804. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24805. return;
  24806. }
  24807. }
  24808. zOut = bufpt;
  24809. nsd = 16 + flag_altform2*10;
  24810. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  24811. /* The sign in front of the number */
  24812. if( prefix ){
  24813. *(bufpt++) = prefix;
  24814. }
  24815. /* Digits prior to the decimal point */
  24816. if( e2<0 ){
  24817. *(bufpt++) = '0';
  24818. }else{
  24819. for(; e2>=0; e2--){
  24820. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24821. }
  24822. }
  24823. /* The decimal point */
  24824. if( flag_dp ){
  24825. *(bufpt++) = '.';
  24826. }
  24827. /* "0" digits after the decimal point but before the first
  24828. ** significant digit of the number */
  24829. for(e2++; e2<0; precision--, e2++){
  24830. assert( precision>0 );
  24831. *(bufpt++) = '0';
  24832. }
  24833. /* Significant digits after the decimal point */
  24834. while( (precision--)>0 ){
  24835. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24836. }
  24837. /* Remove trailing zeros and the "." if no digits follow the "." */
  24838. if( flag_rtz && flag_dp ){
  24839. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  24840. assert( bufpt>zOut );
  24841. if( bufpt[-1]=='.' ){
  24842. if( flag_altform2 ){
  24843. *(bufpt++) = '0';
  24844. }else{
  24845. *(--bufpt) = 0;
  24846. }
  24847. }
  24848. }
  24849. /* Add the "eNNN" suffix */
  24850. if( xtype==etEXP ){
  24851. *(bufpt++) = aDigits[infop->charset];
  24852. if( exp<0 ){
  24853. *(bufpt++) = '-'; exp = -exp;
  24854. }else{
  24855. *(bufpt++) = '+';
  24856. }
  24857. if( exp>=100 ){
  24858. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  24859. exp %= 100;
  24860. }
  24861. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  24862. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  24863. }
  24864. *bufpt = 0;
  24865. /* The converted number is in buf[] and zero terminated. Output it.
  24866. ** Note that the number is in the usual order, not reversed as with
  24867. ** integer conversions. */
  24868. length = (int)(bufpt-zOut);
  24869. bufpt = zOut;
  24870. /* Special case: Add leading zeros if the flag_zeropad flag is
  24871. ** set and we are not left justified */
  24872. if( flag_zeropad && !flag_leftjustify && length < width){
  24873. int i;
  24874. int nPad = width - length;
  24875. for(i=width; i>=nPad; i--){
  24876. bufpt[i] = bufpt[i-nPad];
  24877. }
  24878. i = prefix!=0;
  24879. while( nPad-- ) bufpt[i++] = '0';
  24880. length = width;
  24881. }
  24882. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  24883. break;
  24884. case etSIZE:
  24885. if( !bArgList ){
  24886. *(va_arg(ap,int*)) = pAccum->nChar;
  24887. }
  24888. length = width = 0;
  24889. break;
  24890. case etPERCENT:
  24891. buf[0] = '%';
  24892. bufpt = buf;
  24893. length = 1;
  24894. break;
  24895. case etCHARX:
  24896. if( bArgList ){
  24897. bufpt = getTextArg(pArgList);
  24898. c = bufpt ? bufpt[0] : 0;
  24899. }else{
  24900. c = va_arg(ap,int);
  24901. }
  24902. if( precision>1 ){
  24903. width -= precision-1;
  24904. if( width>1 && !flag_leftjustify ){
  24905. sqlite3AppendChar(pAccum, width-1, ' ');
  24906. width = 0;
  24907. }
  24908. sqlite3AppendChar(pAccum, precision-1, c);
  24909. }
  24910. length = 1;
  24911. buf[0] = c;
  24912. bufpt = buf;
  24913. break;
  24914. case etSTRING:
  24915. case etDYNSTRING:
  24916. if( bArgList ){
  24917. bufpt = getTextArg(pArgList);
  24918. xtype = etSTRING;
  24919. }else{
  24920. bufpt = va_arg(ap,char*);
  24921. }
  24922. if( bufpt==0 ){
  24923. bufpt = "";
  24924. }else if( xtype==etDYNSTRING ){
  24925. zExtra = bufpt;
  24926. }
  24927. if( precision>=0 ){
  24928. for(length=0; length<precision && bufpt[length]; length++){}
  24929. }else{
  24930. length = 0x7fffffff & (int)strlen(bufpt);
  24931. }
  24932. break;
  24933. case etSQLESCAPE: /* Escape ' characters */
  24934. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  24935. case etSQLESCAPE3: { /* Escape " characters */
  24936. int i, j, k, n, isnull;
  24937. int needQuote;
  24938. char ch;
  24939. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  24940. char *escarg;
  24941. if( bArgList ){
  24942. escarg = getTextArg(pArgList);
  24943. }else{
  24944. escarg = va_arg(ap,char*);
  24945. }
  24946. isnull = escarg==0;
  24947. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  24948. k = precision;
  24949. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  24950. if( ch==q ) n++;
  24951. }
  24952. needQuote = !isnull && xtype==etSQLESCAPE2;
  24953. n += i + 3;
  24954. if( n>etBUFSIZE ){
  24955. bufpt = zExtra = sqlite3Malloc( n );
  24956. if( bufpt==0 ){
  24957. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24958. return;
  24959. }
  24960. }else{
  24961. bufpt = buf;
  24962. }
  24963. j = 0;
  24964. if( needQuote ) bufpt[j++] = q;
  24965. k = i;
  24966. for(i=0; i<k; i++){
  24967. bufpt[j++] = ch = escarg[i];
  24968. if( ch==q ) bufpt[j++] = ch;
  24969. }
  24970. if( needQuote ) bufpt[j++] = q;
  24971. bufpt[j] = 0;
  24972. length = j;
  24973. /* The precision in %q and %Q means how many input characters to
  24974. ** consume, not the length of the output...
  24975. ** if( precision>=0 && precision<length ) length = precision; */
  24976. break;
  24977. }
  24978. case etTOKEN: {
  24979. Token *pToken;
  24980. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24981. pToken = va_arg(ap, Token*);
  24982. assert( bArgList==0 );
  24983. if( pToken && pToken->n ){
  24984. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  24985. }
  24986. length = width = 0;
  24987. break;
  24988. }
  24989. case etSRCLIST: {
  24990. SrcList *pSrc;
  24991. int k;
  24992. struct SrcList_item *pItem;
  24993. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24994. pSrc = va_arg(ap, SrcList*);
  24995. k = va_arg(ap, int);
  24996. pItem = &pSrc->a[k];
  24997. assert( bArgList==0 );
  24998. assert( k>=0 && k<pSrc->nSrc );
  24999. if( pItem->zDatabase ){
  25000. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  25001. sqlite3StrAccumAppend(pAccum, ".", 1);
  25002. }
  25003. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  25004. length = width = 0;
  25005. break;
  25006. }
  25007. default: {
  25008. assert( xtype==etINVALID );
  25009. return;
  25010. }
  25011. }/* End switch over the format type */
  25012. /*
  25013. ** The text of the conversion is pointed to by "bufpt" and is
  25014. ** "length" characters long. The field width is "width". Do
  25015. ** the output.
  25016. */
  25017. width -= length;
  25018. if( width>0 ){
  25019. if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  25020. sqlite3StrAccumAppend(pAccum, bufpt, length);
  25021. if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  25022. }else{
  25023. sqlite3StrAccumAppend(pAccum, bufpt, length);
  25024. }
  25025. if( zExtra ){
  25026. sqlite3DbFree(pAccum->db, zExtra);
  25027. zExtra = 0;
  25028. }
  25029. }/* End for loop over the format string */
  25030. } /* End of function */
  25031. /*
  25032. ** Enlarge the memory allocation on a StrAccum object so that it is
  25033. ** able to accept at least N more bytes of text.
  25034. **
  25035. ** Return the number of bytes of text that StrAccum is able to accept
  25036. ** after the attempted enlargement. The value returned might be zero.
  25037. */
  25038. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  25039. char *zNew;
  25040. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  25041. if( p->accError ){
  25042. testcase(p->accError==STRACCUM_TOOBIG);
  25043. testcase(p->accError==STRACCUM_NOMEM);
  25044. return 0;
  25045. }
  25046. if( p->mxAlloc==0 ){
  25047. N = p->nAlloc - p->nChar - 1;
  25048. setStrAccumError(p, STRACCUM_TOOBIG);
  25049. return N;
  25050. }else{
  25051. char *zOld = isMalloced(p) ? p->zText : 0;
  25052. i64 szNew = p->nChar;
  25053. szNew += N + 1;
  25054. if( szNew+p->nChar<=p->mxAlloc ){
  25055. /* Force exponential buffer size growth as long as it does not overflow,
  25056. ** to avoid having to call this routine too often */
  25057. szNew += p->nChar;
  25058. }
  25059. if( szNew > p->mxAlloc ){
  25060. sqlite3StrAccumReset(p);
  25061. setStrAccumError(p, STRACCUM_TOOBIG);
  25062. return 0;
  25063. }else{
  25064. p->nAlloc = (int)szNew;
  25065. }
  25066. if( p->db ){
  25067. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  25068. }else{
  25069. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  25070. }
  25071. if( zNew ){
  25072. assert( p->zText!=0 || p->nChar==0 );
  25073. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  25074. p->zText = zNew;
  25075. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  25076. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25077. }else{
  25078. sqlite3StrAccumReset(p);
  25079. setStrAccumError(p, STRACCUM_NOMEM);
  25080. return 0;
  25081. }
  25082. }
  25083. return N;
  25084. }
  25085. /*
  25086. ** Append N copies of character c to the given string buffer.
  25087. */
  25088. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  25089. testcase( p->nChar + (i64)N > 0x7fffffff );
  25090. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  25091. return;
  25092. }
  25093. while( (N--)>0 ) p->zText[p->nChar++] = c;
  25094. }
  25095. /*
  25096. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  25097. ** So enlarge if first, then do the append.
  25098. **
  25099. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  25100. ** work (enlarging the buffer) using tail recursion, so that the
  25101. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  25102. */
  25103. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  25104. N = sqlite3StrAccumEnlarge(p, N);
  25105. if( N>0 ){
  25106. memcpy(&p->zText[p->nChar], z, N);
  25107. p->nChar += N;
  25108. }
  25109. }
  25110. /*
  25111. ** Append N bytes of text from z to the StrAccum object. Increase the
  25112. ** size of the memory allocation for StrAccum if necessary.
  25113. */
  25114. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  25115. assert( z!=0 || N==0 );
  25116. assert( p->zText!=0 || p->nChar==0 || p->accError );
  25117. assert( N>=0 );
  25118. assert( p->accError==0 || p->nAlloc==0 );
  25119. if( p->nChar+N >= p->nAlloc ){
  25120. enlargeAndAppend(p,z,N);
  25121. }else if( N ){
  25122. assert( p->zText );
  25123. p->nChar += N;
  25124. memcpy(&p->zText[p->nChar-N], z, N);
  25125. }
  25126. }
  25127. /*
  25128. ** Append the complete text of zero-terminated string z[] to the p string.
  25129. */
  25130. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  25131. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  25132. }
  25133. /*
  25134. ** Finish off a string by making sure it is zero-terminated.
  25135. ** Return a pointer to the resulting string. Return a NULL
  25136. ** pointer if any kind of error was encountered.
  25137. */
  25138. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  25139. char *zText;
  25140. assert( p->mxAlloc>0 && !isMalloced(p) );
  25141. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  25142. if( zText ){
  25143. memcpy(zText, p->zText, p->nChar+1);
  25144. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25145. }else{
  25146. setStrAccumError(p, STRACCUM_NOMEM);
  25147. }
  25148. p->zText = zText;
  25149. return zText;
  25150. }
  25151. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  25152. if( p->zText ){
  25153. p->zText[p->nChar] = 0;
  25154. if( p->mxAlloc>0 && !isMalloced(p) ){
  25155. return strAccumFinishRealloc(p);
  25156. }
  25157. }
  25158. return p->zText;
  25159. }
  25160. /*
  25161. ** Reset an StrAccum string. Reclaim all malloced memory.
  25162. */
  25163. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  25164. if( isMalloced(p) ){
  25165. sqlite3DbFree(p->db, p->zText);
  25166. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  25167. }
  25168. p->zText = 0;
  25169. }
  25170. /*
  25171. ** Initialize a string accumulator.
  25172. **
  25173. ** p: The accumulator to be initialized.
  25174. ** db: Pointer to a database connection. May be NULL. Lookaside
  25175. ** memory is used if not NULL. db->mallocFailed is set appropriately
  25176. ** when not NULL.
  25177. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  25178. ** is malloced.
  25179. ** n: Size of zBase in bytes. If total space requirements never exceed
  25180. ** n then no memory allocations ever occur.
  25181. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  25182. ** allocations will ever occur.
  25183. */
  25184. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  25185. p->zText = zBase;
  25186. p->db = db;
  25187. p->nAlloc = n;
  25188. p->mxAlloc = mx;
  25189. p->nChar = 0;
  25190. p->accError = 0;
  25191. p->printfFlags = 0;
  25192. }
  25193. /*
  25194. ** Print into memory obtained from sqliteMalloc(). Use the internal
  25195. ** %-conversion extensions.
  25196. */
  25197. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  25198. char *z;
  25199. char zBase[SQLITE_PRINT_BUF_SIZE];
  25200. StrAccum acc;
  25201. assert( db!=0 );
  25202. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  25203. db->aLimit[SQLITE_LIMIT_LENGTH]);
  25204. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  25205. sqlite3VXPrintf(&acc, zFormat, ap);
  25206. z = sqlite3StrAccumFinish(&acc);
  25207. if( acc.accError==STRACCUM_NOMEM ){
  25208. sqlite3OomFault(db);
  25209. }
  25210. return z;
  25211. }
  25212. /*
  25213. ** Print into memory obtained from sqliteMalloc(). Use the internal
  25214. ** %-conversion extensions.
  25215. */
  25216. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  25217. va_list ap;
  25218. char *z;
  25219. va_start(ap, zFormat);
  25220. z = sqlite3VMPrintf(db, zFormat, ap);
  25221. va_end(ap);
  25222. return z;
  25223. }
  25224. /*
  25225. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  25226. ** %-conversion extensions.
  25227. */
  25228. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  25229. char *z;
  25230. char zBase[SQLITE_PRINT_BUF_SIZE];
  25231. StrAccum acc;
  25232. #ifdef SQLITE_ENABLE_API_ARMOR
  25233. if( zFormat==0 ){
  25234. (void)SQLITE_MISUSE_BKPT;
  25235. return 0;
  25236. }
  25237. #endif
  25238. #ifndef SQLITE_OMIT_AUTOINIT
  25239. if( sqlite3_initialize() ) return 0;
  25240. #endif
  25241. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  25242. sqlite3VXPrintf(&acc, zFormat, ap);
  25243. z = sqlite3StrAccumFinish(&acc);
  25244. return z;
  25245. }
  25246. /*
  25247. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  25248. ** %-conversion extensions.
  25249. */
  25250. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  25251. va_list ap;
  25252. char *z;
  25253. #ifndef SQLITE_OMIT_AUTOINIT
  25254. if( sqlite3_initialize() ) return 0;
  25255. #endif
  25256. va_start(ap, zFormat);
  25257. z = sqlite3_vmprintf(zFormat, ap);
  25258. va_end(ap);
  25259. return z;
  25260. }
  25261. /*
  25262. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  25263. ** current locale settings. This is important for SQLite because we
  25264. ** are not able to use a "," as the decimal point in place of "." as
  25265. ** specified by some locales.
  25266. **
  25267. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  25268. ** from the snprintf() standard. Unfortunately, it is too late to change
  25269. ** this without breaking compatibility, so we just have to live with the
  25270. ** mistake.
  25271. **
  25272. ** sqlite3_vsnprintf() is the varargs version.
  25273. */
  25274. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  25275. StrAccum acc;
  25276. if( n<=0 ) return zBuf;
  25277. #ifdef SQLITE_ENABLE_API_ARMOR
  25278. if( zBuf==0 || zFormat==0 ) {
  25279. (void)SQLITE_MISUSE_BKPT;
  25280. if( zBuf ) zBuf[0] = 0;
  25281. return zBuf;
  25282. }
  25283. #endif
  25284. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  25285. sqlite3VXPrintf(&acc, zFormat, ap);
  25286. zBuf[acc.nChar] = 0;
  25287. return zBuf;
  25288. }
  25289. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  25290. char *z;
  25291. va_list ap;
  25292. va_start(ap,zFormat);
  25293. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  25294. va_end(ap);
  25295. return z;
  25296. }
  25297. /*
  25298. ** This is the routine that actually formats the sqlite3_log() message.
  25299. ** We house it in a separate routine from sqlite3_log() to avoid using
  25300. ** stack space on small-stack systems when logging is disabled.
  25301. **
  25302. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  25303. ** allocate memory because it might be called while the memory allocator
  25304. ** mutex is held.
  25305. **
  25306. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  25307. ** certain format characters (%q) or for very large precisions or widths.
  25308. ** Care must be taken that any sqlite3_log() calls that occur while the
  25309. ** memory mutex is held do not use these mechanisms.
  25310. */
  25311. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  25312. StrAccum acc; /* String accumulator */
  25313. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  25314. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  25315. sqlite3VXPrintf(&acc, zFormat, ap);
  25316. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  25317. sqlite3StrAccumFinish(&acc));
  25318. }
  25319. /*
  25320. ** Format and write a message to the log if logging is enabled.
  25321. */
  25322. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  25323. va_list ap; /* Vararg list */
  25324. if( sqlite3GlobalConfig.xLog ){
  25325. va_start(ap, zFormat);
  25326. renderLogMsg(iErrCode, zFormat, ap);
  25327. va_end(ap);
  25328. }
  25329. }
  25330. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  25331. /*
  25332. ** A version of printf() that understands %lld. Used for debugging.
  25333. ** The printf() built into some versions of windows does not understand %lld
  25334. ** and segfaults if you give it a long long int.
  25335. */
  25336. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  25337. va_list ap;
  25338. StrAccum acc;
  25339. char zBuf[500];
  25340. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  25341. va_start(ap,zFormat);
  25342. sqlite3VXPrintf(&acc, zFormat, ap);
  25343. va_end(ap);
  25344. sqlite3StrAccumFinish(&acc);
  25345. fprintf(stdout,"%s", zBuf);
  25346. fflush(stdout);
  25347. }
  25348. #endif
  25349. /*
  25350. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  25351. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  25352. */
  25353. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  25354. va_list ap;
  25355. va_start(ap,zFormat);
  25356. sqlite3VXPrintf(p, zFormat, ap);
  25357. va_end(ap);
  25358. }
  25359. /************** End of printf.c **********************************************/
  25360. /************** Begin file treeview.c ****************************************/
  25361. /*
  25362. ** 2015-06-08
  25363. **
  25364. ** The author disclaims copyright to this source code. In place of
  25365. ** a legal notice, here is a blessing:
  25366. **
  25367. ** May you do good and not evil.
  25368. ** May you find forgiveness for yourself and forgive others.
  25369. ** May you share freely, never taking more than you give.
  25370. **
  25371. *************************************************************************
  25372. **
  25373. ** This file contains C code to implement the TreeView debugging routines.
  25374. ** These routines print a parse tree to standard output for debugging and
  25375. ** analysis.
  25376. **
  25377. ** The interfaces in this file is only available when compiling
  25378. ** with SQLITE_DEBUG.
  25379. */
  25380. /* #include "sqliteInt.h" */
  25381. #ifdef SQLITE_DEBUG
  25382. /*
  25383. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  25384. ** is not the last item in the tree.
  25385. */
  25386. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  25387. if( p==0 ){
  25388. p = sqlite3_malloc64( sizeof(*p) );
  25389. if( p==0 ) return 0;
  25390. memset(p, 0, sizeof(*p));
  25391. }else{
  25392. p->iLevel++;
  25393. }
  25394. assert( moreToFollow==0 || moreToFollow==1 );
  25395. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  25396. return p;
  25397. }
  25398. /*
  25399. ** Finished with one layer of the tree
  25400. */
  25401. static void sqlite3TreeViewPop(TreeView *p){
  25402. if( p==0 ) return;
  25403. p->iLevel--;
  25404. if( p->iLevel<0 ) sqlite3_free(p);
  25405. }
  25406. /*
  25407. ** Generate a single line of output for the tree, with a prefix that contains
  25408. ** all the appropriate tree lines
  25409. */
  25410. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  25411. va_list ap;
  25412. int i;
  25413. StrAccum acc;
  25414. char zBuf[500];
  25415. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  25416. if( p ){
  25417. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  25418. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  25419. }
  25420. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  25421. }
  25422. va_start(ap, zFormat);
  25423. sqlite3VXPrintf(&acc, zFormat, ap);
  25424. va_end(ap);
  25425. assert( acc.nChar>0 );
  25426. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  25427. sqlite3StrAccumFinish(&acc);
  25428. fprintf(stdout,"%s", zBuf);
  25429. fflush(stdout);
  25430. }
  25431. /*
  25432. ** Shorthand for starting a new tree item that consists of a single label
  25433. */
  25434. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  25435. p = sqlite3TreeViewPush(p, moreFollows);
  25436. sqlite3TreeViewLine(p, "%s", zLabel);
  25437. }
  25438. /*
  25439. ** Generate a human-readable description of a WITH clause.
  25440. */
  25441. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  25442. int i;
  25443. if( pWith==0 ) return;
  25444. if( pWith->nCte==0 ) return;
  25445. if( pWith->pOuter ){
  25446. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  25447. }else{
  25448. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  25449. }
  25450. if( pWith->nCte>0 ){
  25451. pView = sqlite3TreeViewPush(pView, 1);
  25452. for(i=0; i<pWith->nCte; i++){
  25453. StrAccum x;
  25454. char zLine[1000];
  25455. const struct Cte *pCte = &pWith->a[i];
  25456. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  25457. sqlite3XPrintf(&x, "%s", pCte->zName);
  25458. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  25459. char cSep = '(';
  25460. int j;
  25461. for(j=0; j<pCte->pCols->nExpr; j++){
  25462. sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  25463. cSep = ',';
  25464. }
  25465. sqlite3XPrintf(&x, ")");
  25466. }
  25467. sqlite3XPrintf(&x, " AS");
  25468. sqlite3StrAccumFinish(&x);
  25469. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  25470. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  25471. sqlite3TreeViewPop(pView);
  25472. }
  25473. sqlite3TreeViewPop(pView);
  25474. }
  25475. }
  25476. /*
  25477. ** Generate a human-readable description of a Select object.
  25478. */
  25479. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  25480. int n = 0;
  25481. int cnt = 0;
  25482. if( p==0 ){
  25483. sqlite3TreeViewLine(pView, "nil-SELECT");
  25484. return;
  25485. }
  25486. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25487. if( p->pWith ){
  25488. sqlite3TreeViewWith(pView, p->pWith, 1);
  25489. cnt = 1;
  25490. sqlite3TreeViewPush(pView, 1);
  25491. }
  25492. do{
  25493. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  25494. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  25495. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  25496. (int)p->nSelectRow
  25497. );
  25498. if( cnt++ ) sqlite3TreeViewPop(pView);
  25499. if( p->pPrior ){
  25500. n = 1000;
  25501. }else{
  25502. n = 0;
  25503. if( p->pSrc && p->pSrc->nSrc ) n++;
  25504. if( p->pWhere ) n++;
  25505. if( p->pGroupBy ) n++;
  25506. if( p->pHaving ) n++;
  25507. if( p->pOrderBy ) n++;
  25508. if( p->pLimit ) n++;
  25509. if( p->pOffset ) n++;
  25510. }
  25511. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  25512. if( p->pSrc && p->pSrc->nSrc ){
  25513. int i;
  25514. pView = sqlite3TreeViewPush(pView, (n--)>0);
  25515. sqlite3TreeViewLine(pView, "FROM");
  25516. for(i=0; i<p->pSrc->nSrc; i++){
  25517. struct SrcList_item *pItem = &p->pSrc->a[i];
  25518. StrAccum x;
  25519. char zLine[100];
  25520. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  25521. sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
  25522. if( pItem->zDatabase ){
  25523. sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  25524. }else if( pItem->zName ){
  25525. sqlite3XPrintf(&x, " %s", pItem->zName);
  25526. }
  25527. if( pItem->pTab ){
  25528. sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
  25529. }
  25530. if( pItem->zAlias ){
  25531. sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
  25532. }
  25533. if( pItem->fg.jointype & JT_LEFT ){
  25534. sqlite3XPrintf(&x, " LEFT-JOIN");
  25535. }
  25536. sqlite3StrAccumFinish(&x);
  25537. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  25538. if( pItem->pSelect ){
  25539. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  25540. }
  25541. if( pItem->fg.isTabFunc ){
  25542. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  25543. }
  25544. sqlite3TreeViewPop(pView);
  25545. }
  25546. sqlite3TreeViewPop(pView);
  25547. }
  25548. if( p->pWhere ){
  25549. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  25550. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  25551. sqlite3TreeViewPop(pView);
  25552. }
  25553. if( p->pGroupBy ){
  25554. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  25555. }
  25556. if( p->pHaving ){
  25557. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  25558. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  25559. sqlite3TreeViewPop(pView);
  25560. }
  25561. if( p->pOrderBy ){
  25562. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  25563. }
  25564. if( p->pLimit ){
  25565. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  25566. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  25567. sqlite3TreeViewPop(pView);
  25568. }
  25569. if( p->pOffset ){
  25570. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  25571. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  25572. sqlite3TreeViewPop(pView);
  25573. }
  25574. if( p->pPrior ){
  25575. const char *zOp = "UNION";
  25576. switch( p->op ){
  25577. case TK_ALL: zOp = "UNION ALL"; break;
  25578. case TK_INTERSECT: zOp = "INTERSECT"; break;
  25579. case TK_EXCEPT: zOp = "EXCEPT"; break;
  25580. }
  25581. sqlite3TreeViewItem(pView, zOp, 1);
  25582. }
  25583. p = p->pPrior;
  25584. }while( p!=0 );
  25585. sqlite3TreeViewPop(pView);
  25586. }
  25587. /*
  25588. ** Generate a human-readable explanation of an expression tree.
  25589. */
  25590. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  25591. const char *zBinOp = 0; /* Binary operator */
  25592. const char *zUniOp = 0; /* Unary operator */
  25593. char zFlgs[60];
  25594. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25595. if( pExpr==0 ){
  25596. sqlite3TreeViewLine(pView, "nil");
  25597. sqlite3TreeViewPop(pView);
  25598. return;
  25599. }
  25600. if( pExpr->flags ){
  25601. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  25602. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  25603. pExpr->flags, pExpr->iRightJoinTable);
  25604. }else{
  25605. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  25606. }
  25607. }else{
  25608. zFlgs[0] = 0;
  25609. }
  25610. switch( pExpr->op ){
  25611. case TK_AGG_COLUMN: {
  25612. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  25613. pExpr->iTable, pExpr->iColumn, zFlgs);
  25614. break;
  25615. }
  25616. case TK_COLUMN: {
  25617. if( pExpr->iTable<0 ){
  25618. /* This only happens when coding check constraints */
  25619. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  25620. }else{
  25621. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  25622. pExpr->iTable, pExpr->iColumn, zFlgs);
  25623. }
  25624. break;
  25625. }
  25626. case TK_INTEGER: {
  25627. if( pExpr->flags & EP_IntValue ){
  25628. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  25629. }else{
  25630. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  25631. }
  25632. break;
  25633. }
  25634. #ifndef SQLITE_OMIT_FLOATING_POINT
  25635. case TK_FLOAT: {
  25636. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25637. break;
  25638. }
  25639. #endif
  25640. case TK_STRING: {
  25641. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  25642. break;
  25643. }
  25644. case TK_NULL: {
  25645. sqlite3TreeViewLine(pView,"NULL");
  25646. break;
  25647. }
  25648. #ifndef SQLITE_OMIT_BLOB_LITERAL
  25649. case TK_BLOB: {
  25650. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25651. break;
  25652. }
  25653. #endif
  25654. case TK_VARIABLE: {
  25655. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  25656. pExpr->u.zToken, pExpr->iColumn);
  25657. break;
  25658. }
  25659. case TK_REGISTER: {
  25660. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  25661. break;
  25662. }
  25663. case TK_ID: {
  25664. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  25665. break;
  25666. }
  25667. #ifndef SQLITE_OMIT_CAST
  25668. case TK_CAST: {
  25669. /* Expressions of the form: CAST(pLeft AS token) */
  25670. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  25671. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25672. break;
  25673. }
  25674. #endif /* SQLITE_OMIT_CAST */
  25675. case TK_LT: zBinOp = "LT"; break;
  25676. case TK_LE: zBinOp = "LE"; break;
  25677. case TK_GT: zBinOp = "GT"; break;
  25678. case TK_GE: zBinOp = "GE"; break;
  25679. case TK_NE: zBinOp = "NE"; break;
  25680. case TK_EQ: zBinOp = "EQ"; break;
  25681. case TK_IS: zBinOp = "IS"; break;
  25682. case TK_ISNOT: zBinOp = "ISNOT"; break;
  25683. case TK_AND: zBinOp = "AND"; break;
  25684. case TK_OR: zBinOp = "OR"; break;
  25685. case TK_PLUS: zBinOp = "ADD"; break;
  25686. case TK_STAR: zBinOp = "MUL"; break;
  25687. case TK_MINUS: zBinOp = "SUB"; break;
  25688. case TK_REM: zBinOp = "REM"; break;
  25689. case TK_BITAND: zBinOp = "BITAND"; break;
  25690. case TK_BITOR: zBinOp = "BITOR"; break;
  25691. case TK_SLASH: zBinOp = "DIV"; break;
  25692. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  25693. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  25694. case TK_CONCAT: zBinOp = "CONCAT"; break;
  25695. case TK_DOT: zBinOp = "DOT"; break;
  25696. case TK_UMINUS: zUniOp = "UMINUS"; break;
  25697. case TK_UPLUS: zUniOp = "UPLUS"; break;
  25698. case TK_BITNOT: zUniOp = "BITNOT"; break;
  25699. case TK_NOT: zUniOp = "NOT"; break;
  25700. case TK_ISNULL: zUniOp = "ISNULL"; break;
  25701. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  25702. case TK_SPAN: {
  25703. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  25704. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25705. break;
  25706. }
  25707. case TK_COLLATE: {
  25708. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  25709. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25710. break;
  25711. }
  25712. case TK_AGG_FUNCTION:
  25713. case TK_FUNCTION: {
  25714. ExprList *pFarg; /* List of function arguments */
  25715. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  25716. pFarg = 0;
  25717. }else{
  25718. pFarg = pExpr->x.pList;
  25719. }
  25720. if( pExpr->op==TK_AGG_FUNCTION ){
  25721. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  25722. pExpr->op2, pExpr->u.zToken);
  25723. }else{
  25724. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  25725. }
  25726. if( pFarg ){
  25727. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  25728. }
  25729. break;
  25730. }
  25731. #ifndef SQLITE_OMIT_SUBQUERY
  25732. case TK_EXISTS: {
  25733. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  25734. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25735. break;
  25736. }
  25737. case TK_SELECT: {
  25738. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  25739. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25740. break;
  25741. }
  25742. case TK_IN: {
  25743. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  25744. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25745. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  25746. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25747. }else{
  25748. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25749. }
  25750. break;
  25751. }
  25752. #endif /* SQLITE_OMIT_SUBQUERY */
  25753. /*
  25754. ** x BETWEEN y AND z
  25755. **
  25756. ** This is equivalent to
  25757. **
  25758. ** x>=y AND x<=z
  25759. **
  25760. ** X is stored in pExpr->pLeft.
  25761. ** Y is stored in pExpr->pList->a[0].pExpr.
  25762. ** Z is stored in pExpr->pList->a[1].pExpr.
  25763. */
  25764. case TK_BETWEEN: {
  25765. Expr *pX = pExpr->pLeft;
  25766. Expr *pY = pExpr->x.pList->a[0].pExpr;
  25767. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  25768. sqlite3TreeViewLine(pView, "BETWEEN");
  25769. sqlite3TreeViewExpr(pView, pX, 1);
  25770. sqlite3TreeViewExpr(pView, pY, 1);
  25771. sqlite3TreeViewExpr(pView, pZ, 0);
  25772. break;
  25773. }
  25774. case TK_TRIGGER: {
  25775. /* If the opcode is TK_TRIGGER, then the expression is a reference
  25776. ** to a column in the new.* or old.* pseudo-tables available to
  25777. ** trigger programs. In this case Expr.iTable is set to 1 for the
  25778. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  25779. ** is set to the column of the pseudo-table to read, or to -1 to
  25780. ** read the rowid field.
  25781. */
  25782. sqlite3TreeViewLine(pView, "%s(%d)",
  25783. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  25784. break;
  25785. }
  25786. case TK_CASE: {
  25787. sqlite3TreeViewLine(pView, "CASE");
  25788. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25789. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25790. break;
  25791. }
  25792. #ifndef SQLITE_OMIT_TRIGGER
  25793. case TK_RAISE: {
  25794. const char *zType = "unk";
  25795. switch( pExpr->affinity ){
  25796. case OE_Rollback: zType = "rollback"; break;
  25797. case OE_Abort: zType = "abort"; break;
  25798. case OE_Fail: zType = "fail"; break;
  25799. case OE_Ignore: zType = "ignore"; break;
  25800. }
  25801. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  25802. break;
  25803. }
  25804. #endif
  25805. case TK_MATCH: {
  25806. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  25807. pExpr->iTable, pExpr->iColumn, zFlgs);
  25808. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25809. break;
  25810. }
  25811. case TK_VECTOR: {
  25812. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  25813. break;
  25814. }
  25815. case TK_SELECT_COLUMN: {
  25816. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  25817. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  25818. break;
  25819. }
  25820. case TK_IF_NULL_ROW: {
  25821. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  25822. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25823. break;
  25824. }
  25825. default: {
  25826. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  25827. break;
  25828. }
  25829. }
  25830. if( zBinOp ){
  25831. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  25832. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25833. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25834. }else if( zUniOp ){
  25835. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  25836. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25837. }
  25838. sqlite3TreeViewPop(pView);
  25839. }
  25840. /*
  25841. ** Generate a human-readable explanation of an expression list.
  25842. */
  25843. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  25844. TreeView *pView,
  25845. const ExprList *pList,
  25846. const char *zLabel
  25847. ){
  25848. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  25849. if( pList==0 ){
  25850. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  25851. }else{
  25852. int i;
  25853. sqlite3TreeViewLine(pView, "%s", zLabel);
  25854. for(i=0; i<pList->nExpr; i++){
  25855. int j = pList->a[i].u.x.iOrderByCol;
  25856. if( j ){
  25857. sqlite3TreeViewPush(pView, 0);
  25858. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  25859. }
  25860. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  25861. if( j ) sqlite3TreeViewPop(pView);
  25862. }
  25863. }
  25864. }
  25865. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  25866. TreeView *pView,
  25867. const ExprList *pList,
  25868. u8 moreToFollow,
  25869. const char *zLabel
  25870. ){
  25871. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25872. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  25873. sqlite3TreeViewPop(pView);
  25874. }
  25875. #endif /* SQLITE_DEBUG */
  25876. /************** End of treeview.c ********************************************/
  25877. /************** Begin file random.c ******************************************/
  25878. /*
  25879. ** 2001 September 15
  25880. **
  25881. ** The author disclaims copyright to this source code. In place of
  25882. ** a legal notice, here is a blessing:
  25883. **
  25884. ** May you do good and not evil.
  25885. ** May you find forgiveness for yourself and forgive others.
  25886. ** May you share freely, never taking more than you give.
  25887. **
  25888. *************************************************************************
  25889. ** This file contains code to implement a pseudo-random number
  25890. ** generator (PRNG) for SQLite.
  25891. **
  25892. ** Random numbers are used by some of the database backends in order
  25893. ** to generate random integer keys for tables or random filenames.
  25894. */
  25895. /* #include "sqliteInt.h" */
  25896. /* All threads share a single random number generator.
  25897. ** This structure is the current state of the generator.
  25898. */
  25899. static SQLITE_WSD struct sqlite3PrngType {
  25900. unsigned char isInit; /* True if initialized */
  25901. unsigned char i, j; /* State variables */
  25902. unsigned char s[256]; /* State variables */
  25903. } sqlite3Prng;
  25904. /*
  25905. ** Return N random bytes.
  25906. */
  25907. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  25908. unsigned char t;
  25909. unsigned char *zBuf = pBuf;
  25910. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  25911. ** state vector. If writable static data is unsupported on the target,
  25912. ** we have to locate the state vector at run-time. In the more common
  25913. ** case where writable static data is supported, wsdPrng can refer directly
  25914. ** to the "sqlite3Prng" state vector declared above.
  25915. */
  25916. #ifdef SQLITE_OMIT_WSD
  25917. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  25918. # define wsdPrng p[0]
  25919. #else
  25920. # define wsdPrng sqlite3Prng
  25921. #endif
  25922. #if SQLITE_THREADSAFE
  25923. sqlite3_mutex *mutex;
  25924. #endif
  25925. #ifndef SQLITE_OMIT_AUTOINIT
  25926. if( sqlite3_initialize() ) return;
  25927. #endif
  25928. #if SQLITE_THREADSAFE
  25929. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  25930. #endif
  25931. sqlite3_mutex_enter(mutex);
  25932. if( N<=0 || pBuf==0 ){
  25933. wsdPrng.isInit = 0;
  25934. sqlite3_mutex_leave(mutex);
  25935. return;
  25936. }
  25937. /* Initialize the state of the random number generator once,
  25938. ** the first time this routine is called. The seed value does
  25939. ** not need to contain a lot of randomness since we are not
  25940. ** trying to do secure encryption or anything like that...
  25941. **
  25942. ** Nothing in this file or anywhere else in SQLite does any kind of
  25943. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  25944. ** number generator) not as an encryption device.
  25945. */
  25946. if( !wsdPrng.isInit ){
  25947. int i;
  25948. char k[256];
  25949. wsdPrng.j = 0;
  25950. wsdPrng.i = 0;
  25951. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  25952. for(i=0; i<256; i++){
  25953. wsdPrng.s[i] = (u8)i;
  25954. }
  25955. for(i=0; i<256; i++){
  25956. wsdPrng.j += wsdPrng.s[i] + k[i];
  25957. t = wsdPrng.s[wsdPrng.j];
  25958. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  25959. wsdPrng.s[i] = t;
  25960. }
  25961. wsdPrng.isInit = 1;
  25962. }
  25963. assert( N>0 );
  25964. do{
  25965. wsdPrng.i++;
  25966. t = wsdPrng.s[wsdPrng.i];
  25967. wsdPrng.j += t;
  25968. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  25969. wsdPrng.s[wsdPrng.j] = t;
  25970. t += wsdPrng.s[wsdPrng.i];
  25971. *(zBuf++) = wsdPrng.s[t];
  25972. }while( --N );
  25973. sqlite3_mutex_leave(mutex);
  25974. }
  25975. #ifndef SQLITE_UNTESTABLE
  25976. /*
  25977. ** For testing purposes, we sometimes want to preserve the state of
  25978. ** PRNG and restore the PRNG to its saved state at a later time, or
  25979. ** to reset the PRNG to its initial state. These routines accomplish
  25980. ** those tasks.
  25981. **
  25982. ** The sqlite3_test_control() interface calls these routines to
  25983. ** control the PRNG.
  25984. */
  25985. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  25986. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  25987. memcpy(
  25988. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25989. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25990. sizeof(sqlite3Prng)
  25991. );
  25992. }
  25993. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  25994. memcpy(
  25995. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25996. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25997. sizeof(sqlite3Prng)
  25998. );
  25999. }
  26000. #endif /* SQLITE_UNTESTABLE */
  26001. /************** End of random.c **********************************************/
  26002. /************** Begin file threads.c *****************************************/
  26003. /*
  26004. ** 2012 July 21
  26005. **
  26006. ** The author disclaims copyright to this source code. In place of
  26007. ** a legal notice, here is a blessing:
  26008. **
  26009. ** May you do good and not evil.
  26010. ** May you find forgiveness for yourself and forgive others.
  26011. ** May you share freely, never taking more than you give.
  26012. **
  26013. ******************************************************************************
  26014. **
  26015. ** This file presents a simple cross-platform threading interface for
  26016. ** use internally by SQLite.
  26017. **
  26018. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  26019. ** runs independently of its creator until it is joined using
  26020. ** sqlite3ThreadJoin(), at which point it terminates.
  26021. **
  26022. ** Threads do not have to be real. It could be that the work of the
  26023. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  26024. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  26025. ** single threaded systems. Nothing in SQLite requires multiple threads.
  26026. ** This interface exists so that applications that want to take advantage
  26027. ** of multiple cores can do so, while also allowing applications to stay
  26028. ** single-threaded if desired.
  26029. */
  26030. /* #include "sqliteInt.h" */
  26031. #if SQLITE_OS_WIN
  26032. /* # include "os_win.h" */
  26033. #endif
  26034. #if SQLITE_MAX_WORKER_THREADS>0
  26035. /********************************* Unix Pthreads ****************************/
  26036. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  26037. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  26038. /* #include <pthread.h> */
  26039. /* A running thread */
  26040. struct SQLiteThread {
  26041. pthread_t tid; /* Thread ID */
  26042. int done; /* Set to true when thread finishes */
  26043. void *pOut; /* Result returned by the thread */
  26044. void *(*xTask)(void*); /* The thread routine */
  26045. void *pIn; /* Argument to the thread */
  26046. };
  26047. /* Create a new thread */
  26048. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26049. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26050. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26051. void *pIn /* Argument passed into xTask() */
  26052. ){
  26053. SQLiteThread *p;
  26054. int rc;
  26055. assert( ppThread!=0 );
  26056. assert( xTask!=0 );
  26057. /* This routine is never used in single-threaded mode */
  26058. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  26059. *ppThread = 0;
  26060. p = sqlite3Malloc(sizeof(*p));
  26061. if( p==0 ) return SQLITE_NOMEM_BKPT;
  26062. memset(p, 0, sizeof(*p));
  26063. p->xTask = xTask;
  26064. p->pIn = pIn;
  26065. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  26066. ** function that returns SQLITE_ERROR when passed the argument 200, that
  26067. ** forces worker threads to run sequentially and deterministically
  26068. ** for testing purposes. */
  26069. if( sqlite3FaultSim(200) ){
  26070. rc = 1;
  26071. }else{
  26072. rc = pthread_create(&p->tid, 0, xTask, pIn);
  26073. }
  26074. if( rc ){
  26075. p->done = 1;
  26076. p->pOut = xTask(pIn);
  26077. }
  26078. *ppThread = p;
  26079. return SQLITE_OK;
  26080. }
  26081. /* Get the results of the thread */
  26082. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  26083. int rc;
  26084. assert( ppOut!=0 );
  26085. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  26086. if( p->done ){
  26087. *ppOut = p->pOut;
  26088. rc = SQLITE_OK;
  26089. }else{
  26090. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  26091. }
  26092. sqlite3_free(p);
  26093. return rc;
  26094. }
  26095. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  26096. /******************************** End Unix Pthreads *************************/
  26097. /********************************* Win32 Threads ****************************/
  26098. #if SQLITE_OS_WIN_THREADS
  26099. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  26100. #include <process.h>
  26101. /* A running thread */
  26102. struct SQLiteThread {
  26103. void *tid; /* The thread handle */
  26104. unsigned id; /* The thread identifier */
  26105. void *(*xTask)(void*); /* The routine to run as a thread */
  26106. void *pIn; /* Argument to xTask */
  26107. void *pResult; /* Result of xTask */
  26108. };
  26109. /* Thread procedure Win32 compatibility shim */
  26110. static unsigned __stdcall sqlite3ThreadProc(
  26111. void *pArg /* IN: Pointer to the SQLiteThread structure */
  26112. ){
  26113. SQLiteThread *p = (SQLiteThread *)pArg;
  26114. assert( p!=0 );
  26115. #if 0
  26116. /*
  26117. ** This assert appears to trigger spuriously on certain
  26118. ** versions of Windows, possibly due to _beginthreadex()
  26119. ** and/or CreateThread() not fully setting their thread
  26120. ** ID parameter before starting the thread.
  26121. */
  26122. assert( p->id==GetCurrentThreadId() );
  26123. #endif
  26124. assert( p->xTask!=0 );
  26125. p->pResult = p->xTask(p->pIn);
  26126. _endthreadex(0);
  26127. return 0; /* NOT REACHED */
  26128. }
  26129. /* Create a new thread */
  26130. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26131. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26132. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26133. void *pIn /* Argument passed into xTask() */
  26134. ){
  26135. SQLiteThread *p;
  26136. assert( ppThread!=0 );
  26137. assert( xTask!=0 );
  26138. *ppThread = 0;
  26139. p = sqlite3Malloc(sizeof(*p));
  26140. if( p==0 ) return SQLITE_NOMEM_BKPT;
  26141. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  26142. ** function that returns SQLITE_ERROR when passed the argument 200, that
  26143. ** forces worker threads to run sequentially and deterministically
  26144. ** (via the sqlite3FaultSim() term of the conditional) for testing
  26145. ** purposes. */
  26146. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  26147. memset(p, 0, sizeof(*p));
  26148. }else{
  26149. p->xTask = xTask;
  26150. p->pIn = pIn;
  26151. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  26152. if( p->tid==0 ){
  26153. memset(p, 0, sizeof(*p));
  26154. }
  26155. }
  26156. if( p->xTask==0 ){
  26157. p->id = GetCurrentThreadId();
  26158. p->pResult = xTask(pIn);
  26159. }
  26160. *ppThread = p;
  26161. return SQLITE_OK;
  26162. }
  26163. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  26164. /* Get the results of the thread */
  26165. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  26166. DWORD rc;
  26167. BOOL bRc;
  26168. assert( ppOut!=0 );
  26169. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  26170. if( p->xTask==0 ){
  26171. /* assert( p->id==GetCurrentThreadId() ); */
  26172. rc = WAIT_OBJECT_0;
  26173. assert( p->tid==0 );
  26174. }else{
  26175. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  26176. rc = sqlite3Win32Wait((HANDLE)p->tid);
  26177. assert( rc!=WAIT_IO_COMPLETION );
  26178. bRc = CloseHandle((HANDLE)p->tid);
  26179. assert( bRc );
  26180. }
  26181. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  26182. sqlite3_free(p);
  26183. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  26184. }
  26185. #endif /* SQLITE_OS_WIN_THREADS */
  26186. /******************************** End Win32 Threads *************************/
  26187. /********************************* Single-Threaded **************************/
  26188. #ifndef SQLITE_THREADS_IMPLEMENTED
  26189. /*
  26190. ** This implementation does not actually create a new thread. It does the
  26191. ** work of the thread in the main thread, when either the thread is created
  26192. ** or when it is joined
  26193. */
  26194. /* A running thread */
  26195. struct SQLiteThread {
  26196. void *(*xTask)(void*); /* The routine to run as a thread */
  26197. void *pIn; /* Argument to xTask */
  26198. void *pResult; /* Result of xTask */
  26199. };
  26200. /* Create a new thread */
  26201. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26202. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26203. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26204. void *pIn /* Argument passed into xTask() */
  26205. ){
  26206. SQLiteThread *p;
  26207. assert( ppThread!=0 );
  26208. assert( xTask!=0 );
  26209. *ppThread = 0;
  26210. p = sqlite3Malloc(sizeof(*p));
  26211. if( p==0 ) return SQLITE_NOMEM_BKPT;
  26212. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  26213. p->xTask = xTask;
  26214. p->pIn = pIn;
  26215. }else{
  26216. p->xTask = 0;
  26217. p->pResult = xTask(pIn);
  26218. }
  26219. *ppThread = p;
  26220. return SQLITE_OK;
  26221. }
  26222. /* Get the results of the thread */
  26223. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  26224. assert( ppOut!=0 );
  26225. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  26226. if( p->xTask ){
  26227. *ppOut = p->xTask(p->pIn);
  26228. }else{
  26229. *ppOut = p->pResult;
  26230. }
  26231. sqlite3_free(p);
  26232. #if defined(SQLITE_TEST)
  26233. {
  26234. void *pTstAlloc = sqlite3Malloc(10);
  26235. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  26236. sqlite3_free(pTstAlloc);
  26237. }
  26238. #endif
  26239. return SQLITE_OK;
  26240. }
  26241. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  26242. /****************************** End Single-Threaded *************************/
  26243. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  26244. /************** End of threads.c *********************************************/
  26245. /************** Begin file utf.c *********************************************/
  26246. /*
  26247. ** 2004 April 13
  26248. **
  26249. ** The author disclaims copyright to this source code. In place of
  26250. ** a legal notice, here is a blessing:
  26251. **
  26252. ** May you do good and not evil.
  26253. ** May you find forgiveness for yourself and forgive others.
  26254. ** May you share freely, never taking more than you give.
  26255. **
  26256. *************************************************************************
  26257. ** This file contains routines used to translate between UTF-8,
  26258. ** UTF-16, UTF-16BE, and UTF-16LE.
  26259. **
  26260. ** Notes on UTF-8:
  26261. **
  26262. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  26263. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  26264. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  26265. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  26266. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  26267. **
  26268. **
  26269. ** Notes on UTF-16: (with wwww+1==uuuuu)
  26270. **
  26271. ** Word-0 Word-1 Value
  26272. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  26273. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  26274. **
  26275. **
  26276. ** BOM or Byte Order Mark:
  26277. ** 0xff 0xfe little-endian utf-16 follows
  26278. ** 0xfe 0xff big-endian utf-16 follows
  26279. **
  26280. */
  26281. /* #include "sqliteInt.h" */
  26282. /* #include <assert.h> */
  26283. /* #include "vdbeInt.h" */
  26284. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  26285. /*
  26286. ** The following constant value is used by the SQLITE_BIGENDIAN and
  26287. ** SQLITE_LITTLEENDIAN macros.
  26288. */
  26289. SQLITE_PRIVATE const int sqlite3one = 1;
  26290. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  26291. /*
  26292. ** This lookup table is used to help decode the first byte of
  26293. ** a multi-byte UTF8 character.
  26294. */
  26295. static const unsigned char sqlite3Utf8Trans1[] = {
  26296. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  26297. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  26298. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  26299. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  26300. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  26301. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  26302. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  26303. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  26304. };
  26305. #define WRITE_UTF8(zOut, c) { \
  26306. if( c<0x00080 ){ \
  26307. *zOut++ = (u8)(c&0xFF); \
  26308. } \
  26309. else if( c<0x00800 ){ \
  26310. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  26311. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  26312. } \
  26313. else if( c<0x10000 ){ \
  26314. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  26315. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  26316. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  26317. }else{ \
  26318. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  26319. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  26320. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  26321. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  26322. } \
  26323. }
  26324. #define WRITE_UTF16LE(zOut, c) { \
  26325. if( c<=0xFFFF ){ \
  26326. *zOut++ = (u8)(c&0x00FF); \
  26327. *zOut++ = (u8)((c>>8)&0x00FF); \
  26328. }else{ \
  26329. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  26330. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  26331. *zOut++ = (u8)(c&0x00FF); \
  26332. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  26333. } \
  26334. }
  26335. #define WRITE_UTF16BE(zOut, c) { \
  26336. if( c<=0xFFFF ){ \
  26337. *zOut++ = (u8)((c>>8)&0x00FF); \
  26338. *zOut++ = (u8)(c&0x00FF); \
  26339. }else{ \
  26340. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  26341. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  26342. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  26343. *zOut++ = (u8)(c&0x00FF); \
  26344. } \
  26345. }
  26346. #define READ_UTF16LE(zIn, TERM, c){ \
  26347. c = (*zIn++); \
  26348. c += ((*zIn++)<<8); \
  26349. if( c>=0xD800 && c<0xE000 && TERM ){ \
  26350. int c2 = (*zIn++); \
  26351. c2 += ((*zIn++)<<8); \
  26352. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  26353. } \
  26354. }
  26355. #define READ_UTF16BE(zIn, TERM, c){ \
  26356. c = ((*zIn++)<<8); \
  26357. c += (*zIn++); \
  26358. if( c>=0xD800 && c<0xE000 && TERM ){ \
  26359. int c2 = ((*zIn++)<<8); \
  26360. c2 += (*zIn++); \
  26361. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  26362. } \
  26363. }
  26364. /*
  26365. ** Translate a single UTF-8 character. Return the unicode value.
  26366. **
  26367. ** During translation, assume that the byte that zTerm points
  26368. ** is a 0x00.
  26369. **
  26370. ** Write a pointer to the next unread byte back into *pzNext.
  26371. **
  26372. ** Notes On Invalid UTF-8:
  26373. **
  26374. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  26375. ** be encoded as a multi-byte character. Any multi-byte character that
  26376. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  26377. **
  26378. ** * This routine never allows a UTF16 surrogate value to be encoded.
  26379. ** If a multi-byte character attempts to encode a value between
  26380. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  26381. **
  26382. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  26383. ** byte of a character are interpreted as single-byte characters
  26384. ** and rendered as themselves even though they are technically
  26385. ** invalid characters.
  26386. **
  26387. ** * This routine accepts over-length UTF8 encodings
  26388. ** for unicode values 0x80 and greater. It does not change over-length
  26389. ** encodings to 0xfffd as some systems recommend.
  26390. */
  26391. #define READ_UTF8(zIn, zTerm, c) \
  26392. c = *(zIn++); \
  26393. if( c>=0xc0 ){ \
  26394. c = sqlite3Utf8Trans1[c-0xc0]; \
  26395. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  26396. c = (c<<6) + (0x3f & *(zIn++)); \
  26397. } \
  26398. if( c<0x80 \
  26399. || (c&0xFFFFF800)==0xD800 \
  26400. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  26401. }
  26402. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  26403. const unsigned char **pz /* Pointer to string from which to read char */
  26404. ){
  26405. unsigned int c;
  26406. /* Same as READ_UTF8() above but without the zTerm parameter.
  26407. ** For this routine, we assume the UTF8 string is always zero-terminated.
  26408. */
  26409. c = *((*pz)++);
  26410. if( c>=0xc0 ){
  26411. c = sqlite3Utf8Trans1[c-0xc0];
  26412. while( (*(*pz) & 0xc0)==0x80 ){
  26413. c = (c<<6) + (0x3f & *((*pz)++));
  26414. }
  26415. if( c<0x80
  26416. || (c&0xFFFFF800)==0xD800
  26417. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  26418. }
  26419. return c;
  26420. }
  26421. /*
  26422. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  26423. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  26424. */
  26425. /* #define TRANSLATE_TRACE 1 */
  26426. #ifndef SQLITE_OMIT_UTF16
  26427. /*
  26428. ** This routine transforms the internal text encoding used by pMem to
  26429. ** desiredEnc. It is an error if the string is already of the desired
  26430. ** encoding, or if *pMem does not contain a string value.
  26431. */
  26432. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  26433. int len; /* Maximum length of output string in bytes */
  26434. unsigned char *zOut; /* Output buffer */
  26435. unsigned char *zIn; /* Input iterator */
  26436. unsigned char *zTerm; /* End of input */
  26437. unsigned char *z; /* Output iterator */
  26438. unsigned int c;
  26439. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  26440. assert( pMem->flags&MEM_Str );
  26441. assert( pMem->enc!=desiredEnc );
  26442. assert( pMem->enc!=0 );
  26443. assert( pMem->n>=0 );
  26444. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  26445. {
  26446. char zBuf[100];
  26447. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  26448. fprintf(stderr, "INPUT: %s\n", zBuf);
  26449. }
  26450. #endif
  26451. /* If the translation is between UTF-16 little and big endian, then
  26452. ** all that is required is to swap the byte order. This case is handled
  26453. ** differently from the others.
  26454. */
  26455. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  26456. u8 temp;
  26457. int rc;
  26458. rc = sqlite3VdbeMemMakeWriteable(pMem);
  26459. if( rc!=SQLITE_OK ){
  26460. assert( rc==SQLITE_NOMEM );
  26461. return SQLITE_NOMEM_BKPT;
  26462. }
  26463. zIn = (u8*)pMem->z;
  26464. zTerm = &zIn[pMem->n&~1];
  26465. while( zIn<zTerm ){
  26466. temp = *zIn;
  26467. *zIn = *(zIn+1);
  26468. zIn++;
  26469. *zIn++ = temp;
  26470. }
  26471. pMem->enc = desiredEnc;
  26472. goto translate_out;
  26473. }
  26474. /* Set len to the maximum number of bytes required in the output buffer. */
  26475. if( desiredEnc==SQLITE_UTF8 ){
  26476. /* When converting from UTF-16, the maximum growth results from
  26477. ** translating a 2-byte character to a 4-byte UTF-8 character.
  26478. ** A single byte is required for the output string
  26479. ** nul-terminator.
  26480. */
  26481. pMem->n &= ~1;
  26482. len = pMem->n * 2 + 1;
  26483. }else{
  26484. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  26485. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  26486. ** character. Two bytes are required in the output buffer for the
  26487. ** nul-terminator.
  26488. */
  26489. len = pMem->n * 2 + 2;
  26490. }
  26491. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  26492. ** byte past the end.
  26493. **
  26494. ** Variable zOut is set to point at the output buffer, space obtained
  26495. ** from sqlite3_malloc().
  26496. */
  26497. zIn = (u8*)pMem->z;
  26498. zTerm = &zIn[pMem->n];
  26499. zOut = sqlite3DbMallocRaw(pMem->db, len);
  26500. if( !zOut ){
  26501. return SQLITE_NOMEM_BKPT;
  26502. }
  26503. z = zOut;
  26504. if( pMem->enc==SQLITE_UTF8 ){
  26505. if( desiredEnc==SQLITE_UTF16LE ){
  26506. /* UTF-8 -> UTF-16 Little-endian */
  26507. while( zIn<zTerm ){
  26508. READ_UTF8(zIn, zTerm, c);
  26509. WRITE_UTF16LE(z, c);
  26510. }
  26511. }else{
  26512. assert( desiredEnc==SQLITE_UTF16BE );
  26513. /* UTF-8 -> UTF-16 Big-endian */
  26514. while( zIn<zTerm ){
  26515. READ_UTF8(zIn, zTerm, c);
  26516. WRITE_UTF16BE(z, c);
  26517. }
  26518. }
  26519. pMem->n = (int)(z - zOut);
  26520. *z++ = 0;
  26521. }else{
  26522. assert( desiredEnc==SQLITE_UTF8 );
  26523. if( pMem->enc==SQLITE_UTF16LE ){
  26524. /* UTF-16 Little-endian -> UTF-8 */
  26525. while( zIn<zTerm ){
  26526. READ_UTF16LE(zIn, zIn<zTerm, c);
  26527. WRITE_UTF8(z, c);
  26528. }
  26529. }else{
  26530. /* UTF-16 Big-endian -> UTF-8 */
  26531. while( zIn<zTerm ){
  26532. READ_UTF16BE(zIn, zIn<zTerm, c);
  26533. WRITE_UTF8(z, c);
  26534. }
  26535. }
  26536. pMem->n = (int)(z - zOut);
  26537. }
  26538. *z = 0;
  26539. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  26540. c = pMem->flags;
  26541. sqlite3VdbeMemRelease(pMem);
  26542. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  26543. pMem->enc = desiredEnc;
  26544. pMem->z = (char*)zOut;
  26545. pMem->zMalloc = pMem->z;
  26546. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  26547. translate_out:
  26548. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  26549. {
  26550. char zBuf[100];
  26551. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  26552. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  26553. }
  26554. #endif
  26555. return SQLITE_OK;
  26556. }
  26557. #endif /* SQLITE_OMIT_UTF16 */
  26558. #ifndef SQLITE_OMIT_UTF16
  26559. /*
  26560. ** This routine checks for a byte-order mark at the beginning of the
  26561. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  26562. ** the encoding of the Mem adjusted. This routine does not do any
  26563. ** byte-swapping, it just sets Mem.enc appropriately.
  26564. **
  26565. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  26566. ** changed by this function.
  26567. */
  26568. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  26569. int rc = SQLITE_OK;
  26570. u8 bom = 0;
  26571. assert( pMem->n>=0 );
  26572. if( pMem->n>1 ){
  26573. u8 b1 = *(u8 *)pMem->z;
  26574. u8 b2 = *(((u8 *)pMem->z) + 1);
  26575. if( b1==0xFE && b2==0xFF ){
  26576. bom = SQLITE_UTF16BE;
  26577. }
  26578. if( b1==0xFF && b2==0xFE ){
  26579. bom = SQLITE_UTF16LE;
  26580. }
  26581. }
  26582. if( bom ){
  26583. rc = sqlite3VdbeMemMakeWriteable(pMem);
  26584. if( rc==SQLITE_OK ){
  26585. pMem->n -= 2;
  26586. memmove(pMem->z, &pMem->z[2], pMem->n);
  26587. pMem->z[pMem->n] = '\0';
  26588. pMem->z[pMem->n+1] = '\0';
  26589. pMem->flags |= MEM_Term;
  26590. pMem->enc = bom;
  26591. }
  26592. }
  26593. return rc;
  26594. }
  26595. #endif /* SQLITE_OMIT_UTF16 */
  26596. /*
  26597. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  26598. ** return the number of unicode characters in pZ up to (but not including)
  26599. ** the first 0x00 byte. If nByte is not less than zero, return the
  26600. ** number of unicode characters in the first nByte of pZ (or up to
  26601. ** the first 0x00, whichever comes first).
  26602. */
  26603. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  26604. int r = 0;
  26605. const u8 *z = (const u8*)zIn;
  26606. const u8 *zTerm;
  26607. if( nByte>=0 ){
  26608. zTerm = &z[nByte];
  26609. }else{
  26610. zTerm = (const u8*)(-1);
  26611. }
  26612. assert( z<=zTerm );
  26613. while( *z!=0 && z<zTerm ){
  26614. SQLITE_SKIP_UTF8(z);
  26615. r++;
  26616. }
  26617. return r;
  26618. }
  26619. /* This test function is not currently used by the automated test-suite.
  26620. ** Hence it is only available in debug builds.
  26621. */
  26622. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  26623. /*
  26624. ** Translate UTF-8 to UTF-8.
  26625. **
  26626. ** This has the effect of making sure that the string is well-formed
  26627. ** UTF-8. Miscoded characters are removed.
  26628. **
  26629. ** The translation is done in-place and aborted if the output
  26630. ** overruns the input.
  26631. */
  26632. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  26633. unsigned char *zOut = zIn;
  26634. unsigned char *zStart = zIn;
  26635. u32 c;
  26636. while( zIn[0] && zOut<=zIn ){
  26637. c = sqlite3Utf8Read((const u8**)&zIn);
  26638. if( c!=0xfffd ){
  26639. WRITE_UTF8(zOut, c);
  26640. }
  26641. }
  26642. *zOut = 0;
  26643. return (int)(zOut - zStart);
  26644. }
  26645. #endif
  26646. #ifndef SQLITE_OMIT_UTF16
  26647. /*
  26648. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  26649. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  26650. ** be freed by the calling function.
  26651. **
  26652. ** NULL is returned if there is an allocation error.
  26653. */
  26654. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  26655. Mem m;
  26656. memset(&m, 0, sizeof(m));
  26657. m.db = db;
  26658. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  26659. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  26660. if( db->mallocFailed ){
  26661. sqlite3VdbeMemRelease(&m);
  26662. m.z = 0;
  26663. }
  26664. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  26665. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  26666. assert( m.z || db->mallocFailed );
  26667. return m.z;
  26668. }
  26669. /*
  26670. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  26671. ** Return the number of bytes in the first nChar unicode characters
  26672. ** in pZ. nChar must be non-negative.
  26673. */
  26674. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  26675. int c;
  26676. unsigned char const *z = zIn;
  26677. int n = 0;
  26678. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  26679. while( n<nChar ){
  26680. READ_UTF16BE(z, 1, c);
  26681. n++;
  26682. }
  26683. }else{
  26684. while( n<nChar ){
  26685. READ_UTF16LE(z, 1, c);
  26686. n++;
  26687. }
  26688. }
  26689. return (int)(z-(unsigned char const *)zIn);
  26690. }
  26691. #if defined(SQLITE_TEST)
  26692. /*
  26693. ** This routine is called from the TCL test function "translate_selftest".
  26694. ** It checks that the primitives for serializing and deserializing
  26695. ** characters in each encoding are inverses of each other.
  26696. */
  26697. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  26698. unsigned int i, t;
  26699. unsigned char zBuf[20];
  26700. unsigned char *z;
  26701. int n;
  26702. unsigned int c;
  26703. for(i=0; i<0x00110000; i++){
  26704. z = zBuf;
  26705. WRITE_UTF8(z, i);
  26706. n = (int)(z-zBuf);
  26707. assert( n>0 && n<=4 );
  26708. z[0] = 0;
  26709. z = zBuf;
  26710. c = sqlite3Utf8Read((const u8**)&z);
  26711. t = i;
  26712. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  26713. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  26714. assert( c==t );
  26715. assert( (z-zBuf)==n );
  26716. }
  26717. for(i=0; i<0x00110000; i++){
  26718. if( i>=0xD800 && i<0xE000 ) continue;
  26719. z = zBuf;
  26720. WRITE_UTF16LE(z, i);
  26721. n = (int)(z-zBuf);
  26722. assert( n>0 && n<=4 );
  26723. z[0] = 0;
  26724. z = zBuf;
  26725. READ_UTF16LE(z, 1, c);
  26726. assert( c==i );
  26727. assert( (z-zBuf)==n );
  26728. }
  26729. for(i=0; i<0x00110000; i++){
  26730. if( i>=0xD800 && i<0xE000 ) continue;
  26731. z = zBuf;
  26732. WRITE_UTF16BE(z, i);
  26733. n = (int)(z-zBuf);
  26734. assert( n>0 && n<=4 );
  26735. z[0] = 0;
  26736. z = zBuf;
  26737. READ_UTF16BE(z, 1, c);
  26738. assert( c==i );
  26739. assert( (z-zBuf)==n );
  26740. }
  26741. }
  26742. #endif /* SQLITE_TEST */
  26743. #endif /* SQLITE_OMIT_UTF16 */
  26744. /************** End of utf.c *************************************************/
  26745. /************** Begin file util.c ********************************************/
  26746. /*
  26747. ** 2001 September 15
  26748. **
  26749. ** The author disclaims copyright to this source code. In place of
  26750. ** a legal notice, here is a blessing:
  26751. **
  26752. ** May you do good and not evil.
  26753. ** May you find forgiveness for yourself and forgive others.
  26754. ** May you share freely, never taking more than you give.
  26755. **
  26756. *************************************************************************
  26757. ** Utility functions used throughout sqlite.
  26758. **
  26759. ** This file contains functions for allocating memory, comparing
  26760. ** strings, and stuff like that.
  26761. **
  26762. */
  26763. /* #include "sqliteInt.h" */
  26764. /* #include <stdarg.h> */
  26765. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  26766. # include <math.h>
  26767. #endif
  26768. /*
  26769. ** Routine needed to support the testcase() macro.
  26770. */
  26771. #ifdef SQLITE_COVERAGE_TEST
  26772. SQLITE_PRIVATE void sqlite3Coverage(int x){
  26773. static unsigned dummy = 0;
  26774. dummy += (unsigned)x;
  26775. }
  26776. #endif
  26777. /*
  26778. ** Give a callback to the test harness that can be used to simulate faults
  26779. ** in places where it is difficult or expensive to do so purely by means
  26780. ** of inputs.
  26781. **
  26782. ** The intent of the integer argument is to let the fault simulator know
  26783. ** which of multiple sqlite3FaultSim() calls has been hit.
  26784. **
  26785. ** Return whatever integer value the test callback returns, or return
  26786. ** SQLITE_OK if no test callback is installed.
  26787. */
  26788. #ifndef SQLITE_UNTESTABLE
  26789. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  26790. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  26791. return xCallback ? xCallback(iTest) : SQLITE_OK;
  26792. }
  26793. #endif
  26794. #ifndef SQLITE_OMIT_FLOATING_POINT
  26795. /*
  26796. ** Return true if the floating point value is Not a Number (NaN).
  26797. **
  26798. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  26799. ** Otherwise, we have our own implementation that works on most systems.
  26800. */
  26801. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  26802. int rc; /* The value return */
  26803. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  26804. /*
  26805. ** Systems that support the isnan() library function should probably
  26806. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  26807. ** found that many systems do not have a working isnan() function so
  26808. ** this implementation is provided as an alternative.
  26809. **
  26810. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  26811. ** On the other hand, the use of -ffast-math comes with the following
  26812. ** warning:
  26813. **
  26814. ** This option [-ffast-math] should never be turned on by any
  26815. ** -O option since it can result in incorrect output for programs
  26816. ** which depend on an exact implementation of IEEE or ISO
  26817. ** rules/specifications for math functions.
  26818. **
  26819. ** Under MSVC, this NaN test may fail if compiled with a floating-
  26820. ** point precision mode other than /fp:precise. From the MSDN
  26821. ** documentation:
  26822. **
  26823. ** The compiler [with /fp:precise] will properly handle comparisons
  26824. ** involving NaN. For example, x != x evaluates to true if x is NaN
  26825. ** ...
  26826. */
  26827. #ifdef __FAST_MATH__
  26828. # error SQLite will not work correctly with the -ffast-math option of GCC.
  26829. #endif
  26830. volatile double y = x;
  26831. volatile double z = y;
  26832. rc = (y!=z);
  26833. #else /* if HAVE_ISNAN */
  26834. rc = isnan(x);
  26835. #endif /* HAVE_ISNAN */
  26836. testcase( rc );
  26837. return rc;
  26838. }
  26839. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26840. /*
  26841. ** Compute a string length that is limited to what can be stored in
  26842. ** lower 30 bits of a 32-bit signed integer.
  26843. **
  26844. ** The value returned will never be negative. Nor will it ever be greater
  26845. ** than the actual length of the string. For very long strings (greater
  26846. ** than 1GiB) the value returned might be less than the true string length.
  26847. */
  26848. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  26849. if( z==0 ) return 0;
  26850. return 0x3fffffff & (int)strlen(z);
  26851. }
  26852. /*
  26853. ** Return the declared type of a column. Or return zDflt if the column
  26854. ** has no declared type.
  26855. **
  26856. ** The column type is an extra string stored after the zero-terminator on
  26857. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  26858. */
  26859. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  26860. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  26861. return pCol->zName + strlen(pCol->zName) + 1;
  26862. }
  26863. /*
  26864. ** Helper function for sqlite3Error() - called rarely. Broken out into
  26865. ** a separate routine to avoid unnecessary register saves on entry to
  26866. ** sqlite3Error().
  26867. */
  26868. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  26869. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  26870. sqlite3SystemError(db, err_code);
  26871. }
  26872. /*
  26873. ** Set the current error code to err_code and clear any prior error message.
  26874. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  26875. ** that would be appropriate.
  26876. */
  26877. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  26878. assert( db!=0 );
  26879. db->errCode = err_code;
  26880. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  26881. }
  26882. /*
  26883. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  26884. ** to do based on the SQLite error code in rc.
  26885. */
  26886. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  26887. if( rc==SQLITE_IOERR_NOMEM ) return;
  26888. rc &= 0xff;
  26889. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  26890. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  26891. }
  26892. }
  26893. /*
  26894. ** Set the most recent error code and error string for the sqlite
  26895. ** handle "db". The error code is set to "err_code".
  26896. **
  26897. ** If it is not NULL, string zFormat specifies the format of the
  26898. ** error string in the style of the printf functions: The following
  26899. ** format characters are allowed:
  26900. **
  26901. ** %s Insert a string
  26902. ** %z A string that should be freed after use
  26903. ** %d Insert an integer
  26904. ** %T Insert a token
  26905. ** %S Insert the first element of a SrcList
  26906. **
  26907. ** zFormat and any string tokens that follow it are assumed to be
  26908. ** encoded in UTF-8.
  26909. **
  26910. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  26911. ** should be called with err_code set to SQLITE_OK and zFormat set
  26912. ** to NULL.
  26913. */
  26914. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  26915. assert( db!=0 );
  26916. db->errCode = err_code;
  26917. sqlite3SystemError(db, err_code);
  26918. if( zFormat==0 ){
  26919. sqlite3Error(db, err_code);
  26920. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  26921. char *z;
  26922. va_list ap;
  26923. va_start(ap, zFormat);
  26924. z = sqlite3VMPrintf(db, zFormat, ap);
  26925. va_end(ap);
  26926. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  26927. }
  26928. }
  26929. /*
  26930. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  26931. ** The following formatting characters are allowed:
  26932. **
  26933. ** %s Insert a string
  26934. ** %z A string that should be freed after use
  26935. ** %d Insert an integer
  26936. ** %T Insert a token
  26937. ** %S Insert the first element of a SrcList
  26938. **
  26939. ** This function should be used to report any error that occurs while
  26940. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  26941. ** last thing the sqlite3_prepare() function does is copy the error
  26942. ** stored by this function into the database handle using sqlite3Error().
  26943. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  26944. ** during statement execution (sqlite3_step() etc.).
  26945. */
  26946. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  26947. char *zMsg;
  26948. va_list ap;
  26949. sqlite3 *db = pParse->db;
  26950. va_start(ap, zFormat);
  26951. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  26952. va_end(ap);
  26953. if( db->suppressErr ){
  26954. sqlite3DbFree(db, zMsg);
  26955. }else{
  26956. pParse->nErr++;
  26957. sqlite3DbFree(db, pParse->zErrMsg);
  26958. pParse->zErrMsg = zMsg;
  26959. pParse->rc = SQLITE_ERROR;
  26960. }
  26961. }
  26962. /*
  26963. ** Convert an SQL-style quoted string into a normal string by removing
  26964. ** the quote characters. The conversion is done in-place. If the
  26965. ** input does not begin with a quote character, then this routine
  26966. ** is a no-op.
  26967. **
  26968. ** The input string must be zero-terminated. A new zero-terminator
  26969. ** is added to the dequoted string.
  26970. **
  26971. ** The return value is -1 if no dequoting occurs or the length of the
  26972. ** dequoted string, exclusive of the zero terminator, if dequoting does
  26973. ** occur.
  26974. **
  26975. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  26976. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  26977. ** "a-b-c".
  26978. */
  26979. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  26980. char quote;
  26981. int i, j;
  26982. if( z==0 ) return;
  26983. quote = z[0];
  26984. if( !sqlite3Isquote(quote) ) return;
  26985. if( quote=='[' ) quote = ']';
  26986. for(i=1, j=0;; i++){
  26987. assert( z[i] );
  26988. if( z[i]==quote ){
  26989. if( z[i+1]==quote ){
  26990. z[j++] = quote;
  26991. i++;
  26992. }else{
  26993. break;
  26994. }
  26995. }else{
  26996. z[j++] = z[i];
  26997. }
  26998. }
  26999. z[j] = 0;
  27000. }
  27001. /*
  27002. ** Generate a Token object from a string
  27003. */
  27004. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  27005. p->z = z;
  27006. p->n = sqlite3Strlen30(z);
  27007. }
  27008. /* Convenient short-hand */
  27009. #define UpperToLower sqlite3UpperToLower
  27010. /*
  27011. ** Some systems have stricmp(). Others have strcasecmp(). Because
  27012. ** there is no consistency, we will define our own.
  27013. **
  27014. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  27015. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  27016. ** the contents of two buffers containing UTF-8 strings in a
  27017. ** case-independent fashion, using the same definition of "case
  27018. ** independence" that SQLite uses internally when comparing identifiers.
  27019. */
  27020. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  27021. if( zLeft==0 ){
  27022. return zRight ? -1 : 0;
  27023. }else if( zRight==0 ){
  27024. return 1;
  27025. }
  27026. return sqlite3StrICmp(zLeft, zRight);
  27027. }
  27028. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  27029. unsigned char *a, *b;
  27030. int c;
  27031. a = (unsigned char *)zLeft;
  27032. b = (unsigned char *)zRight;
  27033. for(;;){
  27034. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  27035. if( c || *a==0 ) break;
  27036. a++;
  27037. b++;
  27038. }
  27039. return c;
  27040. }
  27041. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  27042. register unsigned char *a, *b;
  27043. if( zLeft==0 ){
  27044. return zRight ? -1 : 0;
  27045. }else if( zRight==0 ){
  27046. return 1;
  27047. }
  27048. a = (unsigned char *)zLeft;
  27049. b = (unsigned char *)zRight;
  27050. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  27051. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  27052. }
  27053. /*
  27054. ** The string z[] is an text representation of a real number.
  27055. ** Convert this string to a double and write it into *pResult.
  27056. **
  27057. ** The string z[] is length bytes in length (bytes, not characters) and
  27058. ** uses the encoding enc. The string is not necessarily zero-terminated.
  27059. **
  27060. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  27061. ** if the string is empty or contains extraneous text. Valid numbers
  27062. ** are in one of these formats:
  27063. **
  27064. ** [+-]digits[E[+-]digits]
  27065. ** [+-]digits.[digits][E[+-]digits]
  27066. ** [+-].digits[E[+-]digits]
  27067. **
  27068. ** Leading and trailing whitespace is ignored for the purpose of determining
  27069. ** validity.
  27070. **
  27071. ** If some prefix of the input string is a valid number, this routine
  27072. ** returns FALSE but it still converts the prefix and writes the result
  27073. ** into *pResult.
  27074. */
  27075. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  27076. #ifndef SQLITE_OMIT_FLOATING_POINT
  27077. int incr;
  27078. const char *zEnd = z + length;
  27079. /* sign * significand * (10 ^ (esign * exponent)) */
  27080. int sign = 1; /* sign of significand */
  27081. i64 s = 0; /* significand */
  27082. int d = 0; /* adjust exponent for shifting decimal point */
  27083. int esign = 1; /* sign of exponent */
  27084. int e = 0; /* exponent */
  27085. int eValid = 1; /* True exponent is either not used or is well-formed */
  27086. double result;
  27087. int nDigits = 0;
  27088. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  27089. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  27090. *pResult = 0.0; /* Default return value, in case of an error */
  27091. if( enc==SQLITE_UTF8 ){
  27092. incr = 1;
  27093. }else{
  27094. int i;
  27095. incr = 2;
  27096. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  27097. for(i=3-enc; i<length && z[i]==0; i+=2){}
  27098. nonNum = i<length;
  27099. zEnd = &z[i^1];
  27100. z += (enc&1);
  27101. }
  27102. /* skip leading spaces */
  27103. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  27104. if( z>=zEnd ) return 0;
  27105. /* get sign of significand */
  27106. if( *z=='-' ){
  27107. sign = -1;
  27108. z+=incr;
  27109. }else if( *z=='+' ){
  27110. z+=incr;
  27111. }
  27112. /* copy max significant digits to significand */
  27113. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  27114. s = s*10 + (*z - '0');
  27115. z+=incr, nDigits++;
  27116. }
  27117. /* skip non-significant significand digits
  27118. ** (increase exponent by d to shift decimal left) */
  27119. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  27120. if( z>=zEnd ) goto do_atof_calc;
  27121. /* if decimal point is present */
  27122. if( *z=='.' ){
  27123. z+=incr;
  27124. /* copy digits from after decimal to significand
  27125. ** (decrease exponent by d to shift decimal right) */
  27126. while( z<zEnd && sqlite3Isdigit(*z) ){
  27127. if( s<((LARGEST_INT64-9)/10) ){
  27128. s = s*10 + (*z - '0');
  27129. d--;
  27130. }
  27131. z+=incr, nDigits++;
  27132. }
  27133. }
  27134. if( z>=zEnd ) goto do_atof_calc;
  27135. /* if exponent is present */
  27136. if( *z=='e' || *z=='E' ){
  27137. z+=incr;
  27138. eValid = 0;
  27139. /* This branch is needed to avoid a (harmless) buffer overread. The
  27140. ** special comment alerts the mutation tester that the correct answer
  27141. ** is obtained even if the branch is omitted */
  27142. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  27143. /* get sign of exponent */
  27144. if( *z=='-' ){
  27145. esign = -1;
  27146. z+=incr;
  27147. }else if( *z=='+' ){
  27148. z+=incr;
  27149. }
  27150. /* copy digits to exponent */
  27151. while( z<zEnd && sqlite3Isdigit(*z) ){
  27152. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  27153. z+=incr;
  27154. eValid = 1;
  27155. }
  27156. }
  27157. /* skip trailing spaces */
  27158. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  27159. do_atof_calc:
  27160. /* adjust exponent by d, and update sign */
  27161. e = (e*esign) + d;
  27162. if( e<0 ) {
  27163. esign = -1;
  27164. e *= -1;
  27165. } else {
  27166. esign = 1;
  27167. }
  27168. if( s==0 ) {
  27169. /* In the IEEE 754 standard, zero is signed. */
  27170. result = sign<0 ? -(double)0 : (double)0;
  27171. } else {
  27172. /* Attempt to reduce exponent.
  27173. **
  27174. ** Branches that are not required for the correct answer but which only
  27175. ** help to obtain the correct answer faster are marked with special
  27176. ** comments, as a hint to the mutation tester.
  27177. */
  27178. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  27179. if( esign>0 ){
  27180. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  27181. s *= 10;
  27182. }else{
  27183. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  27184. s /= 10;
  27185. }
  27186. e--;
  27187. }
  27188. /* adjust the sign of significand */
  27189. s = sign<0 ? -s : s;
  27190. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  27191. result = (double)s;
  27192. }else{
  27193. LONGDOUBLE_TYPE scale = 1.0;
  27194. /* attempt to handle extremely small/large numbers better */
  27195. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  27196. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  27197. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  27198. if( esign<0 ){
  27199. result = s / scale;
  27200. result /= 1.0e+308;
  27201. }else{
  27202. result = s * scale;
  27203. result *= 1.0e+308;
  27204. }
  27205. }else{ assert( e>=342 );
  27206. if( esign<0 ){
  27207. result = 0.0*s;
  27208. }else{
  27209. #ifdef INFINITY
  27210. result = INFINITY*s;
  27211. #else
  27212. result = 1e308*1e308*s; /* Infinity */
  27213. #endif
  27214. }
  27215. }
  27216. }else{
  27217. /* 1.0e+22 is the largest power of 10 than can be
  27218. ** represented exactly. */
  27219. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  27220. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  27221. if( esign<0 ){
  27222. result = s / scale;
  27223. }else{
  27224. result = s * scale;
  27225. }
  27226. }
  27227. }
  27228. }
  27229. /* store the result */
  27230. *pResult = result;
  27231. /* return true if number and no extra non-whitespace chracters after */
  27232. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  27233. #else
  27234. return !sqlite3Atoi64(z, pResult, length, enc);
  27235. #endif /* SQLITE_OMIT_FLOATING_POINT */
  27236. }
  27237. /*
  27238. ** Compare the 19-character string zNum against the text representation
  27239. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  27240. ** if zNum is less than, equal to, or greater than the string.
  27241. ** Note that zNum must contain exactly 19 characters.
  27242. **
  27243. ** Unlike memcmp() this routine is guaranteed to return the difference
  27244. ** in the values of the last digit if the only difference is in the
  27245. ** last digit. So, for example,
  27246. **
  27247. ** compare2pow63("9223372036854775800", 1)
  27248. **
  27249. ** will return -8.
  27250. */
  27251. static int compare2pow63(const char *zNum, int incr){
  27252. int c = 0;
  27253. int i;
  27254. /* 012345678901234567 */
  27255. const char *pow63 = "922337203685477580";
  27256. for(i=0; c==0 && i<18; i++){
  27257. c = (zNum[i*incr]-pow63[i])*10;
  27258. }
  27259. if( c==0 ){
  27260. c = zNum[18*incr] - '8';
  27261. testcase( c==(-1) );
  27262. testcase( c==0 );
  27263. testcase( c==(+1) );
  27264. }
  27265. return c;
  27266. }
  27267. /*
  27268. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  27269. ** routine does *not* accept hexadecimal notation.
  27270. **
  27271. ** Returns:
  27272. **
  27273. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  27274. ** 1 Excess text after the integer value
  27275. ** 2 Integer too large for a 64-bit signed integer or is malformed
  27276. ** 3 Special case of 9223372036854775808
  27277. **
  27278. ** length is the number of bytes in the string (bytes, not characters).
  27279. ** The string is not necessarily zero-terminated. The encoding is
  27280. ** given by enc.
  27281. */
  27282. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  27283. int incr;
  27284. u64 u = 0;
  27285. int neg = 0; /* assume positive */
  27286. int i;
  27287. int c = 0;
  27288. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  27289. int rc; /* Baseline return code */
  27290. const char *zStart;
  27291. const char *zEnd = zNum + length;
  27292. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  27293. if( enc==SQLITE_UTF8 ){
  27294. incr = 1;
  27295. }else{
  27296. incr = 2;
  27297. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  27298. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  27299. nonNum = i<length;
  27300. zEnd = &zNum[i^1];
  27301. zNum += (enc&1);
  27302. }
  27303. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  27304. if( zNum<zEnd ){
  27305. if( *zNum=='-' ){
  27306. neg = 1;
  27307. zNum+=incr;
  27308. }else if( *zNum=='+' ){
  27309. zNum+=incr;
  27310. }
  27311. }
  27312. zStart = zNum;
  27313. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  27314. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  27315. u = u*10 + c - '0';
  27316. }
  27317. if( u>LARGEST_INT64 ){
  27318. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  27319. }else if( neg ){
  27320. *pNum = -(i64)u;
  27321. }else{
  27322. *pNum = (i64)u;
  27323. }
  27324. testcase( i==18 );
  27325. testcase( i==19 );
  27326. testcase( i==20 );
  27327. if( &zNum[i]<zEnd /* Extra bytes at the end */
  27328. || (i==0 && zStart==zNum) /* No digits */
  27329. || nonNum /* UTF16 with high-order bytes non-zero */
  27330. ){
  27331. rc = 1;
  27332. }else{
  27333. rc = 0;
  27334. }
  27335. if( i>19*incr ){ /* Too many digits */
  27336. /* zNum is empty or contains non-numeric text or is longer
  27337. ** than 19 digits (thus guaranteeing that it is too large) */
  27338. return 2;
  27339. }else if( i<19*incr ){
  27340. /* Less than 19 digits, so we know that it fits in 64 bits */
  27341. assert( u<=LARGEST_INT64 );
  27342. return rc;
  27343. }else{
  27344. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  27345. c = compare2pow63(zNum, incr);
  27346. if( c<0 ){
  27347. /* zNum is less than 9223372036854775808 so it fits */
  27348. assert( u<=LARGEST_INT64 );
  27349. return rc;
  27350. }else if( c>0 ){
  27351. /* zNum is greater than 9223372036854775808 so it overflows */
  27352. return 2;
  27353. }else{
  27354. /* zNum is exactly 9223372036854775808. Fits if negative. The
  27355. ** special case 2 overflow if positive */
  27356. assert( u-1==LARGEST_INT64 );
  27357. return neg ? rc : 3;
  27358. }
  27359. }
  27360. }
  27361. /*
  27362. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  27363. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  27364. ** whereas sqlite3Atoi64() does not.
  27365. **
  27366. ** Returns:
  27367. **
  27368. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  27369. ** 1 Excess text after the integer value
  27370. ** 2 Integer too large for a 64-bit signed integer or is malformed
  27371. ** 3 Special case of 9223372036854775808
  27372. */
  27373. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  27374. #ifndef SQLITE_OMIT_HEX_INTEGER
  27375. if( z[0]=='0'
  27376. && (z[1]=='x' || z[1]=='X')
  27377. ){
  27378. u64 u = 0;
  27379. int i, k;
  27380. for(i=2; z[i]=='0'; i++){}
  27381. for(k=i; sqlite3Isxdigit(z[k]); k++){
  27382. u = u*16 + sqlite3HexToInt(z[k]);
  27383. }
  27384. memcpy(pOut, &u, 8);
  27385. return (z[k]==0 && k-i<=16) ? 0 : 2;
  27386. }else
  27387. #endif /* SQLITE_OMIT_HEX_INTEGER */
  27388. {
  27389. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  27390. }
  27391. }
  27392. /*
  27393. ** If zNum represents an integer that will fit in 32-bits, then set
  27394. ** *pValue to that integer and return true. Otherwise return false.
  27395. **
  27396. ** This routine accepts both decimal and hexadecimal notation for integers.
  27397. **
  27398. ** Any non-numeric characters that following zNum are ignored.
  27399. ** This is different from sqlite3Atoi64() which requires the
  27400. ** input number to be zero-terminated.
  27401. */
  27402. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  27403. sqlite_int64 v = 0;
  27404. int i, c;
  27405. int neg = 0;
  27406. if( zNum[0]=='-' ){
  27407. neg = 1;
  27408. zNum++;
  27409. }else if( zNum[0]=='+' ){
  27410. zNum++;
  27411. }
  27412. #ifndef SQLITE_OMIT_HEX_INTEGER
  27413. else if( zNum[0]=='0'
  27414. && (zNum[1]=='x' || zNum[1]=='X')
  27415. && sqlite3Isxdigit(zNum[2])
  27416. ){
  27417. u32 u = 0;
  27418. zNum += 2;
  27419. while( zNum[0]=='0' ) zNum++;
  27420. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  27421. u = u*16 + sqlite3HexToInt(zNum[i]);
  27422. }
  27423. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  27424. memcpy(pValue, &u, 4);
  27425. return 1;
  27426. }else{
  27427. return 0;
  27428. }
  27429. }
  27430. #endif
  27431. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  27432. while( zNum[0]=='0' ) zNum++;
  27433. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  27434. v = v*10 + c;
  27435. }
  27436. /* The longest decimal representation of a 32 bit integer is 10 digits:
  27437. **
  27438. ** 1234567890
  27439. ** 2^31 -> 2147483648
  27440. */
  27441. testcase( i==10 );
  27442. if( i>10 ){
  27443. return 0;
  27444. }
  27445. testcase( v-neg==2147483647 );
  27446. if( v-neg>2147483647 ){
  27447. return 0;
  27448. }
  27449. if( neg ){
  27450. v = -v;
  27451. }
  27452. *pValue = (int)v;
  27453. return 1;
  27454. }
  27455. /*
  27456. ** Return a 32-bit integer value extracted from a string. If the
  27457. ** string is not an integer, just return 0.
  27458. */
  27459. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  27460. int x = 0;
  27461. if( z ) sqlite3GetInt32(z, &x);
  27462. return x;
  27463. }
  27464. /*
  27465. ** The variable-length integer encoding is as follows:
  27466. **
  27467. ** KEY:
  27468. ** A = 0xxxxxxx 7 bits of data and one flag bit
  27469. ** B = 1xxxxxxx 7 bits of data and one flag bit
  27470. ** C = xxxxxxxx 8 bits of data
  27471. **
  27472. ** 7 bits - A
  27473. ** 14 bits - BA
  27474. ** 21 bits - BBA
  27475. ** 28 bits - BBBA
  27476. ** 35 bits - BBBBA
  27477. ** 42 bits - BBBBBA
  27478. ** 49 bits - BBBBBBA
  27479. ** 56 bits - BBBBBBBA
  27480. ** 64 bits - BBBBBBBBC
  27481. */
  27482. /*
  27483. ** Write a 64-bit variable-length integer to memory starting at p[0].
  27484. ** The length of data write will be between 1 and 9 bytes. The number
  27485. ** of bytes written is returned.
  27486. **
  27487. ** A variable-length integer consists of the lower 7 bits of each byte
  27488. ** for all bytes that have the 8th bit set and one byte with the 8th
  27489. ** bit clear. Except, if we get to the 9th byte, it stores the full
  27490. ** 8 bits and is the last byte.
  27491. */
  27492. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  27493. int i, j, n;
  27494. u8 buf[10];
  27495. if( v & (((u64)0xff000000)<<32) ){
  27496. p[8] = (u8)v;
  27497. v >>= 8;
  27498. for(i=7; i>=0; i--){
  27499. p[i] = (u8)((v & 0x7f) | 0x80);
  27500. v >>= 7;
  27501. }
  27502. return 9;
  27503. }
  27504. n = 0;
  27505. do{
  27506. buf[n++] = (u8)((v & 0x7f) | 0x80);
  27507. v >>= 7;
  27508. }while( v!=0 );
  27509. buf[0] &= 0x7f;
  27510. assert( n<=9 );
  27511. for(i=0, j=n-1; j>=0; j--, i++){
  27512. p[i] = buf[j];
  27513. }
  27514. return n;
  27515. }
  27516. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  27517. if( v<=0x7f ){
  27518. p[0] = v&0x7f;
  27519. return 1;
  27520. }
  27521. if( v<=0x3fff ){
  27522. p[0] = ((v>>7)&0x7f)|0x80;
  27523. p[1] = v&0x7f;
  27524. return 2;
  27525. }
  27526. return putVarint64(p,v);
  27527. }
  27528. /*
  27529. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  27530. ** are defined here rather than simply putting the constant expressions
  27531. ** inline in order to work around bugs in the RVT compiler.
  27532. **
  27533. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  27534. **
  27535. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  27536. */
  27537. #define SLOT_2_0 0x001fc07f
  27538. #define SLOT_4_2_0 0xf01fc07f
  27539. /*
  27540. ** Read a 64-bit variable-length integer from memory starting at p[0].
  27541. ** Return the number of bytes read. The value is stored in *v.
  27542. */
  27543. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  27544. u32 a,b,s;
  27545. a = *p;
  27546. /* a: p0 (unmasked) */
  27547. if (!(a&0x80))
  27548. {
  27549. *v = a;
  27550. return 1;
  27551. }
  27552. p++;
  27553. b = *p;
  27554. /* b: p1 (unmasked) */
  27555. if (!(b&0x80))
  27556. {
  27557. a &= 0x7f;
  27558. a = a<<7;
  27559. a |= b;
  27560. *v = a;
  27561. return 2;
  27562. }
  27563. /* Verify that constants are precomputed correctly */
  27564. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  27565. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  27566. p++;
  27567. a = a<<14;
  27568. a |= *p;
  27569. /* a: p0<<14 | p2 (unmasked) */
  27570. if (!(a&0x80))
  27571. {
  27572. a &= SLOT_2_0;
  27573. b &= 0x7f;
  27574. b = b<<7;
  27575. a |= b;
  27576. *v = a;
  27577. return 3;
  27578. }
  27579. /* CSE1 from below */
  27580. a &= SLOT_2_0;
  27581. p++;
  27582. b = b<<14;
  27583. b |= *p;
  27584. /* b: p1<<14 | p3 (unmasked) */
  27585. if (!(b&0x80))
  27586. {
  27587. b &= SLOT_2_0;
  27588. /* moved CSE1 up */
  27589. /* a &= (0x7f<<14)|(0x7f); */
  27590. a = a<<7;
  27591. a |= b;
  27592. *v = a;
  27593. return 4;
  27594. }
  27595. /* a: p0<<14 | p2 (masked) */
  27596. /* b: p1<<14 | p3 (unmasked) */
  27597. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27598. /* moved CSE1 up */
  27599. /* a &= (0x7f<<14)|(0x7f); */
  27600. b &= SLOT_2_0;
  27601. s = a;
  27602. /* s: p0<<14 | p2 (masked) */
  27603. p++;
  27604. a = a<<14;
  27605. a |= *p;
  27606. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27607. if (!(a&0x80))
  27608. {
  27609. /* we can skip these cause they were (effectively) done above
  27610. ** while calculating s */
  27611. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27612. /* b &= (0x7f<<14)|(0x7f); */
  27613. b = b<<7;
  27614. a |= b;
  27615. s = s>>18;
  27616. *v = ((u64)s)<<32 | a;
  27617. return 5;
  27618. }
  27619. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27620. s = s<<7;
  27621. s |= b;
  27622. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27623. p++;
  27624. b = b<<14;
  27625. b |= *p;
  27626. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  27627. if (!(b&0x80))
  27628. {
  27629. /* we can skip this cause it was (effectively) done above in calc'ing s */
  27630. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27631. a &= SLOT_2_0;
  27632. a = a<<7;
  27633. a |= b;
  27634. s = s>>18;
  27635. *v = ((u64)s)<<32 | a;
  27636. return 6;
  27637. }
  27638. p++;
  27639. a = a<<14;
  27640. a |= *p;
  27641. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  27642. if (!(a&0x80))
  27643. {
  27644. a &= SLOT_4_2_0;
  27645. b &= SLOT_2_0;
  27646. b = b<<7;
  27647. a |= b;
  27648. s = s>>11;
  27649. *v = ((u64)s)<<32 | a;
  27650. return 7;
  27651. }
  27652. /* CSE2 from below */
  27653. a &= SLOT_2_0;
  27654. p++;
  27655. b = b<<14;
  27656. b |= *p;
  27657. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  27658. if (!(b&0x80))
  27659. {
  27660. b &= SLOT_4_2_0;
  27661. /* moved CSE2 up */
  27662. /* a &= (0x7f<<14)|(0x7f); */
  27663. a = a<<7;
  27664. a |= b;
  27665. s = s>>4;
  27666. *v = ((u64)s)<<32 | a;
  27667. return 8;
  27668. }
  27669. p++;
  27670. a = a<<15;
  27671. a |= *p;
  27672. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  27673. /* moved CSE2 up */
  27674. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  27675. b &= SLOT_2_0;
  27676. b = b<<8;
  27677. a |= b;
  27678. s = s<<4;
  27679. b = p[-4];
  27680. b &= 0x7f;
  27681. b = b>>3;
  27682. s |= b;
  27683. *v = ((u64)s)<<32 | a;
  27684. return 9;
  27685. }
  27686. /*
  27687. ** Read a 32-bit variable-length integer from memory starting at p[0].
  27688. ** Return the number of bytes read. The value is stored in *v.
  27689. **
  27690. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  27691. ** integer, then set *v to 0xffffffff.
  27692. **
  27693. ** A MACRO version, getVarint32, is provided which inlines the
  27694. ** single-byte case. All code should use the MACRO version as
  27695. ** this function assumes the single-byte case has already been handled.
  27696. */
  27697. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  27698. u32 a,b;
  27699. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  27700. ** by the getVarin32() macro */
  27701. a = *p;
  27702. /* a: p0 (unmasked) */
  27703. #ifndef getVarint32
  27704. if (!(a&0x80))
  27705. {
  27706. /* Values between 0 and 127 */
  27707. *v = a;
  27708. return 1;
  27709. }
  27710. #endif
  27711. /* The 2-byte case */
  27712. p++;
  27713. b = *p;
  27714. /* b: p1 (unmasked) */
  27715. if (!(b&0x80))
  27716. {
  27717. /* Values between 128 and 16383 */
  27718. a &= 0x7f;
  27719. a = a<<7;
  27720. *v = a | b;
  27721. return 2;
  27722. }
  27723. /* The 3-byte case */
  27724. p++;
  27725. a = a<<14;
  27726. a |= *p;
  27727. /* a: p0<<14 | p2 (unmasked) */
  27728. if (!(a&0x80))
  27729. {
  27730. /* Values between 16384 and 2097151 */
  27731. a &= (0x7f<<14)|(0x7f);
  27732. b &= 0x7f;
  27733. b = b<<7;
  27734. *v = a | b;
  27735. return 3;
  27736. }
  27737. /* A 32-bit varint is used to store size information in btrees.
  27738. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  27739. ** A 3-byte varint is sufficient, for example, to record the size
  27740. ** of a 1048569-byte BLOB or string.
  27741. **
  27742. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  27743. ** rare larger cases can be handled by the slower 64-bit varint
  27744. ** routine.
  27745. */
  27746. #if 1
  27747. {
  27748. u64 v64;
  27749. u8 n;
  27750. p -= 2;
  27751. n = sqlite3GetVarint(p, &v64);
  27752. assert( n>3 && n<=9 );
  27753. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  27754. *v = 0xffffffff;
  27755. }else{
  27756. *v = (u32)v64;
  27757. }
  27758. return n;
  27759. }
  27760. #else
  27761. /* For following code (kept for historical record only) shows an
  27762. ** unrolling for the 3- and 4-byte varint cases. This code is
  27763. ** slightly faster, but it is also larger and much harder to test.
  27764. */
  27765. p++;
  27766. b = b<<14;
  27767. b |= *p;
  27768. /* b: p1<<14 | p3 (unmasked) */
  27769. if (!(b&0x80))
  27770. {
  27771. /* Values between 2097152 and 268435455 */
  27772. b &= (0x7f<<14)|(0x7f);
  27773. a &= (0x7f<<14)|(0x7f);
  27774. a = a<<7;
  27775. *v = a | b;
  27776. return 4;
  27777. }
  27778. p++;
  27779. a = a<<14;
  27780. a |= *p;
  27781. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27782. if (!(a&0x80))
  27783. {
  27784. /* Values between 268435456 and 34359738367 */
  27785. a &= SLOT_4_2_0;
  27786. b &= SLOT_4_2_0;
  27787. b = b<<7;
  27788. *v = a | b;
  27789. return 5;
  27790. }
  27791. /* We can only reach this point when reading a corrupt database
  27792. ** file. In that case we are not in any hurry. Use the (relatively
  27793. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  27794. ** value. */
  27795. {
  27796. u64 v64;
  27797. u8 n;
  27798. p -= 4;
  27799. n = sqlite3GetVarint(p, &v64);
  27800. assert( n>5 && n<=9 );
  27801. *v = (u32)v64;
  27802. return n;
  27803. }
  27804. #endif
  27805. }
  27806. /*
  27807. ** Return the number of bytes that will be needed to store the given
  27808. ** 64-bit integer.
  27809. */
  27810. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  27811. int i;
  27812. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  27813. return i;
  27814. }
  27815. /*
  27816. ** Read or write a four-byte big-endian integer value.
  27817. */
  27818. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  27819. #if SQLITE_BYTEORDER==4321
  27820. u32 x;
  27821. memcpy(&x,p,4);
  27822. return x;
  27823. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27824. u32 x;
  27825. memcpy(&x,p,4);
  27826. return __builtin_bswap32(x);
  27827. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27828. u32 x;
  27829. memcpy(&x,p,4);
  27830. return _byteswap_ulong(x);
  27831. #else
  27832. testcase( p[0]&0x80 );
  27833. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  27834. #endif
  27835. }
  27836. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  27837. #if SQLITE_BYTEORDER==4321
  27838. memcpy(p,&v,4);
  27839. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27840. u32 x = __builtin_bswap32(v);
  27841. memcpy(p,&x,4);
  27842. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27843. u32 x = _byteswap_ulong(v);
  27844. memcpy(p,&x,4);
  27845. #else
  27846. p[0] = (u8)(v>>24);
  27847. p[1] = (u8)(v>>16);
  27848. p[2] = (u8)(v>>8);
  27849. p[3] = (u8)v;
  27850. #endif
  27851. }
  27852. /*
  27853. ** Translate a single byte of Hex into an integer.
  27854. ** This routine only works if h really is a valid hexadecimal
  27855. ** character: 0..9a..fA..F
  27856. */
  27857. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  27858. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  27859. #ifdef SQLITE_ASCII
  27860. h += 9*(1&(h>>6));
  27861. #endif
  27862. #ifdef SQLITE_EBCDIC
  27863. h += 9*(1&~(h>>4));
  27864. #endif
  27865. return (u8)(h & 0xf);
  27866. }
  27867. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  27868. /*
  27869. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  27870. ** value. Return a pointer to its binary value. Space to hold the
  27871. ** binary value has been obtained from malloc and must be freed by
  27872. ** the calling routine.
  27873. */
  27874. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  27875. char *zBlob;
  27876. int i;
  27877. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  27878. n--;
  27879. if( zBlob ){
  27880. for(i=0; i<n; i+=2){
  27881. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  27882. }
  27883. zBlob[i/2] = 0;
  27884. }
  27885. return zBlob;
  27886. }
  27887. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  27888. /*
  27889. ** Log an error that is an API call on a connection pointer that should
  27890. ** not have been used. The "type" of connection pointer is given as the
  27891. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  27892. */
  27893. static void logBadConnection(const char *zType){
  27894. sqlite3_log(SQLITE_MISUSE,
  27895. "API call with %s database connection pointer",
  27896. zType
  27897. );
  27898. }
  27899. /*
  27900. ** Check to make sure we have a valid db pointer. This test is not
  27901. ** foolproof but it does provide some measure of protection against
  27902. ** misuse of the interface such as passing in db pointers that are
  27903. ** NULL or which have been previously closed. If this routine returns
  27904. ** 1 it means that the db pointer is valid and 0 if it should not be
  27905. ** dereferenced for any reason. The calling function should invoke
  27906. ** SQLITE_MISUSE immediately.
  27907. **
  27908. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  27909. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  27910. ** open properly and is not fit for general use but which can be
  27911. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  27912. */
  27913. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  27914. u32 magic;
  27915. if( db==0 ){
  27916. logBadConnection("NULL");
  27917. return 0;
  27918. }
  27919. magic = db->magic;
  27920. if( magic!=SQLITE_MAGIC_OPEN ){
  27921. if( sqlite3SafetyCheckSickOrOk(db) ){
  27922. testcase( sqlite3GlobalConfig.xLog!=0 );
  27923. logBadConnection("unopened");
  27924. }
  27925. return 0;
  27926. }else{
  27927. return 1;
  27928. }
  27929. }
  27930. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  27931. u32 magic;
  27932. magic = db->magic;
  27933. if( magic!=SQLITE_MAGIC_SICK &&
  27934. magic!=SQLITE_MAGIC_OPEN &&
  27935. magic!=SQLITE_MAGIC_BUSY ){
  27936. testcase( sqlite3GlobalConfig.xLog!=0 );
  27937. logBadConnection("invalid");
  27938. return 0;
  27939. }else{
  27940. return 1;
  27941. }
  27942. }
  27943. /*
  27944. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  27945. ** the other 64-bit signed integer at *pA and store the result in *pA.
  27946. ** Return 0 on success. Or if the operation would have resulted in an
  27947. ** overflow, leave *pA unchanged and return 1.
  27948. */
  27949. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  27950. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  27951. return __builtin_add_overflow(*pA, iB, pA);
  27952. #else
  27953. i64 iA = *pA;
  27954. testcase( iA==0 ); testcase( iA==1 );
  27955. testcase( iB==-1 ); testcase( iB==0 );
  27956. if( iB>=0 ){
  27957. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  27958. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  27959. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  27960. }else{
  27961. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  27962. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  27963. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  27964. }
  27965. *pA += iB;
  27966. return 0;
  27967. #endif
  27968. }
  27969. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  27970. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  27971. return __builtin_sub_overflow(*pA, iB, pA);
  27972. #else
  27973. testcase( iB==SMALLEST_INT64+1 );
  27974. if( iB==SMALLEST_INT64 ){
  27975. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  27976. if( (*pA)>=0 ) return 1;
  27977. *pA -= iB;
  27978. return 0;
  27979. }else{
  27980. return sqlite3AddInt64(pA, -iB);
  27981. }
  27982. #endif
  27983. }
  27984. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  27985. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  27986. return __builtin_mul_overflow(*pA, iB, pA);
  27987. #else
  27988. i64 iA = *pA;
  27989. if( iB>0 ){
  27990. if( iA>LARGEST_INT64/iB ) return 1;
  27991. if( iA<SMALLEST_INT64/iB ) return 1;
  27992. }else if( iB<0 ){
  27993. if( iA>0 ){
  27994. if( iB<SMALLEST_INT64/iA ) return 1;
  27995. }else if( iA<0 ){
  27996. if( iB==SMALLEST_INT64 ) return 1;
  27997. if( iA==SMALLEST_INT64 ) return 1;
  27998. if( -iA>LARGEST_INT64/-iB ) return 1;
  27999. }
  28000. }
  28001. *pA = iA*iB;
  28002. return 0;
  28003. #endif
  28004. }
  28005. /*
  28006. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  28007. ** if the integer has a value of -2147483648, return +2147483647
  28008. */
  28009. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  28010. if( x>=0 ) return x;
  28011. if( x==(int)0x80000000 ) return 0x7fffffff;
  28012. return -x;
  28013. }
  28014. #ifdef SQLITE_ENABLE_8_3_NAMES
  28015. /*
  28016. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  28017. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  28018. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  28019. ** three characters, then shorten the suffix on z[] to be the last three
  28020. ** characters of the original suffix.
  28021. **
  28022. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  28023. ** do the suffix shortening regardless of URI parameter.
  28024. **
  28025. ** Examples:
  28026. **
  28027. ** test.db-journal => test.nal
  28028. ** test.db-wal => test.wal
  28029. ** test.db-shm => test.shm
  28030. ** test.db-mj7f3319fa => test.9fa
  28031. */
  28032. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  28033. #if SQLITE_ENABLE_8_3_NAMES<2
  28034. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  28035. #endif
  28036. {
  28037. int i, sz;
  28038. sz = sqlite3Strlen30(z);
  28039. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  28040. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  28041. }
  28042. }
  28043. #endif
  28044. /*
  28045. ** Find (an approximate) sum of two LogEst values. This computation is
  28046. ** not a simple "+" operator because LogEst is stored as a logarithmic
  28047. ** value.
  28048. **
  28049. */
  28050. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  28051. static const unsigned char x[] = {
  28052. 10, 10, /* 0,1 */
  28053. 9, 9, /* 2,3 */
  28054. 8, 8, /* 4,5 */
  28055. 7, 7, 7, /* 6,7,8 */
  28056. 6, 6, 6, /* 9,10,11 */
  28057. 5, 5, 5, /* 12-14 */
  28058. 4, 4, 4, 4, /* 15-18 */
  28059. 3, 3, 3, 3, 3, 3, /* 19-24 */
  28060. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  28061. };
  28062. if( a>=b ){
  28063. if( a>b+49 ) return a;
  28064. if( a>b+31 ) return a+1;
  28065. return a+x[a-b];
  28066. }else{
  28067. if( b>a+49 ) return b;
  28068. if( b>a+31 ) return b+1;
  28069. return b+x[b-a];
  28070. }
  28071. }
  28072. /*
  28073. ** Convert an integer into a LogEst. In other words, compute an
  28074. ** approximation for 10*log2(x).
  28075. */
  28076. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  28077. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  28078. LogEst y = 40;
  28079. if( x<8 ){
  28080. if( x<2 ) return 0;
  28081. while( x<8 ){ y -= 10; x <<= 1; }
  28082. }else{
  28083. #if GCC_VERSION>=5004000
  28084. int i = 60 - __builtin_clzll(x);
  28085. y += i*10;
  28086. x >>= i;
  28087. #else
  28088. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  28089. while( x>15 ){ y += 10; x >>= 1; }
  28090. #endif
  28091. }
  28092. return a[x&7] + y - 10;
  28093. }
  28094. #ifndef SQLITE_OMIT_VIRTUALTABLE
  28095. /*
  28096. ** Convert a double into a LogEst
  28097. ** In other words, compute an approximation for 10*log2(x).
  28098. */
  28099. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  28100. u64 a;
  28101. LogEst e;
  28102. assert( sizeof(x)==8 && sizeof(a)==8 );
  28103. if( x<=1 ) return 0;
  28104. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  28105. memcpy(&a, &x, 8);
  28106. e = (a>>52) - 1022;
  28107. return e*10;
  28108. }
  28109. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  28110. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  28111. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  28112. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  28113. /*
  28114. ** Convert a LogEst into an integer.
  28115. **
  28116. ** Note that this routine is only used when one or more of various
  28117. ** non-standard compile-time options is enabled.
  28118. */
  28119. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  28120. u64 n;
  28121. n = x%10;
  28122. x /= 10;
  28123. if( n>=5 ) n -= 2;
  28124. else if( n>=1 ) n -= 1;
  28125. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  28126. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  28127. if( x>60 ) return (u64)LARGEST_INT64;
  28128. #else
  28129. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  28130. ** possible to this routine is 310, resulting in a maximum x of 31 */
  28131. assert( x<=60 );
  28132. #endif
  28133. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  28134. }
  28135. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  28136. /*
  28137. ** Add a new name/number pair to a VList. This might require that the
  28138. ** VList object be reallocated, so return the new VList. If an OOM
  28139. ** error occurs, the original VList returned and the
  28140. ** db->mallocFailed flag is set.
  28141. **
  28142. ** A VList is really just an array of integers. To destroy a VList,
  28143. ** simply pass it to sqlite3DbFree().
  28144. **
  28145. ** The first integer is the number of integers allocated for the whole
  28146. ** VList. The second integer is the number of integers actually used.
  28147. ** Each name/number pair is encoded by subsequent groups of 3 or more
  28148. ** integers.
  28149. **
  28150. ** Each name/number pair starts with two integers which are the numeric
  28151. ** value for the pair and the size of the name/number pair, respectively.
  28152. ** The text name overlays one or more following integers. The text name
  28153. ** is always zero-terminated.
  28154. **
  28155. ** Conceptually:
  28156. **
  28157. ** struct VList {
  28158. ** int nAlloc; // Number of allocated slots
  28159. ** int nUsed; // Number of used slots
  28160. ** struct VListEntry {
  28161. ** int iValue; // Value for this entry
  28162. ** int nSlot; // Slots used by this entry
  28163. ** // ... variable name goes here
  28164. ** } a[0];
  28165. ** }
  28166. **
  28167. ** During code generation, pointers to the variable names within the
  28168. ** VList are taken. When that happens, nAlloc is set to zero as an
  28169. ** indication that the VList may never again be enlarged, since the
  28170. ** accompanying realloc() would invalidate the pointers.
  28171. */
  28172. SQLITE_PRIVATE VList *sqlite3VListAdd(
  28173. sqlite3 *db, /* The database connection used for malloc() */
  28174. VList *pIn, /* The input VList. Might be NULL */
  28175. const char *zName, /* Name of symbol to add */
  28176. int nName, /* Bytes of text in zName */
  28177. int iVal /* Value to associate with zName */
  28178. ){
  28179. int nInt; /* number of sizeof(int) objects needed for zName */
  28180. char *z; /* Pointer to where zName will be stored */
  28181. int i; /* Index in pIn[] where zName is stored */
  28182. nInt = nName/4 + 3;
  28183. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  28184. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  28185. /* Enlarge the allocation */
  28186. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  28187. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  28188. if( pOut==0 ) return pIn;
  28189. if( pIn==0 ) pOut[1] = 2;
  28190. pIn = pOut;
  28191. pIn[0] = nAlloc;
  28192. }
  28193. i = pIn[1];
  28194. pIn[i] = iVal;
  28195. pIn[i+1] = nInt;
  28196. z = (char*)&pIn[i+2];
  28197. pIn[1] = i+nInt;
  28198. assert( pIn[1]<=pIn[0] );
  28199. memcpy(z, zName, nName);
  28200. z[nName] = 0;
  28201. return pIn;
  28202. }
  28203. /*
  28204. ** Return a pointer to the name of a variable in the given VList that
  28205. ** has the value iVal. Or return a NULL if there is no such variable in
  28206. ** the list
  28207. */
  28208. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  28209. int i, mx;
  28210. if( pIn==0 ) return 0;
  28211. mx = pIn[1];
  28212. i = 2;
  28213. do{
  28214. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  28215. i += pIn[i+1];
  28216. }while( i<mx );
  28217. return 0;
  28218. }
  28219. /*
  28220. ** Return the number of the variable named zName, if it is in VList.
  28221. ** or return 0 if there is no such variable.
  28222. */
  28223. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  28224. int i, mx;
  28225. if( pIn==0 ) return 0;
  28226. mx = pIn[1];
  28227. i = 2;
  28228. do{
  28229. const char *z = (const char*)&pIn[i+2];
  28230. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  28231. i += pIn[i+1];
  28232. }while( i<mx );
  28233. return 0;
  28234. }
  28235. /************** End of util.c ************************************************/
  28236. /************** Begin file hash.c ********************************************/
  28237. /*
  28238. ** 2001 September 22
  28239. **
  28240. ** The author disclaims copyright to this source code. In place of
  28241. ** a legal notice, here is a blessing:
  28242. **
  28243. ** May you do good and not evil.
  28244. ** May you find forgiveness for yourself and forgive others.
  28245. ** May you share freely, never taking more than you give.
  28246. **
  28247. *************************************************************************
  28248. ** This is the implementation of generic hash-tables
  28249. ** used in SQLite.
  28250. */
  28251. /* #include "sqliteInt.h" */
  28252. /* #include <assert.h> */
  28253. /* Turn bulk memory into a hash table object by initializing the
  28254. ** fields of the Hash structure.
  28255. **
  28256. ** "pNew" is a pointer to the hash table that is to be initialized.
  28257. */
  28258. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  28259. assert( pNew!=0 );
  28260. pNew->first = 0;
  28261. pNew->count = 0;
  28262. pNew->htsize = 0;
  28263. pNew->ht = 0;
  28264. }
  28265. /* Remove all entries from a hash table. Reclaim all memory.
  28266. ** Call this routine to delete a hash table or to reset a hash table
  28267. ** to the empty state.
  28268. */
  28269. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  28270. HashElem *elem; /* For looping over all elements of the table */
  28271. assert( pH!=0 );
  28272. elem = pH->first;
  28273. pH->first = 0;
  28274. sqlite3_free(pH->ht);
  28275. pH->ht = 0;
  28276. pH->htsize = 0;
  28277. while( elem ){
  28278. HashElem *next_elem = elem->next;
  28279. sqlite3_free(elem);
  28280. elem = next_elem;
  28281. }
  28282. pH->count = 0;
  28283. }
  28284. /*
  28285. ** The hashing function.
  28286. */
  28287. static unsigned int strHash(const char *z){
  28288. unsigned int h = 0;
  28289. unsigned char c;
  28290. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  28291. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  28292. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  28293. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  28294. h += sqlite3UpperToLower[c];
  28295. h *= 0x9e3779b1;
  28296. }
  28297. return h;
  28298. }
  28299. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  28300. ** insert pNew into the pEntry hash bucket.
  28301. */
  28302. static void insertElement(
  28303. Hash *pH, /* The complete hash table */
  28304. struct _ht *pEntry, /* The entry into which pNew is inserted */
  28305. HashElem *pNew /* The element to be inserted */
  28306. ){
  28307. HashElem *pHead; /* First element already in pEntry */
  28308. if( pEntry ){
  28309. pHead = pEntry->count ? pEntry->chain : 0;
  28310. pEntry->count++;
  28311. pEntry->chain = pNew;
  28312. }else{
  28313. pHead = 0;
  28314. }
  28315. if( pHead ){
  28316. pNew->next = pHead;
  28317. pNew->prev = pHead->prev;
  28318. if( pHead->prev ){ pHead->prev->next = pNew; }
  28319. else { pH->first = pNew; }
  28320. pHead->prev = pNew;
  28321. }else{
  28322. pNew->next = pH->first;
  28323. if( pH->first ){ pH->first->prev = pNew; }
  28324. pNew->prev = 0;
  28325. pH->first = pNew;
  28326. }
  28327. }
  28328. /* Resize the hash table so that it cantains "new_size" buckets.
  28329. **
  28330. ** The hash table might fail to resize if sqlite3_malloc() fails or
  28331. ** if the new size is the same as the prior size.
  28332. ** Return TRUE if the resize occurs and false if not.
  28333. */
  28334. static int rehash(Hash *pH, unsigned int new_size){
  28335. struct _ht *new_ht; /* The new hash table */
  28336. HashElem *elem, *next_elem; /* For looping over existing elements */
  28337. #if SQLITE_MALLOC_SOFT_LIMIT>0
  28338. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  28339. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  28340. }
  28341. if( new_size==pH->htsize ) return 0;
  28342. #endif
  28343. /* The inability to allocates space for a larger hash table is
  28344. ** a performance hit but it is not a fatal error. So mark the
  28345. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  28346. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  28347. ** only zeroes the requested number of bytes whereas this module will
  28348. ** use the actual amount of space allocated for the hash table (which
  28349. ** may be larger than the requested amount).
  28350. */
  28351. sqlite3BeginBenignMalloc();
  28352. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  28353. sqlite3EndBenignMalloc();
  28354. if( new_ht==0 ) return 0;
  28355. sqlite3_free(pH->ht);
  28356. pH->ht = new_ht;
  28357. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  28358. memset(new_ht, 0, new_size*sizeof(struct _ht));
  28359. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  28360. unsigned int h = strHash(elem->pKey) % new_size;
  28361. next_elem = elem->next;
  28362. insertElement(pH, &new_ht[h], elem);
  28363. }
  28364. return 1;
  28365. }
  28366. /* This function (for internal use only) locates an element in an
  28367. ** hash table that matches the given key. If no element is found,
  28368. ** a pointer to a static null element with HashElem.data==0 is returned.
  28369. ** If pH is not NULL, then the hash for this key is written to *pH.
  28370. */
  28371. static HashElem *findElementWithHash(
  28372. const Hash *pH, /* The pH to be searched */
  28373. const char *pKey, /* The key we are searching for */
  28374. unsigned int *pHash /* Write the hash value here */
  28375. ){
  28376. HashElem *elem; /* Used to loop thru the element list */
  28377. int count; /* Number of elements left to test */
  28378. unsigned int h; /* The computed hash */
  28379. static HashElem nullElement = { 0, 0, 0, 0 };
  28380. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  28381. struct _ht *pEntry;
  28382. h = strHash(pKey) % pH->htsize;
  28383. pEntry = &pH->ht[h];
  28384. elem = pEntry->chain;
  28385. count = pEntry->count;
  28386. }else{
  28387. h = 0;
  28388. elem = pH->first;
  28389. count = pH->count;
  28390. }
  28391. if( pHash ) *pHash = h;
  28392. while( count-- ){
  28393. assert( elem!=0 );
  28394. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  28395. return elem;
  28396. }
  28397. elem = elem->next;
  28398. }
  28399. return &nullElement;
  28400. }
  28401. /* Remove a single entry from the hash table given a pointer to that
  28402. ** element and a hash on the element's key.
  28403. */
  28404. static void removeElementGivenHash(
  28405. Hash *pH, /* The pH containing "elem" */
  28406. HashElem* elem, /* The element to be removed from the pH */
  28407. unsigned int h /* Hash value for the element */
  28408. ){
  28409. struct _ht *pEntry;
  28410. if( elem->prev ){
  28411. elem->prev->next = elem->next;
  28412. }else{
  28413. pH->first = elem->next;
  28414. }
  28415. if( elem->next ){
  28416. elem->next->prev = elem->prev;
  28417. }
  28418. if( pH->ht ){
  28419. pEntry = &pH->ht[h];
  28420. if( pEntry->chain==elem ){
  28421. pEntry->chain = elem->next;
  28422. }
  28423. pEntry->count--;
  28424. assert( pEntry->count>=0 );
  28425. }
  28426. sqlite3_free( elem );
  28427. pH->count--;
  28428. if( pH->count==0 ){
  28429. assert( pH->first==0 );
  28430. assert( pH->count==0 );
  28431. sqlite3HashClear(pH);
  28432. }
  28433. }
  28434. /* Attempt to locate an element of the hash table pH with a key
  28435. ** that matches pKey. Return the data for this element if it is
  28436. ** found, or NULL if there is no match.
  28437. */
  28438. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  28439. assert( pH!=0 );
  28440. assert( pKey!=0 );
  28441. return findElementWithHash(pH, pKey, 0)->data;
  28442. }
  28443. /* Insert an element into the hash table pH. The key is pKey
  28444. ** and the data is "data".
  28445. **
  28446. ** If no element exists with a matching key, then a new
  28447. ** element is created and NULL is returned.
  28448. **
  28449. ** If another element already exists with the same key, then the
  28450. ** new data replaces the old data and the old data is returned.
  28451. ** The key is not copied in this instance. If a malloc fails, then
  28452. ** the new data is returned and the hash table is unchanged.
  28453. **
  28454. ** If the "data" parameter to this function is NULL, then the
  28455. ** element corresponding to "key" is removed from the hash table.
  28456. */
  28457. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  28458. unsigned int h; /* the hash of the key modulo hash table size */
  28459. HashElem *elem; /* Used to loop thru the element list */
  28460. HashElem *new_elem; /* New element added to the pH */
  28461. assert( pH!=0 );
  28462. assert( pKey!=0 );
  28463. elem = findElementWithHash(pH,pKey,&h);
  28464. if( elem->data ){
  28465. void *old_data = elem->data;
  28466. if( data==0 ){
  28467. removeElementGivenHash(pH,elem,h);
  28468. }else{
  28469. elem->data = data;
  28470. elem->pKey = pKey;
  28471. }
  28472. return old_data;
  28473. }
  28474. if( data==0 ) return 0;
  28475. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  28476. if( new_elem==0 ) return data;
  28477. new_elem->pKey = pKey;
  28478. new_elem->data = data;
  28479. pH->count++;
  28480. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  28481. if( rehash(pH, pH->count*2) ){
  28482. assert( pH->htsize>0 );
  28483. h = strHash(pKey) % pH->htsize;
  28484. }
  28485. }
  28486. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  28487. return 0;
  28488. }
  28489. /************** End of hash.c ************************************************/
  28490. /************** Begin file opcodes.c *****************************************/
  28491. /* Automatically generated. Do not edit */
  28492. /* See the tool/mkopcodec.tcl script for details. */
  28493. #if !defined(SQLITE_OMIT_EXPLAIN) \
  28494. || defined(VDBE_PROFILE) \
  28495. || defined(SQLITE_DEBUG)
  28496. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  28497. # define OpHelp(X) "\0" X
  28498. #else
  28499. # define OpHelp(X)
  28500. #endif
  28501. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  28502. static const char *const azName[] = {
  28503. /* 0 */ "Savepoint" OpHelp(""),
  28504. /* 1 */ "AutoCommit" OpHelp(""),
  28505. /* 2 */ "Transaction" OpHelp(""),
  28506. /* 3 */ "SorterNext" OpHelp(""),
  28507. /* 4 */ "PrevIfOpen" OpHelp(""),
  28508. /* 5 */ "NextIfOpen" OpHelp(""),
  28509. /* 6 */ "Prev" OpHelp(""),
  28510. /* 7 */ "Next" OpHelp(""),
  28511. /* 8 */ "Checkpoint" OpHelp(""),
  28512. /* 9 */ "JournalMode" OpHelp(""),
  28513. /* 10 */ "Vacuum" OpHelp(""),
  28514. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  28515. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  28516. /* 13 */ "Goto" OpHelp(""),
  28517. /* 14 */ "Gosub" OpHelp(""),
  28518. /* 15 */ "InitCoroutine" OpHelp(""),
  28519. /* 16 */ "Yield" OpHelp(""),
  28520. /* 17 */ "MustBeInt" OpHelp(""),
  28521. /* 18 */ "Jump" OpHelp(""),
  28522. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  28523. /* 20 */ "Once" OpHelp(""),
  28524. /* 21 */ "If" OpHelp(""),
  28525. /* 22 */ "IfNot" OpHelp(""),
  28526. /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  28527. /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  28528. /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  28529. /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  28530. /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  28531. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  28532. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  28533. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  28534. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  28535. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  28536. /* 33 */ "Last" OpHelp(""),
  28537. /* 34 */ "IfSmaller" OpHelp(""),
  28538. /* 35 */ "SorterSort" OpHelp(""),
  28539. /* 36 */ "Sort" OpHelp(""),
  28540. /* 37 */ "Rewind" OpHelp(""),
  28541. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  28542. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  28543. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  28544. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  28545. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  28546. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  28547. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  28548. /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  28549. /* 46 */ "Program" OpHelp(""),
  28550. /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  28551. /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  28552. /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  28553. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  28554. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  28555. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  28556. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  28557. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  28558. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  28559. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  28560. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  28561. /* 58 */ "ElseNotEq" OpHelp(""),
  28562. /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  28563. /* 60 */ "IncrVacuum" OpHelp(""),
  28564. /* 61 */ "VNext" OpHelp(""),
  28565. /* 62 */ "Init" OpHelp("Start at P2"),
  28566. /* 63 */ "Return" OpHelp(""),
  28567. /* 64 */ "EndCoroutine" OpHelp(""),
  28568. /* 65 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  28569. /* 66 */ "Halt" OpHelp(""),
  28570. /* 67 */ "Integer" OpHelp("r[P2]=P1"),
  28571. /* 68 */ "Int64" OpHelp("r[P2]=P4"),
  28572. /* 69 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  28573. /* 70 */ "Null" OpHelp("r[P2..P3]=NULL"),
  28574. /* 71 */ "SoftNull" OpHelp("r[P1]=NULL"),
  28575. /* 72 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  28576. /* 73 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  28577. /* 74 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  28578. /* 75 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  28579. /* 76 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  28580. /* 77 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  28581. /* 78 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  28582. /* 79 */ "CollSeq" OpHelp(""),
  28583. /* 80 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  28584. /* 81 */ "RealAffinity" OpHelp(""),
  28585. /* 82 */ "Cast" OpHelp("affinity(r[P1])"),
  28586. /* 83 */ "Permutation" OpHelp(""),
  28587. /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  28588. /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  28589. /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  28590. /* 87 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  28591. /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  28592. /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  28593. /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  28594. /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  28595. /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  28596. /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  28597. /* 94 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  28598. /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  28599. /* 96 */ "Column" OpHelp("r[P3]=PX"),
  28600. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  28601. /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  28602. /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  28603. /* 100 */ "Count" OpHelp("r[P2]=count()"),
  28604. /* 101 */ "ReadCookie" OpHelp(""),
  28605. /* 102 */ "SetCookie" OpHelp(""),
  28606. /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  28607. /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  28608. /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  28609. /* 106 */ "OpenDup" OpHelp(""),
  28610. /* 107 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  28611. /* 108 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  28612. /* 109 */ "SorterOpen" OpHelp(""),
  28613. /* 110 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  28614. /* 111 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  28615. /* 112 */ "Close" OpHelp(""),
  28616. /* 113 */ "ColumnsUsed" OpHelp(""),
  28617. /* 114 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  28618. /* 115 */ "NewRowid" OpHelp("r[P2]=rowid"),
  28619. /* 116 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  28620. /* 117 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  28621. /* 118 */ "Delete" OpHelp(""),
  28622. /* 119 */ "ResetCount" OpHelp(""),
  28623. /* 120 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  28624. /* 121 */ "SorterData" OpHelp("r[P2]=data"),
  28625. /* 122 */ "RowData" OpHelp("r[P2]=data"),
  28626. /* 123 */ "Rowid" OpHelp("r[P2]=rowid"),
  28627. /* 124 */ "NullRow" OpHelp(""),
  28628. /* 125 */ "SeekEnd" OpHelp(""),
  28629. /* 126 */ "SorterInsert" OpHelp("key=r[P2]"),
  28630. /* 127 */ "IdxInsert" OpHelp("key=r[P2]"),
  28631. /* 128 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  28632. /* 129 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  28633. /* 130 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  28634. /* 131 */ "Destroy" OpHelp(""),
  28635. /* 132 */ "Real" OpHelp("r[P2]=P4"),
  28636. /* 133 */ "Clear" OpHelp(""),
  28637. /* 134 */ "ResetSorter" OpHelp(""),
  28638. /* 135 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  28639. /* 136 */ "SqlExec" OpHelp(""),
  28640. /* 137 */ "ParseSchema" OpHelp(""),
  28641. /* 138 */ "LoadAnalysis" OpHelp(""),
  28642. /* 139 */ "DropTable" OpHelp(""),
  28643. /* 140 */ "DropIndex" OpHelp(""),
  28644. /* 141 */ "DropTrigger" OpHelp(""),
  28645. /* 142 */ "IntegrityCk" OpHelp(""),
  28646. /* 143 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  28647. /* 144 */ "Param" OpHelp(""),
  28648. /* 145 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  28649. /* 146 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  28650. /* 147 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  28651. /* 148 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28652. /* 149 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28653. /* 150 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  28654. /* 151 */ "Expire" OpHelp(""),
  28655. /* 152 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  28656. /* 153 */ "VBegin" OpHelp(""),
  28657. /* 154 */ "VCreate" OpHelp(""),
  28658. /* 155 */ "VDestroy" OpHelp(""),
  28659. /* 156 */ "VOpen" OpHelp(""),
  28660. /* 157 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  28661. /* 158 */ "VRename" OpHelp(""),
  28662. /* 159 */ "Pagecount" OpHelp(""),
  28663. /* 160 */ "MaxPgcnt" OpHelp(""),
  28664. /* 161 */ "PureFunc0" OpHelp(""),
  28665. /* 162 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  28666. /* 163 */ "PureFunc" OpHelp(""),
  28667. /* 164 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  28668. /* 165 */ "CursorHint" OpHelp(""),
  28669. /* 166 */ "Noop" OpHelp(""),
  28670. /* 167 */ "Explain" OpHelp(""),
  28671. };
  28672. return azName[i];
  28673. }
  28674. #endif
  28675. /************** End of opcodes.c *********************************************/
  28676. /************** Begin file os_unix.c *****************************************/
  28677. /*
  28678. ** 2004 May 22
  28679. **
  28680. ** The author disclaims copyright to this source code. In place of
  28681. ** a legal notice, here is a blessing:
  28682. **
  28683. ** May you do good and not evil.
  28684. ** May you find forgiveness for yourself and forgive others.
  28685. ** May you share freely, never taking more than you give.
  28686. **
  28687. ******************************************************************************
  28688. **
  28689. ** This file contains the VFS implementation for unix-like operating systems
  28690. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  28691. **
  28692. ** There are actually several different VFS implementations in this file.
  28693. ** The differences are in the way that file locking is done. The default
  28694. ** implementation uses Posix Advisory Locks. Alternative implementations
  28695. ** use flock(), dot-files, various proprietary locking schemas, or simply
  28696. ** skip locking all together.
  28697. **
  28698. ** This source file is organized into divisions where the logic for various
  28699. ** subfunctions is contained within the appropriate division. PLEASE
  28700. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  28701. ** in the correct division and should be clearly labeled.
  28702. **
  28703. ** The layout of divisions is as follows:
  28704. **
  28705. ** * General-purpose declarations and utility functions.
  28706. ** * Unique file ID logic used by VxWorks.
  28707. ** * Various locking primitive implementations (all except proxy locking):
  28708. ** + for Posix Advisory Locks
  28709. ** + for no-op locks
  28710. ** + for dot-file locks
  28711. ** + for flock() locking
  28712. ** + for named semaphore locks (VxWorks only)
  28713. ** + for AFP filesystem locks (MacOSX only)
  28714. ** * sqlite3_file methods not associated with locking.
  28715. ** * Definitions of sqlite3_io_methods objects for all locking
  28716. ** methods plus "finder" functions for each locking method.
  28717. ** * sqlite3_vfs method implementations.
  28718. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  28719. ** * Definitions of sqlite3_vfs objects for all locking methods
  28720. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  28721. */
  28722. /* #include "sqliteInt.h" */
  28723. #if SQLITE_OS_UNIX /* This file is used on unix only */
  28724. /*
  28725. ** There are various methods for file locking used for concurrency
  28726. ** control:
  28727. **
  28728. ** 1. POSIX locking (the default),
  28729. ** 2. No locking,
  28730. ** 3. Dot-file locking,
  28731. ** 4. flock() locking,
  28732. ** 5. AFP locking (OSX only),
  28733. ** 6. Named POSIX semaphores (VXWorks only),
  28734. ** 7. proxy locking. (OSX only)
  28735. **
  28736. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  28737. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  28738. ** selection of the appropriate locking style based on the filesystem
  28739. ** where the database is located.
  28740. */
  28741. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  28742. # if defined(__APPLE__)
  28743. # define SQLITE_ENABLE_LOCKING_STYLE 1
  28744. # else
  28745. # define SQLITE_ENABLE_LOCKING_STYLE 0
  28746. # endif
  28747. #endif
  28748. /* Use pread() and pwrite() if they are available */
  28749. #if defined(__APPLE__)
  28750. # define HAVE_PREAD 1
  28751. # define HAVE_PWRITE 1
  28752. #endif
  28753. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  28754. # undef USE_PREAD
  28755. # define USE_PREAD64 1
  28756. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  28757. # undef USE_PREAD64
  28758. # define USE_PREAD 1
  28759. #endif
  28760. /*
  28761. ** standard include files.
  28762. */
  28763. #include <sys/types.h>
  28764. #include <sys/stat.h>
  28765. #include <fcntl.h>
  28766. #include <sys/ioctl.h>
  28767. #include <unistd.h>
  28768. /* #include <time.h> */
  28769. #include <sys/time.h>
  28770. #include <errno.h>
  28771. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28772. # include <sys/mman.h>
  28773. #endif
  28774. #if SQLITE_ENABLE_LOCKING_STYLE
  28775. /* # include <sys/ioctl.h> */
  28776. # include <sys/file.h>
  28777. # include <sys/param.h>
  28778. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  28779. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  28780. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  28781. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  28782. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  28783. # define HAVE_GETHOSTUUID 1
  28784. # else
  28785. # warning "gethostuuid() is disabled."
  28786. # endif
  28787. #endif
  28788. #if OS_VXWORKS
  28789. /* # include <sys/ioctl.h> */
  28790. # include <semaphore.h>
  28791. # include <limits.h>
  28792. #endif /* OS_VXWORKS */
  28793. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28794. # include <sys/mount.h>
  28795. #endif
  28796. #ifdef HAVE_UTIME
  28797. # include <utime.h>
  28798. #endif
  28799. /*
  28800. ** Allowed values of unixFile.fsFlags
  28801. */
  28802. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  28803. /*
  28804. ** If we are to be thread-safe, include the pthreads header and define
  28805. ** the SQLITE_UNIX_THREADS macro.
  28806. */
  28807. #if SQLITE_THREADSAFE
  28808. /* # include <pthread.h> */
  28809. # define SQLITE_UNIX_THREADS 1
  28810. #endif
  28811. /*
  28812. ** Default permissions when creating a new file
  28813. */
  28814. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  28815. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  28816. #endif
  28817. /*
  28818. ** Default permissions when creating auto proxy dir
  28819. */
  28820. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  28821. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  28822. #endif
  28823. /*
  28824. ** Maximum supported path-length.
  28825. */
  28826. #define MAX_PATHNAME 512
  28827. /*
  28828. ** Maximum supported symbolic links
  28829. */
  28830. #define SQLITE_MAX_SYMLINKS 100
  28831. /* Always cast the getpid() return type for compatibility with
  28832. ** kernel modules in VxWorks. */
  28833. #define osGetpid(X) (pid_t)getpid()
  28834. /*
  28835. ** Only set the lastErrno if the error code is a real error and not
  28836. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  28837. */
  28838. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  28839. /* Forward references */
  28840. typedef struct unixShm unixShm; /* Connection shared memory */
  28841. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  28842. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  28843. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  28844. /*
  28845. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  28846. ** cannot be closed immediately. In these cases, instances of the following
  28847. ** structure are used to store the file descriptor while waiting for an
  28848. ** opportunity to either close or reuse it.
  28849. */
  28850. struct UnixUnusedFd {
  28851. int fd; /* File descriptor to close */
  28852. int flags; /* Flags this file descriptor was opened with */
  28853. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  28854. };
  28855. /*
  28856. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  28857. ** VFS implementations.
  28858. */
  28859. typedef struct unixFile unixFile;
  28860. struct unixFile {
  28861. sqlite3_io_methods const *pMethod; /* Always the first entry */
  28862. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  28863. unixInodeInfo *pInode; /* Info about locks on this inode */
  28864. int h; /* The file descriptor */
  28865. unsigned char eFileLock; /* The type of lock held on this fd */
  28866. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  28867. int lastErrno; /* The unix errno from last I/O error */
  28868. void *lockingContext; /* Locking style specific state */
  28869. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  28870. const char *zPath; /* Name of the file */
  28871. unixShm *pShm; /* Shared memory segment information */
  28872. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  28873. #if SQLITE_MAX_MMAP_SIZE>0
  28874. int nFetchOut; /* Number of outstanding xFetch refs */
  28875. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  28876. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  28877. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  28878. void *pMapRegion; /* Memory mapped region */
  28879. #endif
  28880. int sectorSize; /* Device sector size */
  28881. int deviceCharacteristics; /* Precomputed device characteristics */
  28882. #if SQLITE_ENABLE_LOCKING_STYLE
  28883. int openFlags; /* The flags specified at open() */
  28884. #endif
  28885. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  28886. unsigned fsFlags; /* cached details from statfs() */
  28887. #endif
  28888. #if OS_VXWORKS
  28889. struct vxworksFileId *pId; /* Unique file ID */
  28890. #endif
  28891. #ifdef SQLITE_DEBUG
  28892. /* The next group of variables are used to track whether or not the
  28893. ** transaction counter in bytes 24-27 of database files are updated
  28894. ** whenever any part of the database changes. An assertion fault will
  28895. ** occur if a file is updated without also updating the transaction
  28896. ** counter. This test is made to avoid new problems similar to the
  28897. ** one described by ticket #3584.
  28898. */
  28899. unsigned char transCntrChng; /* True if the transaction counter changed */
  28900. unsigned char dbUpdate; /* True if any part of database file changed */
  28901. unsigned char inNormalWrite; /* True if in a normal write operation */
  28902. #endif
  28903. #ifdef SQLITE_TEST
  28904. /* In test mode, increase the size of this structure a bit so that
  28905. ** it is larger than the struct CrashFile defined in test6.c.
  28906. */
  28907. char aPadding[32];
  28908. #endif
  28909. };
  28910. /* This variable holds the process id (pid) from when the xRandomness()
  28911. ** method was called. If xOpen() is called from a different process id,
  28912. ** indicating that a fork() has occurred, the PRNG will be reset.
  28913. */
  28914. static pid_t randomnessPid = 0;
  28915. /*
  28916. ** Allowed values for the unixFile.ctrlFlags bitmask:
  28917. */
  28918. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  28919. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  28920. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  28921. #ifndef SQLITE_DISABLE_DIRSYNC
  28922. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  28923. #else
  28924. # define UNIXFILE_DIRSYNC 0x00
  28925. #endif
  28926. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  28927. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  28928. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  28929. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  28930. /*
  28931. ** Include code that is common to all os_*.c files
  28932. */
  28933. /************** Include os_common.h in the middle of os_unix.c ***************/
  28934. /************** Begin file os_common.h ***************************************/
  28935. /*
  28936. ** 2004 May 22
  28937. **
  28938. ** The author disclaims copyright to this source code. In place of
  28939. ** a legal notice, here is a blessing:
  28940. **
  28941. ** May you do good and not evil.
  28942. ** May you find forgiveness for yourself and forgive others.
  28943. ** May you share freely, never taking more than you give.
  28944. **
  28945. ******************************************************************************
  28946. **
  28947. ** This file contains macros and a little bit of code that is common to
  28948. ** all of the platform-specific files (os_*.c) and is #included into those
  28949. ** files.
  28950. **
  28951. ** This file should be #included by the os_*.c files only. It is not a
  28952. ** general purpose header file.
  28953. */
  28954. #ifndef _OS_COMMON_H_
  28955. #define _OS_COMMON_H_
  28956. /*
  28957. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28958. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28959. ** switch. The following code should catch this problem at compile-time.
  28960. */
  28961. #ifdef MEMORY_DEBUG
  28962. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28963. #endif
  28964. /*
  28965. ** Macros for performance tracing. Normally turned off. Only works
  28966. ** on i486 hardware.
  28967. */
  28968. #ifdef SQLITE_PERFORMANCE_TRACE
  28969. /*
  28970. ** hwtime.h contains inline assembler code for implementing
  28971. ** high-performance timing routines.
  28972. */
  28973. /************** Include hwtime.h in the middle of os_common.h ****************/
  28974. /************** Begin file hwtime.h ******************************************/
  28975. /*
  28976. ** 2008 May 27
  28977. **
  28978. ** The author disclaims copyright to this source code. In place of
  28979. ** a legal notice, here is a blessing:
  28980. **
  28981. ** May you do good and not evil.
  28982. ** May you find forgiveness for yourself and forgive others.
  28983. ** May you share freely, never taking more than you give.
  28984. **
  28985. ******************************************************************************
  28986. **
  28987. ** This file contains inline asm code for retrieving "high-performance"
  28988. ** counters for x86 class CPUs.
  28989. */
  28990. #ifndef SQLITE_HWTIME_H
  28991. #define SQLITE_HWTIME_H
  28992. /*
  28993. ** The following routine only works on pentium-class (or newer) processors.
  28994. ** It uses the RDTSC opcode to read the cycle count value out of the
  28995. ** processor and returns that value. This can be used for high-res
  28996. ** profiling.
  28997. */
  28998. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28999. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  29000. #if defined(__GNUC__)
  29001. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29002. unsigned int lo, hi;
  29003. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  29004. return (sqlite_uint64)hi << 32 | lo;
  29005. }
  29006. #elif defined(_MSC_VER)
  29007. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  29008. __asm {
  29009. rdtsc
  29010. ret ; return value at EDX:EAX
  29011. }
  29012. }
  29013. #endif
  29014. #elif (defined(__GNUC__) && defined(__x86_64__))
  29015. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29016. unsigned long val;
  29017. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  29018. return val;
  29019. }
  29020. #elif (defined(__GNUC__) && defined(__ppc__))
  29021. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29022. unsigned long long retval;
  29023. unsigned long junk;
  29024. __asm__ __volatile__ ("\n\
  29025. 1: mftbu %1\n\
  29026. mftb %L0\n\
  29027. mftbu %0\n\
  29028. cmpw %0,%1\n\
  29029. bne 1b"
  29030. : "=r" (retval), "=r" (junk));
  29031. return retval;
  29032. }
  29033. #else
  29034. #error Need implementation of sqlite3Hwtime() for your platform.
  29035. /*
  29036. ** To compile without implementing sqlite3Hwtime() for your platform,
  29037. ** you can remove the above #error and use the following
  29038. ** stub function. You will lose timing support for many
  29039. ** of the debugging and testing utilities, but it should at
  29040. ** least compile and run.
  29041. */
  29042. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  29043. #endif
  29044. #endif /* !defined(SQLITE_HWTIME_H) */
  29045. /************** End of hwtime.h **********************************************/
  29046. /************** Continuing where we left off in os_common.h ******************/
  29047. static sqlite_uint64 g_start;
  29048. static sqlite_uint64 g_elapsed;
  29049. #define TIMER_START g_start=sqlite3Hwtime()
  29050. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  29051. #define TIMER_ELAPSED g_elapsed
  29052. #else
  29053. #define TIMER_START
  29054. #define TIMER_END
  29055. #define TIMER_ELAPSED ((sqlite_uint64)0)
  29056. #endif
  29057. /*
  29058. ** If we compile with the SQLITE_TEST macro set, then the following block
  29059. ** of code will give us the ability to simulate a disk I/O error. This
  29060. ** is used for testing the I/O recovery logic.
  29061. */
  29062. #if defined(SQLITE_TEST)
  29063. SQLITE_API extern int sqlite3_io_error_hit;
  29064. SQLITE_API extern int sqlite3_io_error_hardhit;
  29065. SQLITE_API extern int sqlite3_io_error_pending;
  29066. SQLITE_API extern int sqlite3_io_error_persist;
  29067. SQLITE_API extern int sqlite3_io_error_benign;
  29068. SQLITE_API extern int sqlite3_diskfull_pending;
  29069. SQLITE_API extern int sqlite3_diskfull;
  29070. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  29071. #define SimulateIOError(CODE) \
  29072. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29073. || sqlite3_io_error_pending-- == 1 ) \
  29074. { local_ioerr(); CODE; }
  29075. static void local_ioerr(){
  29076. IOTRACE(("IOERR\n"));
  29077. sqlite3_io_error_hit++;
  29078. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29079. }
  29080. #define SimulateDiskfullError(CODE) \
  29081. if( sqlite3_diskfull_pending ){ \
  29082. if( sqlite3_diskfull_pending == 1 ){ \
  29083. local_ioerr(); \
  29084. sqlite3_diskfull = 1; \
  29085. sqlite3_io_error_hit = 1; \
  29086. CODE; \
  29087. }else{ \
  29088. sqlite3_diskfull_pending--; \
  29089. } \
  29090. }
  29091. #else
  29092. #define SimulateIOErrorBenign(X)
  29093. #define SimulateIOError(A)
  29094. #define SimulateDiskfullError(A)
  29095. #endif /* defined(SQLITE_TEST) */
  29096. /*
  29097. ** When testing, keep a count of the number of open files.
  29098. */
  29099. #if defined(SQLITE_TEST)
  29100. SQLITE_API extern int sqlite3_open_file_count;
  29101. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29102. #else
  29103. #define OpenCounter(X)
  29104. #endif /* defined(SQLITE_TEST) */
  29105. #endif /* !defined(_OS_COMMON_H_) */
  29106. /************** End of os_common.h *******************************************/
  29107. /************** Continuing where we left off in os_unix.c ********************/
  29108. /*
  29109. ** Define various macros that are missing from some systems.
  29110. */
  29111. #ifndef O_LARGEFILE
  29112. # define O_LARGEFILE 0
  29113. #endif
  29114. #ifdef SQLITE_DISABLE_LFS
  29115. # undef O_LARGEFILE
  29116. # define O_LARGEFILE 0
  29117. #endif
  29118. #ifndef O_NOFOLLOW
  29119. # define O_NOFOLLOW 0
  29120. #endif
  29121. #ifndef O_BINARY
  29122. # define O_BINARY 0
  29123. #endif
  29124. /*
  29125. ** The threadid macro resolves to the thread-id or to 0. Used for
  29126. ** testing and debugging only.
  29127. */
  29128. #if SQLITE_THREADSAFE
  29129. #define threadid pthread_self()
  29130. #else
  29131. #define threadid 0
  29132. #endif
  29133. /*
  29134. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  29135. */
  29136. #if !defined(HAVE_MREMAP)
  29137. # if defined(__linux__) && defined(_GNU_SOURCE)
  29138. # define HAVE_MREMAP 1
  29139. # else
  29140. # define HAVE_MREMAP 0
  29141. # endif
  29142. #endif
  29143. /*
  29144. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  29145. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  29146. */
  29147. #ifdef __ANDROID__
  29148. # define lseek lseek64
  29149. #endif
  29150. #ifdef __linux__
  29151. /*
  29152. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  29153. */
  29154. #define F2FS_IOCTL_MAGIC 0xf5
  29155. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  29156. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  29157. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  29158. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  29159. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  29160. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  29161. #endif /* __linux__ */
  29162. /*
  29163. ** Different Unix systems declare open() in different ways. Same use
  29164. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  29165. ** The difference is important when using a pointer to the function.
  29166. **
  29167. ** The safest way to deal with the problem is to always use this wrapper
  29168. ** which always has the same well-defined interface.
  29169. */
  29170. static int posixOpen(const char *zFile, int flags, int mode){
  29171. return open(zFile, flags, mode);
  29172. }
  29173. /* Forward reference */
  29174. static int openDirectory(const char*, int*);
  29175. static int unixGetpagesize(void);
  29176. /*
  29177. ** Many system calls are accessed through pointer-to-functions so that
  29178. ** they may be overridden at runtime to facilitate fault injection during
  29179. ** testing and sandboxing. The following array holds the names and pointers
  29180. ** to all overrideable system calls.
  29181. */
  29182. static struct unix_syscall {
  29183. const char *zName; /* Name of the system call */
  29184. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  29185. sqlite3_syscall_ptr pDefault; /* Default value */
  29186. } aSyscall[] = {
  29187. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  29188. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  29189. { "close", (sqlite3_syscall_ptr)close, 0 },
  29190. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  29191. { "access", (sqlite3_syscall_ptr)access, 0 },
  29192. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  29193. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  29194. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  29195. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  29196. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  29197. /*
  29198. ** The DJGPP compiler environment looks mostly like Unix, but it
  29199. ** lacks the fcntl() system call. So redefine fcntl() to be something
  29200. ** that always succeeds. This means that locking does not occur under
  29201. ** DJGPP. But it is DOS - what did you expect?
  29202. */
  29203. #ifdef __DJGPP__
  29204. { "fstat", 0, 0 },
  29205. #define osFstat(a,b,c) 0
  29206. #else
  29207. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  29208. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  29209. #endif
  29210. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  29211. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  29212. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  29213. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  29214. { "read", (sqlite3_syscall_ptr)read, 0 },
  29215. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  29216. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  29217. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  29218. #else
  29219. { "pread", (sqlite3_syscall_ptr)0, 0 },
  29220. #endif
  29221. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  29222. #if defined(USE_PREAD64)
  29223. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  29224. #else
  29225. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  29226. #endif
  29227. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  29228. { "write", (sqlite3_syscall_ptr)write, 0 },
  29229. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  29230. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  29231. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  29232. #else
  29233. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  29234. #endif
  29235. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  29236. aSyscall[12].pCurrent)
  29237. #if defined(USE_PREAD64)
  29238. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  29239. #else
  29240. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  29241. #endif
  29242. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  29243. aSyscall[13].pCurrent)
  29244. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  29245. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  29246. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  29247. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  29248. #else
  29249. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  29250. #endif
  29251. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  29252. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  29253. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  29254. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  29255. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  29256. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  29257. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  29258. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  29259. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  29260. #if defined(HAVE_FCHOWN)
  29261. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  29262. #else
  29263. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  29264. #endif
  29265. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  29266. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  29267. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  29268. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29269. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  29270. #else
  29271. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  29272. #endif
  29273. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  29274. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29275. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  29276. #else
  29277. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  29278. #endif
  29279. #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
  29280. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  29281. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  29282. #else
  29283. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  29284. #endif
  29285. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  29286. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29287. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  29288. #else
  29289. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  29290. #endif
  29291. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  29292. #if defined(HAVE_READLINK)
  29293. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  29294. #else
  29295. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  29296. #endif
  29297. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  29298. #if defined(HAVE_LSTAT)
  29299. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  29300. #else
  29301. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  29302. #endif
  29303. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  29304. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  29305. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  29306. }; /* End of the overrideable system calls */
  29307. /*
  29308. ** On some systems, calls to fchown() will trigger a message in a security
  29309. ** log if they come from non-root processes. So avoid calling fchown() if
  29310. ** we are not running as root.
  29311. */
  29312. static int robustFchown(int fd, uid_t uid, gid_t gid){
  29313. #if defined(HAVE_FCHOWN)
  29314. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  29315. #else
  29316. return 0;
  29317. #endif
  29318. }
  29319. /*
  29320. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  29321. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  29322. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  29323. ** system call named zName.
  29324. */
  29325. static int unixSetSystemCall(
  29326. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  29327. const char *zName, /* Name of system call to override */
  29328. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  29329. ){
  29330. unsigned int i;
  29331. int rc = SQLITE_NOTFOUND;
  29332. UNUSED_PARAMETER(pNotUsed);
  29333. if( zName==0 ){
  29334. /* If no zName is given, restore all system calls to their default
  29335. ** settings and return NULL
  29336. */
  29337. rc = SQLITE_OK;
  29338. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29339. if( aSyscall[i].pDefault ){
  29340. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  29341. }
  29342. }
  29343. }else{
  29344. /* If zName is specified, operate on only the one system call
  29345. ** specified.
  29346. */
  29347. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29348. if( strcmp(zName, aSyscall[i].zName)==0 ){
  29349. if( aSyscall[i].pDefault==0 ){
  29350. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  29351. }
  29352. rc = SQLITE_OK;
  29353. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  29354. aSyscall[i].pCurrent = pNewFunc;
  29355. break;
  29356. }
  29357. }
  29358. }
  29359. return rc;
  29360. }
  29361. /*
  29362. ** Return the value of a system call. Return NULL if zName is not a
  29363. ** recognized system call name. NULL is also returned if the system call
  29364. ** is currently undefined.
  29365. */
  29366. static sqlite3_syscall_ptr unixGetSystemCall(
  29367. sqlite3_vfs *pNotUsed,
  29368. const char *zName
  29369. ){
  29370. unsigned int i;
  29371. UNUSED_PARAMETER(pNotUsed);
  29372. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29373. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  29374. }
  29375. return 0;
  29376. }
  29377. /*
  29378. ** Return the name of the first system call after zName. If zName==NULL
  29379. ** then return the name of the first system call. Return NULL if zName
  29380. ** is the last system call or if zName is not the name of a valid
  29381. ** system call.
  29382. */
  29383. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  29384. int i = -1;
  29385. UNUSED_PARAMETER(p);
  29386. if( zName ){
  29387. for(i=0; i<ArraySize(aSyscall)-1; i++){
  29388. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  29389. }
  29390. }
  29391. for(i++; i<ArraySize(aSyscall); i++){
  29392. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  29393. }
  29394. return 0;
  29395. }
  29396. /*
  29397. ** Do not accept any file descriptor less than this value, in order to avoid
  29398. ** opening database file using file descriptors that are commonly used for
  29399. ** standard input, output, and error.
  29400. */
  29401. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  29402. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  29403. #endif
  29404. /*
  29405. ** Invoke open(). Do so multiple times, until it either succeeds or
  29406. ** fails for some reason other than EINTR.
  29407. **
  29408. ** If the file creation mode "m" is 0 then set it to the default for
  29409. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  29410. ** 0644) as modified by the system umask. If m is not 0, then
  29411. ** make the file creation mode be exactly m ignoring the umask.
  29412. **
  29413. ** The m parameter will be non-zero only when creating -wal, -journal,
  29414. ** and -shm files. We want those files to have *exactly* the same
  29415. ** permissions as their original database, unadulterated by the umask.
  29416. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  29417. ** transaction crashes and leaves behind hot journals, then any
  29418. ** process that is able to write to the database will also be able to
  29419. ** recover the hot journals.
  29420. */
  29421. static int robust_open(const char *z, int f, mode_t m){
  29422. int fd;
  29423. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  29424. while(1){
  29425. #if defined(O_CLOEXEC)
  29426. fd = osOpen(z,f|O_CLOEXEC,m2);
  29427. #else
  29428. fd = osOpen(z,f,m2);
  29429. #endif
  29430. if( fd<0 ){
  29431. if( errno==EINTR ) continue;
  29432. break;
  29433. }
  29434. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  29435. osClose(fd);
  29436. sqlite3_log(SQLITE_WARNING,
  29437. "attempt to open \"%s\" as file descriptor %d", z, fd);
  29438. fd = -1;
  29439. if( osOpen("/dev/null", f, m)<0 ) break;
  29440. }
  29441. if( fd>=0 ){
  29442. if( m!=0 ){
  29443. struct stat statbuf;
  29444. if( osFstat(fd, &statbuf)==0
  29445. && statbuf.st_size==0
  29446. && (statbuf.st_mode&0777)!=m
  29447. ){
  29448. osFchmod(fd, m);
  29449. }
  29450. }
  29451. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  29452. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  29453. #endif
  29454. }
  29455. return fd;
  29456. }
  29457. /*
  29458. ** Helper functions to obtain and relinquish the global mutex. The
  29459. ** global mutex is used to protect the unixInodeInfo and
  29460. ** vxworksFileId objects used by this file, all of which may be
  29461. ** shared by multiple threads.
  29462. **
  29463. ** Function unixMutexHeld() is used to assert() that the global mutex
  29464. ** is held when required. This function is only used as part of assert()
  29465. ** statements. e.g.
  29466. **
  29467. ** unixEnterMutex()
  29468. ** assert( unixMutexHeld() );
  29469. ** unixEnterLeave()
  29470. */
  29471. static void unixEnterMutex(void){
  29472. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  29473. }
  29474. static void unixLeaveMutex(void){
  29475. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  29476. }
  29477. #ifdef SQLITE_DEBUG
  29478. static int unixMutexHeld(void) {
  29479. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  29480. }
  29481. #endif
  29482. #ifdef SQLITE_HAVE_OS_TRACE
  29483. /*
  29484. ** Helper function for printing out trace information from debugging
  29485. ** binaries. This returns the string representation of the supplied
  29486. ** integer lock-type.
  29487. */
  29488. static const char *azFileLock(int eFileLock){
  29489. switch( eFileLock ){
  29490. case NO_LOCK: return "NONE";
  29491. case SHARED_LOCK: return "SHARED";
  29492. case RESERVED_LOCK: return "RESERVED";
  29493. case PENDING_LOCK: return "PENDING";
  29494. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  29495. }
  29496. return "ERROR";
  29497. }
  29498. #endif
  29499. #ifdef SQLITE_LOCK_TRACE
  29500. /*
  29501. ** Print out information about all locking operations.
  29502. **
  29503. ** This routine is used for troubleshooting locks on multithreaded
  29504. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  29505. ** command-line option on the compiler. This code is normally
  29506. ** turned off.
  29507. */
  29508. static int lockTrace(int fd, int op, struct flock *p){
  29509. char *zOpName, *zType;
  29510. int s;
  29511. int savedErrno;
  29512. if( op==F_GETLK ){
  29513. zOpName = "GETLK";
  29514. }else if( op==F_SETLK ){
  29515. zOpName = "SETLK";
  29516. }else{
  29517. s = osFcntl(fd, op, p);
  29518. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  29519. return s;
  29520. }
  29521. if( p->l_type==F_RDLCK ){
  29522. zType = "RDLCK";
  29523. }else if( p->l_type==F_WRLCK ){
  29524. zType = "WRLCK";
  29525. }else if( p->l_type==F_UNLCK ){
  29526. zType = "UNLCK";
  29527. }else{
  29528. assert( 0 );
  29529. }
  29530. assert( p->l_whence==SEEK_SET );
  29531. s = osFcntl(fd, op, p);
  29532. savedErrno = errno;
  29533. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  29534. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  29535. (int)p->l_pid, s);
  29536. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  29537. struct flock l2;
  29538. l2 = *p;
  29539. osFcntl(fd, F_GETLK, &l2);
  29540. if( l2.l_type==F_RDLCK ){
  29541. zType = "RDLCK";
  29542. }else if( l2.l_type==F_WRLCK ){
  29543. zType = "WRLCK";
  29544. }else if( l2.l_type==F_UNLCK ){
  29545. zType = "UNLCK";
  29546. }else{
  29547. assert( 0 );
  29548. }
  29549. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  29550. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  29551. }
  29552. errno = savedErrno;
  29553. return s;
  29554. }
  29555. #undef osFcntl
  29556. #define osFcntl lockTrace
  29557. #endif /* SQLITE_LOCK_TRACE */
  29558. /*
  29559. ** Retry ftruncate() calls that fail due to EINTR
  29560. **
  29561. ** All calls to ftruncate() within this file should be made through
  29562. ** this wrapper. On the Android platform, bypassing the logic below
  29563. ** could lead to a corrupt database.
  29564. */
  29565. static int robust_ftruncate(int h, sqlite3_int64 sz){
  29566. int rc;
  29567. #ifdef __ANDROID__
  29568. /* On Android, ftruncate() always uses 32-bit offsets, even if
  29569. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  29570. ** truncate a file to any size larger than 2GiB. Silently ignore any
  29571. ** such attempts. */
  29572. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  29573. rc = SQLITE_OK;
  29574. }else
  29575. #endif
  29576. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  29577. return rc;
  29578. }
  29579. /*
  29580. ** This routine translates a standard POSIX errno code into something
  29581. ** useful to the clients of the sqlite3 functions. Specifically, it is
  29582. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  29583. ** and a variety of "please close the file descriptor NOW" errors into
  29584. ** SQLITE_IOERR
  29585. **
  29586. ** Errors during initialization of locks, or file system support for locks,
  29587. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  29588. */
  29589. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  29590. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  29591. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  29592. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  29593. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  29594. switch (posixError) {
  29595. case EACCES:
  29596. case EAGAIN:
  29597. case ETIMEDOUT:
  29598. case EBUSY:
  29599. case EINTR:
  29600. case ENOLCK:
  29601. /* random NFS retry error, unless during file system support
  29602. * introspection, in which it actually means what it says */
  29603. return SQLITE_BUSY;
  29604. case EPERM:
  29605. return SQLITE_PERM;
  29606. default:
  29607. return sqliteIOErr;
  29608. }
  29609. }
  29610. /******************************************************************************
  29611. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  29612. **
  29613. ** On most versions of unix, we can get a unique ID for a file by concatenating
  29614. ** the device number and the inode number. But this does not work on VxWorks.
  29615. ** On VxWorks, a unique file id must be based on the canonical filename.
  29616. **
  29617. ** A pointer to an instance of the following structure can be used as a
  29618. ** unique file ID in VxWorks. Each instance of this structure contains
  29619. ** a copy of the canonical filename. There is also a reference count.
  29620. ** The structure is reclaimed when the number of pointers to it drops to
  29621. ** zero.
  29622. **
  29623. ** There are never very many files open at one time and lookups are not
  29624. ** a performance-critical path, so it is sufficient to put these
  29625. ** structures on a linked list.
  29626. */
  29627. struct vxworksFileId {
  29628. struct vxworksFileId *pNext; /* Next in a list of them all */
  29629. int nRef; /* Number of references to this one */
  29630. int nName; /* Length of the zCanonicalName[] string */
  29631. char *zCanonicalName; /* Canonical filename */
  29632. };
  29633. #if OS_VXWORKS
  29634. /*
  29635. ** All unique filenames are held on a linked list headed by this
  29636. ** variable:
  29637. */
  29638. static struct vxworksFileId *vxworksFileList = 0;
  29639. /*
  29640. ** Simplify a filename into its canonical form
  29641. ** by making the following changes:
  29642. **
  29643. ** * removing any trailing and duplicate /
  29644. ** * convert /./ into just /
  29645. ** * convert /A/../ where A is any simple name into just /
  29646. **
  29647. ** Changes are made in-place. Return the new name length.
  29648. **
  29649. ** The original filename is in z[0..n-1]. Return the number of
  29650. ** characters in the simplified name.
  29651. */
  29652. static int vxworksSimplifyName(char *z, int n){
  29653. int i, j;
  29654. while( n>1 && z[n-1]=='/' ){ n--; }
  29655. for(i=j=0; i<n; i++){
  29656. if( z[i]=='/' ){
  29657. if( z[i+1]=='/' ) continue;
  29658. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  29659. i += 1;
  29660. continue;
  29661. }
  29662. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  29663. while( j>0 && z[j-1]!='/' ){ j--; }
  29664. if( j>0 ){ j--; }
  29665. i += 2;
  29666. continue;
  29667. }
  29668. }
  29669. z[j++] = z[i];
  29670. }
  29671. z[j] = 0;
  29672. return j;
  29673. }
  29674. /*
  29675. ** Find a unique file ID for the given absolute pathname. Return
  29676. ** a pointer to the vxworksFileId object. This pointer is the unique
  29677. ** file ID.
  29678. **
  29679. ** The nRef field of the vxworksFileId object is incremented before
  29680. ** the object is returned. A new vxworksFileId object is created
  29681. ** and added to the global list if necessary.
  29682. **
  29683. ** If a memory allocation error occurs, return NULL.
  29684. */
  29685. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  29686. struct vxworksFileId *pNew; /* search key and new file ID */
  29687. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  29688. int n; /* Length of zAbsoluteName string */
  29689. assert( zAbsoluteName[0]=='/' );
  29690. n = (int)strlen(zAbsoluteName);
  29691. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  29692. if( pNew==0 ) return 0;
  29693. pNew->zCanonicalName = (char*)&pNew[1];
  29694. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  29695. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  29696. /* Search for an existing entry that matching the canonical name.
  29697. ** If found, increment the reference count and return a pointer to
  29698. ** the existing file ID.
  29699. */
  29700. unixEnterMutex();
  29701. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  29702. if( pCandidate->nName==n
  29703. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  29704. ){
  29705. sqlite3_free(pNew);
  29706. pCandidate->nRef++;
  29707. unixLeaveMutex();
  29708. return pCandidate;
  29709. }
  29710. }
  29711. /* No match was found. We will make a new file ID */
  29712. pNew->nRef = 1;
  29713. pNew->nName = n;
  29714. pNew->pNext = vxworksFileList;
  29715. vxworksFileList = pNew;
  29716. unixLeaveMutex();
  29717. return pNew;
  29718. }
  29719. /*
  29720. ** Decrement the reference count on a vxworksFileId object. Free
  29721. ** the object when the reference count reaches zero.
  29722. */
  29723. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  29724. unixEnterMutex();
  29725. assert( pId->nRef>0 );
  29726. pId->nRef--;
  29727. if( pId->nRef==0 ){
  29728. struct vxworksFileId **pp;
  29729. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  29730. assert( *pp==pId );
  29731. *pp = pId->pNext;
  29732. sqlite3_free(pId);
  29733. }
  29734. unixLeaveMutex();
  29735. }
  29736. #endif /* OS_VXWORKS */
  29737. /*************** End of Unique File ID Utility Used By VxWorks ****************
  29738. ******************************************************************************/
  29739. /******************************************************************************
  29740. *************************** Posix Advisory Locking ****************************
  29741. **
  29742. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  29743. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  29744. ** sets or clears a lock, that operation overrides any prior locks set
  29745. ** by the same process. It does not explicitly say so, but this implies
  29746. ** that it overrides locks set by the same process using a different
  29747. ** file descriptor. Consider this test case:
  29748. **
  29749. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  29750. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  29751. **
  29752. ** Suppose ./file1 and ./file2 are really the same file (because
  29753. ** one is a hard or symbolic link to the other) then if you set
  29754. ** an exclusive lock on fd1, then try to get an exclusive lock
  29755. ** on fd2, it works. I would have expected the second lock to
  29756. ** fail since there was already a lock on the file due to fd1.
  29757. ** But not so. Since both locks came from the same process, the
  29758. ** second overrides the first, even though they were on different
  29759. ** file descriptors opened on different file names.
  29760. **
  29761. ** This means that we cannot use POSIX locks to synchronize file access
  29762. ** among competing threads of the same process. POSIX locks will work fine
  29763. ** to synchronize access for threads in separate processes, but not
  29764. ** threads within the same process.
  29765. **
  29766. ** To work around the problem, SQLite has to manage file locks internally
  29767. ** on its own. Whenever a new database is opened, we have to find the
  29768. ** specific inode of the database file (the inode is determined by the
  29769. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  29770. ** and check for locks already existing on that inode. When locks are
  29771. ** created or removed, we have to look at our own internal record of the
  29772. ** locks to see if another thread has previously set a lock on that same
  29773. ** inode.
  29774. **
  29775. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  29776. ** For VxWorks, we have to use the alternative unique ID system based on
  29777. ** canonical filename and implemented in the previous division.)
  29778. **
  29779. ** The sqlite3_file structure for POSIX is no longer just an integer file
  29780. ** descriptor. It is now a structure that holds the integer file
  29781. ** descriptor and a pointer to a structure that describes the internal
  29782. ** locks on the corresponding inode. There is one locking structure
  29783. ** per inode, so if the same inode is opened twice, both unixFile structures
  29784. ** point to the same locking structure. The locking structure keeps
  29785. ** a reference count (so we will know when to delete it) and a "cnt"
  29786. ** field that tells us its internal lock status. cnt==0 means the
  29787. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  29788. ** cnt>0 means there are cnt shared locks on the file.
  29789. **
  29790. ** Any attempt to lock or unlock a file first checks the locking
  29791. ** structure. The fcntl() system call is only invoked to set a
  29792. ** POSIX lock if the internal lock structure transitions between
  29793. ** a locked and an unlocked state.
  29794. **
  29795. ** But wait: there are yet more problems with POSIX advisory locks.
  29796. **
  29797. ** If you close a file descriptor that points to a file that has locks,
  29798. ** all locks on that file that are owned by the current process are
  29799. ** released. To work around this problem, each unixInodeInfo object
  29800. ** maintains a count of the number of pending locks on tha inode.
  29801. ** When an attempt is made to close an unixFile, if there are
  29802. ** other unixFile open on the same inode that are holding locks, the call
  29803. ** to close() the file descriptor is deferred until all of the locks clear.
  29804. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  29805. ** be closed and that list is walked (and cleared) when the last lock
  29806. ** clears.
  29807. **
  29808. ** Yet another problem: LinuxThreads do not play well with posix locks.
  29809. **
  29810. ** Many older versions of linux use the LinuxThreads library which is
  29811. ** not posix compliant. Under LinuxThreads, a lock created by thread
  29812. ** A cannot be modified or overridden by a different thread B.
  29813. ** Only thread A can modify the lock. Locking behavior is correct
  29814. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  29815. ** on linux - with NPTL a lock created by thread A can override locks
  29816. ** in thread B. But there is no way to know at compile-time which
  29817. ** threading library is being used. So there is no way to know at
  29818. ** compile-time whether or not thread A can override locks on thread B.
  29819. ** One has to do a run-time check to discover the behavior of the
  29820. ** current process.
  29821. **
  29822. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  29823. ** was dropped beginning with version 3.7.0. SQLite will still work with
  29824. ** LinuxThreads provided that (1) there is no more than one connection
  29825. ** per database file in the same process and (2) database connections
  29826. ** do not move across threads.
  29827. */
  29828. /*
  29829. ** An instance of the following structure serves as the key used
  29830. ** to locate a particular unixInodeInfo object.
  29831. */
  29832. struct unixFileId {
  29833. dev_t dev; /* Device number */
  29834. #if OS_VXWORKS
  29835. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  29836. #else
  29837. /* We are told that some versions of Android contain a bug that
  29838. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  29839. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  29840. ** To work around this, always allocate 64-bits for the inode number.
  29841. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  29842. ** but that should not be a big deal. */
  29843. /* WAS: ino_t ino; */
  29844. u64 ino; /* Inode number */
  29845. #endif
  29846. };
  29847. /*
  29848. ** An instance of the following structure is allocated for each open
  29849. ** inode. Or, on LinuxThreads, there is one of these structures for
  29850. ** each inode opened by each thread.
  29851. **
  29852. ** A single inode can have multiple file descriptors, so each unixFile
  29853. ** structure contains a pointer to an instance of this object and this
  29854. ** object keeps a count of the number of unixFile pointing to it.
  29855. */
  29856. struct unixInodeInfo {
  29857. struct unixFileId fileId; /* The lookup key */
  29858. int nShared; /* Number of SHARED locks held */
  29859. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  29860. unsigned char bProcessLock; /* An exclusive process lock is held */
  29861. int nRef; /* Number of pointers to this structure */
  29862. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  29863. int nLock; /* Number of outstanding file locks */
  29864. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  29865. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  29866. unixInodeInfo *pPrev; /* .... doubly linked */
  29867. #if SQLITE_ENABLE_LOCKING_STYLE
  29868. unsigned long long sharedByte; /* for AFP simulated shared lock */
  29869. #endif
  29870. #if OS_VXWORKS
  29871. sem_t *pSem; /* Named POSIX semaphore */
  29872. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  29873. #endif
  29874. };
  29875. /*
  29876. ** A lists of all unixInodeInfo objects.
  29877. */
  29878. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  29879. static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
  29880. /*
  29881. **
  29882. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  29883. ** unixLogError().
  29884. **
  29885. ** It is invoked after an error occurs in an OS function and errno has been
  29886. ** set. It logs a message using sqlite3_log() containing the current value of
  29887. ** errno and, if possible, the human-readable equivalent from strerror() or
  29888. ** strerror_r().
  29889. **
  29890. ** The first argument passed to the macro should be the error code that
  29891. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  29892. ** The two subsequent arguments should be the name of the OS function that
  29893. ** failed (e.g. "unlink", "open") and the associated file-system path,
  29894. ** if any.
  29895. */
  29896. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  29897. static int unixLogErrorAtLine(
  29898. int errcode, /* SQLite error code */
  29899. const char *zFunc, /* Name of OS function that failed */
  29900. const char *zPath, /* File path associated with error */
  29901. int iLine /* Source line number where error occurred */
  29902. ){
  29903. char *zErr; /* Message from strerror() or equivalent */
  29904. int iErrno = errno; /* Saved syscall error number */
  29905. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  29906. ** the strerror() function to obtain the human-readable error message
  29907. ** equivalent to errno. Otherwise, use strerror_r().
  29908. */
  29909. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  29910. char aErr[80];
  29911. memset(aErr, 0, sizeof(aErr));
  29912. zErr = aErr;
  29913. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  29914. ** assume that the system provides the GNU version of strerror_r() that
  29915. ** returns a pointer to a buffer containing the error message. That pointer
  29916. ** may point to aErr[], or it may point to some static storage somewhere.
  29917. ** Otherwise, assume that the system provides the POSIX version of
  29918. ** strerror_r(), which always writes an error message into aErr[].
  29919. **
  29920. ** If the code incorrectly assumes that it is the POSIX version that is
  29921. ** available, the error message will often be an empty string. Not a
  29922. ** huge problem. Incorrectly concluding that the GNU version is available
  29923. ** could lead to a segfault though.
  29924. */
  29925. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  29926. zErr =
  29927. # endif
  29928. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  29929. #elif SQLITE_THREADSAFE
  29930. /* This is a threadsafe build, but strerror_r() is not available. */
  29931. zErr = "";
  29932. #else
  29933. /* Non-threadsafe build, use strerror(). */
  29934. zErr = strerror(iErrno);
  29935. #endif
  29936. if( zPath==0 ) zPath = "";
  29937. sqlite3_log(errcode,
  29938. "os_unix.c:%d: (%d) %s(%s) - %s",
  29939. iLine, iErrno, zFunc, zPath, zErr
  29940. );
  29941. return errcode;
  29942. }
  29943. /*
  29944. ** Close a file descriptor.
  29945. **
  29946. ** We assume that close() almost always works, since it is only in a
  29947. ** very sick application or on a very sick platform that it might fail.
  29948. ** If it does fail, simply leak the file descriptor, but do log the
  29949. ** error.
  29950. **
  29951. ** Note that it is not safe to retry close() after EINTR since the
  29952. ** file descriptor might have already been reused by another thread.
  29953. ** So we don't even try to recover from an EINTR. Just log the error
  29954. ** and move on.
  29955. */
  29956. static void robust_close(unixFile *pFile, int h, int lineno){
  29957. if( osClose(h) ){
  29958. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  29959. pFile ? pFile->zPath : 0, lineno);
  29960. }
  29961. }
  29962. /*
  29963. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  29964. ** a convenient place to set a breakpoint.
  29965. */
  29966. static void storeLastErrno(unixFile *pFile, int error){
  29967. pFile->lastErrno = error;
  29968. }
  29969. /*
  29970. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  29971. */
  29972. static void closePendingFds(unixFile *pFile){
  29973. unixInodeInfo *pInode = pFile->pInode;
  29974. UnixUnusedFd *p;
  29975. UnixUnusedFd *pNext;
  29976. for(p=pInode->pUnused; p; p=pNext){
  29977. pNext = p->pNext;
  29978. robust_close(pFile, p->fd, __LINE__);
  29979. sqlite3_free(p);
  29980. nUnusedFd--;
  29981. }
  29982. pInode->pUnused = 0;
  29983. }
  29984. /*
  29985. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  29986. **
  29987. ** The mutex entered using the unixEnterMutex() function must be held
  29988. ** when this function is called.
  29989. */
  29990. static void releaseInodeInfo(unixFile *pFile){
  29991. unixInodeInfo *pInode = pFile->pInode;
  29992. assert( unixMutexHeld() );
  29993. if( ALWAYS(pInode) ){
  29994. pInode->nRef--;
  29995. if( pInode->nRef==0 ){
  29996. assert( pInode->pShmNode==0 );
  29997. closePendingFds(pFile);
  29998. if( pInode->pPrev ){
  29999. assert( pInode->pPrev->pNext==pInode );
  30000. pInode->pPrev->pNext = pInode->pNext;
  30001. }else{
  30002. assert( inodeList==pInode );
  30003. inodeList = pInode->pNext;
  30004. }
  30005. if( pInode->pNext ){
  30006. assert( pInode->pNext->pPrev==pInode );
  30007. pInode->pNext->pPrev = pInode->pPrev;
  30008. }
  30009. sqlite3_free(pInode);
  30010. }
  30011. }
  30012. assert( inodeList!=0 || nUnusedFd==0 );
  30013. }
  30014. /*
  30015. ** Given a file descriptor, locate the unixInodeInfo object that
  30016. ** describes that file descriptor. Create a new one if necessary. The
  30017. ** return value might be uninitialized if an error occurs.
  30018. **
  30019. ** The mutex entered using the unixEnterMutex() function must be held
  30020. ** when this function is called.
  30021. **
  30022. ** Return an appropriate error code.
  30023. */
  30024. static int findInodeInfo(
  30025. unixFile *pFile, /* Unix file with file desc used in the key */
  30026. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  30027. ){
  30028. int rc; /* System call return code */
  30029. int fd; /* The file descriptor for pFile */
  30030. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  30031. struct stat statbuf; /* Low-level file information */
  30032. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  30033. assert( unixMutexHeld() );
  30034. /* Get low-level information about the file that we can used to
  30035. ** create a unique name for the file.
  30036. */
  30037. fd = pFile->h;
  30038. rc = osFstat(fd, &statbuf);
  30039. if( rc!=0 ){
  30040. storeLastErrno(pFile, errno);
  30041. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  30042. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  30043. #endif
  30044. return SQLITE_IOERR;
  30045. }
  30046. #ifdef __APPLE__
  30047. /* On OS X on an msdos filesystem, the inode number is reported
  30048. ** incorrectly for zero-size files. See ticket #3260. To work
  30049. ** around this problem (we consider it a bug in OS X, not SQLite)
  30050. ** we always increase the file size to 1 by writing a single byte
  30051. ** prior to accessing the inode number. The one byte written is
  30052. ** an ASCII 'S' character which also happens to be the first byte
  30053. ** in the header of every SQLite database. In this way, if there
  30054. ** is a race condition such that another thread has already populated
  30055. ** the first page of the database, no damage is done.
  30056. */
  30057. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  30058. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  30059. if( rc!=1 ){
  30060. storeLastErrno(pFile, errno);
  30061. return SQLITE_IOERR;
  30062. }
  30063. rc = osFstat(fd, &statbuf);
  30064. if( rc!=0 ){
  30065. storeLastErrno(pFile, errno);
  30066. return SQLITE_IOERR;
  30067. }
  30068. }
  30069. #endif
  30070. memset(&fileId, 0, sizeof(fileId));
  30071. fileId.dev = statbuf.st_dev;
  30072. #if OS_VXWORKS
  30073. fileId.pId = pFile->pId;
  30074. #else
  30075. fileId.ino = (u64)statbuf.st_ino;
  30076. #endif
  30077. assert( inodeList!=0 || nUnusedFd==0 );
  30078. pInode = inodeList;
  30079. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  30080. pInode = pInode->pNext;
  30081. }
  30082. if( pInode==0 ){
  30083. pInode = sqlite3_malloc64( sizeof(*pInode) );
  30084. if( pInode==0 ){
  30085. return SQLITE_NOMEM_BKPT;
  30086. }
  30087. memset(pInode, 0, sizeof(*pInode));
  30088. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  30089. pInode->nRef = 1;
  30090. pInode->pNext = inodeList;
  30091. pInode->pPrev = 0;
  30092. if( inodeList ) inodeList->pPrev = pInode;
  30093. inodeList = pInode;
  30094. }else{
  30095. pInode->nRef++;
  30096. }
  30097. *ppInode = pInode;
  30098. return SQLITE_OK;
  30099. }
  30100. /*
  30101. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  30102. */
  30103. static int fileHasMoved(unixFile *pFile){
  30104. #if OS_VXWORKS
  30105. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  30106. #else
  30107. struct stat buf;
  30108. return pFile->pInode!=0 &&
  30109. (osStat(pFile->zPath, &buf)!=0
  30110. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  30111. #endif
  30112. }
  30113. /*
  30114. ** Check a unixFile that is a database. Verify the following:
  30115. **
  30116. ** (1) There is exactly one hard link on the file
  30117. ** (2) The file is not a symbolic link
  30118. ** (3) The file has not been renamed or unlinked
  30119. **
  30120. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  30121. */
  30122. static void verifyDbFile(unixFile *pFile){
  30123. struct stat buf;
  30124. int rc;
  30125. /* These verifications occurs for the main database only */
  30126. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  30127. rc = osFstat(pFile->h, &buf);
  30128. if( rc!=0 ){
  30129. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  30130. return;
  30131. }
  30132. if( buf.st_nlink==0 ){
  30133. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  30134. return;
  30135. }
  30136. if( buf.st_nlink>1 ){
  30137. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  30138. return;
  30139. }
  30140. if( fileHasMoved(pFile) ){
  30141. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  30142. return;
  30143. }
  30144. }
  30145. /*
  30146. ** This routine checks if there is a RESERVED lock held on the specified
  30147. ** file by this or any other process. If such a lock is held, set *pResOut
  30148. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30149. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30150. */
  30151. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  30152. int rc = SQLITE_OK;
  30153. int reserved = 0;
  30154. unixFile *pFile = (unixFile*)id;
  30155. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30156. assert( pFile );
  30157. assert( pFile->eFileLock<=SHARED_LOCK );
  30158. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  30159. /* Check if a thread in this process holds such a lock */
  30160. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  30161. reserved = 1;
  30162. }
  30163. /* Otherwise see if some other process holds it.
  30164. */
  30165. #ifndef __DJGPP__
  30166. if( !reserved && !pFile->pInode->bProcessLock ){
  30167. struct flock lock;
  30168. lock.l_whence = SEEK_SET;
  30169. lock.l_start = RESERVED_BYTE;
  30170. lock.l_len = 1;
  30171. lock.l_type = F_WRLCK;
  30172. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  30173. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  30174. storeLastErrno(pFile, errno);
  30175. } else if( lock.l_type!=F_UNLCK ){
  30176. reserved = 1;
  30177. }
  30178. }
  30179. #endif
  30180. unixLeaveMutex();
  30181. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  30182. *pResOut = reserved;
  30183. return rc;
  30184. }
  30185. /*
  30186. ** Attempt to set a system-lock on the file pFile. The lock is
  30187. ** described by pLock.
  30188. **
  30189. ** If the pFile was opened read/write from unix-excl, then the only lock
  30190. ** ever obtained is an exclusive lock, and it is obtained exactly once
  30191. ** the first time any lock is attempted. All subsequent system locking
  30192. ** operations become no-ops. Locking operations still happen internally,
  30193. ** in order to coordinate access between separate database connections
  30194. ** within this process, but all of that is handled in memory and the
  30195. ** operating system does not participate.
  30196. **
  30197. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  30198. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  30199. ** and is read-only.
  30200. **
  30201. ** Zero is returned if the call completes successfully, or -1 if a call
  30202. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  30203. */
  30204. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  30205. int rc;
  30206. unixInodeInfo *pInode = pFile->pInode;
  30207. assert( unixMutexHeld() );
  30208. assert( pInode!=0 );
  30209. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  30210. if( pInode->bProcessLock==0 ){
  30211. struct flock lock;
  30212. assert( pInode->nLock==0 );
  30213. lock.l_whence = SEEK_SET;
  30214. lock.l_start = SHARED_FIRST;
  30215. lock.l_len = SHARED_SIZE;
  30216. lock.l_type = F_WRLCK;
  30217. rc = osFcntl(pFile->h, F_SETLK, &lock);
  30218. if( rc<0 ) return rc;
  30219. pInode->bProcessLock = 1;
  30220. pInode->nLock++;
  30221. }else{
  30222. rc = 0;
  30223. }
  30224. }else{
  30225. rc = osFcntl(pFile->h, F_SETLK, pLock);
  30226. }
  30227. return rc;
  30228. }
  30229. /*
  30230. ** Lock the file with the lock specified by parameter eFileLock - one
  30231. ** of the following:
  30232. **
  30233. ** (1) SHARED_LOCK
  30234. ** (2) RESERVED_LOCK
  30235. ** (3) PENDING_LOCK
  30236. ** (4) EXCLUSIVE_LOCK
  30237. **
  30238. ** Sometimes when requesting one lock state, additional lock states
  30239. ** are inserted in between. The locking might fail on one of the later
  30240. ** transitions leaving the lock state different from what it started but
  30241. ** still short of its goal. The following chart shows the allowed
  30242. ** transitions and the inserted intermediate states:
  30243. **
  30244. ** UNLOCKED -> SHARED
  30245. ** SHARED -> RESERVED
  30246. ** SHARED -> (PENDING) -> EXCLUSIVE
  30247. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30248. ** PENDING -> EXCLUSIVE
  30249. **
  30250. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30251. ** routine to lower a locking level.
  30252. */
  30253. static int unixLock(sqlite3_file *id, int eFileLock){
  30254. /* The following describes the implementation of the various locks and
  30255. ** lock transitions in terms of the POSIX advisory shared and exclusive
  30256. ** lock primitives (called read-locks and write-locks below, to avoid
  30257. ** confusion with SQLite lock names). The algorithms are complicated
  30258. ** slightly in order to be compatible with Windows95 systems simultaneously
  30259. ** accessing the same database file, in case that is ever required.
  30260. **
  30261. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  30262. ** byte', each single bytes at well known offsets, and the 'shared byte
  30263. ** range', a range of 510 bytes at a well known offset.
  30264. **
  30265. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  30266. ** byte'. If this is successful, 'shared byte range' is read-locked
  30267. ** and the lock on the 'pending byte' released. (Legacy note: When
  30268. ** SQLite was first developed, Windows95 systems were still very common,
  30269. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  30270. ** single randomly selected by from the 'shared byte range' is locked.
  30271. ** Windows95 is now pretty much extinct, but this work-around for the
  30272. ** lack of shared-locks on Windows95 lives on, for backwards
  30273. ** compatibility.)
  30274. **
  30275. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  30276. ** A RESERVED lock is implemented by grabbing a write-lock on the
  30277. ** 'reserved byte'.
  30278. **
  30279. ** A process may only obtain a PENDING lock after it has obtained a
  30280. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  30281. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  30282. ** obtained, but existing SHARED locks are allowed to persist. A process
  30283. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  30284. ** This property is used by the algorithm for rolling back a journal file
  30285. ** after a crash.
  30286. **
  30287. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  30288. ** implemented by obtaining a write-lock on the entire 'shared byte
  30289. ** range'. Since all other locks require a read-lock on one of the bytes
  30290. ** within this range, this ensures that no other locks are held on the
  30291. ** database.
  30292. */
  30293. int rc = SQLITE_OK;
  30294. unixFile *pFile = (unixFile*)id;
  30295. unixInodeInfo *pInode;
  30296. struct flock lock;
  30297. int tErrno = 0;
  30298. assert( pFile );
  30299. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  30300. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  30301. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  30302. osGetpid(0)));
  30303. /* If there is already a lock of this type or more restrictive on the
  30304. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  30305. ** unixEnterMutex() hasn't been called yet.
  30306. */
  30307. if( pFile->eFileLock>=eFileLock ){
  30308. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  30309. azFileLock(eFileLock)));
  30310. return SQLITE_OK;
  30311. }
  30312. /* Make sure the locking sequence is correct.
  30313. ** (1) We never move from unlocked to anything higher than shared lock.
  30314. ** (2) SQLite never explicitly requests a pendig lock.
  30315. ** (3) A shared lock is always held when a reserve lock is requested.
  30316. */
  30317. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  30318. assert( eFileLock!=PENDING_LOCK );
  30319. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  30320. /* This mutex is needed because pFile->pInode is shared across threads
  30321. */
  30322. unixEnterMutex();
  30323. pInode = pFile->pInode;
  30324. /* If some thread using this PID has a lock via a different unixFile*
  30325. ** handle that precludes the requested lock, return BUSY.
  30326. */
  30327. if( (pFile->eFileLock!=pInode->eFileLock &&
  30328. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  30329. ){
  30330. rc = SQLITE_BUSY;
  30331. goto end_lock;
  30332. }
  30333. /* If a SHARED lock is requested, and some thread using this PID already
  30334. ** has a SHARED or RESERVED lock, then increment reference counts and
  30335. ** return SQLITE_OK.
  30336. */
  30337. if( eFileLock==SHARED_LOCK &&
  30338. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  30339. assert( eFileLock==SHARED_LOCK );
  30340. assert( pFile->eFileLock==0 );
  30341. assert( pInode->nShared>0 );
  30342. pFile->eFileLock = SHARED_LOCK;
  30343. pInode->nShared++;
  30344. pInode->nLock++;
  30345. goto end_lock;
  30346. }
  30347. /* A PENDING lock is needed before acquiring a SHARED lock and before
  30348. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  30349. ** be released.
  30350. */
  30351. lock.l_len = 1L;
  30352. lock.l_whence = SEEK_SET;
  30353. if( eFileLock==SHARED_LOCK
  30354. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  30355. ){
  30356. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  30357. lock.l_start = PENDING_BYTE;
  30358. if( unixFileLock(pFile, &lock) ){
  30359. tErrno = errno;
  30360. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30361. if( rc!=SQLITE_BUSY ){
  30362. storeLastErrno(pFile, tErrno);
  30363. }
  30364. goto end_lock;
  30365. }
  30366. }
  30367. /* If control gets to this point, then actually go ahead and make
  30368. ** operating system calls for the specified lock.
  30369. */
  30370. if( eFileLock==SHARED_LOCK ){
  30371. assert( pInode->nShared==0 );
  30372. assert( pInode->eFileLock==0 );
  30373. assert( rc==SQLITE_OK );
  30374. /* Now get the read-lock */
  30375. lock.l_start = SHARED_FIRST;
  30376. lock.l_len = SHARED_SIZE;
  30377. if( unixFileLock(pFile, &lock) ){
  30378. tErrno = errno;
  30379. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30380. }
  30381. /* Drop the temporary PENDING lock */
  30382. lock.l_start = PENDING_BYTE;
  30383. lock.l_len = 1L;
  30384. lock.l_type = F_UNLCK;
  30385. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  30386. /* This could happen with a network mount */
  30387. tErrno = errno;
  30388. rc = SQLITE_IOERR_UNLOCK;
  30389. }
  30390. if( rc ){
  30391. if( rc!=SQLITE_BUSY ){
  30392. storeLastErrno(pFile, tErrno);
  30393. }
  30394. goto end_lock;
  30395. }else{
  30396. pFile->eFileLock = SHARED_LOCK;
  30397. pInode->nLock++;
  30398. pInode->nShared = 1;
  30399. }
  30400. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  30401. /* We are trying for an exclusive lock but another thread in this
  30402. ** same process is still holding a shared lock. */
  30403. rc = SQLITE_BUSY;
  30404. }else{
  30405. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  30406. ** assumed that there is a SHARED or greater lock on the file
  30407. ** already.
  30408. */
  30409. assert( 0!=pFile->eFileLock );
  30410. lock.l_type = F_WRLCK;
  30411. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  30412. if( eFileLock==RESERVED_LOCK ){
  30413. lock.l_start = RESERVED_BYTE;
  30414. lock.l_len = 1L;
  30415. }else{
  30416. lock.l_start = SHARED_FIRST;
  30417. lock.l_len = SHARED_SIZE;
  30418. }
  30419. if( unixFileLock(pFile, &lock) ){
  30420. tErrno = errno;
  30421. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30422. if( rc!=SQLITE_BUSY ){
  30423. storeLastErrno(pFile, tErrno);
  30424. }
  30425. }
  30426. }
  30427. #ifdef SQLITE_DEBUG
  30428. /* Set up the transaction-counter change checking flags when
  30429. ** transitioning from a SHARED to a RESERVED lock. The change
  30430. ** from SHARED to RESERVED marks the beginning of a normal
  30431. ** write operation (not a hot journal rollback).
  30432. */
  30433. if( rc==SQLITE_OK
  30434. && pFile->eFileLock<=SHARED_LOCK
  30435. && eFileLock==RESERVED_LOCK
  30436. ){
  30437. pFile->transCntrChng = 0;
  30438. pFile->dbUpdate = 0;
  30439. pFile->inNormalWrite = 1;
  30440. }
  30441. #endif
  30442. if( rc==SQLITE_OK ){
  30443. pFile->eFileLock = eFileLock;
  30444. pInode->eFileLock = eFileLock;
  30445. }else if( eFileLock==EXCLUSIVE_LOCK ){
  30446. pFile->eFileLock = PENDING_LOCK;
  30447. pInode->eFileLock = PENDING_LOCK;
  30448. }
  30449. end_lock:
  30450. unixLeaveMutex();
  30451. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  30452. rc==SQLITE_OK ? "ok" : "failed"));
  30453. return rc;
  30454. }
  30455. /*
  30456. ** Add the file descriptor used by file handle pFile to the corresponding
  30457. ** pUnused list.
  30458. */
  30459. static void setPendingFd(unixFile *pFile){
  30460. unixInodeInfo *pInode = pFile->pInode;
  30461. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  30462. p->pNext = pInode->pUnused;
  30463. pInode->pUnused = p;
  30464. pFile->h = -1;
  30465. pFile->pPreallocatedUnused = 0;
  30466. nUnusedFd++;
  30467. }
  30468. /*
  30469. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30470. ** must be either NO_LOCK or SHARED_LOCK.
  30471. **
  30472. ** If the locking level of the file descriptor is already at or below
  30473. ** the requested locking level, this routine is a no-op.
  30474. **
  30475. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  30476. ** the byte range is divided into 2 parts and the first part is unlocked then
  30477. ** set to a read lock, then the other part is simply unlocked. This works
  30478. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  30479. ** remove the write lock on a region when a read lock is set.
  30480. */
  30481. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  30482. unixFile *pFile = (unixFile*)id;
  30483. unixInodeInfo *pInode;
  30484. struct flock lock;
  30485. int rc = SQLITE_OK;
  30486. assert( pFile );
  30487. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  30488. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  30489. osGetpid(0)));
  30490. assert( eFileLock<=SHARED_LOCK );
  30491. if( pFile->eFileLock<=eFileLock ){
  30492. return SQLITE_OK;
  30493. }
  30494. unixEnterMutex();
  30495. pInode = pFile->pInode;
  30496. assert( pInode->nShared!=0 );
  30497. if( pFile->eFileLock>SHARED_LOCK ){
  30498. assert( pInode->eFileLock==pFile->eFileLock );
  30499. #ifdef SQLITE_DEBUG
  30500. /* When reducing a lock such that other processes can start
  30501. ** reading the database file again, make sure that the
  30502. ** transaction counter was updated if any part of the database
  30503. ** file changed. If the transaction counter is not updated,
  30504. ** other connections to the same file might not realize that
  30505. ** the file has changed and hence might not know to flush their
  30506. ** cache. The use of a stale cache can lead to database corruption.
  30507. */
  30508. pFile->inNormalWrite = 0;
  30509. #endif
  30510. /* downgrading to a shared lock on NFS involves clearing the write lock
  30511. ** before establishing the readlock - to avoid a race condition we downgrade
  30512. ** the lock in 2 blocks, so that part of the range will be covered by a
  30513. ** write lock until the rest is covered by a read lock:
  30514. ** 1: [WWWWW]
  30515. ** 2: [....W]
  30516. ** 3: [RRRRW]
  30517. ** 4: [RRRR.]
  30518. */
  30519. if( eFileLock==SHARED_LOCK ){
  30520. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  30521. (void)handleNFSUnlock;
  30522. assert( handleNFSUnlock==0 );
  30523. #endif
  30524. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30525. if( handleNFSUnlock ){
  30526. int tErrno; /* Error code from system call errors */
  30527. off_t divSize = SHARED_SIZE - 1;
  30528. lock.l_type = F_UNLCK;
  30529. lock.l_whence = SEEK_SET;
  30530. lock.l_start = SHARED_FIRST;
  30531. lock.l_len = divSize;
  30532. if( unixFileLock(pFile, &lock)==(-1) ){
  30533. tErrno = errno;
  30534. rc = SQLITE_IOERR_UNLOCK;
  30535. storeLastErrno(pFile, tErrno);
  30536. goto end_unlock;
  30537. }
  30538. lock.l_type = F_RDLCK;
  30539. lock.l_whence = SEEK_SET;
  30540. lock.l_start = SHARED_FIRST;
  30541. lock.l_len = divSize;
  30542. if( unixFileLock(pFile, &lock)==(-1) ){
  30543. tErrno = errno;
  30544. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  30545. if( IS_LOCK_ERROR(rc) ){
  30546. storeLastErrno(pFile, tErrno);
  30547. }
  30548. goto end_unlock;
  30549. }
  30550. lock.l_type = F_UNLCK;
  30551. lock.l_whence = SEEK_SET;
  30552. lock.l_start = SHARED_FIRST+divSize;
  30553. lock.l_len = SHARED_SIZE-divSize;
  30554. if( unixFileLock(pFile, &lock)==(-1) ){
  30555. tErrno = errno;
  30556. rc = SQLITE_IOERR_UNLOCK;
  30557. storeLastErrno(pFile, tErrno);
  30558. goto end_unlock;
  30559. }
  30560. }else
  30561. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30562. {
  30563. lock.l_type = F_RDLCK;
  30564. lock.l_whence = SEEK_SET;
  30565. lock.l_start = SHARED_FIRST;
  30566. lock.l_len = SHARED_SIZE;
  30567. if( unixFileLock(pFile, &lock) ){
  30568. /* In theory, the call to unixFileLock() cannot fail because another
  30569. ** process is holding an incompatible lock. If it does, this
  30570. ** indicates that the other process is not following the locking
  30571. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  30572. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  30573. ** an assert to fail). */
  30574. rc = SQLITE_IOERR_RDLOCK;
  30575. storeLastErrno(pFile, errno);
  30576. goto end_unlock;
  30577. }
  30578. }
  30579. }
  30580. lock.l_type = F_UNLCK;
  30581. lock.l_whence = SEEK_SET;
  30582. lock.l_start = PENDING_BYTE;
  30583. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  30584. if( unixFileLock(pFile, &lock)==0 ){
  30585. pInode->eFileLock = SHARED_LOCK;
  30586. }else{
  30587. rc = SQLITE_IOERR_UNLOCK;
  30588. storeLastErrno(pFile, errno);
  30589. goto end_unlock;
  30590. }
  30591. }
  30592. if( eFileLock==NO_LOCK ){
  30593. /* Decrement the shared lock counter. Release the lock using an
  30594. ** OS call only when all threads in this same process have released
  30595. ** the lock.
  30596. */
  30597. pInode->nShared--;
  30598. if( pInode->nShared==0 ){
  30599. lock.l_type = F_UNLCK;
  30600. lock.l_whence = SEEK_SET;
  30601. lock.l_start = lock.l_len = 0L;
  30602. if( unixFileLock(pFile, &lock)==0 ){
  30603. pInode->eFileLock = NO_LOCK;
  30604. }else{
  30605. rc = SQLITE_IOERR_UNLOCK;
  30606. storeLastErrno(pFile, errno);
  30607. pInode->eFileLock = NO_LOCK;
  30608. pFile->eFileLock = NO_LOCK;
  30609. }
  30610. }
  30611. /* Decrement the count of locks against this same file. When the
  30612. ** count reaches zero, close any other file descriptors whose close
  30613. ** was deferred because of outstanding locks.
  30614. */
  30615. pInode->nLock--;
  30616. assert( pInode->nLock>=0 );
  30617. if( pInode->nLock==0 ){
  30618. closePendingFds(pFile);
  30619. }
  30620. }
  30621. end_unlock:
  30622. unixLeaveMutex();
  30623. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  30624. return rc;
  30625. }
  30626. /*
  30627. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30628. ** must be either NO_LOCK or SHARED_LOCK.
  30629. **
  30630. ** If the locking level of the file descriptor is already at or below
  30631. ** the requested locking level, this routine is a no-op.
  30632. */
  30633. static int unixUnlock(sqlite3_file *id, int eFileLock){
  30634. #if SQLITE_MAX_MMAP_SIZE>0
  30635. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  30636. #endif
  30637. return posixUnlock(id, eFileLock, 0);
  30638. }
  30639. #if SQLITE_MAX_MMAP_SIZE>0
  30640. static int unixMapfile(unixFile *pFd, i64 nByte);
  30641. static void unixUnmapfile(unixFile *pFd);
  30642. #endif
  30643. /*
  30644. ** This function performs the parts of the "close file" operation
  30645. ** common to all locking schemes. It closes the directory and file
  30646. ** handles, if they are valid, and sets all fields of the unixFile
  30647. ** structure to 0.
  30648. **
  30649. ** It is *not* necessary to hold the mutex when this routine is called,
  30650. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  30651. ** vxworksReleaseFileId() routine.
  30652. */
  30653. static int closeUnixFile(sqlite3_file *id){
  30654. unixFile *pFile = (unixFile*)id;
  30655. #if SQLITE_MAX_MMAP_SIZE>0
  30656. unixUnmapfile(pFile);
  30657. #endif
  30658. if( pFile->h>=0 ){
  30659. robust_close(pFile, pFile->h, __LINE__);
  30660. pFile->h = -1;
  30661. }
  30662. #if OS_VXWORKS
  30663. if( pFile->pId ){
  30664. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30665. osUnlink(pFile->pId->zCanonicalName);
  30666. }
  30667. vxworksReleaseFileId(pFile->pId);
  30668. pFile->pId = 0;
  30669. }
  30670. #endif
  30671. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  30672. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30673. osUnlink(pFile->zPath);
  30674. sqlite3_free(*(char**)&pFile->zPath);
  30675. pFile->zPath = 0;
  30676. }
  30677. #endif
  30678. OSTRACE(("CLOSE %-3d\n", pFile->h));
  30679. OpenCounter(-1);
  30680. sqlite3_free(pFile->pPreallocatedUnused);
  30681. memset(pFile, 0, sizeof(unixFile));
  30682. return SQLITE_OK;
  30683. }
  30684. /*
  30685. ** Close a file.
  30686. */
  30687. static int unixClose(sqlite3_file *id){
  30688. int rc = SQLITE_OK;
  30689. unixFile *pFile = (unixFile *)id;
  30690. verifyDbFile(pFile);
  30691. unixUnlock(id, NO_LOCK);
  30692. unixEnterMutex();
  30693. /* unixFile.pInode is always valid here. Otherwise, a different close
  30694. ** routine (e.g. nolockClose()) would be called instead.
  30695. */
  30696. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  30697. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  30698. /* If there are outstanding locks, do not actually close the file just
  30699. ** yet because that would clear those locks. Instead, add the file
  30700. ** descriptor to pInode->pUnused list. It will be automatically closed
  30701. ** when the last lock is cleared.
  30702. */
  30703. setPendingFd(pFile);
  30704. }
  30705. releaseInodeInfo(pFile);
  30706. rc = closeUnixFile(id);
  30707. unixLeaveMutex();
  30708. return rc;
  30709. }
  30710. /************** End of the posix advisory lock implementation *****************
  30711. ******************************************************************************/
  30712. /******************************************************************************
  30713. ****************************** No-op Locking **********************************
  30714. **
  30715. ** Of the various locking implementations available, this is by far the
  30716. ** simplest: locking is ignored. No attempt is made to lock the database
  30717. ** file for reading or writing.
  30718. **
  30719. ** This locking mode is appropriate for use on read-only databases
  30720. ** (ex: databases that are burned into CD-ROM, for example.) It can
  30721. ** also be used if the application employs some external mechanism to
  30722. ** prevent simultaneous access of the same database by two or more
  30723. ** database connections. But there is a serious risk of database
  30724. ** corruption if this locking mode is used in situations where multiple
  30725. ** database connections are accessing the same database file at the same
  30726. ** time and one or more of those connections are writing.
  30727. */
  30728. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  30729. UNUSED_PARAMETER(NotUsed);
  30730. *pResOut = 0;
  30731. return SQLITE_OK;
  30732. }
  30733. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  30734. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30735. return SQLITE_OK;
  30736. }
  30737. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  30738. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30739. return SQLITE_OK;
  30740. }
  30741. /*
  30742. ** Close the file.
  30743. */
  30744. static int nolockClose(sqlite3_file *id) {
  30745. return closeUnixFile(id);
  30746. }
  30747. /******************* End of the no-op lock implementation *********************
  30748. ******************************************************************************/
  30749. /******************************************************************************
  30750. ************************* Begin dot-file Locking ******************************
  30751. **
  30752. ** The dotfile locking implementation uses the existence of separate lock
  30753. ** files (really a directory) to control access to the database. This works
  30754. ** on just about every filesystem imaginable. But there are serious downsides:
  30755. **
  30756. ** (1) There is zero concurrency. A single reader blocks all other
  30757. ** connections from reading or writing the database.
  30758. **
  30759. ** (2) An application crash or power loss can leave stale lock files
  30760. ** sitting around that need to be cleared manually.
  30761. **
  30762. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  30763. ** other locking strategy is available.
  30764. **
  30765. ** Dotfile locking works by creating a subdirectory in the same directory as
  30766. ** the database and with the same name but with a ".lock" extension added.
  30767. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  30768. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  30769. */
  30770. /*
  30771. ** The file suffix added to the data base filename in order to create the
  30772. ** lock directory.
  30773. */
  30774. #define DOTLOCK_SUFFIX ".lock"
  30775. /*
  30776. ** This routine checks if there is a RESERVED lock held on the specified
  30777. ** file by this or any other process. If such a lock is held, set *pResOut
  30778. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30779. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30780. **
  30781. ** In dotfile locking, either a lock exists or it does not. So in this
  30782. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  30783. ** is held on the file and false if the file is unlocked.
  30784. */
  30785. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30786. int rc = SQLITE_OK;
  30787. int reserved = 0;
  30788. unixFile *pFile = (unixFile*)id;
  30789. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30790. assert( pFile );
  30791. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  30792. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  30793. *pResOut = reserved;
  30794. return rc;
  30795. }
  30796. /*
  30797. ** Lock the file with the lock specified by parameter eFileLock - one
  30798. ** of the following:
  30799. **
  30800. ** (1) SHARED_LOCK
  30801. ** (2) RESERVED_LOCK
  30802. ** (3) PENDING_LOCK
  30803. ** (4) EXCLUSIVE_LOCK
  30804. **
  30805. ** Sometimes when requesting one lock state, additional lock states
  30806. ** are inserted in between. The locking might fail on one of the later
  30807. ** transitions leaving the lock state different from what it started but
  30808. ** still short of its goal. The following chart shows the allowed
  30809. ** transitions and the inserted intermediate states:
  30810. **
  30811. ** UNLOCKED -> SHARED
  30812. ** SHARED -> RESERVED
  30813. ** SHARED -> (PENDING) -> EXCLUSIVE
  30814. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30815. ** PENDING -> EXCLUSIVE
  30816. **
  30817. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30818. ** routine to lower a locking level.
  30819. **
  30820. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  30821. ** But we track the other locking levels internally.
  30822. */
  30823. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  30824. unixFile *pFile = (unixFile*)id;
  30825. char *zLockFile = (char *)pFile->lockingContext;
  30826. int rc = SQLITE_OK;
  30827. /* If we have any lock, then the lock file already exists. All we have
  30828. ** to do is adjust our internal record of the lock level.
  30829. */
  30830. if( pFile->eFileLock > NO_LOCK ){
  30831. pFile->eFileLock = eFileLock;
  30832. /* Always update the timestamp on the old file */
  30833. #ifdef HAVE_UTIME
  30834. utime(zLockFile, NULL);
  30835. #else
  30836. utimes(zLockFile, NULL);
  30837. #endif
  30838. return SQLITE_OK;
  30839. }
  30840. /* grab an exclusive lock */
  30841. rc = osMkdir(zLockFile, 0777);
  30842. if( rc<0 ){
  30843. /* failed to open/create the lock directory */
  30844. int tErrno = errno;
  30845. if( EEXIST == tErrno ){
  30846. rc = SQLITE_BUSY;
  30847. } else {
  30848. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30849. if( rc!=SQLITE_BUSY ){
  30850. storeLastErrno(pFile, tErrno);
  30851. }
  30852. }
  30853. return rc;
  30854. }
  30855. /* got it, set the type and return ok */
  30856. pFile->eFileLock = eFileLock;
  30857. return rc;
  30858. }
  30859. /*
  30860. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30861. ** must be either NO_LOCK or SHARED_LOCK.
  30862. **
  30863. ** If the locking level of the file descriptor is already at or below
  30864. ** the requested locking level, this routine is a no-op.
  30865. **
  30866. ** When the locking level reaches NO_LOCK, delete the lock file.
  30867. */
  30868. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  30869. unixFile *pFile = (unixFile*)id;
  30870. char *zLockFile = (char *)pFile->lockingContext;
  30871. int rc;
  30872. assert( pFile );
  30873. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  30874. pFile->eFileLock, osGetpid(0)));
  30875. assert( eFileLock<=SHARED_LOCK );
  30876. /* no-op if possible */
  30877. if( pFile->eFileLock==eFileLock ){
  30878. return SQLITE_OK;
  30879. }
  30880. /* To downgrade to shared, simply update our internal notion of the
  30881. ** lock state. No need to mess with the file on disk.
  30882. */
  30883. if( eFileLock==SHARED_LOCK ){
  30884. pFile->eFileLock = SHARED_LOCK;
  30885. return SQLITE_OK;
  30886. }
  30887. /* To fully unlock the database, delete the lock file */
  30888. assert( eFileLock==NO_LOCK );
  30889. rc = osRmdir(zLockFile);
  30890. if( rc<0 ){
  30891. int tErrno = errno;
  30892. if( tErrno==ENOENT ){
  30893. rc = SQLITE_OK;
  30894. }else{
  30895. rc = SQLITE_IOERR_UNLOCK;
  30896. storeLastErrno(pFile, tErrno);
  30897. }
  30898. return rc;
  30899. }
  30900. pFile->eFileLock = NO_LOCK;
  30901. return SQLITE_OK;
  30902. }
  30903. /*
  30904. ** Close a file. Make sure the lock has been released before closing.
  30905. */
  30906. static int dotlockClose(sqlite3_file *id) {
  30907. unixFile *pFile = (unixFile*)id;
  30908. assert( id!=0 );
  30909. dotlockUnlock(id, NO_LOCK);
  30910. sqlite3_free(pFile->lockingContext);
  30911. return closeUnixFile(id);
  30912. }
  30913. /****************** End of the dot-file lock implementation *******************
  30914. ******************************************************************************/
  30915. /******************************************************************************
  30916. ************************** Begin flock Locking ********************************
  30917. **
  30918. ** Use the flock() system call to do file locking.
  30919. **
  30920. ** flock() locking is like dot-file locking in that the various
  30921. ** fine-grain locking levels supported by SQLite are collapsed into
  30922. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  30923. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  30924. ** still works when you do this, but concurrency is reduced since
  30925. ** only a single process can be reading the database at a time.
  30926. **
  30927. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  30928. */
  30929. #if SQLITE_ENABLE_LOCKING_STYLE
  30930. /*
  30931. ** Retry flock() calls that fail with EINTR
  30932. */
  30933. #ifdef EINTR
  30934. static int robust_flock(int fd, int op){
  30935. int rc;
  30936. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  30937. return rc;
  30938. }
  30939. #else
  30940. # define robust_flock(a,b) flock(a,b)
  30941. #endif
  30942. /*
  30943. ** This routine checks if there is a RESERVED lock held on the specified
  30944. ** file by this or any other process. If such a lock is held, set *pResOut
  30945. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30946. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30947. */
  30948. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  30949. int rc = SQLITE_OK;
  30950. int reserved = 0;
  30951. unixFile *pFile = (unixFile*)id;
  30952. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30953. assert( pFile );
  30954. /* Check if a thread in this process holds such a lock */
  30955. if( pFile->eFileLock>SHARED_LOCK ){
  30956. reserved = 1;
  30957. }
  30958. /* Otherwise see if some other process holds it. */
  30959. if( !reserved ){
  30960. /* attempt to get the lock */
  30961. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  30962. if( !lrc ){
  30963. /* got the lock, unlock it */
  30964. lrc = robust_flock(pFile->h, LOCK_UN);
  30965. if ( lrc ) {
  30966. int tErrno = errno;
  30967. /* unlock failed with an error */
  30968. lrc = SQLITE_IOERR_UNLOCK;
  30969. storeLastErrno(pFile, tErrno);
  30970. rc = lrc;
  30971. }
  30972. } else {
  30973. int tErrno = errno;
  30974. reserved = 1;
  30975. /* someone else might have it reserved */
  30976. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30977. if( IS_LOCK_ERROR(lrc) ){
  30978. storeLastErrno(pFile, tErrno);
  30979. rc = lrc;
  30980. }
  30981. }
  30982. }
  30983. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  30984. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30985. if( (rc & 0xff) == SQLITE_IOERR ){
  30986. rc = SQLITE_OK;
  30987. reserved=1;
  30988. }
  30989. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30990. *pResOut = reserved;
  30991. return rc;
  30992. }
  30993. /*
  30994. ** Lock the file with the lock specified by parameter eFileLock - one
  30995. ** of the following:
  30996. **
  30997. ** (1) SHARED_LOCK
  30998. ** (2) RESERVED_LOCK
  30999. ** (3) PENDING_LOCK
  31000. ** (4) EXCLUSIVE_LOCK
  31001. **
  31002. ** Sometimes when requesting one lock state, additional lock states
  31003. ** are inserted in between. The locking might fail on one of the later
  31004. ** transitions leaving the lock state different from what it started but
  31005. ** still short of its goal. The following chart shows the allowed
  31006. ** transitions and the inserted intermediate states:
  31007. **
  31008. ** UNLOCKED -> SHARED
  31009. ** SHARED -> RESERVED
  31010. ** SHARED -> (PENDING) -> EXCLUSIVE
  31011. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31012. ** PENDING -> EXCLUSIVE
  31013. **
  31014. ** flock() only really support EXCLUSIVE locks. We track intermediate
  31015. ** lock states in the sqlite3_file structure, but all locks SHARED or
  31016. ** above are really EXCLUSIVE locks and exclude all other processes from
  31017. ** access the file.
  31018. **
  31019. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31020. ** routine to lower a locking level.
  31021. */
  31022. static int flockLock(sqlite3_file *id, int eFileLock) {
  31023. int rc = SQLITE_OK;
  31024. unixFile *pFile = (unixFile*)id;
  31025. assert( pFile );
  31026. /* if we already have a lock, it is exclusive.
  31027. ** Just adjust level and punt on outta here. */
  31028. if (pFile->eFileLock > NO_LOCK) {
  31029. pFile->eFileLock = eFileLock;
  31030. return SQLITE_OK;
  31031. }
  31032. /* grab an exclusive lock */
  31033. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  31034. int tErrno = errno;
  31035. /* didn't get, must be busy */
  31036. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31037. if( IS_LOCK_ERROR(rc) ){
  31038. storeLastErrno(pFile, tErrno);
  31039. }
  31040. } else {
  31041. /* got it, set the type and return ok */
  31042. pFile->eFileLock = eFileLock;
  31043. }
  31044. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  31045. rc==SQLITE_OK ? "ok" : "failed"));
  31046. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  31047. if( (rc & 0xff) == SQLITE_IOERR ){
  31048. rc = SQLITE_BUSY;
  31049. }
  31050. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  31051. return rc;
  31052. }
  31053. /*
  31054. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31055. ** must be either NO_LOCK or SHARED_LOCK.
  31056. **
  31057. ** If the locking level of the file descriptor is already at or below
  31058. ** the requested locking level, this routine is a no-op.
  31059. */
  31060. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  31061. unixFile *pFile = (unixFile*)id;
  31062. assert( pFile );
  31063. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  31064. pFile->eFileLock, osGetpid(0)));
  31065. assert( eFileLock<=SHARED_LOCK );
  31066. /* no-op if possible */
  31067. if( pFile->eFileLock==eFileLock ){
  31068. return SQLITE_OK;
  31069. }
  31070. /* shared can just be set because we always have an exclusive */
  31071. if (eFileLock==SHARED_LOCK) {
  31072. pFile->eFileLock = eFileLock;
  31073. return SQLITE_OK;
  31074. }
  31075. /* no, really, unlock. */
  31076. if( robust_flock(pFile->h, LOCK_UN) ){
  31077. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  31078. return SQLITE_OK;
  31079. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  31080. return SQLITE_IOERR_UNLOCK;
  31081. }else{
  31082. pFile->eFileLock = NO_LOCK;
  31083. return SQLITE_OK;
  31084. }
  31085. }
  31086. /*
  31087. ** Close a file.
  31088. */
  31089. static int flockClose(sqlite3_file *id) {
  31090. assert( id!=0 );
  31091. flockUnlock(id, NO_LOCK);
  31092. return closeUnixFile(id);
  31093. }
  31094. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  31095. /******************* End of the flock lock implementation *********************
  31096. ******************************************************************************/
  31097. /******************************************************************************
  31098. ************************ Begin Named Semaphore Locking ************************
  31099. **
  31100. ** Named semaphore locking is only supported on VxWorks.
  31101. **
  31102. ** Semaphore locking is like dot-lock and flock in that it really only
  31103. ** supports EXCLUSIVE locking. Only a single process can read or write
  31104. ** the database file at a time. This reduces potential concurrency, but
  31105. ** makes the lock implementation much easier.
  31106. */
  31107. #if OS_VXWORKS
  31108. /*
  31109. ** This routine checks if there is a RESERVED lock held on the specified
  31110. ** file by this or any other process. If such a lock is held, set *pResOut
  31111. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31112. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31113. */
  31114. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  31115. int rc = SQLITE_OK;
  31116. int reserved = 0;
  31117. unixFile *pFile = (unixFile*)id;
  31118. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31119. assert( pFile );
  31120. /* Check if a thread in this process holds such a lock */
  31121. if( pFile->eFileLock>SHARED_LOCK ){
  31122. reserved = 1;
  31123. }
  31124. /* Otherwise see if some other process holds it. */
  31125. if( !reserved ){
  31126. sem_t *pSem = pFile->pInode->pSem;
  31127. if( sem_trywait(pSem)==-1 ){
  31128. int tErrno = errno;
  31129. if( EAGAIN != tErrno ){
  31130. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  31131. storeLastErrno(pFile, tErrno);
  31132. } else {
  31133. /* someone else has the lock when we are in NO_LOCK */
  31134. reserved = (pFile->eFileLock < SHARED_LOCK);
  31135. }
  31136. }else{
  31137. /* we could have it if we want it */
  31138. sem_post(pSem);
  31139. }
  31140. }
  31141. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  31142. *pResOut = reserved;
  31143. return rc;
  31144. }
  31145. /*
  31146. ** Lock the file with the lock specified by parameter eFileLock - one
  31147. ** of the following:
  31148. **
  31149. ** (1) SHARED_LOCK
  31150. ** (2) RESERVED_LOCK
  31151. ** (3) PENDING_LOCK
  31152. ** (4) EXCLUSIVE_LOCK
  31153. **
  31154. ** Sometimes when requesting one lock state, additional lock states
  31155. ** are inserted in between. The locking might fail on one of the later
  31156. ** transitions leaving the lock state different from what it started but
  31157. ** still short of its goal. The following chart shows the allowed
  31158. ** transitions and the inserted intermediate states:
  31159. **
  31160. ** UNLOCKED -> SHARED
  31161. ** SHARED -> RESERVED
  31162. ** SHARED -> (PENDING) -> EXCLUSIVE
  31163. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31164. ** PENDING -> EXCLUSIVE
  31165. **
  31166. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  31167. ** lock states in the sqlite3_file structure, but all locks SHARED or
  31168. ** above are really EXCLUSIVE locks and exclude all other processes from
  31169. ** access the file.
  31170. **
  31171. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31172. ** routine to lower a locking level.
  31173. */
  31174. static int semXLock(sqlite3_file *id, int eFileLock) {
  31175. unixFile *pFile = (unixFile*)id;
  31176. sem_t *pSem = pFile->pInode->pSem;
  31177. int rc = SQLITE_OK;
  31178. /* if we already have a lock, it is exclusive.
  31179. ** Just adjust level and punt on outta here. */
  31180. if (pFile->eFileLock > NO_LOCK) {
  31181. pFile->eFileLock = eFileLock;
  31182. rc = SQLITE_OK;
  31183. goto sem_end_lock;
  31184. }
  31185. /* lock semaphore now but bail out when already locked. */
  31186. if( sem_trywait(pSem)==-1 ){
  31187. rc = SQLITE_BUSY;
  31188. goto sem_end_lock;
  31189. }
  31190. /* got it, set the type and return ok */
  31191. pFile->eFileLock = eFileLock;
  31192. sem_end_lock:
  31193. return rc;
  31194. }
  31195. /*
  31196. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31197. ** must be either NO_LOCK or SHARED_LOCK.
  31198. **
  31199. ** If the locking level of the file descriptor is already at or below
  31200. ** the requested locking level, this routine is a no-op.
  31201. */
  31202. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  31203. unixFile *pFile = (unixFile*)id;
  31204. sem_t *pSem = pFile->pInode->pSem;
  31205. assert( pFile );
  31206. assert( pSem );
  31207. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  31208. pFile->eFileLock, osGetpid(0)));
  31209. assert( eFileLock<=SHARED_LOCK );
  31210. /* no-op if possible */
  31211. if( pFile->eFileLock==eFileLock ){
  31212. return SQLITE_OK;
  31213. }
  31214. /* shared can just be set because we always have an exclusive */
  31215. if (eFileLock==SHARED_LOCK) {
  31216. pFile->eFileLock = eFileLock;
  31217. return SQLITE_OK;
  31218. }
  31219. /* no, really unlock. */
  31220. if ( sem_post(pSem)==-1 ) {
  31221. int rc, tErrno = errno;
  31222. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  31223. if( IS_LOCK_ERROR(rc) ){
  31224. storeLastErrno(pFile, tErrno);
  31225. }
  31226. return rc;
  31227. }
  31228. pFile->eFileLock = NO_LOCK;
  31229. return SQLITE_OK;
  31230. }
  31231. /*
  31232. ** Close a file.
  31233. */
  31234. static int semXClose(sqlite3_file *id) {
  31235. if( id ){
  31236. unixFile *pFile = (unixFile*)id;
  31237. semXUnlock(id, NO_LOCK);
  31238. assert( pFile );
  31239. unixEnterMutex();
  31240. releaseInodeInfo(pFile);
  31241. unixLeaveMutex();
  31242. closeUnixFile(id);
  31243. }
  31244. return SQLITE_OK;
  31245. }
  31246. #endif /* OS_VXWORKS */
  31247. /*
  31248. ** Named semaphore locking is only available on VxWorks.
  31249. **
  31250. *************** End of the named semaphore lock implementation ****************
  31251. ******************************************************************************/
  31252. /******************************************************************************
  31253. *************************** Begin AFP Locking *********************************
  31254. **
  31255. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  31256. ** on Apple Macintosh computers - both OS9 and OSX.
  31257. **
  31258. ** Third-party implementations of AFP are available. But this code here
  31259. ** only works on OSX.
  31260. */
  31261. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31262. /*
  31263. ** The afpLockingContext structure contains all afp lock specific state
  31264. */
  31265. typedef struct afpLockingContext afpLockingContext;
  31266. struct afpLockingContext {
  31267. int reserved;
  31268. const char *dbPath; /* Name of the open file */
  31269. };
  31270. struct ByteRangeLockPB2
  31271. {
  31272. unsigned long long offset; /* offset to first byte to lock */
  31273. unsigned long long length; /* nbr of bytes to lock */
  31274. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  31275. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  31276. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  31277. int fd; /* file desc to assoc this lock with */
  31278. };
  31279. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  31280. /*
  31281. ** This is a utility for setting or clearing a bit-range lock on an
  31282. ** AFP filesystem.
  31283. **
  31284. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  31285. */
  31286. static int afpSetLock(
  31287. const char *path, /* Name of the file to be locked or unlocked */
  31288. unixFile *pFile, /* Open file descriptor on path */
  31289. unsigned long long offset, /* First byte to be locked */
  31290. unsigned long long length, /* Number of bytes to lock */
  31291. int setLockFlag /* True to set lock. False to clear lock */
  31292. ){
  31293. struct ByteRangeLockPB2 pb;
  31294. int err;
  31295. pb.unLockFlag = setLockFlag ? 0 : 1;
  31296. pb.startEndFlag = 0;
  31297. pb.offset = offset;
  31298. pb.length = length;
  31299. pb.fd = pFile->h;
  31300. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  31301. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  31302. offset, length));
  31303. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  31304. if ( err==-1 ) {
  31305. int rc;
  31306. int tErrno = errno;
  31307. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  31308. path, tErrno, strerror(tErrno)));
  31309. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  31310. rc = SQLITE_BUSY;
  31311. #else
  31312. rc = sqliteErrorFromPosixError(tErrno,
  31313. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  31314. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  31315. if( IS_LOCK_ERROR(rc) ){
  31316. storeLastErrno(pFile, tErrno);
  31317. }
  31318. return rc;
  31319. } else {
  31320. return SQLITE_OK;
  31321. }
  31322. }
  31323. /*
  31324. ** This routine checks if there is a RESERVED lock held on the specified
  31325. ** file by this or any other process. If such a lock is held, set *pResOut
  31326. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31327. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31328. */
  31329. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  31330. int rc = SQLITE_OK;
  31331. int reserved = 0;
  31332. unixFile *pFile = (unixFile*)id;
  31333. afpLockingContext *context;
  31334. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31335. assert( pFile );
  31336. context = (afpLockingContext *) pFile->lockingContext;
  31337. if( context->reserved ){
  31338. *pResOut = 1;
  31339. return SQLITE_OK;
  31340. }
  31341. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  31342. /* Check if a thread in this process holds such a lock */
  31343. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  31344. reserved = 1;
  31345. }
  31346. /* Otherwise see if some other process holds it.
  31347. */
  31348. if( !reserved ){
  31349. /* lock the RESERVED byte */
  31350. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  31351. if( SQLITE_OK==lrc ){
  31352. /* if we succeeded in taking the reserved lock, unlock it to restore
  31353. ** the original state */
  31354. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  31355. } else {
  31356. /* if we failed to get the lock then someone else must have it */
  31357. reserved = 1;
  31358. }
  31359. if( IS_LOCK_ERROR(lrc) ){
  31360. rc=lrc;
  31361. }
  31362. }
  31363. unixLeaveMutex();
  31364. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  31365. *pResOut = reserved;
  31366. return rc;
  31367. }
  31368. /*
  31369. ** Lock the file with the lock specified by parameter eFileLock - one
  31370. ** of the following:
  31371. **
  31372. ** (1) SHARED_LOCK
  31373. ** (2) RESERVED_LOCK
  31374. ** (3) PENDING_LOCK
  31375. ** (4) EXCLUSIVE_LOCK
  31376. **
  31377. ** Sometimes when requesting one lock state, additional lock states
  31378. ** are inserted in between. The locking might fail on one of the later
  31379. ** transitions leaving the lock state different from what it started but
  31380. ** still short of its goal. The following chart shows the allowed
  31381. ** transitions and the inserted intermediate states:
  31382. **
  31383. ** UNLOCKED -> SHARED
  31384. ** SHARED -> RESERVED
  31385. ** SHARED -> (PENDING) -> EXCLUSIVE
  31386. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31387. ** PENDING -> EXCLUSIVE
  31388. **
  31389. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31390. ** routine to lower a locking level.
  31391. */
  31392. static int afpLock(sqlite3_file *id, int eFileLock){
  31393. int rc = SQLITE_OK;
  31394. unixFile *pFile = (unixFile*)id;
  31395. unixInodeInfo *pInode = pFile->pInode;
  31396. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  31397. assert( pFile );
  31398. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  31399. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  31400. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  31401. /* If there is already a lock of this type or more restrictive on the
  31402. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  31403. ** unixEnterMutex() hasn't been called yet.
  31404. */
  31405. if( pFile->eFileLock>=eFileLock ){
  31406. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  31407. azFileLock(eFileLock)));
  31408. return SQLITE_OK;
  31409. }
  31410. /* Make sure the locking sequence is correct
  31411. ** (1) We never move from unlocked to anything higher than shared lock.
  31412. ** (2) SQLite never explicitly requests a pendig lock.
  31413. ** (3) A shared lock is always held when a reserve lock is requested.
  31414. */
  31415. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  31416. assert( eFileLock!=PENDING_LOCK );
  31417. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  31418. /* This mutex is needed because pFile->pInode is shared across threads
  31419. */
  31420. unixEnterMutex();
  31421. pInode = pFile->pInode;
  31422. /* If some thread using this PID has a lock via a different unixFile*
  31423. ** handle that precludes the requested lock, return BUSY.
  31424. */
  31425. if( (pFile->eFileLock!=pInode->eFileLock &&
  31426. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  31427. ){
  31428. rc = SQLITE_BUSY;
  31429. goto afp_end_lock;
  31430. }
  31431. /* If a SHARED lock is requested, and some thread using this PID already
  31432. ** has a SHARED or RESERVED lock, then increment reference counts and
  31433. ** return SQLITE_OK.
  31434. */
  31435. if( eFileLock==SHARED_LOCK &&
  31436. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  31437. assert( eFileLock==SHARED_LOCK );
  31438. assert( pFile->eFileLock==0 );
  31439. assert( pInode->nShared>0 );
  31440. pFile->eFileLock = SHARED_LOCK;
  31441. pInode->nShared++;
  31442. pInode->nLock++;
  31443. goto afp_end_lock;
  31444. }
  31445. /* A PENDING lock is needed before acquiring a SHARED lock and before
  31446. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  31447. ** be released.
  31448. */
  31449. if( eFileLock==SHARED_LOCK
  31450. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  31451. ){
  31452. int failed;
  31453. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  31454. if (failed) {
  31455. rc = failed;
  31456. goto afp_end_lock;
  31457. }
  31458. }
  31459. /* If control gets to this point, then actually go ahead and make
  31460. ** operating system calls for the specified lock.
  31461. */
  31462. if( eFileLock==SHARED_LOCK ){
  31463. int lrc1, lrc2, lrc1Errno = 0;
  31464. long lk, mask;
  31465. assert( pInode->nShared==0 );
  31466. assert( pInode->eFileLock==0 );
  31467. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  31468. /* Now get the read-lock SHARED_LOCK */
  31469. /* note that the quality of the randomness doesn't matter that much */
  31470. lk = random();
  31471. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  31472. lrc1 = afpSetLock(context->dbPath, pFile,
  31473. SHARED_FIRST+pInode->sharedByte, 1, 1);
  31474. if( IS_LOCK_ERROR(lrc1) ){
  31475. lrc1Errno = pFile->lastErrno;
  31476. }
  31477. /* Drop the temporary PENDING lock */
  31478. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  31479. if( IS_LOCK_ERROR(lrc1) ) {
  31480. storeLastErrno(pFile, lrc1Errno);
  31481. rc = lrc1;
  31482. goto afp_end_lock;
  31483. } else if( IS_LOCK_ERROR(lrc2) ){
  31484. rc = lrc2;
  31485. goto afp_end_lock;
  31486. } else if( lrc1 != SQLITE_OK ) {
  31487. rc = lrc1;
  31488. } else {
  31489. pFile->eFileLock = SHARED_LOCK;
  31490. pInode->nLock++;
  31491. pInode->nShared = 1;
  31492. }
  31493. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  31494. /* We are trying for an exclusive lock but another thread in this
  31495. ** same process is still holding a shared lock. */
  31496. rc = SQLITE_BUSY;
  31497. }else{
  31498. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  31499. ** assumed that there is a SHARED or greater lock on the file
  31500. ** already.
  31501. */
  31502. int failed = 0;
  31503. assert( 0!=pFile->eFileLock );
  31504. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  31505. /* Acquire a RESERVED lock */
  31506. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  31507. if( !failed ){
  31508. context->reserved = 1;
  31509. }
  31510. }
  31511. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  31512. /* Acquire an EXCLUSIVE lock */
  31513. /* Remove the shared lock before trying the range. we'll need to
  31514. ** reestablish the shared lock if we can't get the afpUnlock
  31515. */
  31516. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  31517. pInode->sharedByte, 1, 0)) ){
  31518. int failed2 = SQLITE_OK;
  31519. /* now attemmpt to get the exclusive lock range */
  31520. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  31521. SHARED_SIZE, 1);
  31522. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  31523. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  31524. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  31525. ** a critical I/O error
  31526. */
  31527. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  31528. SQLITE_IOERR_LOCK;
  31529. goto afp_end_lock;
  31530. }
  31531. }else{
  31532. rc = failed;
  31533. }
  31534. }
  31535. if( failed ){
  31536. rc = failed;
  31537. }
  31538. }
  31539. if( rc==SQLITE_OK ){
  31540. pFile->eFileLock = eFileLock;
  31541. pInode->eFileLock = eFileLock;
  31542. }else if( eFileLock==EXCLUSIVE_LOCK ){
  31543. pFile->eFileLock = PENDING_LOCK;
  31544. pInode->eFileLock = PENDING_LOCK;
  31545. }
  31546. afp_end_lock:
  31547. unixLeaveMutex();
  31548. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  31549. rc==SQLITE_OK ? "ok" : "failed"));
  31550. return rc;
  31551. }
  31552. /*
  31553. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31554. ** must be either NO_LOCK or SHARED_LOCK.
  31555. **
  31556. ** If the locking level of the file descriptor is already at or below
  31557. ** the requested locking level, this routine is a no-op.
  31558. */
  31559. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  31560. int rc = SQLITE_OK;
  31561. unixFile *pFile = (unixFile*)id;
  31562. unixInodeInfo *pInode;
  31563. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  31564. int skipShared = 0;
  31565. #ifdef SQLITE_TEST
  31566. int h = pFile->h;
  31567. #endif
  31568. assert( pFile );
  31569. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  31570. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  31571. osGetpid(0)));
  31572. assert( eFileLock<=SHARED_LOCK );
  31573. if( pFile->eFileLock<=eFileLock ){
  31574. return SQLITE_OK;
  31575. }
  31576. unixEnterMutex();
  31577. pInode = pFile->pInode;
  31578. assert( pInode->nShared!=0 );
  31579. if( pFile->eFileLock>SHARED_LOCK ){
  31580. assert( pInode->eFileLock==pFile->eFileLock );
  31581. SimulateIOErrorBenign(1);
  31582. SimulateIOError( h=(-1) )
  31583. SimulateIOErrorBenign(0);
  31584. #ifdef SQLITE_DEBUG
  31585. /* When reducing a lock such that other processes can start
  31586. ** reading the database file again, make sure that the
  31587. ** transaction counter was updated if any part of the database
  31588. ** file changed. If the transaction counter is not updated,
  31589. ** other connections to the same file might not realize that
  31590. ** the file has changed and hence might not know to flush their
  31591. ** cache. The use of a stale cache can lead to database corruption.
  31592. */
  31593. assert( pFile->inNormalWrite==0
  31594. || pFile->dbUpdate==0
  31595. || pFile->transCntrChng==1 );
  31596. pFile->inNormalWrite = 0;
  31597. #endif
  31598. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  31599. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  31600. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  31601. /* only re-establish the shared lock if necessary */
  31602. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31603. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  31604. } else {
  31605. skipShared = 1;
  31606. }
  31607. }
  31608. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  31609. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  31610. }
  31611. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  31612. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  31613. if( !rc ){
  31614. context->reserved = 0;
  31615. }
  31616. }
  31617. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  31618. pInode->eFileLock = SHARED_LOCK;
  31619. }
  31620. }
  31621. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  31622. /* Decrement the shared lock counter. Release the lock using an
  31623. ** OS call only when all threads in this same process have released
  31624. ** the lock.
  31625. */
  31626. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31627. pInode->nShared--;
  31628. if( pInode->nShared==0 ){
  31629. SimulateIOErrorBenign(1);
  31630. SimulateIOError( h=(-1) )
  31631. SimulateIOErrorBenign(0);
  31632. if( !skipShared ){
  31633. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  31634. }
  31635. if( !rc ){
  31636. pInode->eFileLock = NO_LOCK;
  31637. pFile->eFileLock = NO_LOCK;
  31638. }
  31639. }
  31640. if( rc==SQLITE_OK ){
  31641. pInode->nLock--;
  31642. assert( pInode->nLock>=0 );
  31643. if( pInode->nLock==0 ){
  31644. closePendingFds(pFile);
  31645. }
  31646. }
  31647. }
  31648. unixLeaveMutex();
  31649. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  31650. return rc;
  31651. }
  31652. /*
  31653. ** Close a file & cleanup AFP specific locking context
  31654. */
  31655. static int afpClose(sqlite3_file *id) {
  31656. int rc = SQLITE_OK;
  31657. unixFile *pFile = (unixFile*)id;
  31658. assert( id!=0 );
  31659. afpUnlock(id, NO_LOCK);
  31660. unixEnterMutex();
  31661. if( pFile->pInode && pFile->pInode->nLock ){
  31662. /* If there are outstanding locks, do not actually close the file just
  31663. ** yet because that would clear those locks. Instead, add the file
  31664. ** descriptor to pInode->aPending. It will be automatically closed when
  31665. ** the last lock is cleared.
  31666. */
  31667. setPendingFd(pFile);
  31668. }
  31669. releaseInodeInfo(pFile);
  31670. sqlite3_free(pFile->lockingContext);
  31671. rc = closeUnixFile(id);
  31672. unixLeaveMutex();
  31673. return rc;
  31674. }
  31675. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31676. /*
  31677. ** The code above is the AFP lock implementation. The code is specific
  31678. ** to MacOSX and does not work on other unix platforms. No alternative
  31679. ** is available. If you don't compile for a mac, then the "unix-afp"
  31680. ** VFS is not available.
  31681. **
  31682. ********************* End of the AFP lock implementation **********************
  31683. ******************************************************************************/
  31684. /******************************************************************************
  31685. *************************** Begin NFS Locking ********************************/
  31686. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31687. /*
  31688. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31689. ** must be either NO_LOCK or SHARED_LOCK.
  31690. **
  31691. ** If the locking level of the file descriptor is already at or below
  31692. ** the requested locking level, this routine is a no-op.
  31693. */
  31694. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  31695. return posixUnlock(id, eFileLock, 1);
  31696. }
  31697. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31698. /*
  31699. ** The code above is the NFS lock implementation. The code is specific
  31700. ** to MacOSX and does not work on other unix platforms. No alternative
  31701. ** is available.
  31702. **
  31703. ********************* End of the NFS lock implementation **********************
  31704. ******************************************************************************/
  31705. /******************************************************************************
  31706. **************** Non-locking sqlite3_file methods *****************************
  31707. **
  31708. ** The next division contains implementations for all methods of the
  31709. ** sqlite3_file object other than the locking methods. The locking
  31710. ** methods were defined in divisions above (one locking method per
  31711. ** division). Those methods that are common to all locking modes
  31712. ** are gather together into this division.
  31713. */
  31714. /*
  31715. ** Seek to the offset passed as the second argument, then read cnt
  31716. ** bytes into pBuf. Return the number of bytes actually read.
  31717. **
  31718. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  31719. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  31720. ** one system to another. Since SQLite does not define USE_PREAD
  31721. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  31722. ** See tickets #2741 and #2681.
  31723. **
  31724. ** To avoid stomping the errno value on a failed read the lastErrno value
  31725. ** is set before returning.
  31726. */
  31727. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  31728. int got;
  31729. int prior = 0;
  31730. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  31731. i64 newOffset;
  31732. #endif
  31733. TIMER_START;
  31734. assert( cnt==(cnt&0x1ffff) );
  31735. assert( id->h>2 );
  31736. do{
  31737. #if defined(USE_PREAD)
  31738. got = osPread(id->h, pBuf, cnt, offset);
  31739. SimulateIOError( got = -1 );
  31740. #elif defined(USE_PREAD64)
  31741. got = osPread64(id->h, pBuf, cnt, offset);
  31742. SimulateIOError( got = -1 );
  31743. #else
  31744. newOffset = lseek(id->h, offset, SEEK_SET);
  31745. SimulateIOError( newOffset = -1 );
  31746. if( newOffset<0 ){
  31747. storeLastErrno((unixFile*)id, errno);
  31748. return -1;
  31749. }
  31750. got = osRead(id->h, pBuf, cnt);
  31751. #endif
  31752. if( got==cnt ) break;
  31753. if( got<0 ){
  31754. if( errno==EINTR ){ got = 1; continue; }
  31755. prior = 0;
  31756. storeLastErrno((unixFile*)id, errno);
  31757. break;
  31758. }else if( got>0 ){
  31759. cnt -= got;
  31760. offset += got;
  31761. prior += got;
  31762. pBuf = (void*)(got + (char*)pBuf);
  31763. }
  31764. }while( got>0 );
  31765. TIMER_END;
  31766. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  31767. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  31768. return got+prior;
  31769. }
  31770. /*
  31771. ** Read data from a file into a buffer. Return SQLITE_OK if all
  31772. ** bytes were read successfully and SQLITE_IOERR if anything goes
  31773. ** wrong.
  31774. */
  31775. static int unixRead(
  31776. sqlite3_file *id,
  31777. void *pBuf,
  31778. int amt,
  31779. sqlite3_int64 offset
  31780. ){
  31781. unixFile *pFile = (unixFile *)id;
  31782. int got;
  31783. assert( id );
  31784. assert( offset>=0 );
  31785. assert( amt>0 );
  31786. /* If this is a database file (not a journal, master-journal or temp
  31787. ** file), the bytes in the locking range should never be read or written. */
  31788. #if 0
  31789. assert( pFile->pPreallocatedUnused==0
  31790. || offset>=PENDING_BYTE+512
  31791. || offset+amt<=PENDING_BYTE
  31792. );
  31793. #endif
  31794. #if SQLITE_MAX_MMAP_SIZE>0
  31795. /* Deal with as much of this read request as possible by transfering
  31796. ** data from the memory mapping using memcpy(). */
  31797. if( offset<pFile->mmapSize ){
  31798. if( offset+amt <= pFile->mmapSize ){
  31799. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  31800. return SQLITE_OK;
  31801. }else{
  31802. int nCopy = pFile->mmapSize - offset;
  31803. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  31804. pBuf = &((u8 *)pBuf)[nCopy];
  31805. amt -= nCopy;
  31806. offset += nCopy;
  31807. }
  31808. }
  31809. #endif
  31810. got = seekAndRead(pFile, offset, pBuf, amt);
  31811. if( got==amt ){
  31812. return SQLITE_OK;
  31813. }else if( got<0 ){
  31814. /* lastErrno set by seekAndRead */
  31815. return SQLITE_IOERR_READ;
  31816. }else{
  31817. storeLastErrno(pFile, 0); /* not a system error */
  31818. /* Unread parts of the buffer must be zero-filled */
  31819. memset(&((char*)pBuf)[got], 0, amt-got);
  31820. return SQLITE_IOERR_SHORT_READ;
  31821. }
  31822. }
  31823. /*
  31824. ** Attempt to seek the file-descriptor passed as the first argument to
  31825. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  31826. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  31827. ** return the actual number of bytes written (which may be less than
  31828. ** nBuf).
  31829. */
  31830. static int seekAndWriteFd(
  31831. int fd, /* File descriptor to write to */
  31832. i64 iOff, /* File offset to begin writing at */
  31833. const void *pBuf, /* Copy data from this buffer to the file */
  31834. int nBuf, /* Size of buffer pBuf in bytes */
  31835. int *piErrno /* OUT: Error number if error occurs */
  31836. ){
  31837. int rc = 0; /* Value returned by system call */
  31838. assert( nBuf==(nBuf&0x1ffff) );
  31839. assert( fd>2 );
  31840. assert( piErrno!=0 );
  31841. nBuf &= 0x1ffff;
  31842. TIMER_START;
  31843. #if defined(USE_PREAD)
  31844. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  31845. #elif defined(USE_PREAD64)
  31846. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  31847. #else
  31848. do{
  31849. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  31850. SimulateIOError( iSeek = -1 );
  31851. if( iSeek<0 ){
  31852. rc = -1;
  31853. break;
  31854. }
  31855. rc = osWrite(fd, pBuf, nBuf);
  31856. }while( rc<0 && errno==EINTR );
  31857. #endif
  31858. TIMER_END;
  31859. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  31860. if( rc<0 ) *piErrno = errno;
  31861. return rc;
  31862. }
  31863. /*
  31864. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  31865. ** Return the number of bytes actually read. Update the offset.
  31866. **
  31867. ** To avoid stomping the errno value on a failed write the lastErrno value
  31868. ** is set before returning.
  31869. */
  31870. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  31871. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  31872. }
  31873. /*
  31874. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31875. ** or some other error code on failure.
  31876. */
  31877. static int unixWrite(
  31878. sqlite3_file *id,
  31879. const void *pBuf,
  31880. int amt,
  31881. sqlite3_int64 offset
  31882. ){
  31883. unixFile *pFile = (unixFile*)id;
  31884. int wrote = 0;
  31885. assert( id );
  31886. assert( amt>0 );
  31887. /* If this is a database file (not a journal, master-journal or temp
  31888. ** file), the bytes in the locking range should never be read or written. */
  31889. #if 0
  31890. assert( pFile->pPreallocatedUnused==0
  31891. || offset>=PENDING_BYTE+512
  31892. || offset+amt<=PENDING_BYTE
  31893. );
  31894. #endif
  31895. #ifdef SQLITE_DEBUG
  31896. /* If we are doing a normal write to a database file (as opposed to
  31897. ** doing a hot-journal rollback or a write to some file other than a
  31898. ** normal database file) then record the fact that the database
  31899. ** has changed. If the transaction counter is modified, record that
  31900. ** fact too.
  31901. */
  31902. if( pFile->inNormalWrite ){
  31903. pFile->dbUpdate = 1; /* The database has been modified */
  31904. if( offset<=24 && offset+amt>=27 ){
  31905. int rc;
  31906. char oldCntr[4];
  31907. SimulateIOErrorBenign(1);
  31908. rc = seekAndRead(pFile, 24, oldCntr, 4);
  31909. SimulateIOErrorBenign(0);
  31910. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  31911. pFile->transCntrChng = 1; /* The transaction counter has changed */
  31912. }
  31913. }
  31914. }
  31915. #endif
  31916. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  31917. /* Deal with as much of this write request as possible by transfering
  31918. ** data from the memory mapping using memcpy(). */
  31919. if( offset<pFile->mmapSize ){
  31920. if( offset+amt <= pFile->mmapSize ){
  31921. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31922. return SQLITE_OK;
  31923. }else{
  31924. int nCopy = pFile->mmapSize - offset;
  31925. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31926. pBuf = &((u8 *)pBuf)[nCopy];
  31927. amt -= nCopy;
  31928. offset += nCopy;
  31929. }
  31930. }
  31931. #endif
  31932. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  31933. amt -= wrote;
  31934. offset += wrote;
  31935. pBuf = &((char*)pBuf)[wrote];
  31936. }
  31937. SimulateIOError(( wrote=(-1), amt=1 ));
  31938. SimulateDiskfullError(( wrote=0, amt=1 ));
  31939. if( amt>wrote ){
  31940. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  31941. /* lastErrno set by seekAndWrite */
  31942. return SQLITE_IOERR_WRITE;
  31943. }else{
  31944. storeLastErrno(pFile, 0); /* not a system error */
  31945. return SQLITE_FULL;
  31946. }
  31947. }
  31948. return SQLITE_OK;
  31949. }
  31950. #ifdef SQLITE_TEST
  31951. /*
  31952. ** Count the number of fullsyncs and normal syncs. This is used to test
  31953. ** that syncs and fullsyncs are occurring at the right times.
  31954. */
  31955. SQLITE_API int sqlite3_sync_count = 0;
  31956. SQLITE_API int sqlite3_fullsync_count = 0;
  31957. #endif
  31958. /*
  31959. ** We do not trust systems to provide a working fdatasync(). Some do.
  31960. ** Others do no. To be safe, we will stick with the (slightly slower)
  31961. ** fsync(). If you know that your system does support fdatasync() correctly,
  31962. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  31963. */
  31964. #if !defined(fdatasync) && !HAVE_FDATASYNC
  31965. # define fdatasync fsync
  31966. #endif
  31967. /*
  31968. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  31969. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  31970. ** only available on Mac OS X. But that could change.
  31971. */
  31972. #ifdef F_FULLFSYNC
  31973. # define HAVE_FULLFSYNC 1
  31974. #else
  31975. # define HAVE_FULLFSYNC 0
  31976. #endif
  31977. /*
  31978. ** The fsync() system call does not work as advertised on many
  31979. ** unix systems. The following procedure is an attempt to make
  31980. ** it work better.
  31981. **
  31982. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  31983. ** for testing when we want to run through the test suite quickly.
  31984. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  31985. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  31986. ** or power failure will likely corrupt the database file.
  31987. **
  31988. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  31989. ** The idea behind dataOnly is that it should only write the file content
  31990. ** to disk, not the inode. We only set dataOnly if the file size is
  31991. ** unchanged since the file size is part of the inode. However,
  31992. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  31993. ** file size has changed. The only real difference between fdatasync()
  31994. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  31995. ** inode if the mtime or owner or other inode attributes have changed.
  31996. ** We only care about the file size, not the other file attributes, so
  31997. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  31998. ** So, we always use fdatasync() if it is available, regardless of
  31999. ** the value of the dataOnly flag.
  32000. */
  32001. static int full_fsync(int fd, int fullSync, int dataOnly){
  32002. int rc;
  32003. /* The following "ifdef/elif/else/" block has the same structure as
  32004. ** the one below. It is replicated here solely to avoid cluttering
  32005. ** up the real code with the UNUSED_PARAMETER() macros.
  32006. */
  32007. #ifdef SQLITE_NO_SYNC
  32008. UNUSED_PARAMETER(fd);
  32009. UNUSED_PARAMETER(fullSync);
  32010. UNUSED_PARAMETER(dataOnly);
  32011. #elif HAVE_FULLFSYNC
  32012. UNUSED_PARAMETER(dataOnly);
  32013. #else
  32014. UNUSED_PARAMETER(fullSync);
  32015. UNUSED_PARAMETER(dataOnly);
  32016. #endif
  32017. /* Record the number of times that we do a normal fsync() and
  32018. ** FULLSYNC. This is used during testing to verify that this procedure
  32019. ** gets called with the correct arguments.
  32020. */
  32021. #ifdef SQLITE_TEST
  32022. if( fullSync ) sqlite3_fullsync_count++;
  32023. sqlite3_sync_count++;
  32024. #endif
  32025. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  32026. ** no-op. But go ahead and call fstat() to validate the file
  32027. ** descriptor as we need a method to provoke a failure during
  32028. ** coverate testing.
  32029. */
  32030. #ifdef SQLITE_NO_SYNC
  32031. {
  32032. struct stat buf;
  32033. rc = osFstat(fd, &buf);
  32034. }
  32035. #elif HAVE_FULLFSYNC
  32036. if( fullSync ){
  32037. rc = osFcntl(fd, F_FULLFSYNC, 0);
  32038. }else{
  32039. rc = 1;
  32040. }
  32041. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  32042. ** It shouldn't be possible for fullfsync to fail on the local
  32043. ** file system (on OSX), so failure indicates that FULLFSYNC
  32044. ** isn't supported for this file system. So, attempt an fsync
  32045. ** and (for now) ignore the overhead of a superfluous fcntl call.
  32046. ** It'd be better to detect fullfsync support once and avoid
  32047. ** the fcntl call every time sync is called.
  32048. */
  32049. if( rc ) rc = fsync(fd);
  32050. #elif defined(__APPLE__)
  32051. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  32052. ** so currently we default to the macro that redefines fdatasync to fsync
  32053. */
  32054. rc = fsync(fd);
  32055. #else
  32056. rc = fdatasync(fd);
  32057. #if OS_VXWORKS
  32058. if( rc==-1 && errno==ENOTSUP ){
  32059. rc = fsync(fd);
  32060. }
  32061. #endif /* OS_VXWORKS */
  32062. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  32063. if( OS_VXWORKS && rc!= -1 ){
  32064. rc = 0;
  32065. }
  32066. return rc;
  32067. }
  32068. /*
  32069. ** Open a file descriptor to the directory containing file zFilename.
  32070. ** If successful, *pFd is set to the opened file descriptor and
  32071. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  32072. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  32073. ** value.
  32074. **
  32075. ** The directory file descriptor is used for only one thing - to
  32076. ** fsync() a directory to make sure file creation and deletion events
  32077. ** are flushed to disk. Such fsyncs are not needed on newer
  32078. ** journaling filesystems, but are required on older filesystems.
  32079. **
  32080. ** This routine can be overridden using the xSetSysCall interface.
  32081. ** The ability to override this routine was added in support of the
  32082. ** chromium sandbox. Opening a directory is a security risk (we are
  32083. ** told) so making it overrideable allows the chromium sandbox to
  32084. ** replace this routine with a harmless no-op. To make this routine
  32085. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  32086. ** *pFd set to a negative number.
  32087. **
  32088. ** If SQLITE_OK is returned, the caller is responsible for closing
  32089. ** the file descriptor *pFd using close().
  32090. */
  32091. static int openDirectory(const char *zFilename, int *pFd){
  32092. int ii;
  32093. int fd = -1;
  32094. char zDirname[MAX_PATHNAME+1];
  32095. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  32096. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  32097. if( ii>0 ){
  32098. zDirname[ii] = '\0';
  32099. }else{
  32100. if( zDirname[0]!='/' ) zDirname[0] = '.';
  32101. zDirname[1] = 0;
  32102. }
  32103. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  32104. if( fd>=0 ){
  32105. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  32106. }
  32107. *pFd = fd;
  32108. if( fd>=0 ) return SQLITE_OK;
  32109. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  32110. }
  32111. /*
  32112. ** Make sure all writes to a particular file are committed to disk.
  32113. **
  32114. ** If dataOnly==0 then both the file itself and its metadata (file
  32115. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  32116. ** file data is synced.
  32117. **
  32118. ** Under Unix, also make sure that the directory entry for the file
  32119. ** has been created by fsync-ing the directory that contains the file.
  32120. ** If we do not do this and we encounter a power failure, the directory
  32121. ** entry for the journal might not exist after we reboot. The next
  32122. ** SQLite to access the file will not know that the journal exists (because
  32123. ** the directory entry for the journal was never created) and the transaction
  32124. ** will not roll back - possibly leading to database corruption.
  32125. */
  32126. static int unixSync(sqlite3_file *id, int flags){
  32127. int rc;
  32128. unixFile *pFile = (unixFile*)id;
  32129. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  32130. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  32131. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  32132. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  32133. || (flags&0x0F)==SQLITE_SYNC_FULL
  32134. );
  32135. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  32136. ** line is to test that doing so does not cause any problems.
  32137. */
  32138. SimulateDiskfullError( return SQLITE_FULL );
  32139. assert( pFile );
  32140. OSTRACE(("SYNC %-3d\n", pFile->h));
  32141. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  32142. SimulateIOError( rc=1 );
  32143. if( rc ){
  32144. storeLastErrno(pFile, errno);
  32145. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  32146. }
  32147. /* Also fsync the directory containing the file if the DIRSYNC flag
  32148. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  32149. ** are unable to fsync a directory, so ignore errors on the fsync.
  32150. */
  32151. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  32152. int dirfd;
  32153. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  32154. HAVE_FULLFSYNC, isFullsync));
  32155. rc = osOpenDirectory(pFile->zPath, &dirfd);
  32156. if( rc==SQLITE_OK ){
  32157. full_fsync(dirfd, 0, 0);
  32158. robust_close(pFile, dirfd, __LINE__);
  32159. }else{
  32160. assert( rc==SQLITE_CANTOPEN );
  32161. rc = SQLITE_OK;
  32162. }
  32163. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  32164. }
  32165. return rc;
  32166. }
  32167. /*
  32168. ** Truncate an open file to a specified size
  32169. */
  32170. static int unixTruncate(sqlite3_file *id, i64 nByte){
  32171. unixFile *pFile = (unixFile *)id;
  32172. int rc;
  32173. assert( pFile );
  32174. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  32175. /* If the user has configured a chunk-size for this file, truncate the
  32176. ** file so that it consists of an integer number of chunks (i.e. the
  32177. ** actual file size after the operation may be larger than the requested
  32178. ** size).
  32179. */
  32180. if( pFile->szChunk>0 ){
  32181. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  32182. }
  32183. rc = robust_ftruncate(pFile->h, nByte);
  32184. if( rc ){
  32185. storeLastErrno(pFile, errno);
  32186. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  32187. }else{
  32188. #ifdef SQLITE_DEBUG
  32189. /* If we are doing a normal write to a database file (as opposed to
  32190. ** doing a hot-journal rollback or a write to some file other than a
  32191. ** normal database file) and we truncate the file to zero length,
  32192. ** that effectively updates the change counter. This might happen
  32193. ** when restoring a database using the backup API from a zero-length
  32194. ** source.
  32195. */
  32196. if( pFile->inNormalWrite && nByte==0 ){
  32197. pFile->transCntrChng = 1;
  32198. }
  32199. #endif
  32200. #if SQLITE_MAX_MMAP_SIZE>0
  32201. /* If the file was just truncated to a size smaller than the currently
  32202. ** mapped region, reduce the effective mapping size as well. SQLite will
  32203. ** use read() and write() to access data beyond this point from now on.
  32204. */
  32205. if( nByte<pFile->mmapSize ){
  32206. pFile->mmapSize = nByte;
  32207. }
  32208. #endif
  32209. return SQLITE_OK;
  32210. }
  32211. }
  32212. /*
  32213. ** Determine the current size of a file in bytes
  32214. */
  32215. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  32216. int rc;
  32217. struct stat buf;
  32218. assert( id );
  32219. rc = osFstat(((unixFile*)id)->h, &buf);
  32220. SimulateIOError( rc=1 );
  32221. if( rc!=0 ){
  32222. storeLastErrno((unixFile*)id, errno);
  32223. return SQLITE_IOERR_FSTAT;
  32224. }
  32225. *pSize = buf.st_size;
  32226. /* When opening a zero-size database, the findInodeInfo() procedure
  32227. ** writes a single byte into that file in order to work around a bug
  32228. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  32229. ** layers, we need to report this file size as zero even though it is
  32230. ** really 1. Ticket #3260.
  32231. */
  32232. if( *pSize==1 ) *pSize = 0;
  32233. return SQLITE_OK;
  32234. }
  32235. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32236. /*
  32237. ** Handler for proxy-locking file-control verbs. Defined below in the
  32238. ** proxying locking division.
  32239. */
  32240. static int proxyFileControl(sqlite3_file*,int,void*);
  32241. #endif
  32242. /*
  32243. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  32244. ** file-control operation. Enlarge the database to nBytes in size
  32245. ** (rounded up to the next chunk-size). If the database is already
  32246. ** nBytes or larger, this routine is a no-op.
  32247. */
  32248. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  32249. if( pFile->szChunk>0 ){
  32250. i64 nSize; /* Required file size */
  32251. struct stat buf; /* Used to hold return values of fstat() */
  32252. if( osFstat(pFile->h, &buf) ){
  32253. return SQLITE_IOERR_FSTAT;
  32254. }
  32255. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  32256. if( nSize>(i64)buf.st_size ){
  32257. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  32258. /* The code below is handling the return value of osFallocate()
  32259. ** correctly. posix_fallocate() is defined to "returns zero on success,
  32260. ** or an error number on failure". See the manpage for details. */
  32261. int err;
  32262. do{
  32263. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  32264. }while( err==EINTR );
  32265. if( err ) return SQLITE_IOERR_WRITE;
  32266. #else
  32267. /* If the OS does not have posix_fallocate(), fake it. Write a
  32268. ** single byte to the last byte in each block that falls entirely
  32269. ** within the extended region. Then, if required, a single byte
  32270. ** at offset (nSize-1), to set the size of the file correctly.
  32271. ** This is a similar technique to that used by glibc on systems
  32272. ** that do not have a real fallocate() call.
  32273. */
  32274. int nBlk = buf.st_blksize; /* File-system block size */
  32275. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  32276. i64 iWrite; /* Next offset to write to */
  32277. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  32278. assert( iWrite>=buf.st_size );
  32279. assert( ((iWrite+1)%nBlk)==0 );
  32280. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  32281. if( iWrite>=nSize ) iWrite = nSize - 1;
  32282. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  32283. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  32284. }
  32285. #endif
  32286. }
  32287. }
  32288. #if SQLITE_MAX_MMAP_SIZE>0
  32289. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  32290. int rc;
  32291. if( pFile->szChunk<=0 ){
  32292. if( robust_ftruncate(pFile->h, nByte) ){
  32293. storeLastErrno(pFile, errno);
  32294. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  32295. }
  32296. }
  32297. rc = unixMapfile(pFile, nByte);
  32298. return rc;
  32299. }
  32300. #endif
  32301. return SQLITE_OK;
  32302. }
  32303. /*
  32304. ** If *pArg is initially negative then this is a query. Set *pArg to
  32305. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  32306. **
  32307. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  32308. */
  32309. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  32310. if( *pArg<0 ){
  32311. *pArg = (pFile->ctrlFlags & mask)!=0;
  32312. }else if( (*pArg)==0 ){
  32313. pFile->ctrlFlags &= ~mask;
  32314. }else{
  32315. pFile->ctrlFlags |= mask;
  32316. }
  32317. }
  32318. /* Forward declaration */
  32319. static int unixGetTempname(int nBuf, char *zBuf);
  32320. /*
  32321. ** Information and control of an open file handle.
  32322. */
  32323. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  32324. unixFile *pFile = (unixFile*)id;
  32325. switch( op ){
  32326. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  32327. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  32328. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  32329. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  32330. }
  32331. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  32332. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  32333. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  32334. }
  32335. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  32336. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  32337. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  32338. }
  32339. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  32340. case SQLITE_FCNTL_LOCKSTATE: {
  32341. *(int*)pArg = pFile->eFileLock;
  32342. return SQLITE_OK;
  32343. }
  32344. case SQLITE_FCNTL_LAST_ERRNO: {
  32345. *(int*)pArg = pFile->lastErrno;
  32346. return SQLITE_OK;
  32347. }
  32348. case SQLITE_FCNTL_CHUNK_SIZE: {
  32349. pFile->szChunk = *(int *)pArg;
  32350. return SQLITE_OK;
  32351. }
  32352. case SQLITE_FCNTL_SIZE_HINT: {
  32353. int rc;
  32354. SimulateIOErrorBenign(1);
  32355. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  32356. SimulateIOErrorBenign(0);
  32357. return rc;
  32358. }
  32359. case SQLITE_FCNTL_PERSIST_WAL: {
  32360. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  32361. return SQLITE_OK;
  32362. }
  32363. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  32364. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  32365. return SQLITE_OK;
  32366. }
  32367. case SQLITE_FCNTL_VFSNAME: {
  32368. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  32369. return SQLITE_OK;
  32370. }
  32371. case SQLITE_FCNTL_TEMPFILENAME: {
  32372. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  32373. if( zTFile ){
  32374. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  32375. *(char**)pArg = zTFile;
  32376. }
  32377. return SQLITE_OK;
  32378. }
  32379. case SQLITE_FCNTL_HAS_MOVED: {
  32380. *(int*)pArg = fileHasMoved(pFile);
  32381. return SQLITE_OK;
  32382. }
  32383. #if SQLITE_MAX_MMAP_SIZE>0
  32384. case SQLITE_FCNTL_MMAP_SIZE: {
  32385. i64 newLimit = *(i64*)pArg;
  32386. int rc = SQLITE_OK;
  32387. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  32388. newLimit = sqlite3GlobalConfig.mxMmap;
  32389. }
  32390. /* The value of newLimit may be eventually cast to (size_t) and passed
  32391. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  32392. ** 64-bit type. */
  32393. if( newLimit>0 && sizeof(size_t)<8 ){
  32394. newLimit = (newLimit & 0x7FFFFFFF);
  32395. }
  32396. *(i64*)pArg = pFile->mmapSizeMax;
  32397. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  32398. pFile->mmapSizeMax = newLimit;
  32399. if( pFile->mmapSize>0 ){
  32400. unixUnmapfile(pFile);
  32401. rc = unixMapfile(pFile, -1);
  32402. }
  32403. }
  32404. return rc;
  32405. }
  32406. #endif
  32407. #ifdef SQLITE_DEBUG
  32408. /* The pager calls this method to signal that it has done
  32409. ** a rollback and that the database is therefore unchanged and
  32410. ** it hence it is OK for the transaction change counter to be
  32411. ** unchanged.
  32412. */
  32413. case SQLITE_FCNTL_DB_UNCHANGED: {
  32414. ((unixFile*)id)->dbUpdate = 0;
  32415. return SQLITE_OK;
  32416. }
  32417. #endif
  32418. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32419. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  32420. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  32421. return proxyFileControl(id,op,pArg);
  32422. }
  32423. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  32424. }
  32425. return SQLITE_NOTFOUND;
  32426. }
  32427. /*
  32428. ** If pFd->sectorSize is non-zero when this function is called, it is a
  32429. ** no-op. Otherwise, the values of pFd->sectorSize and
  32430. ** pFd->deviceCharacteristics are set according to the file-system
  32431. ** characteristics.
  32432. **
  32433. ** There are two versions of this function. One for QNX and one for all
  32434. ** other systems.
  32435. */
  32436. #ifndef __QNXNTO__
  32437. static void setDeviceCharacteristics(unixFile *pFd){
  32438. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  32439. if( pFd->sectorSize==0 ){
  32440. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  32441. int res;
  32442. u32 f = 0;
  32443. /* Check for support for F2FS atomic batch writes. */
  32444. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  32445. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  32446. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  32447. }
  32448. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  32449. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  32450. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  32451. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  32452. }
  32453. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  32454. }
  32455. }
  32456. #else
  32457. #include <sys/dcmd_blk.h>
  32458. #include <sys/statvfs.h>
  32459. static void setDeviceCharacteristics(unixFile *pFile){
  32460. if( pFile->sectorSize == 0 ){
  32461. struct statvfs fsInfo;
  32462. /* Set defaults for non-supported filesystems */
  32463. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  32464. pFile->deviceCharacteristics = 0;
  32465. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  32466. return pFile->sectorSize;
  32467. }
  32468. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  32469. pFile->sectorSize = fsInfo.f_bsize;
  32470. pFile->deviceCharacteristics =
  32471. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  32472. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  32473. ** the write succeeds */
  32474. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  32475. ** so it is ordered */
  32476. 0;
  32477. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  32478. pFile->sectorSize = fsInfo.f_bsize;
  32479. pFile->deviceCharacteristics =
  32480. /* etfs cluster size writes are atomic */
  32481. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  32482. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  32483. ** the write succeeds */
  32484. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  32485. ** so it is ordered */
  32486. 0;
  32487. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  32488. pFile->sectorSize = fsInfo.f_bsize;
  32489. pFile->deviceCharacteristics =
  32490. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  32491. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  32492. ** the write succeeds */
  32493. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  32494. ** so it is ordered */
  32495. 0;
  32496. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  32497. pFile->sectorSize = fsInfo.f_bsize;
  32498. pFile->deviceCharacteristics =
  32499. /* full bitset of atomics from max sector size and smaller */
  32500. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  32501. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  32502. ** so it is ordered */
  32503. 0;
  32504. }else if( strstr(fsInfo.f_basetype, "dos") ){
  32505. pFile->sectorSize = fsInfo.f_bsize;
  32506. pFile->deviceCharacteristics =
  32507. /* full bitset of atomics from max sector size and smaller */
  32508. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  32509. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  32510. ** so it is ordered */
  32511. 0;
  32512. }else{
  32513. pFile->deviceCharacteristics =
  32514. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  32515. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  32516. ** the write succeeds */
  32517. 0;
  32518. }
  32519. }
  32520. /* Last chance verification. If the sector size isn't a multiple of 512
  32521. ** then it isn't valid.*/
  32522. if( pFile->sectorSize % 512 != 0 ){
  32523. pFile->deviceCharacteristics = 0;
  32524. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  32525. }
  32526. }
  32527. #endif
  32528. /*
  32529. ** Return the sector size in bytes of the underlying block device for
  32530. ** the specified file. This is almost always 512 bytes, but may be
  32531. ** larger for some devices.
  32532. **
  32533. ** SQLite code assumes this function cannot fail. It also assumes that
  32534. ** if two files are created in the same file-system directory (i.e.
  32535. ** a database and its journal file) that the sector size will be the
  32536. ** same for both.
  32537. */
  32538. static int unixSectorSize(sqlite3_file *id){
  32539. unixFile *pFd = (unixFile*)id;
  32540. setDeviceCharacteristics(pFd);
  32541. return pFd->sectorSize;
  32542. }
  32543. /*
  32544. ** Return the device characteristics for the file.
  32545. **
  32546. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  32547. ** However, that choice is controversial since technically the underlying
  32548. ** file system does not always provide powersafe overwrites. (In other
  32549. ** words, after a power-loss event, parts of the file that were never
  32550. ** written might end up being altered.) However, non-PSOW behavior is very,
  32551. ** very rare. And asserting PSOW makes a large reduction in the amount
  32552. ** of required I/O for journaling, since a lot of padding is eliminated.
  32553. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  32554. ** available to turn it off and URI query parameter available to turn it off.
  32555. */
  32556. static int unixDeviceCharacteristics(sqlite3_file *id){
  32557. unixFile *pFd = (unixFile*)id;
  32558. setDeviceCharacteristics(pFd);
  32559. return pFd->deviceCharacteristics;
  32560. }
  32561. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32562. /*
  32563. ** Return the system page size.
  32564. **
  32565. ** This function should not be called directly by other code in this file.
  32566. ** Instead, it should be called via macro osGetpagesize().
  32567. */
  32568. static int unixGetpagesize(void){
  32569. #if OS_VXWORKS
  32570. return 1024;
  32571. #elif defined(_BSD_SOURCE)
  32572. return getpagesize();
  32573. #else
  32574. return (int)sysconf(_SC_PAGESIZE);
  32575. #endif
  32576. }
  32577. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  32578. #ifndef SQLITE_OMIT_WAL
  32579. /*
  32580. ** Object used to represent an shared memory buffer.
  32581. **
  32582. ** When multiple threads all reference the same wal-index, each thread
  32583. ** has its own unixShm object, but they all point to a single instance
  32584. ** of this unixShmNode object. In other words, each wal-index is opened
  32585. ** only once per process.
  32586. **
  32587. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  32588. ** We could coalesce this object into unixInodeInfo, but that would mean
  32589. ** every open file that does not use shared memory (in other words, most
  32590. ** open files) would have to carry around this extra information. So
  32591. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  32592. ** and the unixShmNode object is created only when needed.
  32593. **
  32594. ** unixMutexHeld() must be true when creating or destroying
  32595. ** this object or while reading or writing the following fields:
  32596. **
  32597. ** nRef
  32598. **
  32599. ** The following fields are read-only after the object is created:
  32600. **
  32601. ** fid
  32602. ** zFilename
  32603. **
  32604. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  32605. ** unixMutexHeld() is true when reading or writing any other field
  32606. ** in this structure.
  32607. */
  32608. struct unixShmNode {
  32609. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  32610. sqlite3_mutex *mutex; /* Mutex to access this object */
  32611. char *zFilename; /* Name of the mmapped file */
  32612. int h; /* Open file descriptor */
  32613. int szRegion; /* Size of shared-memory regions */
  32614. u16 nRegion; /* Size of array apRegion */
  32615. u8 isReadonly; /* True if read-only */
  32616. char **apRegion; /* Array of mapped shared-memory regions */
  32617. int nRef; /* Number of unixShm objects pointing to this */
  32618. unixShm *pFirst; /* All unixShm objects pointing to this */
  32619. #ifdef SQLITE_DEBUG
  32620. u8 exclMask; /* Mask of exclusive locks held */
  32621. u8 sharedMask; /* Mask of shared locks held */
  32622. u8 nextShmId; /* Next available unixShm.id value */
  32623. #endif
  32624. };
  32625. /*
  32626. ** Structure used internally by this VFS to record the state of an
  32627. ** open shared memory connection.
  32628. **
  32629. ** The following fields are initialized when this object is created and
  32630. ** are read-only thereafter:
  32631. **
  32632. ** unixShm.pFile
  32633. ** unixShm.id
  32634. **
  32635. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  32636. ** while accessing any read/write fields.
  32637. */
  32638. struct unixShm {
  32639. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  32640. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  32641. u8 hasMutex; /* True if holding the unixShmNode mutex */
  32642. u8 id; /* Id of this connection within its unixShmNode */
  32643. u16 sharedMask; /* Mask of shared locks held */
  32644. u16 exclMask; /* Mask of exclusive locks held */
  32645. };
  32646. /*
  32647. ** Constants used for locking
  32648. */
  32649. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  32650. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  32651. /*
  32652. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  32653. **
  32654. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  32655. ** otherwise.
  32656. */
  32657. static int unixShmSystemLock(
  32658. unixFile *pFile, /* Open connection to the WAL file */
  32659. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  32660. int ofst, /* First byte of the locking range */
  32661. int n /* Number of bytes to lock */
  32662. ){
  32663. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  32664. struct flock f; /* The posix advisory locking structure */
  32665. int rc = SQLITE_OK; /* Result code form fcntl() */
  32666. /* Access to the unixShmNode object is serialized by the caller */
  32667. pShmNode = pFile->pInode->pShmNode;
  32668. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  32669. /* Shared locks never span more than one byte */
  32670. assert( n==1 || lockType!=F_RDLCK );
  32671. /* Locks are within range */
  32672. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  32673. if( pShmNode->h>=0 ){
  32674. /* Initialize the locking parameters */
  32675. memset(&f, 0, sizeof(f));
  32676. f.l_type = lockType;
  32677. f.l_whence = SEEK_SET;
  32678. f.l_start = ofst;
  32679. f.l_len = n;
  32680. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  32681. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  32682. }
  32683. /* Update the global lock state and do debug tracing */
  32684. #ifdef SQLITE_DEBUG
  32685. { u16 mask;
  32686. OSTRACE(("SHM-LOCK "));
  32687. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  32688. if( rc==SQLITE_OK ){
  32689. if( lockType==F_UNLCK ){
  32690. OSTRACE(("unlock %d ok", ofst));
  32691. pShmNode->exclMask &= ~mask;
  32692. pShmNode->sharedMask &= ~mask;
  32693. }else if( lockType==F_RDLCK ){
  32694. OSTRACE(("read-lock %d ok", ofst));
  32695. pShmNode->exclMask &= ~mask;
  32696. pShmNode->sharedMask |= mask;
  32697. }else{
  32698. assert( lockType==F_WRLCK );
  32699. OSTRACE(("write-lock %d ok", ofst));
  32700. pShmNode->exclMask |= mask;
  32701. pShmNode->sharedMask &= ~mask;
  32702. }
  32703. }else{
  32704. if( lockType==F_UNLCK ){
  32705. OSTRACE(("unlock %d failed", ofst));
  32706. }else if( lockType==F_RDLCK ){
  32707. OSTRACE(("read-lock failed"));
  32708. }else{
  32709. assert( lockType==F_WRLCK );
  32710. OSTRACE(("write-lock %d failed", ofst));
  32711. }
  32712. }
  32713. OSTRACE((" - afterwards %03x,%03x\n",
  32714. pShmNode->sharedMask, pShmNode->exclMask));
  32715. }
  32716. #endif
  32717. return rc;
  32718. }
  32719. /*
  32720. ** Return the minimum number of 32KB shm regions that should be mapped at
  32721. ** a time, assuming that each mapping must be an integer multiple of the
  32722. ** current system page-size.
  32723. **
  32724. ** Usually, this is 1. The exception seems to be systems that are configured
  32725. ** to use 64KB pages - in this case each mapping must cover at least two
  32726. ** shm regions.
  32727. */
  32728. static int unixShmRegionPerMap(void){
  32729. int shmsz = 32*1024; /* SHM region size */
  32730. int pgsz = osGetpagesize(); /* System page size */
  32731. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  32732. if( pgsz<shmsz ) return 1;
  32733. return pgsz/shmsz;
  32734. }
  32735. /*
  32736. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  32737. **
  32738. ** This is not a VFS shared-memory method; it is a utility function called
  32739. ** by VFS shared-memory methods.
  32740. */
  32741. static void unixShmPurge(unixFile *pFd){
  32742. unixShmNode *p = pFd->pInode->pShmNode;
  32743. assert( unixMutexHeld() );
  32744. if( p && ALWAYS(p->nRef==0) ){
  32745. int nShmPerMap = unixShmRegionPerMap();
  32746. int i;
  32747. assert( p->pInode==pFd->pInode );
  32748. sqlite3_mutex_free(p->mutex);
  32749. for(i=0; i<p->nRegion; i+=nShmPerMap){
  32750. if( p->h>=0 ){
  32751. osMunmap(p->apRegion[i], p->szRegion);
  32752. }else{
  32753. sqlite3_free(p->apRegion[i]);
  32754. }
  32755. }
  32756. sqlite3_free(p->apRegion);
  32757. if( p->h>=0 ){
  32758. robust_close(pFd, p->h, __LINE__);
  32759. p->h = -1;
  32760. }
  32761. p->pInode->pShmNode = 0;
  32762. sqlite3_free(p);
  32763. }
  32764. }
  32765. /*
  32766. ** Open a shared-memory area associated with open database file pDbFd.
  32767. ** This particular implementation uses mmapped files.
  32768. **
  32769. ** The file used to implement shared-memory is in the same directory
  32770. ** as the open database file and has the same name as the open database
  32771. ** file with the "-shm" suffix added. For example, if the database file
  32772. ** is "/home/user1/config.db" then the file that is created and mmapped
  32773. ** for shared memory will be called "/home/user1/config.db-shm".
  32774. **
  32775. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  32776. ** some other tmpfs mount. But if a file in a different directory
  32777. ** from the database file is used, then differing access permissions
  32778. ** or a chroot() might cause two different processes on the same
  32779. ** database to end up using different files for shared memory -
  32780. ** meaning that their memory would not really be shared - resulting
  32781. ** in database corruption. Nevertheless, this tmpfs file usage
  32782. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  32783. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  32784. ** option results in an incompatible build of SQLite; builds of SQLite
  32785. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  32786. ** same database file at the same time, database corruption will likely
  32787. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  32788. ** "unsupported" and may go away in a future SQLite release.
  32789. **
  32790. ** When opening a new shared-memory file, if no other instances of that
  32791. ** file are currently open, in this process or in other processes, then
  32792. ** the file must be truncated to zero length or have its header cleared.
  32793. **
  32794. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  32795. ** that means that an exclusive lock is held on the database file and
  32796. ** that no other processes are able to read or write the database. In
  32797. ** that case, we do not really need shared memory. No shared memory
  32798. ** file is created. The shared memory will be simulated with heap memory.
  32799. */
  32800. static int unixOpenSharedMemory(unixFile *pDbFd){
  32801. struct unixShm *p = 0; /* The connection to be opened */
  32802. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  32803. int rc; /* Result code */
  32804. unixInodeInfo *pInode; /* The inode of fd */
  32805. char *zShmFilename; /* Name of the file used for SHM */
  32806. int nShmFilename; /* Size of the SHM filename in bytes */
  32807. /* Allocate space for the new unixShm object. */
  32808. p = sqlite3_malloc64( sizeof(*p) );
  32809. if( p==0 ) return SQLITE_NOMEM_BKPT;
  32810. memset(p, 0, sizeof(*p));
  32811. assert( pDbFd->pShm==0 );
  32812. /* Check to see if a unixShmNode object already exists. Reuse an existing
  32813. ** one if present. Create a new one if necessary.
  32814. */
  32815. unixEnterMutex();
  32816. pInode = pDbFd->pInode;
  32817. pShmNode = pInode->pShmNode;
  32818. if( pShmNode==0 ){
  32819. struct stat sStat; /* fstat() info for database file */
  32820. #ifndef SQLITE_SHM_DIRECTORY
  32821. const char *zBasePath = pDbFd->zPath;
  32822. #endif
  32823. /* Call fstat() to figure out the permissions on the database file. If
  32824. ** a new *-shm file is created, an attempt will be made to create it
  32825. ** with the same permissions.
  32826. */
  32827. if( osFstat(pDbFd->h, &sStat) ){
  32828. rc = SQLITE_IOERR_FSTAT;
  32829. goto shm_open_err;
  32830. }
  32831. #ifdef SQLITE_SHM_DIRECTORY
  32832. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  32833. #else
  32834. nShmFilename = 6 + (int)strlen(zBasePath);
  32835. #endif
  32836. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  32837. if( pShmNode==0 ){
  32838. rc = SQLITE_NOMEM_BKPT;
  32839. goto shm_open_err;
  32840. }
  32841. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  32842. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  32843. #ifdef SQLITE_SHM_DIRECTORY
  32844. sqlite3_snprintf(nShmFilename, zShmFilename,
  32845. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  32846. (u32)sStat.st_ino, (u32)sStat.st_dev);
  32847. #else
  32848. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  32849. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  32850. #endif
  32851. pShmNode->h = -1;
  32852. pDbFd->pInode->pShmNode = pShmNode;
  32853. pShmNode->pInode = pDbFd->pInode;
  32854. if( sqlite3GlobalConfig.bCoreMutex ){
  32855. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32856. if( pShmNode->mutex==0 ){
  32857. rc = SQLITE_NOMEM_BKPT;
  32858. goto shm_open_err;
  32859. }
  32860. }
  32861. if( pInode->bProcessLock==0 ){
  32862. int openFlags = O_RDWR | O_CREAT;
  32863. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  32864. openFlags = O_RDONLY;
  32865. pShmNode->isReadonly = 1;
  32866. }
  32867. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  32868. if( pShmNode->h<0 ){
  32869. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  32870. goto shm_open_err;
  32871. }
  32872. /* If this process is running as root, make sure that the SHM file
  32873. ** is owned by the same user that owns the original database. Otherwise,
  32874. ** the original owner will not be able to connect.
  32875. */
  32876. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  32877. /* Check to see if another process is holding the dead-man switch.
  32878. ** If not, truncate the file to zero length.
  32879. */
  32880. rc = SQLITE_OK;
  32881. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  32882. if( robust_ftruncate(pShmNode->h, 0) ){
  32883. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  32884. }
  32885. }
  32886. if( rc==SQLITE_OK ){
  32887. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  32888. }
  32889. if( rc ) goto shm_open_err;
  32890. }
  32891. }
  32892. /* Make the new connection a child of the unixShmNode */
  32893. p->pShmNode = pShmNode;
  32894. #ifdef SQLITE_DEBUG
  32895. p->id = pShmNode->nextShmId++;
  32896. #endif
  32897. pShmNode->nRef++;
  32898. pDbFd->pShm = p;
  32899. unixLeaveMutex();
  32900. /* The reference count on pShmNode has already been incremented under
  32901. ** the cover of the unixEnterMutex() mutex and the pointer from the
  32902. ** new (struct unixShm) object to the pShmNode has been set. All that is
  32903. ** left to do is to link the new object into the linked list starting
  32904. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  32905. ** mutex.
  32906. */
  32907. sqlite3_mutex_enter(pShmNode->mutex);
  32908. p->pNext = pShmNode->pFirst;
  32909. pShmNode->pFirst = p;
  32910. sqlite3_mutex_leave(pShmNode->mutex);
  32911. return SQLITE_OK;
  32912. /* Jump here on any error */
  32913. shm_open_err:
  32914. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  32915. sqlite3_free(p);
  32916. unixLeaveMutex();
  32917. return rc;
  32918. }
  32919. /*
  32920. ** This function is called to obtain a pointer to region iRegion of the
  32921. ** shared-memory associated with the database file fd. Shared-memory regions
  32922. ** are numbered starting from zero. Each shared-memory region is szRegion
  32923. ** bytes in size.
  32924. **
  32925. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32926. **
  32927. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  32928. ** region has not been allocated (by any client, including one running in a
  32929. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32930. ** bExtend is non-zero and the requested shared-memory region has not yet
  32931. ** been allocated, it is allocated by this function.
  32932. **
  32933. ** If the shared-memory region has already been allocated or is allocated by
  32934. ** this call as described above, then it is mapped into this processes
  32935. ** address space (if it is not already), *pp is set to point to the mapped
  32936. ** memory and SQLITE_OK returned.
  32937. */
  32938. static int unixShmMap(
  32939. sqlite3_file *fd, /* Handle open on database file */
  32940. int iRegion, /* Region to retrieve */
  32941. int szRegion, /* Size of regions */
  32942. int bExtend, /* True to extend file if necessary */
  32943. void volatile **pp /* OUT: Mapped memory */
  32944. ){
  32945. unixFile *pDbFd = (unixFile*)fd;
  32946. unixShm *p;
  32947. unixShmNode *pShmNode;
  32948. int rc = SQLITE_OK;
  32949. int nShmPerMap = unixShmRegionPerMap();
  32950. int nReqRegion;
  32951. /* If the shared-memory file has not yet been opened, open it now. */
  32952. if( pDbFd->pShm==0 ){
  32953. rc = unixOpenSharedMemory(pDbFd);
  32954. if( rc!=SQLITE_OK ) return rc;
  32955. }
  32956. p = pDbFd->pShm;
  32957. pShmNode = p->pShmNode;
  32958. sqlite3_mutex_enter(pShmNode->mutex);
  32959. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32960. assert( pShmNode->pInode==pDbFd->pInode );
  32961. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  32962. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  32963. /* Minimum number of regions required to be mapped. */
  32964. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  32965. if( pShmNode->nRegion<nReqRegion ){
  32966. char **apNew; /* New apRegion[] array */
  32967. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  32968. struct stat sStat; /* Used by fstat() */
  32969. pShmNode->szRegion = szRegion;
  32970. if( pShmNode->h>=0 ){
  32971. /* The requested region is not mapped into this processes address space.
  32972. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32973. ** large enough to contain the requested region).
  32974. */
  32975. if( osFstat(pShmNode->h, &sStat) ){
  32976. rc = SQLITE_IOERR_SHMSIZE;
  32977. goto shmpage_out;
  32978. }
  32979. if( sStat.st_size<nByte ){
  32980. /* The requested memory region does not exist. If bExtend is set to
  32981. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32982. */
  32983. if( !bExtend ){
  32984. goto shmpage_out;
  32985. }
  32986. /* Alternatively, if bExtend is true, extend the file. Do this by
  32987. ** writing a single byte to the end of each (OS) page being
  32988. ** allocated or extended. Technically, we need only write to the
  32989. ** last page in order to extend the file. But writing to all new
  32990. ** pages forces the OS to allocate them immediately, which reduces
  32991. ** the chances of SIGBUS while accessing the mapped region later on.
  32992. */
  32993. else{
  32994. static const int pgsz = 4096;
  32995. int iPg;
  32996. /* Write to the last byte of each newly allocated or extended page */
  32997. assert( (nByte % pgsz)==0 );
  32998. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  32999. int x = 0;
  33000. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  33001. const char *zFile = pShmNode->zFilename;
  33002. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  33003. goto shmpage_out;
  33004. }
  33005. }
  33006. }
  33007. }
  33008. }
  33009. /* Map the requested memory region into this processes address space. */
  33010. apNew = (char **)sqlite3_realloc(
  33011. pShmNode->apRegion, nReqRegion*sizeof(char *)
  33012. );
  33013. if( !apNew ){
  33014. rc = SQLITE_IOERR_NOMEM_BKPT;
  33015. goto shmpage_out;
  33016. }
  33017. pShmNode->apRegion = apNew;
  33018. while( pShmNode->nRegion<nReqRegion ){
  33019. int nMap = szRegion*nShmPerMap;
  33020. int i;
  33021. void *pMem;
  33022. if( pShmNode->h>=0 ){
  33023. pMem = osMmap(0, nMap,
  33024. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  33025. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  33026. );
  33027. if( pMem==MAP_FAILED ){
  33028. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  33029. goto shmpage_out;
  33030. }
  33031. }else{
  33032. pMem = sqlite3_malloc64(szRegion);
  33033. if( pMem==0 ){
  33034. rc = SQLITE_NOMEM_BKPT;
  33035. goto shmpage_out;
  33036. }
  33037. memset(pMem, 0, szRegion);
  33038. }
  33039. for(i=0; i<nShmPerMap; i++){
  33040. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  33041. }
  33042. pShmNode->nRegion += nShmPerMap;
  33043. }
  33044. }
  33045. shmpage_out:
  33046. if( pShmNode->nRegion>iRegion ){
  33047. *pp = pShmNode->apRegion[iRegion];
  33048. }else{
  33049. *pp = 0;
  33050. }
  33051. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  33052. sqlite3_mutex_leave(pShmNode->mutex);
  33053. return rc;
  33054. }
  33055. /*
  33056. ** Change the lock state for a shared-memory segment.
  33057. **
  33058. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  33059. ** different here than in posix. In xShmLock(), one can go from unlocked
  33060. ** to shared and back or from unlocked to exclusive and back. But one may
  33061. ** not go from shared to exclusive or from exclusive to shared.
  33062. */
  33063. static int unixShmLock(
  33064. sqlite3_file *fd, /* Database file holding the shared memory */
  33065. int ofst, /* First lock to acquire or release */
  33066. int n, /* Number of locks to acquire or release */
  33067. int flags /* What to do with the lock */
  33068. ){
  33069. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  33070. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  33071. unixShm *pX; /* For looping over all siblings */
  33072. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  33073. int rc = SQLITE_OK; /* Result code */
  33074. u16 mask; /* Mask of locks to take or release */
  33075. assert( pShmNode==pDbFd->pInode->pShmNode );
  33076. assert( pShmNode->pInode==pDbFd->pInode );
  33077. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  33078. assert( n>=1 );
  33079. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  33080. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  33081. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  33082. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  33083. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  33084. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  33085. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  33086. mask = (1<<(ofst+n)) - (1<<ofst);
  33087. assert( n>1 || mask==(1<<ofst) );
  33088. sqlite3_mutex_enter(pShmNode->mutex);
  33089. if( flags & SQLITE_SHM_UNLOCK ){
  33090. u16 allMask = 0; /* Mask of locks held by siblings */
  33091. /* See if any siblings hold this same lock */
  33092. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33093. if( pX==p ) continue;
  33094. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  33095. allMask |= pX->sharedMask;
  33096. }
  33097. /* Unlock the system-level locks */
  33098. if( (mask & allMask)==0 ){
  33099. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  33100. }else{
  33101. rc = SQLITE_OK;
  33102. }
  33103. /* Undo the local locks */
  33104. if( rc==SQLITE_OK ){
  33105. p->exclMask &= ~mask;
  33106. p->sharedMask &= ~mask;
  33107. }
  33108. }else if( flags & SQLITE_SHM_SHARED ){
  33109. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  33110. /* Find out which shared locks are already held by sibling connections.
  33111. ** If any sibling already holds an exclusive lock, go ahead and return
  33112. ** SQLITE_BUSY.
  33113. */
  33114. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33115. if( (pX->exclMask & mask)!=0 ){
  33116. rc = SQLITE_BUSY;
  33117. break;
  33118. }
  33119. allShared |= pX->sharedMask;
  33120. }
  33121. /* Get shared locks at the system level, if necessary */
  33122. if( rc==SQLITE_OK ){
  33123. if( (allShared & mask)==0 ){
  33124. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  33125. }else{
  33126. rc = SQLITE_OK;
  33127. }
  33128. }
  33129. /* Get the local shared locks */
  33130. if( rc==SQLITE_OK ){
  33131. p->sharedMask |= mask;
  33132. }
  33133. }else{
  33134. /* Make sure no sibling connections hold locks that will block this
  33135. ** lock. If any do, return SQLITE_BUSY right away.
  33136. */
  33137. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33138. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  33139. rc = SQLITE_BUSY;
  33140. break;
  33141. }
  33142. }
  33143. /* Get the exclusive locks at the system level. Then if successful
  33144. ** also mark the local connection as being locked.
  33145. */
  33146. if( rc==SQLITE_OK ){
  33147. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  33148. if( rc==SQLITE_OK ){
  33149. assert( (p->sharedMask & mask)==0 );
  33150. p->exclMask |= mask;
  33151. }
  33152. }
  33153. }
  33154. sqlite3_mutex_leave(pShmNode->mutex);
  33155. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  33156. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  33157. return rc;
  33158. }
  33159. /*
  33160. ** Implement a memory barrier or memory fence on shared memory.
  33161. **
  33162. ** All loads and stores begun before the barrier must complete before
  33163. ** any load or store begun after the barrier.
  33164. */
  33165. static void unixShmBarrier(
  33166. sqlite3_file *fd /* Database file holding the shared memory */
  33167. ){
  33168. UNUSED_PARAMETER(fd);
  33169. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  33170. unixEnterMutex(); /* Also mutex, for redundancy */
  33171. unixLeaveMutex();
  33172. }
  33173. /*
  33174. ** Close a connection to shared-memory. Delete the underlying
  33175. ** storage if deleteFlag is true.
  33176. **
  33177. ** If there is no shared memory associated with the connection then this
  33178. ** routine is a harmless no-op.
  33179. */
  33180. static int unixShmUnmap(
  33181. sqlite3_file *fd, /* The underlying database file */
  33182. int deleteFlag /* Delete shared-memory if true */
  33183. ){
  33184. unixShm *p; /* The connection to be closed */
  33185. unixShmNode *pShmNode; /* The underlying shared-memory file */
  33186. unixShm **pp; /* For looping over sibling connections */
  33187. unixFile *pDbFd; /* The underlying database file */
  33188. pDbFd = (unixFile*)fd;
  33189. p = pDbFd->pShm;
  33190. if( p==0 ) return SQLITE_OK;
  33191. pShmNode = p->pShmNode;
  33192. assert( pShmNode==pDbFd->pInode->pShmNode );
  33193. assert( pShmNode->pInode==pDbFd->pInode );
  33194. /* Remove connection p from the set of connections associated
  33195. ** with pShmNode */
  33196. sqlite3_mutex_enter(pShmNode->mutex);
  33197. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  33198. *pp = p->pNext;
  33199. /* Free the connection p */
  33200. sqlite3_free(p);
  33201. pDbFd->pShm = 0;
  33202. sqlite3_mutex_leave(pShmNode->mutex);
  33203. /* If pShmNode->nRef has reached 0, then close the underlying
  33204. ** shared-memory file, too */
  33205. unixEnterMutex();
  33206. assert( pShmNode->nRef>0 );
  33207. pShmNode->nRef--;
  33208. if( pShmNode->nRef==0 ){
  33209. if( deleteFlag && pShmNode->h>=0 ){
  33210. osUnlink(pShmNode->zFilename);
  33211. }
  33212. unixShmPurge(pDbFd);
  33213. }
  33214. unixLeaveMutex();
  33215. return SQLITE_OK;
  33216. }
  33217. #else
  33218. # define unixShmMap 0
  33219. # define unixShmLock 0
  33220. # define unixShmBarrier 0
  33221. # define unixShmUnmap 0
  33222. #endif /* #ifndef SQLITE_OMIT_WAL */
  33223. #if SQLITE_MAX_MMAP_SIZE>0
  33224. /*
  33225. ** If it is currently memory mapped, unmap file pFd.
  33226. */
  33227. static void unixUnmapfile(unixFile *pFd){
  33228. assert( pFd->nFetchOut==0 );
  33229. if( pFd->pMapRegion ){
  33230. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  33231. pFd->pMapRegion = 0;
  33232. pFd->mmapSize = 0;
  33233. pFd->mmapSizeActual = 0;
  33234. }
  33235. }
  33236. /*
  33237. ** Attempt to set the size of the memory mapping maintained by file
  33238. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  33239. **
  33240. ** If successful, this function sets the following variables:
  33241. **
  33242. ** unixFile.pMapRegion
  33243. ** unixFile.mmapSize
  33244. ** unixFile.mmapSizeActual
  33245. **
  33246. ** If unsuccessful, an error message is logged via sqlite3_log() and
  33247. ** the three variables above are zeroed. In this case SQLite should
  33248. ** continue accessing the database using the xRead() and xWrite()
  33249. ** methods.
  33250. */
  33251. static void unixRemapfile(
  33252. unixFile *pFd, /* File descriptor object */
  33253. i64 nNew /* Required mapping size */
  33254. ){
  33255. const char *zErr = "mmap";
  33256. int h = pFd->h; /* File descriptor open on db file */
  33257. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  33258. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  33259. u8 *pNew = 0; /* Location of new mapping */
  33260. int flags = PROT_READ; /* Flags to pass to mmap() */
  33261. assert( pFd->nFetchOut==0 );
  33262. assert( nNew>pFd->mmapSize );
  33263. assert( nNew<=pFd->mmapSizeMax );
  33264. assert( nNew>0 );
  33265. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  33266. assert( MAP_FAILED!=0 );
  33267. #ifdef SQLITE_MMAP_READWRITE
  33268. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  33269. #endif
  33270. if( pOrig ){
  33271. #if HAVE_MREMAP
  33272. i64 nReuse = pFd->mmapSize;
  33273. #else
  33274. const int szSyspage = osGetpagesize();
  33275. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  33276. #endif
  33277. u8 *pReq = &pOrig[nReuse];
  33278. /* Unmap any pages of the existing mapping that cannot be reused. */
  33279. if( nReuse!=nOrig ){
  33280. osMunmap(pReq, nOrig-nReuse);
  33281. }
  33282. #if HAVE_MREMAP
  33283. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  33284. zErr = "mremap";
  33285. #else
  33286. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  33287. if( pNew!=MAP_FAILED ){
  33288. if( pNew!=pReq ){
  33289. osMunmap(pNew, nNew - nReuse);
  33290. pNew = 0;
  33291. }else{
  33292. pNew = pOrig;
  33293. }
  33294. }
  33295. #endif
  33296. /* The attempt to extend the existing mapping failed. Free it. */
  33297. if( pNew==MAP_FAILED || pNew==0 ){
  33298. osMunmap(pOrig, nReuse);
  33299. }
  33300. }
  33301. /* If pNew is still NULL, try to create an entirely new mapping. */
  33302. if( pNew==0 ){
  33303. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  33304. }
  33305. if( pNew==MAP_FAILED ){
  33306. pNew = 0;
  33307. nNew = 0;
  33308. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  33309. /* If the mmap() above failed, assume that all subsequent mmap() calls
  33310. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  33311. ** in this case. */
  33312. pFd->mmapSizeMax = 0;
  33313. }
  33314. pFd->pMapRegion = (void *)pNew;
  33315. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  33316. }
  33317. /*
  33318. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  33319. ** is already mapped, the existing mapping is replaced by the new). Or, if
  33320. ** there already exists a mapping for this file, and there are still
  33321. ** outstanding xFetch() references to it, this function is a no-op.
  33322. **
  33323. ** If parameter nByte is non-negative, then it is the requested size of
  33324. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  33325. ** requested size is the size of the file on disk. The actual size of the
  33326. ** created mapping is either the requested size or the value configured
  33327. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  33328. **
  33329. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  33330. ** recreated as a result of outstanding references) or an SQLite error
  33331. ** code otherwise.
  33332. */
  33333. static int unixMapfile(unixFile *pFd, i64 nMap){
  33334. assert( nMap>=0 || pFd->nFetchOut==0 );
  33335. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  33336. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  33337. if( nMap<0 ){
  33338. struct stat statbuf; /* Low-level file information */
  33339. if( osFstat(pFd->h, &statbuf) ){
  33340. return SQLITE_IOERR_FSTAT;
  33341. }
  33342. nMap = statbuf.st_size;
  33343. }
  33344. if( nMap>pFd->mmapSizeMax ){
  33345. nMap = pFd->mmapSizeMax;
  33346. }
  33347. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  33348. if( nMap!=pFd->mmapSize ){
  33349. unixRemapfile(pFd, nMap);
  33350. }
  33351. return SQLITE_OK;
  33352. }
  33353. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  33354. /*
  33355. ** If possible, return a pointer to a mapping of file fd starting at offset
  33356. ** iOff. The mapping must be valid for at least nAmt bytes.
  33357. **
  33358. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  33359. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  33360. ** Finally, if an error does occur, return an SQLite error code. The final
  33361. ** value of *pp is undefined in this case.
  33362. **
  33363. ** If this function does return a pointer, the caller must eventually
  33364. ** release the reference by calling unixUnfetch().
  33365. */
  33366. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  33367. #if SQLITE_MAX_MMAP_SIZE>0
  33368. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  33369. #endif
  33370. *pp = 0;
  33371. #if SQLITE_MAX_MMAP_SIZE>0
  33372. if( pFd->mmapSizeMax>0 ){
  33373. if( pFd->pMapRegion==0 ){
  33374. int rc = unixMapfile(pFd, -1);
  33375. if( rc!=SQLITE_OK ) return rc;
  33376. }
  33377. if( pFd->mmapSize >= iOff+nAmt ){
  33378. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  33379. pFd->nFetchOut++;
  33380. }
  33381. }
  33382. #endif
  33383. return SQLITE_OK;
  33384. }
  33385. /*
  33386. ** If the third argument is non-NULL, then this function releases a
  33387. ** reference obtained by an earlier call to unixFetch(). The second
  33388. ** argument passed to this function must be the same as the corresponding
  33389. ** argument that was passed to the unixFetch() invocation.
  33390. **
  33391. ** Or, if the third argument is NULL, then this function is being called
  33392. ** to inform the VFS layer that, according to POSIX, any existing mapping
  33393. ** may now be invalid and should be unmapped.
  33394. */
  33395. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  33396. #if SQLITE_MAX_MMAP_SIZE>0
  33397. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  33398. UNUSED_PARAMETER(iOff);
  33399. /* If p==0 (unmap the entire file) then there must be no outstanding
  33400. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  33401. ** then there must be at least one outstanding. */
  33402. assert( (p==0)==(pFd->nFetchOut==0) );
  33403. /* If p!=0, it must match the iOff value. */
  33404. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  33405. if( p ){
  33406. pFd->nFetchOut--;
  33407. }else{
  33408. unixUnmapfile(pFd);
  33409. }
  33410. assert( pFd->nFetchOut>=0 );
  33411. #else
  33412. UNUSED_PARAMETER(fd);
  33413. UNUSED_PARAMETER(p);
  33414. UNUSED_PARAMETER(iOff);
  33415. #endif
  33416. return SQLITE_OK;
  33417. }
  33418. /*
  33419. ** Here ends the implementation of all sqlite3_file methods.
  33420. **
  33421. ********************** End sqlite3_file Methods *******************************
  33422. ******************************************************************************/
  33423. /*
  33424. ** This division contains definitions of sqlite3_io_methods objects that
  33425. ** implement various file locking strategies. It also contains definitions
  33426. ** of "finder" functions. A finder-function is used to locate the appropriate
  33427. ** sqlite3_io_methods object for a particular database file. The pAppData
  33428. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  33429. ** the correct finder-function for that VFS.
  33430. **
  33431. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  33432. ** object. The only interesting finder-function is autolockIoFinder, which
  33433. ** looks at the filesystem type and tries to guess the best locking
  33434. ** strategy from that.
  33435. **
  33436. ** For finder-function F, two objects are created:
  33437. **
  33438. ** (1) The real finder-function named "FImpt()".
  33439. **
  33440. ** (2) A constant pointer to this function named just "F".
  33441. **
  33442. **
  33443. ** A pointer to the F pointer is used as the pAppData value for VFS
  33444. ** objects. We have to do this instead of letting pAppData point
  33445. ** directly at the finder-function since C90 rules prevent a void*
  33446. ** from be cast into a function pointer.
  33447. **
  33448. **
  33449. ** Each instance of this macro generates two objects:
  33450. **
  33451. ** * A constant sqlite3_io_methods object call METHOD that has locking
  33452. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  33453. **
  33454. ** * An I/O method finder function called FINDER that returns a pointer
  33455. ** to the METHOD object in the previous bullet.
  33456. */
  33457. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  33458. static const sqlite3_io_methods METHOD = { \
  33459. VERSION, /* iVersion */ \
  33460. CLOSE, /* xClose */ \
  33461. unixRead, /* xRead */ \
  33462. unixWrite, /* xWrite */ \
  33463. unixTruncate, /* xTruncate */ \
  33464. unixSync, /* xSync */ \
  33465. unixFileSize, /* xFileSize */ \
  33466. LOCK, /* xLock */ \
  33467. UNLOCK, /* xUnlock */ \
  33468. CKLOCK, /* xCheckReservedLock */ \
  33469. unixFileControl, /* xFileControl */ \
  33470. unixSectorSize, /* xSectorSize */ \
  33471. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  33472. SHMMAP, /* xShmMap */ \
  33473. unixShmLock, /* xShmLock */ \
  33474. unixShmBarrier, /* xShmBarrier */ \
  33475. unixShmUnmap, /* xShmUnmap */ \
  33476. unixFetch, /* xFetch */ \
  33477. unixUnfetch, /* xUnfetch */ \
  33478. }; \
  33479. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  33480. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  33481. return &METHOD; \
  33482. } \
  33483. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  33484. = FINDER##Impl;
  33485. /*
  33486. ** Here are all of the sqlite3_io_methods objects for each of the
  33487. ** locking strategies. Functions that return pointers to these methods
  33488. ** are also created.
  33489. */
  33490. IOMETHODS(
  33491. posixIoFinder, /* Finder function name */
  33492. posixIoMethods, /* sqlite3_io_methods object name */
  33493. 3, /* shared memory and mmap are enabled */
  33494. unixClose, /* xClose method */
  33495. unixLock, /* xLock method */
  33496. unixUnlock, /* xUnlock method */
  33497. unixCheckReservedLock, /* xCheckReservedLock method */
  33498. unixShmMap /* xShmMap method */
  33499. )
  33500. IOMETHODS(
  33501. nolockIoFinder, /* Finder function name */
  33502. nolockIoMethods, /* sqlite3_io_methods object name */
  33503. 3, /* shared memory is disabled */
  33504. nolockClose, /* xClose method */
  33505. nolockLock, /* xLock method */
  33506. nolockUnlock, /* xUnlock method */
  33507. nolockCheckReservedLock, /* xCheckReservedLock method */
  33508. 0 /* xShmMap method */
  33509. )
  33510. IOMETHODS(
  33511. dotlockIoFinder, /* Finder function name */
  33512. dotlockIoMethods, /* sqlite3_io_methods object name */
  33513. 1, /* shared memory is disabled */
  33514. dotlockClose, /* xClose method */
  33515. dotlockLock, /* xLock method */
  33516. dotlockUnlock, /* xUnlock method */
  33517. dotlockCheckReservedLock, /* xCheckReservedLock method */
  33518. 0 /* xShmMap method */
  33519. )
  33520. #if SQLITE_ENABLE_LOCKING_STYLE
  33521. IOMETHODS(
  33522. flockIoFinder, /* Finder function name */
  33523. flockIoMethods, /* sqlite3_io_methods object name */
  33524. 1, /* shared memory is disabled */
  33525. flockClose, /* xClose method */
  33526. flockLock, /* xLock method */
  33527. flockUnlock, /* xUnlock method */
  33528. flockCheckReservedLock, /* xCheckReservedLock method */
  33529. 0 /* xShmMap method */
  33530. )
  33531. #endif
  33532. #if OS_VXWORKS
  33533. IOMETHODS(
  33534. semIoFinder, /* Finder function name */
  33535. semIoMethods, /* sqlite3_io_methods object name */
  33536. 1, /* shared memory is disabled */
  33537. semXClose, /* xClose method */
  33538. semXLock, /* xLock method */
  33539. semXUnlock, /* xUnlock method */
  33540. semXCheckReservedLock, /* xCheckReservedLock method */
  33541. 0 /* xShmMap method */
  33542. )
  33543. #endif
  33544. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33545. IOMETHODS(
  33546. afpIoFinder, /* Finder function name */
  33547. afpIoMethods, /* sqlite3_io_methods object name */
  33548. 1, /* shared memory is disabled */
  33549. afpClose, /* xClose method */
  33550. afpLock, /* xLock method */
  33551. afpUnlock, /* xUnlock method */
  33552. afpCheckReservedLock, /* xCheckReservedLock method */
  33553. 0 /* xShmMap method */
  33554. )
  33555. #endif
  33556. /*
  33557. ** The proxy locking method is a "super-method" in the sense that it
  33558. ** opens secondary file descriptors for the conch and lock files and
  33559. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  33560. ** secondary files. For this reason, the division that implements
  33561. ** proxy locking is located much further down in the file. But we need
  33562. ** to go ahead and define the sqlite3_io_methods and finder function
  33563. ** for proxy locking here. So we forward declare the I/O methods.
  33564. */
  33565. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33566. static int proxyClose(sqlite3_file*);
  33567. static int proxyLock(sqlite3_file*, int);
  33568. static int proxyUnlock(sqlite3_file*, int);
  33569. static int proxyCheckReservedLock(sqlite3_file*, int*);
  33570. IOMETHODS(
  33571. proxyIoFinder, /* Finder function name */
  33572. proxyIoMethods, /* sqlite3_io_methods object name */
  33573. 1, /* shared memory is disabled */
  33574. proxyClose, /* xClose method */
  33575. proxyLock, /* xLock method */
  33576. proxyUnlock, /* xUnlock method */
  33577. proxyCheckReservedLock, /* xCheckReservedLock method */
  33578. 0 /* xShmMap method */
  33579. )
  33580. #endif
  33581. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  33582. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33583. IOMETHODS(
  33584. nfsIoFinder, /* Finder function name */
  33585. nfsIoMethods, /* sqlite3_io_methods object name */
  33586. 1, /* shared memory is disabled */
  33587. unixClose, /* xClose method */
  33588. unixLock, /* xLock method */
  33589. nfsUnlock, /* xUnlock method */
  33590. unixCheckReservedLock, /* xCheckReservedLock method */
  33591. 0 /* xShmMap method */
  33592. )
  33593. #endif
  33594. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33595. /*
  33596. ** This "finder" function attempts to determine the best locking strategy
  33597. ** for the database file "filePath". It then returns the sqlite3_io_methods
  33598. ** object that implements that strategy.
  33599. **
  33600. ** This is for MacOSX only.
  33601. */
  33602. static const sqlite3_io_methods *autolockIoFinderImpl(
  33603. const char *filePath, /* name of the database file */
  33604. unixFile *pNew /* open file object for the database file */
  33605. ){
  33606. static const struct Mapping {
  33607. const char *zFilesystem; /* Filesystem type name */
  33608. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  33609. } aMap[] = {
  33610. { "hfs", &posixIoMethods },
  33611. { "ufs", &posixIoMethods },
  33612. { "afpfs", &afpIoMethods },
  33613. { "smbfs", &afpIoMethods },
  33614. { "webdav", &nolockIoMethods },
  33615. { 0, 0 }
  33616. };
  33617. int i;
  33618. struct statfs fsInfo;
  33619. struct flock lockInfo;
  33620. if( !filePath ){
  33621. /* If filePath==NULL that means we are dealing with a transient file
  33622. ** that does not need to be locked. */
  33623. return &nolockIoMethods;
  33624. }
  33625. if( statfs(filePath, &fsInfo) != -1 ){
  33626. if( fsInfo.f_flags & MNT_RDONLY ){
  33627. return &nolockIoMethods;
  33628. }
  33629. for(i=0; aMap[i].zFilesystem; i++){
  33630. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  33631. return aMap[i].pMethods;
  33632. }
  33633. }
  33634. }
  33635. /* Default case. Handles, amongst others, "nfs".
  33636. ** Test byte-range lock using fcntl(). If the call succeeds,
  33637. ** assume that the file-system supports POSIX style locks.
  33638. */
  33639. lockInfo.l_len = 1;
  33640. lockInfo.l_start = 0;
  33641. lockInfo.l_whence = SEEK_SET;
  33642. lockInfo.l_type = F_RDLCK;
  33643. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33644. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  33645. return &nfsIoMethods;
  33646. } else {
  33647. return &posixIoMethods;
  33648. }
  33649. }else{
  33650. return &dotlockIoMethods;
  33651. }
  33652. }
  33653. static const sqlite3_io_methods
  33654. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  33655. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33656. #if OS_VXWORKS
  33657. /*
  33658. ** This "finder" function for VxWorks checks to see if posix advisory
  33659. ** locking works. If it does, then that is what is used. If it does not
  33660. ** work, then fallback to named semaphore locking.
  33661. */
  33662. static const sqlite3_io_methods *vxworksIoFinderImpl(
  33663. const char *filePath, /* name of the database file */
  33664. unixFile *pNew /* the open file object */
  33665. ){
  33666. struct flock lockInfo;
  33667. if( !filePath ){
  33668. /* If filePath==NULL that means we are dealing with a transient file
  33669. ** that does not need to be locked. */
  33670. return &nolockIoMethods;
  33671. }
  33672. /* Test if fcntl() is supported and use POSIX style locks.
  33673. ** Otherwise fall back to the named semaphore method.
  33674. */
  33675. lockInfo.l_len = 1;
  33676. lockInfo.l_start = 0;
  33677. lockInfo.l_whence = SEEK_SET;
  33678. lockInfo.l_type = F_RDLCK;
  33679. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33680. return &posixIoMethods;
  33681. }else{
  33682. return &semIoMethods;
  33683. }
  33684. }
  33685. static const sqlite3_io_methods
  33686. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  33687. #endif /* OS_VXWORKS */
  33688. /*
  33689. ** An abstract type for a pointer to an IO method finder function:
  33690. */
  33691. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  33692. /****************************************************************************
  33693. **************************** sqlite3_vfs methods ****************************
  33694. **
  33695. ** This division contains the implementation of methods on the
  33696. ** sqlite3_vfs object.
  33697. */
  33698. /*
  33699. ** Initialize the contents of the unixFile structure pointed to by pId.
  33700. */
  33701. static int fillInUnixFile(
  33702. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33703. int h, /* Open file descriptor of file being opened */
  33704. sqlite3_file *pId, /* Write to the unixFile structure here */
  33705. const char *zFilename, /* Name of the file being opened */
  33706. int ctrlFlags /* Zero or more UNIXFILE_* values */
  33707. ){
  33708. const sqlite3_io_methods *pLockingStyle;
  33709. unixFile *pNew = (unixFile *)pId;
  33710. int rc = SQLITE_OK;
  33711. assert( pNew->pInode==NULL );
  33712. /* No locking occurs in temporary files */
  33713. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  33714. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  33715. pNew->h = h;
  33716. pNew->pVfs = pVfs;
  33717. pNew->zPath = zFilename;
  33718. pNew->ctrlFlags = (u8)ctrlFlags;
  33719. #if SQLITE_MAX_MMAP_SIZE>0
  33720. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33721. #endif
  33722. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  33723. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33724. pNew->ctrlFlags |= UNIXFILE_PSOW;
  33725. }
  33726. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  33727. pNew->ctrlFlags |= UNIXFILE_EXCL;
  33728. }
  33729. #if OS_VXWORKS
  33730. pNew->pId = vxworksFindFileId(zFilename);
  33731. if( pNew->pId==0 ){
  33732. ctrlFlags |= UNIXFILE_NOLOCK;
  33733. rc = SQLITE_NOMEM_BKPT;
  33734. }
  33735. #endif
  33736. if( ctrlFlags & UNIXFILE_NOLOCK ){
  33737. pLockingStyle = &nolockIoMethods;
  33738. }else{
  33739. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  33740. #if SQLITE_ENABLE_LOCKING_STYLE
  33741. /* Cache zFilename in the locking context (AFP and dotlock override) for
  33742. ** proxyLock activation is possible (remote proxy is based on db name)
  33743. ** zFilename remains valid until file is closed, to support */
  33744. pNew->lockingContext = (void*)zFilename;
  33745. #endif
  33746. }
  33747. if( pLockingStyle == &posixIoMethods
  33748. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33749. || pLockingStyle == &nfsIoMethods
  33750. #endif
  33751. ){
  33752. unixEnterMutex();
  33753. rc = findInodeInfo(pNew, &pNew->pInode);
  33754. if( rc!=SQLITE_OK ){
  33755. /* If an error occurred in findInodeInfo(), close the file descriptor
  33756. ** immediately, before releasing the mutex. findInodeInfo() may fail
  33757. ** in two scenarios:
  33758. **
  33759. ** (a) A call to fstat() failed.
  33760. ** (b) A malloc failed.
  33761. **
  33762. ** Scenario (b) may only occur if the process is holding no other
  33763. ** file descriptors open on the same file. If there were other file
  33764. ** descriptors on this file, then no malloc would be required by
  33765. ** findInodeInfo(). If this is the case, it is quite safe to close
  33766. ** handle h - as it is guaranteed that no posix locks will be released
  33767. ** by doing so.
  33768. **
  33769. ** If scenario (a) caused the error then things are not so safe. The
  33770. ** implicit assumption here is that if fstat() fails, things are in
  33771. ** such bad shape that dropping a lock or two doesn't matter much.
  33772. */
  33773. robust_close(pNew, h, __LINE__);
  33774. h = -1;
  33775. }
  33776. unixLeaveMutex();
  33777. }
  33778. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33779. else if( pLockingStyle == &afpIoMethods ){
  33780. /* AFP locking uses the file path so it needs to be included in
  33781. ** the afpLockingContext.
  33782. */
  33783. afpLockingContext *pCtx;
  33784. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  33785. if( pCtx==0 ){
  33786. rc = SQLITE_NOMEM_BKPT;
  33787. }else{
  33788. /* NB: zFilename exists and remains valid until the file is closed
  33789. ** according to requirement F11141. So we do not need to make a
  33790. ** copy of the filename. */
  33791. pCtx->dbPath = zFilename;
  33792. pCtx->reserved = 0;
  33793. srandomdev();
  33794. unixEnterMutex();
  33795. rc = findInodeInfo(pNew, &pNew->pInode);
  33796. if( rc!=SQLITE_OK ){
  33797. sqlite3_free(pNew->lockingContext);
  33798. robust_close(pNew, h, __LINE__);
  33799. h = -1;
  33800. }
  33801. unixLeaveMutex();
  33802. }
  33803. }
  33804. #endif
  33805. else if( pLockingStyle == &dotlockIoMethods ){
  33806. /* Dotfile locking uses the file path so it needs to be included in
  33807. ** the dotlockLockingContext
  33808. */
  33809. char *zLockFile;
  33810. int nFilename;
  33811. assert( zFilename!=0 );
  33812. nFilename = (int)strlen(zFilename) + 6;
  33813. zLockFile = (char *)sqlite3_malloc64(nFilename);
  33814. if( zLockFile==0 ){
  33815. rc = SQLITE_NOMEM_BKPT;
  33816. }else{
  33817. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  33818. }
  33819. pNew->lockingContext = zLockFile;
  33820. }
  33821. #if OS_VXWORKS
  33822. else if( pLockingStyle == &semIoMethods ){
  33823. /* Named semaphore locking uses the file path so it needs to be
  33824. ** included in the semLockingContext
  33825. */
  33826. unixEnterMutex();
  33827. rc = findInodeInfo(pNew, &pNew->pInode);
  33828. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  33829. char *zSemName = pNew->pInode->aSemName;
  33830. int n;
  33831. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  33832. pNew->pId->zCanonicalName);
  33833. for( n=1; zSemName[n]; n++ )
  33834. if( zSemName[n]=='/' ) zSemName[n] = '_';
  33835. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  33836. if( pNew->pInode->pSem == SEM_FAILED ){
  33837. rc = SQLITE_NOMEM_BKPT;
  33838. pNew->pInode->aSemName[0] = '\0';
  33839. }
  33840. }
  33841. unixLeaveMutex();
  33842. }
  33843. #endif
  33844. storeLastErrno(pNew, 0);
  33845. #if OS_VXWORKS
  33846. if( rc!=SQLITE_OK ){
  33847. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33848. h = -1;
  33849. osUnlink(zFilename);
  33850. pNew->ctrlFlags |= UNIXFILE_DELETE;
  33851. }
  33852. #endif
  33853. if( rc!=SQLITE_OK ){
  33854. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33855. }else{
  33856. pNew->pMethod = pLockingStyle;
  33857. OpenCounter(+1);
  33858. verifyDbFile(pNew);
  33859. }
  33860. return rc;
  33861. }
  33862. /*
  33863. ** Return the name of a directory in which to put temporary files.
  33864. ** If no suitable temporary file directory can be found, return NULL.
  33865. */
  33866. static const char *unixTempFileDir(void){
  33867. static const char *azDirs[] = {
  33868. 0,
  33869. 0,
  33870. "/var/tmp",
  33871. "/usr/tmp",
  33872. "/tmp",
  33873. "."
  33874. };
  33875. unsigned int i = 0;
  33876. struct stat buf;
  33877. const char *zDir = sqlite3_temp_directory;
  33878. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  33879. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  33880. while(1){
  33881. if( zDir!=0
  33882. && osStat(zDir, &buf)==0
  33883. && S_ISDIR(buf.st_mode)
  33884. && osAccess(zDir, 03)==0
  33885. ){
  33886. return zDir;
  33887. }
  33888. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  33889. zDir = azDirs[i++];
  33890. }
  33891. return 0;
  33892. }
  33893. /*
  33894. ** Create a temporary file name in zBuf. zBuf must be allocated
  33895. ** by the calling process and must be big enough to hold at least
  33896. ** pVfs->mxPathname bytes.
  33897. */
  33898. static int unixGetTempname(int nBuf, char *zBuf){
  33899. const char *zDir;
  33900. int iLimit = 0;
  33901. /* It's odd to simulate an io-error here, but really this is just
  33902. ** using the io-error infrastructure to test that SQLite handles this
  33903. ** function failing.
  33904. */
  33905. zBuf[0] = 0;
  33906. SimulateIOError( return SQLITE_IOERR );
  33907. zDir = unixTempFileDir();
  33908. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  33909. do{
  33910. u64 r;
  33911. sqlite3_randomness(sizeof(r), &r);
  33912. assert( nBuf>2 );
  33913. zBuf[nBuf-2] = 0;
  33914. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  33915. zDir, r, 0);
  33916. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  33917. }while( osAccess(zBuf,0)==0 );
  33918. return SQLITE_OK;
  33919. }
  33920. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33921. /*
  33922. ** Routine to transform a unixFile into a proxy-locking unixFile.
  33923. ** Implementation in the proxy-lock division, but used by unixOpen()
  33924. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  33925. */
  33926. static int proxyTransformUnixFile(unixFile*, const char*);
  33927. #endif
  33928. /*
  33929. ** Search for an unused file descriptor that was opened on the database
  33930. ** file (not a journal or master-journal file) identified by pathname
  33931. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  33932. ** argument to this function.
  33933. **
  33934. ** Such a file descriptor may exist if a database connection was closed
  33935. ** but the associated file descriptor could not be closed because some
  33936. ** other file descriptor open on the same file is holding a file-lock.
  33937. ** Refer to comments in the unixClose() function and the lengthy comment
  33938. ** describing "Posix Advisory Locking" at the start of this file for
  33939. ** further details. Also, ticket #4018.
  33940. **
  33941. ** If a suitable file descriptor is found, then it is returned. If no
  33942. ** such file descriptor is located, -1 is returned.
  33943. */
  33944. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  33945. UnixUnusedFd *pUnused = 0;
  33946. /* Do not search for an unused file descriptor on vxworks. Not because
  33947. ** vxworks would not benefit from the change (it might, we're not sure),
  33948. ** but because no way to test it is currently available. It is better
  33949. ** not to risk breaking vxworks support for the sake of such an obscure
  33950. ** feature. */
  33951. #if !OS_VXWORKS
  33952. struct stat sStat; /* Results of stat() call */
  33953. unixEnterMutex();
  33954. /* A stat() call may fail for various reasons. If this happens, it is
  33955. ** almost certain that an open() call on the same path will also fail.
  33956. ** For this reason, if an error occurs in the stat() call here, it is
  33957. ** ignored and -1 is returned. The caller will try to open a new file
  33958. ** descriptor on the same path, fail, and return an error to SQLite.
  33959. **
  33960. ** Even if a subsequent open() call does succeed, the consequences of
  33961. ** not searching for a reusable file descriptor are not dire. */
  33962. if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
  33963. unixInodeInfo *pInode;
  33964. pInode = inodeList;
  33965. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  33966. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  33967. pInode = pInode->pNext;
  33968. }
  33969. if( pInode ){
  33970. UnixUnusedFd **pp;
  33971. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  33972. pUnused = *pp;
  33973. if( pUnused ){
  33974. nUnusedFd--;
  33975. *pp = pUnused->pNext;
  33976. }
  33977. }
  33978. }
  33979. unixLeaveMutex();
  33980. #endif /* if !OS_VXWORKS */
  33981. return pUnused;
  33982. }
  33983. /*
  33984. ** Find the mode, uid and gid of file zFile.
  33985. */
  33986. static int getFileMode(
  33987. const char *zFile, /* File name */
  33988. mode_t *pMode, /* OUT: Permissions of zFile */
  33989. uid_t *pUid, /* OUT: uid of zFile. */
  33990. gid_t *pGid /* OUT: gid of zFile. */
  33991. ){
  33992. struct stat sStat; /* Output of stat() on database file */
  33993. int rc = SQLITE_OK;
  33994. if( 0==osStat(zFile, &sStat) ){
  33995. *pMode = sStat.st_mode & 0777;
  33996. *pUid = sStat.st_uid;
  33997. *pGid = sStat.st_gid;
  33998. }else{
  33999. rc = SQLITE_IOERR_FSTAT;
  34000. }
  34001. return rc;
  34002. }
  34003. /*
  34004. ** This function is called by unixOpen() to determine the unix permissions
  34005. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  34006. ** and a value suitable for passing as the third argument to open(2) is
  34007. ** written to *pMode. If an IO error occurs, an SQLite error code is
  34008. ** returned and the value of *pMode is not modified.
  34009. **
  34010. ** In most cases, this routine sets *pMode to 0, which will become
  34011. ** an indication to robust_open() to create the file using
  34012. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  34013. ** But if the file being opened is a WAL or regular journal file, then
  34014. ** this function queries the file-system for the permissions on the
  34015. ** corresponding database file and sets *pMode to this value. Whenever
  34016. ** possible, WAL and journal files are created using the same permissions
  34017. ** as the associated database file.
  34018. **
  34019. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  34020. ** original filename is unavailable. But 8_3_NAMES is only used for
  34021. ** FAT filesystems and permissions do not matter there, so just use
  34022. ** the default permissions.
  34023. */
  34024. static int findCreateFileMode(
  34025. const char *zPath, /* Path of file (possibly) being created */
  34026. int flags, /* Flags passed as 4th argument to xOpen() */
  34027. mode_t *pMode, /* OUT: Permissions to open file with */
  34028. uid_t *pUid, /* OUT: uid to set on the file */
  34029. gid_t *pGid /* OUT: gid to set on the file */
  34030. ){
  34031. int rc = SQLITE_OK; /* Return Code */
  34032. *pMode = 0;
  34033. *pUid = 0;
  34034. *pGid = 0;
  34035. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  34036. char zDb[MAX_PATHNAME+1]; /* Database file path */
  34037. int nDb; /* Number of valid bytes in zDb */
  34038. /* zPath is a path to a WAL or journal file. The following block derives
  34039. ** the path to the associated database file from zPath. This block handles
  34040. ** the following naming conventions:
  34041. **
  34042. ** "<path to db>-journal"
  34043. ** "<path to db>-wal"
  34044. ** "<path to db>-journalNN"
  34045. ** "<path to db>-walNN"
  34046. **
  34047. ** where NN is a decimal number. The NN naming schemes are
  34048. ** used by the test_multiplex.c module.
  34049. */
  34050. nDb = sqlite3Strlen30(zPath) - 1;
  34051. while( zPath[nDb]!='-' ){
  34052. /* In normal operation, the journal file name will always contain
  34053. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  34054. ** rollback journal specifies a master journal with a goofy name, then
  34055. ** the '-' might be missing. */
  34056. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  34057. nDb--;
  34058. }
  34059. memcpy(zDb, zPath, nDb);
  34060. zDb[nDb] = '\0';
  34061. rc = getFileMode(zDb, pMode, pUid, pGid);
  34062. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  34063. *pMode = 0600;
  34064. }else if( flags & SQLITE_OPEN_URI ){
  34065. /* If this is a main database file and the file was opened using a URI
  34066. ** filename, check for the "modeof" parameter. If present, interpret
  34067. ** its value as a filename and try to copy the mode, uid and gid from
  34068. ** that file. */
  34069. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  34070. if( z ){
  34071. rc = getFileMode(z, pMode, pUid, pGid);
  34072. }
  34073. }
  34074. return rc;
  34075. }
  34076. /*
  34077. ** Open the file zPath.
  34078. **
  34079. ** Previously, the SQLite OS layer used three functions in place of this
  34080. ** one:
  34081. **
  34082. ** sqlite3OsOpenReadWrite();
  34083. ** sqlite3OsOpenReadOnly();
  34084. ** sqlite3OsOpenExclusive();
  34085. **
  34086. ** These calls correspond to the following combinations of flags:
  34087. **
  34088. ** ReadWrite() -> (READWRITE | CREATE)
  34089. ** ReadOnly() -> (READONLY)
  34090. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  34091. **
  34092. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  34093. ** true, the file was configured to be automatically deleted when the
  34094. ** file handle closed. To achieve the same effect using this new
  34095. ** interface, add the DELETEONCLOSE flag to those specified above for
  34096. ** OpenExclusive().
  34097. */
  34098. static int unixOpen(
  34099. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  34100. const char *zPath, /* Pathname of file to be opened */
  34101. sqlite3_file *pFile, /* The file descriptor to be filled in */
  34102. int flags, /* Input flags to control the opening */
  34103. int *pOutFlags /* Output flags returned to SQLite core */
  34104. ){
  34105. unixFile *p = (unixFile *)pFile;
  34106. int fd = -1; /* File descriptor returned by open() */
  34107. int openFlags = 0; /* Flags to pass to open() */
  34108. int eType = flags&0xFFFFFF00; /* Type of file to open */
  34109. int noLock; /* True to omit locking primitives */
  34110. int rc = SQLITE_OK; /* Function Return Code */
  34111. int ctrlFlags = 0; /* UNIXFILE_* flags */
  34112. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  34113. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  34114. int isCreate = (flags & SQLITE_OPEN_CREATE);
  34115. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  34116. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  34117. #if SQLITE_ENABLE_LOCKING_STYLE
  34118. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  34119. #endif
  34120. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  34121. struct statfs fsInfo;
  34122. #endif
  34123. /* If creating a master or main-file journal, this function will open
  34124. ** a file-descriptor on the directory too. The first time unixSync()
  34125. ** is called the directory file descriptor will be fsync()ed and close()d.
  34126. */
  34127. int syncDir = (isCreate && (
  34128. eType==SQLITE_OPEN_MASTER_JOURNAL
  34129. || eType==SQLITE_OPEN_MAIN_JOURNAL
  34130. || eType==SQLITE_OPEN_WAL
  34131. ));
  34132. /* If argument zPath is a NULL pointer, this function is required to open
  34133. ** a temporary file. Use this buffer to store the file name in.
  34134. */
  34135. char zTmpname[MAX_PATHNAME+2];
  34136. const char *zName = zPath;
  34137. /* Check the following statements are true:
  34138. **
  34139. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  34140. ** (b) if CREATE is set, then READWRITE must also be set, and
  34141. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  34142. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  34143. */
  34144. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  34145. assert(isCreate==0 || isReadWrite);
  34146. assert(isExclusive==0 || isCreate);
  34147. assert(isDelete==0 || isCreate);
  34148. /* The main DB, main journal, WAL file and master journal are never
  34149. ** automatically deleted. Nor are they ever temporary files. */
  34150. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  34151. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  34152. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  34153. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  34154. /* Assert that the upper layer has set one of the "file-type" flags. */
  34155. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  34156. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  34157. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  34158. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  34159. );
  34160. /* Detect a pid change and reset the PRNG. There is a race condition
  34161. ** here such that two or more threads all trying to open databases at
  34162. ** the same instant might all reset the PRNG. But multiple resets
  34163. ** are harmless.
  34164. */
  34165. if( randomnessPid!=osGetpid(0) ){
  34166. randomnessPid = osGetpid(0);
  34167. sqlite3_randomness(0,0);
  34168. }
  34169. memset(p, 0, sizeof(unixFile));
  34170. if( eType==SQLITE_OPEN_MAIN_DB ){
  34171. UnixUnusedFd *pUnused;
  34172. pUnused = findReusableFd(zName, flags);
  34173. if( pUnused ){
  34174. fd = pUnused->fd;
  34175. }else{
  34176. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  34177. if( !pUnused ){
  34178. return SQLITE_NOMEM_BKPT;
  34179. }
  34180. }
  34181. p->pPreallocatedUnused = pUnused;
  34182. /* Database filenames are double-zero terminated if they are not
  34183. ** URIs with parameters. Hence, they can always be passed into
  34184. ** sqlite3_uri_parameter(). */
  34185. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  34186. }else if( !zName ){
  34187. /* If zName is NULL, the upper layer is requesting a temp file. */
  34188. assert(isDelete && !syncDir);
  34189. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  34190. if( rc!=SQLITE_OK ){
  34191. return rc;
  34192. }
  34193. zName = zTmpname;
  34194. /* Generated temporary filenames are always double-zero terminated
  34195. ** for use by sqlite3_uri_parameter(). */
  34196. assert( zName[strlen(zName)+1]==0 );
  34197. }
  34198. /* Determine the value of the flags parameter passed to POSIX function
  34199. ** open(). These must be calculated even if open() is not called, as
  34200. ** they may be stored as part of the file handle and used by the
  34201. ** 'conch file' locking functions later on. */
  34202. if( isReadonly ) openFlags |= O_RDONLY;
  34203. if( isReadWrite ) openFlags |= O_RDWR;
  34204. if( isCreate ) openFlags |= O_CREAT;
  34205. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  34206. openFlags |= (O_LARGEFILE|O_BINARY);
  34207. if( fd<0 ){
  34208. mode_t openMode; /* Permissions to create file with */
  34209. uid_t uid; /* Userid for the file */
  34210. gid_t gid; /* Groupid for the file */
  34211. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  34212. if( rc!=SQLITE_OK ){
  34213. assert( !p->pPreallocatedUnused );
  34214. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  34215. return rc;
  34216. }
  34217. fd = robust_open(zName, openFlags, openMode);
  34218. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  34219. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  34220. if( fd<0 && errno!=EISDIR && isReadWrite ){
  34221. /* Failed to open the file for read/write access. Try read-only. */
  34222. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  34223. openFlags &= ~(O_RDWR|O_CREAT);
  34224. flags |= SQLITE_OPEN_READONLY;
  34225. openFlags |= O_RDONLY;
  34226. isReadonly = 1;
  34227. fd = robust_open(zName, openFlags, openMode);
  34228. }
  34229. if( fd<0 ){
  34230. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  34231. goto open_finished;
  34232. }
  34233. /* If this process is running as root and if creating a new rollback
  34234. ** journal or WAL file, set the ownership of the journal or WAL to be
  34235. ** the same as the original database.
  34236. */
  34237. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  34238. robustFchown(fd, uid, gid);
  34239. }
  34240. }
  34241. assert( fd>=0 );
  34242. if( pOutFlags ){
  34243. *pOutFlags = flags;
  34244. }
  34245. if( p->pPreallocatedUnused ){
  34246. p->pPreallocatedUnused->fd = fd;
  34247. p->pPreallocatedUnused->flags = flags;
  34248. }
  34249. if( isDelete ){
  34250. #if OS_VXWORKS
  34251. zPath = zName;
  34252. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  34253. zPath = sqlite3_mprintf("%s", zName);
  34254. if( zPath==0 ){
  34255. robust_close(p, fd, __LINE__);
  34256. return SQLITE_NOMEM_BKPT;
  34257. }
  34258. #else
  34259. osUnlink(zName);
  34260. #endif
  34261. }
  34262. #if SQLITE_ENABLE_LOCKING_STYLE
  34263. else{
  34264. p->openFlags = openFlags;
  34265. }
  34266. #endif
  34267. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  34268. if( fstatfs(fd, &fsInfo) == -1 ){
  34269. storeLastErrno(p, errno);
  34270. robust_close(p, fd, __LINE__);
  34271. return SQLITE_IOERR_ACCESS;
  34272. }
  34273. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  34274. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  34275. }
  34276. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  34277. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  34278. }
  34279. #endif
  34280. /* Set up appropriate ctrlFlags */
  34281. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  34282. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  34283. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  34284. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  34285. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  34286. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  34287. #if SQLITE_ENABLE_LOCKING_STYLE
  34288. #if SQLITE_PREFER_PROXY_LOCKING
  34289. isAutoProxy = 1;
  34290. #endif
  34291. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  34292. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  34293. int useProxy = 0;
  34294. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  34295. ** never use proxy, NULL means use proxy for non-local files only. */
  34296. if( envforce!=NULL ){
  34297. useProxy = atoi(envforce)>0;
  34298. }else{
  34299. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  34300. }
  34301. if( useProxy ){
  34302. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  34303. if( rc==SQLITE_OK ){
  34304. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  34305. if( rc!=SQLITE_OK ){
  34306. /* Use unixClose to clean up the resources added in fillInUnixFile
  34307. ** and clear all the structure's references. Specifically,
  34308. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  34309. */
  34310. unixClose(pFile);
  34311. return rc;
  34312. }
  34313. }
  34314. goto open_finished;
  34315. }
  34316. }
  34317. #endif
  34318. assert( zPath==0 || zPath[0]=='/'
  34319. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  34320. );
  34321. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  34322. open_finished:
  34323. if( rc!=SQLITE_OK ){
  34324. sqlite3_free(p->pPreallocatedUnused);
  34325. }
  34326. return rc;
  34327. }
  34328. /*
  34329. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  34330. ** the directory after deleting the file.
  34331. */
  34332. static int unixDelete(
  34333. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  34334. const char *zPath, /* Name of file to be deleted */
  34335. int dirSync /* If true, fsync() directory after deleting file */
  34336. ){
  34337. int rc = SQLITE_OK;
  34338. UNUSED_PARAMETER(NotUsed);
  34339. SimulateIOError(return SQLITE_IOERR_DELETE);
  34340. if( osUnlink(zPath)==(-1) ){
  34341. if( errno==ENOENT
  34342. #if OS_VXWORKS
  34343. || osAccess(zPath,0)!=0
  34344. #endif
  34345. ){
  34346. rc = SQLITE_IOERR_DELETE_NOENT;
  34347. }else{
  34348. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  34349. }
  34350. return rc;
  34351. }
  34352. #ifndef SQLITE_DISABLE_DIRSYNC
  34353. if( (dirSync & 1)!=0 ){
  34354. int fd;
  34355. rc = osOpenDirectory(zPath, &fd);
  34356. if( rc==SQLITE_OK ){
  34357. if( full_fsync(fd,0,0) ){
  34358. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  34359. }
  34360. robust_close(0, fd, __LINE__);
  34361. }else{
  34362. assert( rc==SQLITE_CANTOPEN );
  34363. rc = SQLITE_OK;
  34364. }
  34365. }
  34366. #endif
  34367. return rc;
  34368. }
  34369. /*
  34370. ** Test the existence of or access permissions of file zPath. The
  34371. ** test performed depends on the value of flags:
  34372. **
  34373. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  34374. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  34375. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  34376. **
  34377. ** Otherwise return 0.
  34378. */
  34379. static int unixAccess(
  34380. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  34381. const char *zPath, /* Path of the file to examine */
  34382. int flags, /* What do we want to learn about the zPath file? */
  34383. int *pResOut /* Write result boolean here */
  34384. ){
  34385. UNUSED_PARAMETER(NotUsed);
  34386. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  34387. assert( pResOut!=0 );
  34388. /* The spec says there are three possible values for flags. But only
  34389. ** two of them are actually used */
  34390. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  34391. if( flags==SQLITE_ACCESS_EXISTS ){
  34392. struct stat buf;
  34393. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  34394. }else{
  34395. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  34396. }
  34397. return SQLITE_OK;
  34398. }
  34399. /*
  34400. **
  34401. */
  34402. static int mkFullPathname(
  34403. const char *zPath, /* Input path */
  34404. char *zOut, /* Output buffer */
  34405. int nOut /* Allocated size of buffer zOut */
  34406. ){
  34407. int nPath = sqlite3Strlen30(zPath);
  34408. int iOff = 0;
  34409. if( zPath[0]!='/' ){
  34410. if( osGetcwd(zOut, nOut-2)==0 ){
  34411. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  34412. }
  34413. iOff = sqlite3Strlen30(zOut);
  34414. zOut[iOff++] = '/';
  34415. }
  34416. if( (iOff+nPath+1)>nOut ){
  34417. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  34418. ** even if it returns an error. */
  34419. zOut[iOff] = '\0';
  34420. return SQLITE_CANTOPEN_BKPT;
  34421. }
  34422. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  34423. return SQLITE_OK;
  34424. }
  34425. /*
  34426. ** Turn a relative pathname into a full pathname. The relative path
  34427. ** is stored as a nul-terminated string in the buffer pointed to by
  34428. ** zPath.
  34429. **
  34430. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  34431. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  34432. ** this buffer before returning.
  34433. */
  34434. static int unixFullPathname(
  34435. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  34436. const char *zPath, /* Possibly relative input path */
  34437. int nOut, /* Size of output buffer in bytes */
  34438. char *zOut /* Output buffer */
  34439. ){
  34440. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  34441. return mkFullPathname(zPath, zOut, nOut);
  34442. #else
  34443. int rc = SQLITE_OK;
  34444. int nByte;
  34445. int nLink = 1; /* Number of symbolic links followed so far */
  34446. const char *zIn = zPath; /* Input path for each iteration of loop */
  34447. char *zDel = 0;
  34448. assert( pVfs->mxPathname==MAX_PATHNAME );
  34449. UNUSED_PARAMETER(pVfs);
  34450. /* It's odd to simulate an io-error here, but really this is just
  34451. ** using the io-error infrastructure to test that SQLite handles this
  34452. ** function failing. This function could fail if, for example, the
  34453. ** current working directory has been unlinked.
  34454. */
  34455. SimulateIOError( return SQLITE_ERROR );
  34456. do {
  34457. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  34458. ** link, or false otherwise. */
  34459. int bLink = 0;
  34460. struct stat buf;
  34461. if( osLstat(zIn, &buf)!=0 ){
  34462. if( errno!=ENOENT ){
  34463. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  34464. }
  34465. }else{
  34466. bLink = S_ISLNK(buf.st_mode);
  34467. }
  34468. if( bLink ){
  34469. if( zDel==0 ){
  34470. zDel = sqlite3_malloc(nOut);
  34471. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  34472. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  34473. rc = SQLITE_CANTOPEN_BKPT;
  34474. }
  34475. if( rc==SQLITE_OK ){
  34476. nByte = osReadlink(zIn, zDel, nOut-1);
  34477. if( nByte<0 ){
  34478. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  34479. }else{
  34480. if( zDel[0]!='/' ){
  34481. int n;
  34482. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  34483. if( nByte+n+1>nOut ){
  34484. rc = SQLITE_CANTOPEN_BKPT;
  34485. }else{
  34486. memmove(&zDel[n], zDel, nByte+1);
  34487. memcpy(zDel, zIn, n);
  34488. nByte += n;
  34489. }
  34490. }
  34491. zDel[nByte] = '\0';
  34492. }
  34493. }
  34494. zIn = zDel;
  34495. }
  34496. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  34497. if( rc==SQLITE_OK && zIn!=zOut ){
  34498. rc = mkFullPathname(zIn, zOut, nOut);
  34499. }
  34500. if( bLink==0 ) break;
  34501. zIn = zOut;
  34502. }while( rc==SQLITE_OK );
  34503. sqlite3_free(zDel);
  34504. return rc;
  34505. #endif /* HAVE_READLINK && HAVE_LSTAT */
  34506. }
  34507. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  34508. /*
  34509. ** Interfaces for opening a shared library, finding entry points
  34510. ** within the shared library, and closing the shared library.
  34511. */
  34512. #include <dlfcn.h>
  34513. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  34514. UNUSED_PARAMETER(NotUsed);
  34515. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  34516. }
  34517. /*
  34518. ** SQLite calls this function immediately after a call to unixDlSym() or
  34519. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  34520. ** message is available, it is written to zBufOut. If no error message
  34521. ** is available, zBufOut is left unmodified and SQLite uses a default
  34522. ** error message.
  34523. */
  34524. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  34525. const char *zErr;
  34526. UNUSED_PARAMETER(NotUsed);
  34527. unixEnterMutex();
  34528. zErr = dlerror();
  34529. if( zErr ){
  34530. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  34531. }
  34532. unixLeaveMutex();
  34533. }
  34534. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  34535. /*
  34536. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  34537. ** cast into a pointer to a function. And yet the library dlsym() routine
  34538. ** returns a void* which is really a pointer to a function. So how do we
  34539. ** use dlsym() with -pedantic-errors?
  34540. **
  34541. ** Variable x below is defined to be a pointer to a function taking
  34542. ** parameters void* and const char* and returning a pointer to a function.
  34543. ** We initialize x by assigning it a pointer to the dlsym() function.
  34544. ** (That assignment requires a cast.) Then we call the function that
  34545. ** x points to.
  34546. **
  34547. ** This work-around is unlikely to work correctly on any system where
  34548. ** you really cannot cast a function pointer into void*. But then, on the
  34549. ** other hand, dlsym() will not work on such a system either, so we have
  34550. ** not really lost anything.
  34551. */
  34552. void (*(*x)(void*,const char*))(void);
  34553. UNUSED_PARAMETER(NotUsed);
  34554. x = (void(*(*)(void*,const char*))(void))dlsym;
  34555. return (*x)(p, zSym);
  34556. }
  34557. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  34558. UNUSED_PARAMETER(NotUsed);
  34559. dlclose(pHandle);
  34560. }
  34561. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  34562. #define unixDlOpen 0
  34563. #define unixDlError 0
  34564. #define unixDlSym 0
  34565. #define unixDlClose 0
  34566. #endif
  34567. /*
  34568. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  34569. */
  34570. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  34571. UNUSED_PARAMETER(NotUsed);
  34572. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  34573. /* We have to initialize zBuf to prevent valgrind from reporting
  34574. ** errors. The reports issued by valgrind are incorrect - we would
  34575. ** prefer that the randomness be increased by making use of the
  34576. ** uninitialized space in zBuf - but valgrind errors tend to worry
  34577. ** some users. Rather than argue, it seems easier just to initialize
  34578. ** the whole array and silence valgrind, even if that means less randomness
  34579. ** in the random seed.
  34580. **
  34581. ** When testing, initializing zBuf[] to zero is all we do. That means
  34582. ** that we always use the same random number sequence. This makes the
  34583. ** tests repeatable.
  34584. */
  34585. memset(zBuf, 0, nBuf);
  34586. randomnessPid = osGetpid(0);
  34587. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  34588. {
  34589. int fd, got;
  34590. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  34591. if( fd<0 ){
  34592. time_t t;
  34593. time(&t);
  34594. memcpy(zBuf, &t, sizeof(t));
  34595. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  34596. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  34597. nBuf = sizeof(t) + sizeof(randomnessPid);
  34598. }else{
  34599. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  34600. robust_close(0, fd, __LINE__);
  34601. }
  34602. }
  34603. #endif
  34604. return nBuf;
  34605. }
  34606. /*
  34607. ** Sleep for a little while. Return the amount of time slept.
  34608. ** The argument is the number of microseconds we want to sleep.
  34609. ** The return value is the number of microseconds of sleep actually
  34610. ** requested from the underlying operating system, a number which
  34611. ** might be greater than or equal to the argument, but not less
  34612. ** than the argument.
  34613. */
  34614. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  34615. #if OS_VXWORKS
  34616. struct timespec sp;
  34617. sp.tv_sec = microseconds / 1000000;
  34618. sp.tv_nsec = (microseconds % 1000000) * 1000;
  34619. nanosleep(&sp, NULL);
  34620. UNUSED_PARAMETER(NotUsed);
  34621. return microseconds;
  34622. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  34623. usleep(microseconds);
  34624. UNUSED_PARAMETER(NotUsed);
  34625. return microseconds;
  34626. #else
  34627. int seconds = (microseconds+999999)/1000000;
  34628. sleep(seconds);
  34629. UNUSED_PARAMETER(NotUsed);
  34630. return seconds*1000000;
  34631. #endif
  34632. }
  34633. /*
  34634. ** The following variable, if set to a non-zero value, is interpreted as
  34635. ** the number of seconds since 1970 and is used to set the result of
  34636. ** sqlite3OsCurrentTime() during testing.
  34637. */
  34638. #ifdef SQLITE_TEST
  34639. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  34640. #endif
  34641. /*
  34642. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  34643. ** the current time and date as a Julian Day number times 86_400_000. In
  34644. ** other words, write into *piNow the number of milliseconds since the Julian
  34645. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  34646. ** proleptic Gregorian calendar.
  34647. **
  34648. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  34649. ** cannot be found.
  34650. */
  34651. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  34652. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  34653. int rc = SQLITE_OK;
  34654. #if defined(NO_GETTOD)
  34655. time_t t;
  34656. time(&t);
  34657. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  34658. #elif OS_VXWORKS
  34659. struct timespec sNow;
  34660. clock_gettime(CLOCK_REALTIME, &sNow);
  34661. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  34662. #else
  34663. struct timeval sNow;
  34664. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  34665. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  34666. #endif
  34667. #ifdef SQLITE_TEST
  34668. if( sqlite3_current_time ){
  34669. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  34670. }
  34671. #endif
  34672. UNUSED_PARAMETER(NotUsed);
  34673. return rc;
  34674. }
  34675. #ifndef SQLITE_OMIT_DEPRECATED
  34676. /*
  34677. ** Find the current time (in Universal Coordinated Time). Write the
  34678. ** current time and date as a Julian Day number into *prNow and
  34679. ** return 0. Return 1 if the time and date cannot be found.
  34680. */
  34681. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  34682. sqlite3_int64 i = 0;
  34683. int rc;
  34684. UNUSED_PARAMETER(NotUsed);
  34685. rc = unixCurrentTimeInt64(0, &i);
  34686. *prNow = i/86400000.0;
  34687. return rc;
  34688. }
  34689. #else
  34690. # define unixCurrentTime 0
  34691. #endif
  34692. /*
  34693. ** The xGetLastError() method is designed to return a better
  34694. ** low-level error message when operating-system problems come up
  34695. ** during SQLite operation. Only the integer return code is currently
  34696. ** used.
  34697. */
  34698. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  34699. UNUSED_PARAMETER(NotUsed);
  34700. UNUSED_PARAMETER(NotUsed2);
  34701. UNUSED_PARAMETER(NotUsed3);
  34702. return errno;
  34703. }
  34704. /*
  34705. ************************ End of sqlite3_vfs methods ***************************
  34706. ******************************************************************************/
  34707. /******************************************************************************
  34708. ************************** Begin Proxy Locking ********************************
  34709. **
  34710. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  34711. ** other locking methods on secondary lock files. Proxy locking is a
  34712. ** meta-layer over top of the primitive locking implemented above. For
  34713. ** this reason, the division that implements of proxy locking is deferred
  34714. ** until late in the file (here) after all of the other I/O methods have
  34715. ** been defined - so that the primitive locking methods are available
  34716. ** as services to help with the implementation of proxy locking.
  34717. **
  34718. ****
  34719. **
  34720. ** The default locking schemes in SQLite use byte-range locks on the
  34721. ** database file to coordinate safe, concurrent access by multiple readers
  34722. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  34723. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  34724. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  34725. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  34726. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  34727. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  34728. ** address in the shared range is taken for a SHARED lock, the entire
  34729. ** shared range is taken for an EXCLUSIVE lock):
  34730. **
  34731. ** PENDING_BYTE 0x40000000
  34732. ** RESERVED_BYTE 0x40000001
  34733. ** SHARED_RANGE 0x40000002 -> 0x40000200
  34734. **
  34735. ** This works well on the local file system, but shows a nearly 100x
  34736. ** slowdown in read performance on AFP because the AFP client disables
  34737. ** the read cache when byte-range locks are present. Enabling the read
  34738. ** cache exposes a cache coherency problem that is present on all OS X
  34739. ** supported network file systems. NFS and AFP both observe the
  34740. ** close-to-open semantics for ensuring cache coherency
  34741. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  34742. ** address the requirements for concurrent database access by multiple
  34743. ** readers and writers
  34744. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  34745. **
  34746. ** To address the performance and cache coherency issues, proxy file locking
  34747. ** changes the way database access is controlled by limiting access to a
  34748. ** single host at a time and moving file locks off of the database file
  34749. ** and onto a proxy file on the local file system.
  34750. **
  34751. **
  34752. ** Using proxy locks
  34753. ** -----------------
  34754. **
  34755. ** C APIs
  34756. **
  34757. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  34758. ** <proxy_path> | ":auto:");
  34759. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  34760. ** &<proxy_path>);
  34761. **
  34762. **
  34763. ** SQL pragmas
  34764. **
  34765. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  34766. ** PRAGMA [database.]lock_proxy_file
  34767. **
  34768. ** Specifying ":auto:" means that if there is a conch file with a matching
  34769. ** host ID in it, the proxy path in the conch file will be used, otherwise
  34770. ** a proxy path based on the user's temp dir
  34771. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  34772. ** actual proxy file name is generated from the name and path of the
  34773. ** database file. For example:
  34774. **
  34775. ** For database path "/Users/me/foo.db"
  34776. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  34777. **
  34778. ** Once a lock proxy is configured for a database connection, it can not
  34779. ** be removed, however it may be switched to a different proxy path via
  34780. ** the above APIs (assuming the conch file is not being held by another
  34781. ** connection or process).
  34782. **
  34783. **
  34784. ** How proxy locking works
  34785. ** -----------------------
  34786. **
  34787. ** Proxy file locking relies primarily on two new supporting files:
  34788. **
  34789. ** * conch file to limit access to the database file to a single host
  34790. ** at a time
  34791. **
  34792. ** * proxy file to act as a proxy for the advisory locks normally
  34793. ** taken on the database
  34794. **
  34795. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  34796. ** by taking an sqlite-style shared lock on the conch file, reading the
  34797. ** contents and comparing the host's unique host ID (see below) and lock
  34798. ** proxy path against the values stored in the conch. The conch file is
  34799. ** stored in the same directory as the database file and the file name
  34800. ** is patterned after the database file name as ".<databasename>-conch".
  34801. ** If the conch file does not exist, or its contents do not match the
  34802. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  34803. ** lock and the conch file contents is updated with the host ID and proxy
  34804. ** path and the lock is downgraded to a shared lock again. If the conch
  34805. ** is held by another process (with a shared lock), the exclusive lock
  34806. ** will fail and SQLITE_BUSY is returned.
  34807. **
  34808. ** The proxy file - a single-byte file used for all advisory file locks
  34809. ** normally taken on the database file. This allows for safe sharing
  34810. ** of the database file for multiple readers and writers on the same
  34811. ** host (the conch ensures that they all use the same local lock file).
  34812. **
  34813. ** Requesting the lock proxy does not immediately take the conch, it is
  34814. ** only taken when the first request to lock database file is made.
  34815. ** This matches the semantics of the traditional locking behavior, where
  34816. ** opening a connection to a database file does not take a lock on it.
  34817. ** The shared lock and an open file descriptor are maintained until
  34818. ** the connection to the database is closed.
  34819. **
  34820. ** The proxy file and the lock file are never deleted so they only need
  34821. ** to be created the first time they are used.
  34822. **
  34823. ** Configuration options
  34824. ** ---------------------
  34825. **
  34826. ** SQLITE_PREFER_PROXY_LOCKING
  34827. **
  34828. ** Database files accessed on non-local file systems are
  34829. ** automatically configured for proxy locking, lock files are
  34830. ** named automatically using the same logic as
  34831. ** PRAGMA lock_proxy_file=":auto:"
  34832. **
  34833. ** SQLITE_PROXY_DEBUG
  34834. **
  34835. ** Enables the logging of error messages during host id file
  34836. ** retrieval and creation
  34837. **
  34838. ** LOCKPROXYDIR
  34839. **
  34840. ** Overrides the default directory used for lock proxy files that
  34841. ** are named automatically via the ":auto:" setting
  34842. **
  34843. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  34844. **
  34845. ** Permissions to use when creating a directory for storing the
  34846. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  34847. **
  34848. **
  34849. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  34850. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  34851. ** force proxy locking to be used for every database file opened, and 0
  34852. ** will force automatic proxy locking to be disabled for all database
  34853. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  34854. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  34855. */
  34856. /*
  34857. ** Proxy locking is only available on MacOSX
  34858. */
  34859. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34860. /*
  34861. ** The proxyLockingContext has the path and file structures for the remote
  34862. ** and local proxy files in it
  34863. */
  34864. typedef struct proxyLockingContext proxyLockingContext;
  34865. struct proxyLockingContext {
  34866. unixFile *conchFile; /* Open conch file */
  34867. char *conchFilePath; /* Name of the conch file */
  34868. unixFile *lockProxy; /* Open proxy lock file */
  34869. char *lockProxyPath; /* Name of the proxy lock file */
  34870. char *dbPath; /* Name of the open file */
  34871. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  34872. int nFails; /* Number of conch taking failures */
  34873. void *oldLockingContext; /* Original lockingcontext to restore on close */
  34874. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  34875. };
  34876. /*
  34877. ** The proxy lock file path for the database at dbPath is written into lPath,
  34878. ** which must point to valid, writable memory large enough for a maxLen length
  34879. ** file path.
  34880. */
  34881. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  34882. int len;
  34883. int dbLen;
  34884. int i;
  34885. #ifdef LOCKPROXYDIR
  34886. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  34887. #else
  34888. # ifdef _CS_DARWIN_USER_TEMP_DIR
  34889. {
  34890. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  34891. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  34892. lPath, errno, osGetpid(0)));
  34893. return SQLITE_IOERR_LOCK;
  34894. }
  34895. len = strlcat(lPath, "sqliteplocks", maxLen);
  34896. }
  34897. # else
  34898. len = strlcpy(lPath, "/tmp/", maxLen);
  34899. # endif
  34900. #endif
  34901. if( lPath[len-1]!='/' ){
  34902. len = strlcat(lPath, "/", maxLen);
  34903. }
  34904. /* transform the db path to a unique cache name */
  34905. dbLen = (int)strlen(dbPath);
  34906. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  34907. char c = dbPath[i];
  34908. lPath[i+len] = (c=='/')?'_':c;
  34909. }
  34910. lPath[i+len]='\0';
  34911. strlcat(lPath, ":auto:", maxLen);
  34912. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  34913. return SQLITE_OK;
  34914. }
  34915. /*
  34916. ** Creates the lock file and any missing directories in lockPath
  34917. */
  34918. static int proxyCreateLockPath(const char *lockPath){
  34919. int i, len;
  34920. char buf[MAXPATHLEN];
  34921. int start = 0;
  34922. assert(lockPath!=NULL);
  34923. /* try to create all the intermediate directories */
  34924. len = (int)strlen(lockPath);
  34925. buf[0] = lockPath[0];
  34926. for( i=1; i<len; i++ ){
  34927. if( lockPath[i] == '/' && (i - start > 0) ){
  34928. /* only mkdir if leaf dir != "." or "/" or ".." */
  34929. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  34930. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  34931. buf[i]='\0';
  34932. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  34933. int err=errno;
  34934. if( err!=EEXIST ) {
  34935. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  34936. "'%s' proxy lock path=%s pid=%d\n",
  34937. buf, strerror(err), lockPath, osGetpid(0)));
  34938. return err;
  34939. }
  34940. }
  34941. }
  34942. start=i+1;
  34943. }
  34944. buf[i] = lockPath[i];
  34945. }
  34946. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  34947. return 0;
  34948. }
  34949. /*
  34950. ** Create a new VFS file descriptor (stored in memory obtained from
  34951. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  34952. **
  34953. ** The caller is responsible not only for closing the file descriptor
  34954. ** but also for freeing the memory associated with the file descriptor.
  34955. */
  34956. static int proxyCreateUnixFile(
  34957. const char *path, /* path for the new unixFile */
  34958. unixFile **ppFile, /* unixFile created and returned by ref */
  34959. int islockfile /* if non zero missing dirs will be created */
  34960. ) {
  34961. int fd = -1;
  34962. unixFile *pNew;
  34963. int rc = SQLITE_OK;
  34964. int openFlags = O_RDWR | O_CREAT;
  34965. sqlite3_vfs dummyVfs;
  34966. int terrno = 0;
  34967. UnixUnusedFd *pUnused = NULL;
  34968. /* 1. first try to open/create the file
  34969. ** 2. if that fails, and this is a lock file (not-conch), try creating
  34970. ** the parent directories and then try again.
  34971. ** 3. if that fails, try to open the file read-only
  34972. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  34973. */
  34974. pUnused = findReusableFd(path, openFlags);
  34975. if( pUnused ){
  34976. fd = pUnused->fd;
  34977. }else{
  34978. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  34979. if( !pUnused ){
  34980. return SQLITE_NOMEM_BKPT;
  34981. }
  34982. }
  34983. if( fd<0 ){
  34984. fd = robust_open(path, openFlags, 0);
  34985. terrno = errno;
  34986. if( fd<0 && errno==ENOENT && islockfile ){
  34987. if( proxyCreateLockPath(path) == SQLITE_OK ){
  34988. fd = robust_open(path, openFlags, 0);
  34989. }
  34990. }
  34991. }
  34992. if( fd<0 ){
  34993. openFlags = O_RDONLY;
  34994. fd = robust_open(path, openFlags, 0);
  34995. terrno = errno;
  34996. }
  34997. if( fd<0 ){
  34998. if( islockfile ){
  34999. return SQLITE_BUSY;
  35000. }
  35001. switch (terrno) {
  35002. case EACCES:
  35003. return SQLITE_PERM;
  35004. case EIO:
  35005. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  35006. default:
  35007. return SQLITE_CANTOPEN_BKPT;
  35008. }
  35009. }
  35010. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  35011. if( pNew==NULL ){
  35012. rc = SQLITE_NOMEM_BKPT;
  35013. goto end_create_proxy;
  35014. }
  35015. memset(pNew, 0, sizeof(unixFile));
  35016. pNew->openFlags = openFlags;
  35017. memset(&dummyVfs, 0, sizeof(dummyVfs));
  35018. dummyVfs.pAppData = (void*)&autolockIoFinder;
  35019. dummyVfs.zName = "dummy";
  35020. pUnused->fd = fd;
  35021. pUnused->flags = openFlags;
  35022. pNew->pPreallocatedUnused = pUnused;
  35023. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  35024. if( rc==SQLITE_OK ){
  35025. *ppFile = pNew;
  35026. return SQLITE_OK;
  35027. }
  35028. end_create_proxy:
  35029. robust_close(pNew, fd, __LINE__);
  35030. sqlite3_free(pNew);
  35031. sqlite3_free(pUnused);
  35032. return rc;
  35033. }
  35034. #ifdef SQLITE_TEST
  35035. /* simulate multiple hosts by creating unique hostid file paths */
  35036. SQLITE_API int sqlite3_hostid_num = 0;
  35037. #endif
  35038. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  35039. #ifdef HAVE_GETHOSTUUID
  35040. /* Not always defined in the headers as it ought to be */
  35041. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  35042. #endif
  35043. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  35044. ** bytes of writable memory.
  35045. */
  35046. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  35047. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  35048. memset(pHostID, 0, PROXY_HOSTIDLEN);
  35049. #ifdef HAVE_GETHOSTUUID
  35050. {
  35051. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  35052. if( gethostuuid(pHostID, &timeout) ){
  35053. int err = errno;
  35054. if( pError ){
  35055. *pError = err;
  35056. }
  35057. return SQLITE_IOERR;
  35058. }
  35059. }
  35060. #else
  35061. UNUSED_PARAMETER(pError);
  35062. #endif
  35063. #ifdef SQLITE_TEST
  35064. /* simulate multiple hosts by creating unique hostid file paths */
  35065. if( sqlite3_hostid_num != 0){
  35066. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  35067. }
  35068. #endif
  35069. return SQLITE_OK;
  35070. }
  35071. /* The conch file contains the header, host id and lock file path
  35072. */
  35073. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  35074. #define PROXY_HEADERLEN 1 /* conch file header length */
  35075. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  35076. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  35077. /*
  35078. ** Takes an open conch file, copies the contents to a new path and then moves
  35079. ** it back. The newly created file's file descriptor is assigned to the
  35080. ** conch file structure and finally the original conch file descriptor is
  35081. ** closed. Returns zero if successful.
  35082. */
  35083. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  35084. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35085. unixFile *conchFile = pCtx->conchFile;
  35086. char tPath[MAXPATHLEN];
  35087. char buf[PROXY_MAXCONCHLEN];
  35088. char *cPath = pCtx->conchFilePath;
  35089. size_t readLen = 0;
  35090. size_t pathLen = 0;
  35091. char errmsg[64] = "";
  35092. int fd = -1;
  35093. int rc = -1;
  35094. UNUSED_PARAMETER(myHostID);
  35095. /* create a new path by replace the trailing '-conch' with '-break' */
  35096. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  35097. if( pathLen>MAXPATHLEN || pathLen<6 ||
  35098. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  35099. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  35100. goto end_breaklock;
  35101. }
  35102. /* read the conch content */
  35103. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  35104. if( readLen<PROXY_PATHINDEX ){
  35105. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  35106. goto end_breaklock;
  35107. }
  35108. /* write it out to the temporary break file */
  35109. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  35110. if( fd<0 ){
  35111. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  35112. goto end_breaklock;
  35113. }
  35114. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  35115. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  35116. goto end_breaklock;
  35117. }
  35118. if( rename(tPath, cPath) ){
  35119. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  35120. goto end_breaklock;
  35121. }
  35122. rc = 0;
  35123. fprintf(stderr, "broke stale lock on %s\n", cPath);
  35124. robust_close(pFile, conchFile->h, __LINE__);
  35125. conchFile->h = fd;
  35126. conchFile->openFlags = O_RDWR | O_CREAT;
  35127. end_breaklock:
  35128. if( rc ){
  35129. if( fd>=0 ){
  35130. osUnlink(tPath);
  35131. robust_close(pFile, fd, __LINE__);
  35132. }
  35133. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  35134. }
  35135. return rc;
  35136. }
  35137. /* Take the requested lock on the conch file and break a stale lock if the
  35138. ** host id matches.
  35139. */
  35140. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  35141. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35142. unixFile *conchFile = pCtx->conchFile;
  35143. int rc = SQLITE_OK;
  35144. int nTries = 0;
  35145. struct timespec conchModTime;
  35146. memset(&conchModTime, 0, sizeof(conchModTime));
  35147. do {
  35148. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  35149. nTries ++;
  35150. if( rc==SQLITE_BUSY ){
  35151. /* If the lock failed (busy):
  35152. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  35153. * 2nd try: fail if the mod time changed or host id is different, wait
  35154. * 10 sec and try again
  35155. * 3rd try: break the lock unless the mod time has changed.
  35156. */
  35157. struct stat buf;
  35158. if( osFstat(conchFile->h, &buf) ){
  35159. storeLastErrno(pFile, errno);
  35160. return SQLITE_IOERR_LOCK;
  35161. }
  35162. if( nTries==1 ){
  35163. conchModTime = buf.st_mtimespec;
  35164. usleep(500000); /* wait 0.5 sec and try the lock again*/
  35165. continue;
  35166. }
  35167. assert( nTries>1 );
  35168. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  35169. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  35170. return SQLITE_BUSY;
  35171. }
  35172. if( nTries==2 ){
  35173. char tBuf[PROXY_MAXCONCHLEN];
  35174. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  35175. if( len<0 ){
  35176. storeLastErrno(pFile, errno);
  35177. return SQLITE_IOERR_LOCK;
  35178. }
  35179. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  35180. /* don't break the lock if the host id doesn't match */
  35181. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  35182. return SQLITE_BUSY;
  35183. }
  35184. }else{
  35185. /* don't break the lock on short read or a version mismatch */
  35186. return SQLITE_BUSY;
  35187. }
  35188. usleep(10000000); /* wait 10 sec and try the lock again */
  35189. continue;
  35190. }
  35191. assert( nTries==3 );
  35192. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  35193. rc = SQLITE_OK;
  35194. if( lockType==EXCLUSIVE_LOCK ){
  35195. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  35196. }
  35197. if( !rc ){
  35198. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  35199. }
  35200. }
  35201. }
  35202. } while( rc==SQLITE_BUSY && nTries<3 );
  35203. return rc;
  35204. }
  35205. /* Takes the conch by taking a shared lock and read the contents conch, if
  35206. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  35207. ** lockPath means that the lockPath in the conch file will be used if the
  35208. ** host IDs match, or a new lock path will be generated automatically
  35209. ** and written to the conch file.
  35210. */
  35211. static int proxyTakeConch(unixFile *pFile){
  35212. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35213. if( pCtx->conchHeld!=0 ){
  35214. return SQLITE_OK;
  35215. }else{
  35216. unixFile *conchFile = pCtx->conchFile;
  35217. uuid_t myHostID;
  35218. int pError = 0;
  35219. char readBuf[PROXY_MAXCONCHLEN];
  35220. char lockPath[MAXPATHLEN];
  35221. char *tempLockPath = NULL;
  35222. int rc = SQLITE_OK;
  35223. int createConch = 0;
  35224. int hostIdMatch = 0;
  35225. int readLen = 0;
  35226. int tryOldLockPath = 0;
  35227. int forceNewLockPath = 0;
  35228. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  35229. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  35230. osGetpid(0)));
  35231. rc = proxyGetHostID(myHostID, &pError);
  35232. if( (rc&0xff)==SQLITE_IOERR ){
  35233. storeLastErrno(pFile, pError);
  35234. goto end_takeconch;
  35235. }
  35236. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  35237. if( rc!=SQLITE_OK ){
  35238. goto end_takeconch;
  35239. }
  35240. /* read the existing conch file */
  35241. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  35242. if( readLen<0 ){
  35243. /* I/O error: lastErrno set by seekAndRead */
  35244. storeLastErrno(pFile, conchFile->lastErrno);
  35245. rc = SQLITE_IOERR_READ;
  35246. goto end_takeconch;
  35247. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  35248. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  35249. /* a short read or version format mismatch means we need to create a new
  35250. ** conch file.
  35251. */
  35252. createConch = 1;
  35253. }
  35254. /* if the host id matches and the lock path already exists in the conch
  35255. ** we'll try to use the path there, if we can't open that path, we'll
  35256. ** retry with a new auto-generated path
  35257. */
  35258. do { /* in case we need to try again for an :auto: named lock file */
  35259. if( !createConch && !forceNewLockPath ){
  35260. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  35261. PROXY_HOSTIDLEN);
  35262. /* if the conch has data compare the contents */
  35263. if( !pCtx->lockProxyPath ){
  35264. /* for auto-named local lock file, just check the host ID and we'll
  35265. ** use the local lock file path that's already in there
  35266. */
  35267. if( hostIdMatch ){
  35268. size_t pathLen = (readLen - PROXY_PATHINDEX);
  35269. if( pathLen>=MAXPATHLEN ){
  35270. pathLen=MAXPATHLEN-1;
  35271. }
  35272. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  35273. lockPath[pathLen] = 0;
  35274. tempLockPath = lockPath;
  35275. tryOldLockPath = 1;
  35276. /* create a copy of the lock path if the conch is taken */
  35277. goto end_takeconch;
  35278. }
  35279. }else if( hostIdMatch
  35280. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  35281. readLen-PROXY_PATHINDEX)
  35282. ){
  35283. /* conch host and lock path match */
  35284. goto end_takeconch;
  35285. }
  35286. }
  35287. /* if the conch isn't writable and doesn't match, we can't take it */
  35288. if( (conchFile->openFlags&O_RDWR) == 0 ){
  35289. rc = SQLITE_BUSY;
  35290. goto end_takeconch;
  35291. }
  35292. /* either the conch didn't match or we need to create a new one */
  35293. if( !pCtx->lockProxyPath ){
  35294. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  35295. tempLockPath = lockPath;
  35296. /* create a copy of the lock path _only_ if the conch is taken */
  35297. }
  35298. /* update conch with host and path (this will fail if other process
  35299. ** has a shared lock already), if the host id matches, use the big
  35300. ** stick.
  35301. */
  35302. futimes(conchFile->h, NULL);
  35303. if( hostIdMatch && !createConch ){
  35304. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  35305. /* We are trying for an exclusive lock but another thread in this
  35306. ** same process is still holding a shared lock. */
  35307. rc = SQLITE_BUSY;
  35308. } else {
  35309. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  35310. }
  35311. }else{
  35312. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  35313. }
  35314. if( rc==SQLITE_OK ){
  35315. char writeBuffer[PROXY_MAXCONCHLEN];
  35316. int writeSize = 0;
  35317. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  35318. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  35319. if( pCtx->lockProxyPath!=NULL ){
  35320. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  35321. MAXPATHLEN);
  35322. }else{
  35323. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  35324. }
  35325. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  35326. robust_ftruncate(conchFile->h, writeSize);
  35327. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  35328. full_fsync(conchFile->h,0,0);
  35329. /* If we created a new conch file (not just updated the contents of a
  35330. ** valid conch file), try to match the permissions of the database
  35331. */
  35332. if( rc==SQLITE_OK && createConch ){
  35333. struct stat buf;
  35334. int err = osFstat(pFile->h, &buf);
  35335. if( err==0 ){
  35336. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  35337. S_IROTH|S_IWOTH);
  35338. /* try to match the database file R/W permissions, ignore failure */
  35339. #ifndef SQLITE_PROXY_DEBUG
  35340. osFchmod(conchFile->h, cmode);
  35341. #else
  35342. do{
  35343. rc = osFchmod(conchFile->h, cmode);
  35344. }while( rc==(-1) && errno==EINTR );
  35345. if( rc!=0 ){
  35346. int code = errno;
  35347. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  35348. cmode, code, strerror(code));
  35349. } else {
  35350. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  35351. }
  35352. }else{
  35353. int code = errno;
  35354. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  35355. err, code, strerror(code));
  35356. #endif
  35357. }
  35358. }
  35359. }
  35360. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  35361. end_takeconch:
  35362. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  35363. if( rc==SQLITE_OK && pFile->openFlags ){
  35364. int fd;
  35365. if( pFile->h>=0 ){
  35366. robust_close(pFile, pFile->h, __LINE__);
  35367. }
  35368. pFile->h = -1;
  35369. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  35370. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  35371. if( fd>=0 ){
  35372. pFile->h = fd;
  35373. }else{
  35374. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  35375. during locking */
  35376. }
  35377. }
  35378. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  35379. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  35380. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  35381. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  35382. /* we couldn't create the proxy lock file with the old lock file path
  35383. ** so try again via auto-naming
  35384. */
  35385. forceNewLockPath = 1;
  35386. tryOldLockPath = 0;
  35387. continue; /* go back to the do {} while start point, try again */
  35388. }
  35389. }
  35390. if( rc==SQLITE_OK ){
  35391. /* Need to make a copy of path if we extracted the value
  35392. ** from the conch file or the path was allocated on the stack
  35393. */
  35394. if( tempLockPath ){
  35395. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  35396. if( !pCtx->lockProxyPath ){
  35397. rc = SQLITE_NOMEM_BKPT;
  35398. }
  35399. }
  35400. }
  35401. if( rc==SQLITE_OK ){
  35402. pCtx->conchHeld = 1;
  35403. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  35404. afpLockingContext *afpCtx;
  35405. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  35406. afpCtx->dbPath = pCtx->lockProxyPath;
  35407. }
  35408. } else {
  35409. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  35410. }
  35411. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  35412. rc==SQLITE_OK?"ok":"failed"));
  35413. return rc;
  35414. } while (1); /* in case we need to retry the :auto: lock file -
  35415. ** we should never get here except via the 'continue' call. */
  35416. }
  35417. }
  35418. /*
  35419. ** If pFile holds a lock on a conch file, then release that lock.
  35420. */
  35421. static int proxyReleaseConch(unixFile *pFile){
  35422. int rc = SQLITE_OK; /* Subroutine return code */
  35423. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  35424. unixFile *conchFile; /* Name of the conch file */
  35425. pCtx = (proxyLockingContext *)pFile->lockingContext;
  35426. conchFile = pCtx->conchFile;
  35427. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  35428. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  35429. osGetpid(0)));
  35430. if( pCtx->conchHeld>0 ){
  35431. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  35432. }
  35433. pCtx->conchHeld = 0;
  35434. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  35435. (rc==SQLITE_OK ? "ok" : "failed")));
  35436. return rc;
  35437. }
  35438. /*
  35439. ** Given the name of a database file, compute the name of its conch file.
  35440. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  35441. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  35442. ** or SQLITE_NOMEM if unable to obtain memory.
  35443. **
  35444. ** The caller is responsible for ensuring that the allocated memory
  35445. ** space is eventually freed.
  35446. **
  35447. ** *pConchPath is set to NULL if a memory allocation error occurs.
  35448. */
  35449. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  35450. int i; /* Loop counter */
  35451. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  35452. char *conchPath; /* buffer in which to construct conch name */
  35453. /* Allocate space for the conch filename and initialize the name to
  35454. ** the name of the original database file. */
  35455. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  35456. if( conchPath==0 ){
  35457. return SQLITE_NOMEM_BKPT;
  35458. }
  35459. memcpy(conchPath, dbPath, len+1);
  35460. /* now insert a "." before the last / character */
  35461. for( i=(len-1); i>=0; i-- ){
  35462. if( conchPath[i]=='/' ){
  35463. i++;
  35464. break;
  35465. }
  35466. }
  35467. conchPath[i]='.';
  35468. while ( i<len ){
  35469. conchPath[i+1]=dbPath[i];
  35470. i++;
  35471. }
  35472. /* append the "-conch" suffix to the file */
  35473. memcpy(&conchPath[i+1], "-conch", 7);
  35474. assert( (int)strlen(conchPath) == len+7 );
  35475. return SQLITE_OK;
  35476. }
  35477. /* Takes a fully configured proxy locking-style unix file and switches
  35478. ** the local lock file path
  35479. */
  35480. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  35481. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  35482. char *oldPath = pCtx->lockProxyPath;
  35483. int rc = SQLITE_OK;
  35484. if( pFile->eFileLock!=NO_LOCK ){
  35485. return SQLITE_BUSY;
  35486. }
  35487. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  35488. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  35489. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  35490. return SQLITE_OK;
  35491. }else{
  35492. unixFile *lockProxy = pCtx->lockProxy;
  35493. pCtx->lockProxy=NULL;
  35494. pCtx->conchHeld = 0;
  35495. if( lockProxy!=NULL ){
  35496. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  35497. if( rc ) return rc;
  35498. sqlite3_free(lockProxy);
  35499. }
  35500. sqlite3_free(oldPath);
  35501. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  35502. }
  35503. return rc;
  35504. }
  35505. /*
  35506. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  35507. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  35508. **
  35509. ** This routine find the filename associated with pFile and writes it
  35510. ** int dbPath.
  35511. */
  35512. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  35513. #if defined(__APPLE__)
  35514. if( pFile->pMethod == &afpIoMethods ){
  35515. /* afp style keeps a reference to the db path in the filePath field
  35516. ** of the struct */
  35517. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  35518. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  35519. MAXPATHLEN);
  35520. } else
  35521. #endif
  35522. if( pFile->pMethod == &dotlockIoMethods ){
  35523. /* dot lock style uses the locking context to store the dot lock
  35524. ** file path */
  35525. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  35526. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  35527. }else{
  35528. /* all other styles use the locking context to store the db file path */
  35529. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  35530. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  35531. }
  35532. return SQLITE_OK;
  35533. }
  35534. /*
  35535. ** Takes an already filled in unix file and alters it so all file locking
  35536. ** will be performed on the local proxy lock file. The following fields
  35537. ** are preserved in the locking context so that they can be restored and
  35538. ** the unix structure properly cleaned up at close time:
  35539. ** ->lockingContext
  35540. ** ->pMethod
  35541. */
  35542. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  35543. proxyLockingContext *pCtx;
  35544. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  35545. char *lockPath=NULL;
  35546. int rc = SQLITE_OK;
  35547. if( pFile->eFileLock!=NO_LOCK ){
  35548. return SQLITE_BUSY;
  35549. }
  35550. proxyGetDbPathForUnixFile(pFile, dbPath);
  35551. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  35552. lockPath=NULL;
  35553. }else{
  35554. lockPath=(char *)path;
  35555. }
  35556. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  35557. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  35558. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  35559. if( pCtx==0 ){
  35560. return SQLITE_NOMEM_BKPT;
  35561. }
  35562. memset(pCtx, 0, sizeof(*pCtx));
  35563. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  35564. if( rc==SQLITE_OK ){
  35565. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  35566. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  35567. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  35568. ** (c) the file system is read-only, then enable no-locking access.
  35569. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  35570. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  35571. */
  35572. struct statfs fsInfo;
  35573. struct stat conchInfo;
  35574. int goLockless = 0;
  35575. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  35576. int err = errno;
  35577. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  35578. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  35579. }
  35580. }
  35581. if( goLockless ){
  35582. pCtx->conchHeld = -1; /* read only FS/ lockless */
  35583. rc = SQLITE_OK;
  35584. }
  35585. }
  35586. }
  35587. if( rc==SQLITE_OK && lockPath ){
  35588. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  35589. }
  35590. if( rc==SQLITE_OK ){
  35591. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  35592. if( pCtx->dbPath==NULL ){
  35593. rc = SQLITE_NOMEM_BKPT;
  35594. }
  35595. }
  35596. if( rc==SQLITE_OK ){
  35597. /* all memory is allocated, proxys are created and assigned,
  35598. ** switch the locking context and pMethod then return.
  35599. */
  35600. pCtx->oldLockingContext = pFile->lockingContext;
  35601. pFile->lockingContext = pCtx;
  35602. pCtx->pOldMethod = pFile->pMethod;
  35603. pFile->pMethod = &proxyIoMethods;
  35604. }else{
  35605. if( pCtx->conchFile ){
  35606. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  35607. sqlite3_free(pCtx->conchFile);
  35608. }
  35609. sqlite3DbFree(0, pCtx->lockProxyPath);
  35610. sqlite3_free(pCtx->conchFilePath);
  35611. sqlite3_free(pCtx);
  35612. }
  35613. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  35614. (rc==SQLITE_OK ? "ok" : "failed")));
  35615. return rc;
  35616. }
  35617. /*
  35618. ** This routine handles sqlite3_file_control() calls that are specific
  35619. ** to proxy locking.
  35620. */
  35621. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  35622. switch( op ){
  35623. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  35624. unixFile *pFile = (unixFile*)id;
  35625. if( pFile->pMethod == &proxyIoMethods ){
  35626. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  35627. proxyTakeConch(pFile);
  35628. if( pCtx->lockProxyPath ){
  35629. *(const char **)pArg = pCtx->lockProxyPath;
  35630. }else{
  35631. *(const char **)pArg = ":auto: (not held)";
  35632. }
  35633. } else {
  35634. *(const char **)pArg = NULL;
  35635. }
  35636. return SQLITE_OK;
  35637. }
  35638. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  35639. unixFile *pFile = (unixFile*)id;
  35640. int rc = SQLITE_OK;
  35641. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  35642. if( pArg==NULL || (const char *)pArg==0 ){
  35643. if( isProxyStyle ){
  35644. /* turn off proxy locking - not supported. If support is added for
  35645. ** switching proxy locking mode off then it will need to fail if
  35646. ** the journal mode is WAL mode.
  35647. */
  35648. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  35649. }else{
  35650. /* turn off proxy locking - already off - NOOP */
  35651. rc = SQLITE_OK;
  35652. }
  35653. }else{
  35654. const char *proxyPath = (const char *)pArg;
  35655. if( isProxyStyle ){
  35656. proxyLockingContext *pCtx =
  35657. (proxyLockingContext*)pFile->lockingContext;
  35658. if( !strcmp(pArg, ":auto:")
  35659. || (pCtx->lockProxyPath &&
  35660. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  35661. ){
  35662. rc = SQLITE_OK;
  35663. }else{
  35664. rc = switchLockProxyPath(pFile, proxyPath);
  35665. }
  35666. }else{
  35667. /* turn on proxy file locking */
  35668. rc = proxyTransformUnixFile(pFile, proxyPath);
  35669. }
  35670. }
  35671. return rc;
  35672. }
  35673. default: {
  35674. assert( 0 ); /* The call assures that only valid opcodes are sent */
  35675. }
  35676. }
  35677. /*NOTREACHED*/
  35678. return SQLITE_ERROR;
  35679. }
  35680. /*
  35681. ** Within this division (the proxying locking implementation) the procedures
  35682. ** above this point are all utilities. The lock-related methods of the
  35683. ** proxy-locking sqlite3_io_method object follow.
  35684. */
  35685. /*
  35686. ** This routine checks if there is a RESERVED lock held on the specified
  35687. ** file by this or any other process. If such a lock is held, set *pResOut
  35688. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35689. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35690. */
  35691. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  35692. unixFile *pFile = (unixFile*)id;
  35693. int rc = proxyTakeConch(pFile);
  35694. if( rc==SQLITE_OK ){
  35695. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35696. if( pCtx->conchHeld>0 ){
  35697. unixFile *proxy = pCtx->lockProxy;
  35698. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  35699. }else{ /* conchHeld < 0 is lockless */
  35700. pResOut=0;
  35701. }
  35702. }
  35703. return rc;
  35704. }
  35705. /*
  35706. ** Lock the file with the lock specified by parameter eFileLock - one
  35707. ** of the following:
  35708. **
  35709. ** (1) SHARED_LOCK
  35710. ** (2) RESERVED_LOCK
  35711. ** (3) PENDING_LOCK
  35712. ** (4) EXCLUSIVE_LOCK
  35713. **
  35714. ** Sometimes when requesting one lock state, additional lock states
  35715. ** are inserted in between. The locking might fail on one of the later
  35716. ** transitions leaving the lock state different from what it started but
  35717. ** still short of its goal. The following chart shows the allowed
  35718. ** transitions and the inserted intermediate states:
  35719. **
  35720. ** UNLOCKED -> SHARED
  35721. ** SHARED -> RESERVED
  35722. ** SHARED -> (PENDING) -> EXCLUSIVE
  35723. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35724. ** PENDING -> EXCLUSIVE
  35725. **
  35726. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35727. ** routine to lower a locking level.
  35728. */
  35729. static int proxyLock(sqlite3_file *id, int eFileLock) {
  35730. unixFile *pFile = (unixFile*)id;
  35731. int rc = proxyTakeConch(pFile);
  35732. if( rc==SQLITE_OK ){
  35733. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35734. if( pCtx->conchHeld>0 ){
  35735. unixFile *proxy = pCtx->lockProxy;
  35736. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  35737. pFile->eFileLock = proxy->eFileLock;
  35738. }else{
  35739. /* conchHeld < 0 is lockless */
  35740. }
  35741. }
  35742. return rc;
  35743. }
  35744. /*
  35745. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35746. ** must be either NO_LOCK or SHARED_LOCK.
  35747. **
  35748. ** If the locking level of the file descriptor is already at or below
  35749. ** the requested locking level, this routine is a no-op.
  35750. */
  35751. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  35752. unixFile *pFile = (unixFile*)id;
  35753. int rc = proxyTakeConch(pFile);
  35754. if( rc==SQLITE_OK ){
  35755. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35756. if( pCtx->conchHeld>0 ){
  35757. unixFile *proxy = pCtx->lockProxy;
  35758. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  35759. pFile->eFileLock = proxy->eFileLock;
  35760. }else{
  35761. /* conchHeld < 0 is lockless */
  35762. }
  35763. }
  35764. return rc;
  35765. }
  35766. /*
  35767. ** Close a file that uses proxy locks.
  35768. */
  35769. static int proxyClose(sqlite3_file *id) {
  35770. if( ALWAYS(id) ){
  35771. unixFile *pFile = (unixFile*)id;
  35772. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35773. unixFile *lockProxy = pCtx->lockProxy;
  35774. unixFile *conchFile = pCtx->conchFile;
  35775. int rc = SQLITE_OK;
  35776. if( lockProxy ){
  35777. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  35778. if( rc ) return rc;
  35779. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  35780. if( rc ) return rc;
  35781. sqlite3_free(lockProxy);
  35782. pCtx->lockProxy = 0;
  35783. }
  35784. if( conchFile ){
  35785. if( pCtx->conchHeld ){
  35786. rc = proxyReleaseConch(pFile);
  35787. if( rc ) return rc;
  35788. }
  35789. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  35790. if( rc ) return rc;
  35791. sqlite3_free(conchFile);
  35792. }
  35793. sqlite3DbFree(0, pCtx->lockProxyPath);
  35794. sqlite3_free(pCtx->conchFilePath);
  35795. sqlite3DbFree(0, pCtx->dbPath);
  35796. /* restore the original locking context and pMethod then close it */
  35797. pFile->lockingContext = pCtx->oldLockingContext;
  35798. pFile->pMethod = pCtx->pOldMethod;
  35799. sqlite3_free(pCtx);
  35800. return pFile->pMethod->xClose(id);
  35801. }
  35802. return SQLITE_OK;
  35803. }
  35804. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35805. /*
  35806. ** The proxy locking style is intended for use with AFP filesystems.
  35807. ** And since AFP is only supported on MacOSX, the proxy locking is also
  35808. ** restricted to MacOSX.
  35809. **
  35810. **
  35811. ******************* End of the proxy lock implementation **********************
  35812. ******************************************************************************/
  35813. /*
  35814. ** Initialize the operating system interface.
  35815. **
  35816. ** This routine registers all VFS implementations for unix-like operating
  35817. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  35818. ** should be the only routines in this file that are visible from other
  35819. ** files.
  35820. **
  35821. ** This routine is called once during SQLite initialization and by a
  35822. ** single thread. The memory allocation and mutex subsystems have not
  35823. ** necessarily been initialized when this routine is called, and so they
  35824. ** should not be used.
  35825. */
  35826. SQLITE_API int sqlite3_os_init(void){
  35827. /*
  35828. ** The following macro defines an initializer for an sqlite3_vfs object.
  35829. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  35830. ** to the "finder" function. (pAppData is a pointer to a pointer because
  35831. ** silly C90 rules prohibit a void* from being cast to a function pointer
  35832. ** and so we have to go through the intermediate pointer to avoid problems
  35833. ** when compiling with -pedantic-errors on GCC.)
  35834. **
  35835. ** The FINDER parameter to this macro is the name of the pointer to the
  35836. ** finder-function. The finder-function returns a pointer to the
  35837. ** sqlite_io_methods object that implements the desired locking
  35838. ** behaviors. See the division above that contains the IOMETHODS
  35839. ** macro for addition information on finder-functions.
  35840. **
  35841. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  35842. ** object. But the "autolockIoFinder" available on MacOSX does a little
  35843. ** more than that; it looks at the filesystem type that hosts the
  35844. ** database file and tries to choose an locking method appropriate for
  35845. ** that filesystem time.
  35846. */
  35847. #define UNIXVFS(VFSNAME, FINDER) { \
  35848. 3, /* iVersion */ \
  35849. sizeof(unixFile), /* szOsFile */ \
  35850. MAX_PATHNAME, /* mxPathname */ \
  35851. 0, /* pNext */ \
  35852. VFSNAME, /* zName */ \
  35853. (void*)&FINDER, /* pAppData */ \
  35854. unixOpen, /* xOpen */ \
  35855. unixDelete, /* xDelete */ \
  35856. unixAccess, /* xAccess */ \
  35857. unixFullPathname, /* xFullPathname */ \
  35858. unixDlOpen, /* xDlOpen */ \
  35859. unixDlError, /* xDlError */ \
  35860. unixDlSym, /* xDlSym */ \
  35861. unixDlClose, /* xDlClose */ \
  35862. unixRandomness, /* xRandomness */ \
  35863. unixSleep, /* xSleep */ \
  35864. unixCurrentTime, /* xCurrentTime */ \
  35865. unixGetLastError, /* xGetLastError */ \
  35866. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  35867. unixSetSystemCall, /* xSetSystemCall */ \
  35868. unixGetSystemCall, /* xGetSystemCall */ \
  35869. unixNextSystemCall, /* xNextSystemCall */ \
  35870. }
  35871. /*
  35872. ** All default VFSes for unix are contained in the following array.
  35873. **
  35874. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  35875. ** by the SQLite core when the VFS is registered. So the following
  35876. ** array cannot be const.
  35877. */
  35878. static sqlite3_vfs aVfs[] = {
  35879. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35880. UNIXVFS("unix", autolockIoFinder ),
  35881. #elif OS_VXWORKS
  35882. UNIXVFS("unix", vxworksIoFinder ),
  35883. #else
  35884. UNIXVFS("unix", posixIoFinder ),
  35885. #endif
  35886. UNIXVFS("unix-none", nolockIoFinder ),
  35887. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  35888. UNIXVFS("unix-excl", posixIoFinder ),
  35889. #if OS_VXWORKS
  35890. UNIXVFS("unix-namedsem", semIoFinder ),
  35891. #endif
  35892. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  35893. UNIXVFS("unix-posix", posixIoFinder ),
  35894. #endif
  35895. #if SQLITE_ENABLE_LOCKING_STYLE
  35896. UNIXVFS("unix-flock", flockIoFinder ),
  35897. #endif
  35898. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35899. UNIXVFS("unix-afp", afpIoFinder ),
  35900. UNIXVFS("unix-nfs", nfsIoFinder ),
  35901. UNIXVFS("unix-proxy", proxyIoFinder ),
  35902. #endif
  35903. };
  35904. unsigned int i; /* Loop counter */
  35905. /* Double-check that the aSyscall[] array has been constructed
  35906. ** correctly. See ticket [bb3a86e890c8e96ab] */
  35907. assert( ArraySize(aSyscall)==29 );
  35908. /* Register all VFSes defined in the aVfs[] array */
  35909. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  35910. sqlite3_vfs_register(&aVfs[i], i==0);
  35911. }
  35912. return SQLITE_OK;
  35913. }
  35914. /*
  35915. ** Shutdown the operating system interface.
  35916. **
  35917. ** Some operating systems might need to do some cleanup in this routine,
  35918. ** to release dynamically allocated objects. But not on unix.
  35919. ** This routine is a no-op for unix.
  35920. */
  35921. SQLITE_API int sqlite3_os_end(void){
  35922. return SQLITE_OK;
  35923. }
  35924. #endif /* SQLITE_OS_UNIX */
  35925. /************** End of os_unix.c *********************************************/
  35926. /************** Begin file os_win.c ******************************************/
  35927. /*
  35928. ** 2004 May 22
  35929. **
  35930. ** The author disclaims copyright to this source code. In place of
  35931. ** a legal notice, here is a blessing:
  35932. **
  35933. ** May you do good and not evil.
  35934. ** May you find forgiveness for yourself and forgive others.
  35935. ** May you share freely, never taking more than you give.
  35936. **
  35937. ******************************************************************************
  35938. **
  35939. ** This file contains code that is specific to Windows.
  35940. */
  35941. /* #include "sqliteInt.h" */
  35942. #if SQLITE_OS_WIN /* This file is used for Windows only */
  35943. /*
  35944. ** Include code that is common to all os_*.c files
  35945. */
  35946. /************** Include os_common.h in the middle of os_win.c ****************/
  35947. /************** Begin file os_common.h ***************************************/
  35948. /*
  35949. ** 2004 May 22
  35950. **
  35951. ** The author disclaims copyright to this source code. In place of
  35952. ** a legal notice, here is a blessing:
  35953. **
  35954. ** May you do good and not evil.
  35955. ** May you find forgiveness for yourself and forgive others.
  35956. ** May you share freely, never taking more than you give.
  35957. **
  35958. ******************************************************************************
  35959. **
  35960. ** This file contains macros and a little bit of code that is common to
  35961. ** all of the platform-specific files (os_*.c) and is #included into those
  35962. ** files.
  35963. **
  35964. ** This file should be #included by the os_*.c files only. It is not a
  35965. ** general purpose header file.
  35966. */
  35967. #ifndef _OS_COMMON_H_
  35968. #define _OS_COMMON_H_
  35969. /*
  35970. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  35971. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  35972. ** switch. The following code should catch this problem at compile-time.
  35973. */
  35974. #ifdef MEMORY_DEBUG
  35975. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  35976. #endif
  35977. /*
  35978. ** Macros for performance tracing. Normally turned off. Only works
  35979. ** on i486 hardware.
  35980. */
  35981. #ifdef SQLITE_PERFORMANCE_TRACE
  35982. /*
  35983. ** hwtime.h contains inline assembler code for implementing
  35984. ** high-performance timing routines.
  35985. */
  35986. /************** Include hwtime.h in the middle of os_common.h ****************/
  35987. /************** Begin file hwtime.h ******************************************/
  35988. /*
  35989. ** 2008 May 27
  35990. **
  35991. ** The author disclaims copyright to this source code. In place of
  35992. ** a legal notice, here is a blessing:
  35993. **
  35994. ** May you do good and not evil.
  35995. ** May you find forgiveness for yourself and forgive others.
  35996. ** May you share freely, never taking more than you give.
  35997. **
  35998. ******************************************************************************
  35999. **
  36000. ** This file contains inline asm code for retrieving "high-performance"
  36001. ** counters for x86 class CPUs.
  36002. */
  36003. #ifndef SQLITE_HWTIME_H
  36004. #define SQLITE_HWTIME_H
  36005. /*
  36006. ** The following routine only works on pentium-class (or newer) processors.
  36007. ** It uses the RDTSC opcode to read the cycle count value out of the
  36008. ** processor and returns that value. This can be used for high-res
  36009. ** profiling.
  36010. */
  36011. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  36012. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  36013. #if defined(__GNUC__)
  36014. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36015. unsigned int lo, hi;
  36016. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  36017. return (sqlite_uint64)hi << 32 | lo;
  36018. }
  36019. #elif defined(_MSC_VER)
  36020. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  36021. __asm {
  36022. rdtsc
  36023. ret ; return value at EDX:EAX
  36024. }
  36025. }
  36026. #endif
  36027. #elif (defined(__GNUC__) && defined(__x86_64__))
  36028. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36029. unsigned long val;
  36030. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  36031. return val;
  36032. }
  36033. #elif (defined(__GNUC__) && defined(__ppc__))
  36034. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36035. unsigned long long retval;
  36036. unsigned long junk;
  36037. __asm__ __volatile__ ("\n\
  36038. 1: mftbu %1\n\
  36039. mftb %L0\n\
  36040. mftbu %0\n\
  36041. cmpw %0,%1\n\
  36042. bne 1b"
  36043. : "=r" (retval), "=r" (junk));
  36044. return retval;
  36045. }
  36046. #else
  36047. #error Need implementation of sqlite3Hwtime() for your platform.
  36048. /*
  36049. ** To compile without implementing sqlite3Hwtime() for your platform,
  36050. ** you can remove the above #error and use the following
  36051. ** stub function. You will lose timing support for many
  36052. ** of the debugging and testing utilities, but it should at
  36053. ** least compile and run.
  36054. */
  36055. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  36056. #endif
  36057. #endif /* !defined(SQLITE_HWTIME_H) */
  36058. /************** End of hwtime.h **********************************************/
  36059. /************** Continuing where we left off in os_common.h ******************/
  36060. static sqlite_uint64 g_start;
  36061. static sqlite_uint64 g_elapsed;
  36062. #define TIMER_START g_start=sqlite3Hwtime()
  36063. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  36064. #define TIMER_ELAPSED g_elapsed
  36065. #else
  36066. #define TIMER_START
  36067. #define TIMER_END
  36068. #define TIMER_ELAPSED ((sqlite_uint64)0)
  36069. #endif
  36070. /*
  36071. ** If we compile with the SQLITE_TEST macro set, then the following block
  36072. ** of code will give us the ability to simulate a disk I/O error. This
  36073. ** is used for testing the I/O recovery logic.
  36074. */
  36075. #if defined(SQLITE_TEST)
  36076. SQLITE_API extern int sqlite3_io_error_hit;
  36077. SQLITE_API extern int sqlite3_io_error_hardhit;
  36078. SQLITE_API extern int sqlite3_io_error_pending;
  36079. SQLITE_API extern int sqlite3_io_error_persist;
  36080. SQLITE_API extern int sqlite3_io_error_benign;
  36081. SQLITE_API extern int sqlite3_diskfull_pending;
  36082. SQLITE_API extern int sqlite3_diskfull;
  36083. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  36084. #define SimulateIOError(CODE) \
  36085. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  36086. || sqlite3_io_error_pending-- == 1 ) \
  36087. { local_ioerr(); CODE; }
  36088. static void local_ioerr(){
  36089. IOTRACE(("IOERR\n"));
  36090. sqlite3_io_error_hit++;
  36091. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  36092. }
  36093. #define SimulateDiskfullError(CODE) \
  36094. if( sqlite3_diskfull_pending ){ \
  36095. if( sqlite3_diskfull_pending == 1 ){ \
  36096. local_ioerr(); \
  36097. sqlite3_diskfull = 1; \
  36098. sqlite3_io_error_hit = 1; \
  36099. CODE; \
  36100. }else{ \
  36101. sqlite3_diskfull_pending--; \
  36102. } \
  36103. }
  36104. #else
  36105. #define SimulateIOErrorBenign(X)
  36106. #define SimulateIOError(A)
  36107. #define SimulateDiskfullError(A)
  36108. #endif /* defined(SQLITE_TEST) */
  36109. /*
  36110. ** When testing, keep a count of the number of open files.
  36111. */
  36112. #if defined(SQLITE_TEST)
  36113. SQLITE_API extern int sqlite3_open_file_count;
  36114. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  36115. #else
  36116. #define OpenCounter(X)
  36117. #endif /* defined(SQLITE_TEST) */
  36118. #endif /* !defined(_OS_COMMON_H_) */
  36119. /************** End of os_common.h *******************************************/
  36120. /************** Continuing where we left off in os_win.c *********************/
  36121. /*
  36122. ** Include the header file for the Windows VFS.
  36123. */
  36124. /* #include "os_win.h" */
  36125. /*
  36126. ** Compiling and using WAL mode requires several APIs that are only
  36127. ** available in Windows platforms based on the NT kernel.
  36128. */
  36129. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  36130. # error "WAL mode requires support from the Windows NT kernel, compile\
  36131. with SQLITE_OMIT_WAL."
  36132. #endif
  36133. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  36134. # error "Memory mapped files require support from the Windows NT kernel,\
  36135. compile with SQLITE_MAX_MMAP_SIZE=0."
  36136. #endif
  36137. /*
  36138. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  36139. ** based on the sub-platform)?
  36140. */
  36141. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  36142. # define SQLITE_WIN32_HAS_ANSI
  36143. #endif
  36144. /*
  36145. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  36146. ** based on the sub-platform)?
  36147. */
  36148. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  36149. !defined(SQLITE_WIN32_NO_WIDE)
  36150. # define SQLITE_WIN32_HAS_WIDE
  36151. #endif
  36152. /*
  36153. ** Make sure at least one set of Win32 APIs is available.
  36154. */
  36155. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  36156. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  36157. must be defined."
  36158. #endif
  36159. /*
  36160. ** Define the required Windows SDK version constants if they are not
  36161. ** already available.
  36162. */
  36163. #ifndef NTDDI_WIN8
  36164. # define NTDDI_WIN8 0x06020000
  36165. #endif
  36166. #ifndef NTDDI_WINBLUE
  36167. # define NTDDI_WINBLUE 0x06030000
  36168. #endif
  36169. #ifndef NTDDI_WINTHRESHOLD
  36170. # define NTDDI_WINTHRESHOLD 0x06040000
  36171. #endif
  36172. /*
  36173. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  36174. ** target system. GetVersionEx was first deprecated in Win8.1.
  36175. */
  36176. #ifndef SQLITE_WIN32_GETVERSIONEX
  36177. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  36178. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  36179. # else
  36180. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  36181. # endif
  36182. #endif
  36183. /*
  36184. ** Check to see if the CreateFileMappingA function is supported on the
  36185. ** target system. It is unavailable when using "mincore.lib" on Win10.
  36186. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  36187. */
  36188. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  36189. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  36190. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  36191. # else
  36192. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  36193. # endif
  36194. #endif
  36195. /*
  36196. ** This constant should already be defined (in the "WinDef.h" SDK file).
  36197. */
  36198. #ifndef MAX_PATH
  36199. # define MAX_PATH (260)
  36200. #endif
  36201. /*
  36202. ** Maximum pathname length (in chars) for Win32. This should normally be
  36203. ** MAX_PATH.
  36204. */
  36205. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  36206. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  36207. #endif
  36208. /*
  36209. ** This constant should already be defined (in the "WinNT.h" SDK file).
  36210. */
  36211. #ifndef UNICODE_STRING_MAX_CHARS
  36212. # define UNICODE_STRING_MAX_CHARS (32767)
  36213. #endif
  36214. /*
  36215. ** Maximum pathname length (in chars) for WinNT. This should normally be
  36216. ** UNICODE_STRING_MAX_CHARS.
  36217. */
  36218. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  36219. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  36220. #endif
  36221. /*
  36222. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  36223. ** characters, so we allocate 4 bytes per character assuming worst-case of
  36224. ** 4-bytes-per-character for UTF8.
  36225. */
  36226. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  36227. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  36228. #endif
  36229. /*
  36230. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  36231. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  36232. */
  36233. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  36234. # define SQLITE_WINNT_MAX_PATH_BYTES \
  36235. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  36236. #endif
  36237. /*
  36238. ** Maximum error message length (in chars) for WinRT.
  36239. */
  36240. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  36241. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  36242. #endif
  36243. /*
  36244. ** Returns non-zero if the character should be treated as a directory
  36245. ** separator.
  36246. */
  36247. #ifndef winIsDirSep
  36248. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  36249. #endif
  36250. /*
  36251. ** This macro is used when a local variable is set to a value that is
  36252. ** [sometimes] not used by the code (e.g. via conditional compilation).
  36253. */
  36254. #ifndef UNUSED_VARIABLE_VALUE
  36255. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  36256. #endif
  36257. /*
  36258. ** Returns the character that should be used as the directory separator.
  36259. */
  36260. #ifndef winGetDirSep
  36261. # define winGetDirSep() '\\'
  36262. #endif
  36263. /*
  36264. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  36265. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  36266. ** CE SDK; however, they are not present in the header file)?
  36267. */
  36268. #if SQLITE_WIN32_FILEMAPPING_API && \
  36269. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36270. /*
  36271. ** Two of the file mapping APIs are different under WinRT. Figure out which
  36272. ** set we need.
  36273. */
  36274. #if SQLITE_OS_WINRT
  36275. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  36276. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  36277. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  36278. #else
  36279. #if defined(SQLITE_WIN32_HAS_ANSI)
  36280. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  36281. DWORD, DWORD, DWORD, LPCSTR);
  36282. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  36283. #if defined(SQLITE_WIN32_HAS_WIDE)
  36284. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  36285. DWORD, DWORD, DWORD, LPCWSTR);
  36286. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  36287. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  36288. #endif /* SQLITE_OS_WINRT */
  36289. /*
  36290. ** These file mapping APIs are common to both Win32 and WinRT.
  36291. */
  36292. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  36293. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  36294. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  36295. /*
  36296. ** Some Microsoft compilers lack this definition.
  36297. */
  36298. #ifndef INVALID_FILE_ATTRIBUTES
  36299. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  36300. #endif
  36301. #ifndef FILE_FLAG_MASK
  36302. # define FILE_FLAG_MASK (0xFF3C0000)
  36303. #endif
  36304. #ifndef FILE_ATTRIBUTE_MASK
  36305. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  36306. #endif
  36307. #ifndef SQLITE_OMIT_WAL
  36308. /* Forward references to structures used for WAL */
  36309. typedef struct winShm winShm; /* A connection to shared-memory */
  36310. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  36311. #endif
  36312. /*
  36313. ** WinCE lacks native support for file locking so we have to fake it
  36314. ** with some code of our own.
  36315. */
  36316. #if SQLITE_OS_WINCE
  36317. typedef struct winceLock {
  36318. int nReaders; /* Number of reader locks obtained */
  36319. BOOL bPending; /* Indicates a pending lock has been obtained */
  36320. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  36321. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  36322. } winceLock;
  36323. #endif
  36324. /*
  36325. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  36326. ** portability layer.
  36327. */
  36328. typedef struct winFile winFile;
  36329. struct winFile {
  36330. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  36331. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  36332. HANDLE h; /* Handle for accessing the file */
  36333. u8 locktype; /* Type of lock currently held on this file */
  36334. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  36335. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  36336. DWORD lastErrno; /* The Windows errno from the last I/O error */
  36337. #ifndef SQLITE_OMIT_WAL
  36338. winShm *pShm; /* Instance of shared memory on this file */
  36339. #endif
  36340. const char *zPath; /* Full pathname of this file */
  36341. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  36342. #if SQLITE_OS_WINCE
  36343. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  36344. HANDLE hMutex; /* Mutex used to control access to shared lock */
  36345. HANDLE hShared; /* Shared memory segment used for locking */
  36346. winceLock local; /* Locks obtained by this instance of winFile */
  36347. winceLock *shared; /* Global shared lock memory for the file */
  36348. #endif
  36349. #if SQLITE_MAX_MMAP_SIZE>0
  36350. int nFetchOut; /* Number of outstanding xFetch references */
  36351. HANDLE hMap; /* Handle for accessing memory mapping */
  36352. void *pMapRegion; /* Area memory mapped */
  36353. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  36354. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  36355. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  36356. #endif
  36357. };
  36358. /*
  36359. ** The winVfsAppData structure is used for the pAppData member for all of the
  36360. ** Win32 VFS variants.
  36361. */
  36362. typedef struct winVfsAppData winVfsAppData;
  36363. struct winVfsAppData {
  36364. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  36365. void *pAppData; /* The extra pAppData, if any. */
  36366. BOOL bNoLock; /* Non-zero if locking is disabled. */
  36367. };
  36368. /*
  36369. ** Allowed values for winFile.ctrlFlags
  36370. */
  36371. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  36372. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  36373. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  36374. /*
  36375. * The size of the buffer used by sqlite3_win32_write_debug().
  36376. */
  36377. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  36378. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  36379. #endif
  36380. /*
  36381. * The value used with sqlite3_win32_set_directory() to specify that
  36382. * the data directory should be changed.
  36383. */
  36384. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  36385. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  36386. #endif
  36387. /*
  36388. * The value used with sqlite3_win32_set_directory() to specify that
  36389. * the temporary directory should be changed.
  36390. */
  36391. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  36392. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  36393. #endif
  36394. /*
  36395. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  36396. * various Win32 API heap functions instead of our own.
  36397. */
  36398. #ifdef SQLITE_WIN32_MALLOC
  36399. /*
  36400. * If this is non-zero, an isolated heap will be created by the native Win32
  36401. * allocator subsystem; otherwise, the default process heap will be used. This
  36402. * setting has no effect when compiling for WinRT. By default, this is enabled
  36403. * and an isolated heap will be created to store all allocated data.
  36404. *
  36405. ******************************************************************************
  36406. * WARNING: It is important to note that when this setting is non-zero and the
  36407. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  36408. * function), all data that was allocated using the isolated heap will
  36409. * be freed immediately and any attempt to access any of that freed
  36410. * data will almost certainly result in an immediate access violation.
  36411. ******************************************************************************
  36412. */
  36413. #ifndef SQLITE_WIN32_HEAP_CREATE
  36414. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  36415. #endif
  36416. /*
  36417. * This is the maximum possible initial size of the Win32-specific heap, in
  36418. * bytes.
  36419. */
  36420. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  36421. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  36422. #endif
  36423. /*
  36424. * This is the extra space for the initial size of the Win32-specific heap,
  36425. * in bytes. This value may be zero.
  36426. */
  36427. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  36428. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  36429. #endif
  36430. /*
  36431. * Calculate the maximum legal cache size, in pages, based on the maximum
  36432. * possible initial heap size and the default page size, setting aside the
  36433. * needed extra space.
  36434. */
  36435. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  36436. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  36437. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  36438. (SQLITE_DEFAULT_PAGE_SIZE))
  36439. #endif
  36440. /*
  36441. * This is cache size used in the calculation of the initial size of the
  36442. * Win32-specific heap. It cannot be negative.
  36443. */
  36444. #ifndef SQLITE_WIN32_CACHE_SIZE
  36445. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  36446. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  36447. # else
  36448. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  36449. # endif
  36450. #endif
  36451. /*
  36452. * Make sure that the calculated cache size, in pages, cannot cause the
  36453. * initial size of the Win32-specific heap to exceed the maximum amount
  36454. * of memory that can be specified in the call to HeapCreate.
  36455. */
  36456. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  36457. # undef SQLITE_WIN32_CACHE_SIZE
  36458. # define SQLITE_WIN32_CACHE_SIZE (2000)
  36459. #endif
  36460. /*
  36461. * The initial size of the Win32-specific heap. This value may be zero.
  36462. */
  36463. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  36464. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  36465. (SQLITE_DEFAULT_PAGE_SIZE) + \
  36466. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  36467. #endif
  36468. /*
  36469. * The maximum size of the Win32-specific heap. This value may be zero.
  36470. */
  36471. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  36472. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  36473. #endif
  36474. /*
  36475. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  36476. * zero for the default behavior.
  36477. */
  36478. #ifndef SQLITE_WIN32_HEAP_FLAGS
  36479. # define SQLITE_WIN32_HEAP_FLAGS (0)
  36480. #endif
  36481. /*
  36482. ** The winMemData structure stores information required by the Win32-specific
  36483. ** sqlite3_mem_methods implementation.
  36484. */
  36485. typedef struct winMemData winMemData;
  36486. struct winMemData {
  36487. #ifndef NDEBUG
  36488. u32 magic1; /* Magic number to detect structure corruption. */
  36489. #endif
  36490. HANDLE hHeap; /* The handle to our heap. */
  36491. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  36492. #ifndef NDEBUG
  36493. u32 magic2; /* Magic number to detect structure corruption. */
  36494. #endif
  36495. };
  36496. #ifndef NDEBUG
  36497. #define WINMEM_MAGIC1 0x42b2830b
  36498. #define WINMEM_MAGIC2 0xbd4d7cf4
  36499. #endif
  36500. static struct winMemData win_mem_data = {
  36501. #ifndef NDEBUG
  36502. WINMEM_MAGIC1,
  36503. #endif
  36504. NULL, FALSE
  36505. #ifndef NDEBUG
  36506. ,WINMEM_MAGIC2
  36507. #endif
  36508. };
  36509. #ifndef NDEBUG
  36510. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  36511. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  36512. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  36513. #else
  36514. #define winMemAssertMagic()
  36515. #endif
  36516. #define winMemGetDataPtr() &win_mem_data
  36517. #define winMemGetHeap() win_mem_data.hHeap
  36518. #define winMemGetOwned() win_mem_data.bOwned
  36519. static void *winMemMalloc(int nBytes);
  36520. static void winMemFree(void *pPrior);
  36521. static void *winMemRealloc(void *pPrior, int nBytes);
  36522. static int winMemSize(void *p);
  36523. static int winMemRoundup(int n);
  36524. static int winMemInit(void *pAppData);
  36525. static void winMemShutdown(void *pAppData);
  36526. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  36527. #endif /* SQLITE_WIN32_MALLOC */
  36528. /*
  36529. ** The following variable is (normally) set once and never changes
  36530. ** thereafter. It records whether the operating system is Win9x
  36531. ** or WinNT.
  36532. **
  36533. ** 0: Operating system unknown.
  36534. ** 1: Operating system is Win9x.
  36535. ** 2: Operating system is WinNT.
  36536. **
  36537. ** In order to facilitate testing on a WinNT system, the test fixture
  36538. ** can manually set this value to 1 to emulate Win98 behavior.
  36539. */
  36540. #ifdef SQLITE_TEST
  36541. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36542. #else
  36543. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36544. #endif
  36545. #ifndef SYSCALL
  36546. # define SYSCALL sqlite3_syscall_ptr
  36547. #endif
  36548. /*
  36549. ** This function is not available on Windows CE or WinRT.
  36550. */
  36551. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  36552. # define osAreFileApisANSI() 1
  36553. #endif
  36554. /*
  36555. ** Many system calls are accessed through pointer-to-functions so that
  36556. ** they may be overridden at runtime to facilitate fault injection during
  36557. ** testing and sandboxing. The following array holds the names and pointers
  36558. ** to all overrideable system calls.
  36559. */
  36560. static struct win_syscall {
  36561. const char *zName; /* Name of the system call */
  36562. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  36563. sqlite3_syscall_ptr pDefault; /* Default value */
  36564. } aSyscall[] = {
  36565. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36566. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  36567. #else
  36568. { "AreFileApisANSI", (SYSCALL)0, 0 },
  36569. #endif
  36570. #ifndef osAreFileApisANSI
  36571. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  36572. #endif
  36573. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36574. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  36575. #else
  36576. { "CharLowerW", (SYSCALL)0, 0 },
  36577. #endif
  36578. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  36579. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36580. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  36581. #else
  36582. { "CharUpperW", (SYSCALL)0, 0 },
  36583. #endif
  36584. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  36585. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  36586. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  36587. #if defined(SQLITE_WIN32_HAS_ANSI)
  36588. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  36589. #else
  36590. { "CreateFileA", (SYSCALL)0, 0 },
  36591. #endif
  36592. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  36593. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  36594. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36595. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  36596. #else
  36597. { "CreateFileW", (SYSCALL)0, 0 },
  36598. #endif
  36599. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  36600. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  36601. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  36602. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  36603. SQLITE_WIN32_CREATEFILEMAPPINGA
  36604. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  36605. #else
  36606. { "CreateFileMappingA", (SYSCALL)0, 0 },
  36607. #endif
  36608. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36609. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  36610. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36611. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36612. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  36613. #else
  36614. { "CreateFileMappingW", (SYSCALL)0, 0 },
  36615. #endif
  36616. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36617. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  36618. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36619. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  36620. #else
  36621. { "CreateMutexW", (SYSCALL)0, 0 },
  36622. #endif
  36623. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  36624. LPCWSTR))aSyscall[8].pCurrent)
  36625. #if defined(SQLITE_WIN32_HAS_ANSI)
  36626. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  36627. #else
  36628. { "DeleteFileA", (SYSCALL)0, 0 },
  36629. #endif
  36630. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  36631. #if defined(SQLITE_WIN32_HAS_WIDE)
  36632. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  36633. #else
  36634. { "DeleteFileW", (SYSCALL)0, 0 },
  36635. #endif
  36636. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  36637. #if SQLITE_OS_WINCE
  36638. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  36639. #else
  36640. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  36641. #endif
  36642. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36643. LPFILETIME))aSyscall[11].pCurrent)
  36644. #if SQLITE_OS_WINCE
  36645. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  36646. #else
  36647. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  36648. #endif
  36649. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36650. LPSYSTEMTIME))aSyscall[12].pCurrent)
  36651. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  36652. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  36653. #if defined(SQLITE_WIN32_HAS_ANSI)
  36654. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  36655. #else
  36656. { "FormatMessageA", (SYSCALL)0, 0 },
  36657. #endif
  36658. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  36659. DWORD,va_list*))aSyscall[14].pCurrent)
  36660. #if defined(SQLITE_WIN32_HAS_WIDE)
  36661. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  36662. #else
  36663. { "FormatMessageW", (SYSCALL)0, 0 },
  36664. #endif
  36665. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  36666. DWORD,va_list*))aSyscall[15].pCurrent)
  36667. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36668. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  36669. #else
  36670. { "FreeLibrary", (SYSCALL)0, 0 },
  36671. #endif
  36672. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  36673. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  36674. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  36675. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36676. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  36677. #else
  36678. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  36679. #endif
  36680. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  36681. LPDWORD))aSyscall[18].pCurrent)
  36682. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36683. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  36684. #else
  36685. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  36686. #endif
  36687. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  36688. LPDWORD))aSyscall[19].pCurrent)
  36689. #if defined(SQLITE_WIN32_HAS_ANSI)
  36690. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  36691. #else
  36692. { "GetFileAttributesA", (SYSCALL)0, 0 },
  36693. #endif
  36694. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  36695. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36696. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  36697. #else
  36698. { "GetFileAttributesW", (SYSCALL)0, 0 },
  36699. #endif
  36700. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  36701. #if defined(SQLITE_WIN32_HAS_WIDE)
  36702. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  36703. #else
  36704. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  36705. #endif
  36706. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  36707. LPVOID))aSyscall[22].pCurrent)
  36708. #if !SQLITE_OS_WINRT
  36709. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  36710. #else
  36711. { "GetFileSize", (SYSCALL)0, 0 },
  36712. #endif
  36713. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  36714. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36715. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  36716. #else
  36717. { "GetFullPathNameA", (SYSCALL)0, 0 },
  36718. #endif
  36719. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  36720. LPSTR*))aSyscall[24].pCurrent)
  36721. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36722. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  36723. #else
  36724. { "GetFullPathNameW", (SYSCALL)0, 0 },
  36725. #endif
  36726. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  36727. LPWSTR*))aSyscall[25].pCurrent)
  36728. { "GetLastError", (SYSCALL)GetLastError, 0 },
  36729. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  36730. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36731. #if SQLITE_OS_WINCE
  36732. /* The GetProcAddressA() routine is only available on Windows CE. */
  36733. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  36734. #else
  36735. /* All other Windows platforms expect GetProcAddress() to take
  36736. ** an ANSI string regardless of the _UNICODE setting */
  36737. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  36738. #endif
  36739. #else
  36740. { "GetProcAddressA", (SYSCALL)0, 0 },
  36741. #endif
  36742. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  36743. LPCSTR))aSyscall[27].pCurrent)
  36744. #if !SQLITE_OS_WINRT
  36745. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  36746. #else
  36747. { "GetSystemInfo", (SYSCALL)0, 0 },
  36748. #endif
  36749. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  36750. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  36751. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  36752. #if !SQLITE_OS_WINCE
  36753. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  36754. #else
  36755. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  36756. #endif
  36757. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  36758. LPFILETIME))aSyscall[30].pCurrent)
  36759. #if defined(SQLITE_WIN32_HAS_ANSI)
  36760. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  36761. #else
  36762. { "GetTempPathA", (SYSCALL)0, 0 },
  36763. #endif
  36764. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  36765. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36766. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  36767. #else
  36768. { "GetTempPathW", (SYSCALL)0, 0 },
  36769. #endif
  36770. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  36771. #if !SQLITE_OS_WINRT
  36772. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  36773. #else
  36774. { "GetTickCount", (SYSCALL)0, 0 },
  36775. #endif
  36776. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  36777. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  36778. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  36779. #else
  36780. { "GetVersionExA", (SYSCALL)0, 0 },
  36781. #endif
  36782. #define osGetVersionExA ((BOOL(WINAPI*)( \
  36783. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  36784. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36785. SQLITE_WIN32_GETVERSIONEX
  36786. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  36787. #else
  36788. { "GetVersionExW", (SYSCALL)0, 0 },
  36789. #endif
  36790. #define osGetVersionExW ((BOOL(WINAPI*)( \
  36791. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  36792. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  36793. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  36794. SIZE_T))aSyscall[36].pCurrent)
  36795. #if !SQLITE_OS_WINRT
  36796. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  36797. #else
  36798. { "HeapCreate", (SYSCALL)0, 0 },
  36799. #endif
  36800. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  36801. SIZE_T))aSyscall[37].pCurrent)
  36802. #if !SQLITE_OS_WINRT
  36803. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  36804. #else
  36805. { "HeapDestroy", (SYSCALL)0, 0 },
  36806. #endif
  36807. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  36808. { "HeapFree", (SYSCALL)HeapFree, 0 },
  36809. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  36810. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  36811. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  36812. SIZE_T))aSyscall[40].pCurrent)
  36813. { "HeapSize", (SYSCALL)HeapSize, 0 },
  36814. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  36815. LPCVOID))aSyscall[41].pCurrent)
  36816. #if !SQLITE_OS_WINRT
  36817. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  36818. #else
  36819. { "HeapValidate", (SYSCALL)0, 0 },
  36820. #endif
  36821. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  36822. LPCVOID))aSyscall[42].pCurrent)
  36823. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36824. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  36825. #else
  36826. { "HeapCompact", (SYSCALL)0, 0 },
  36827. #endif
  36828. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  36829. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36830. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  36831. #else
  36832. { "LoadLibraryA", (SYSCALL)0, 0 },
  36833. #endif
  36834. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  36835. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36836. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36837. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  36838. #else
  36839. { "LoadLibraryW", (SYSCALL)0, 0 },
  36840. #endif
  36841. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  36842. #if !SQLITE_OS_WINRT
  36843. { "LocalFree", (SYSCALL)LocalFree, 0 },
  36844. #else
  36845. { "LocalFree", (SYSCALL)0, 0 },
  36846. #endif
  36847. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  36848. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36849. { "LockFile", (SYSCALL)LockFile, 0 },
  36850. #else
  36851. { "LockFile", (SYSCALL)0, 0 },
  36852. #endif
  36853. #ifndef osLockFile
  36854. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36855. DWORD))aSyscall[47].pCurrent)
  36856. #endif
  36857. #if !SQLITE_OS_WINCE
  36858. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  36859. #else
  36860. { "LockFileEx", (SYSCALL)0, 0 },
  36861. #endif
  36862. #ifndef osLockFileEx
  36863. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  36864. LPOVERLAPPED))aSyscall[48].pCurrent)
  36865. #endif
  36866. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  36867. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36868. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  36869. #else
  36870. { "MapViewOfFile", (SYSCALL)0, 0 },
  36871. #endif
  36872. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36873. SIZE_T))aSyscall[49].pCurrent)
  36874. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  36875. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  36876. int))aSyscall[50].pCurrent)
  36877. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  36878. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  36879. LARGE_INTEGER*))aSyscall[51].pCurrent)
  36880. { "ReadFile", (SYSCALL)ReadFile, 0 },
  36881. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  36882. LPOVERLAPPED))aSyscall[52].pCurrent)
  36883. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  36884. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  36885. #if !SQLITE_OS_WINRT
  36886. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  36887. #else
  36888. { "SetFilePointer", (SYSCALL)0, 0 },
  36889. #endif
  36890. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  36891. DWORD))aSyscall[54].pCurrent)
  36892. #if !SQLITE_OS_WINRT
  36893. { "Sleep", (SYSCALL)Sleep, 0 },
  36894. #else
  36895. { "Sleep", (SYSCALL)0, 0 },
  36896. #endif
  36897. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  36898. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  36899. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  36900. LPFILETIME))aSyscall[56].pCurrent)
  36901. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36902. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  36903. #else
  36904. { "UnlockFile", (SYSCALL)0, 0 },
  36905. #endif
  36906. #ifndef osUnlockFile
  36907. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36908. DWORD))aSyscall[57].pCurrent)
  36909. #endif
  36910. #if !SQLITE_OS_WINCE
  36911. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  36912. #else
  36913. { "UnlockFileEx", (SYSCALL)0, 0 },
  36914. #endif
  36915. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36916. LPOVERLAPPED))aSyscall[58].pCurrent)
  36917. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  36918. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  36919. #else
  36920. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  36921. #endif
  36922. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  36923. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  36924. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  36925. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  36926. { "WriteFile", (SYSCALL)WriteFile, 0 },
  36927. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  36928. LPOVERLAPPED))aSyscall[61].pCurrent)
  36929. #if SQLITE_OS_WINRT
  36930. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  36931. #else
  36932. { "CreateEventExW", (SYSCALL)0, 0 },
  36933. #endif
  36934. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  36935. DWORD,DWORD))aSyscall[62].pCurrent)
  36936. #if !SQLITE_OS_WINRT
  36937. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  36938. #else
  36939. { "WaitForSingleObject", (SYSCALL)0, 0 },
  36940. #endif
  36941. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  36942. DWORD))aSyscall[63].pCurrent)
  36943. #if !SQLITE_OS_WINCE
  36944. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  36945. #else
  36946. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  36947. #endif
  36948. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  36949. BOOL))aSyscall[64].pCurrent)
  36950. #if SQLITE_OS_WINRT
  36951. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  36952. #else
  36953. { "SetFilePointerEx", (SYSCALL)0, 0 },
  36954. #endif
  36955. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  36956. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  36957. #if SQLITE_OS_WINRT
  36958. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  36959. #else
  36960. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  36961. #endif
  36962. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  36963. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  36964. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36965. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  36966. #else
  36967. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  36968. #endif
  36969. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  36970. SIZE_T))aSyscall[67].pCurrent)
  36971. #if SQLITE_OS_WINRT
  36972. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  36973. #else
  36974. { "CreateFile2", (SYSCALL)0, 0 },
  36975. #endif
  36976. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  36977. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  36978. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36979. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  36980. #else
  36981. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  36982. #endif
  36983. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  36984. DWORD))aSyscall[69].pCurrent)
  36985. #if SQLITE_OS_WINRT
  36986. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  36987. #else
  36988. { "GetTickCount64", (SYSCALL)0, 0 },
  36989. #endif
  36990. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  36991. #if SQLITE_OS_WINRT
  36992. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  36993. #else
  36994. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  36995. #endif
  36996. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  36997. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  36998. #if defined(SQLITE_WIN32_HAS_ANSI)
  36999. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  37000. #else
  37001. { "OutputDebugStringA", (SYSCALL)0, 0 },
  37002. #endif
  37003. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  37004. #if defined(SQLITE_WIN32_HAS_WIDE)
  37005. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  37006. #else
  37007. { "OutputDebugStringW", (SYSCALL)0, 0 },
  37008. #endif
  37009. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  37010. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  37011. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  37012. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  37013. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  37014. #else
  37015. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  37016. #endif
  37017. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  37018. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  37019. /*
  37020. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  37021. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  37022. ** So do not try to make this is into a redefinable interface.
  37023. */
  37024. #if defined(InterlockedCompareExchange)
  37025. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  37026. #define osInterlockedCompareExchange InterlockedCompareExchange
  37027. #else
  37028. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  37029. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  37030. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  37031. #endif /* defined(InterlockedCompareExchange) */
  37032. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37033. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  37034. #else
  37035. { "UuidCreate", (SYSCALL)0, 0 },
  37036. #endif
  37037. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  37038. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37039. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  37040. #else
  37041. { "UuidCreateSequential", (SYSCALL)0, 0 },
  37042. #endif
  37043. #define osUuidCreateSequential \
  37044. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  37045. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  37046. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  37047. #else
  37048. { "FlushViewOfFile", (SYSCALL)0, 0 },
  37049. #endif
  37050. #define osFlushViewOfFile \
  37051. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  37052. }; /* End of the overrideable system calls */
  37053. /*
  37054. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  37055. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  37056. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  37057. ** system call named zName.
  37058. */
  37059. static int winSetSystemCall(
  37060. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  37061. const char *zName, /* Name of system call to override */
  37062. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  37063. ){
  37064. unsigned int i;
  37065. int rc = SQLITE_NOTFOUND;
  37066. UNUSED_PARAMETER(pNotUsed);
  37067. if( zName==0 ){
  37068. /* If no zName is given, restore all system calls to their default
  37069. ** settings and return NULL
  37070. */
  37071. rc = SQLITE_OK;
  37072. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  37073. if( aSyscall[i].pDefault ){
  37074. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  37075. }
  37076. }
  37077. }else{
  37078. /* If zName is specified, operate on only the one system call
  37079. ** specified.
  37080. */
  37081. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  37082. if( strcmp(zName, aSyscall[i].zName)==0 ){
  37083. if( aSyscall[i].pDefault==0 ){
  37084. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  37085. }
  37086. rc = SQLITE_OK;
  37087. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  37088. aSyscall[i].pCurrent = pNewFunc;
  37089. break;
  37090. }
  37091. }
  37092. }
  37093. return rc;
  37094. }
  37095. /*
  37096. ** Return the value of a system call. Return NULL if zName is not a
  37097. ** recognized system call name. NULL is also returned if the system call
  37098. ** is currently undefined.
  37099. */
  37100. static sqlite3_syscall_ptr winGetSystemCall(
  37101. sqlite3_vfs *pNotUsed,
  37102. const char *zName
  37103. ){
  37104. unsigned int i;
  37105. UNUSED_PARAMETER(pNotUsed);
  37106. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  37107. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  37108. }
  37109. return 0;
  37110. }
  37111. /*
  37112. ** Return the name of the first system call after zName. If zName==NULL
  37113. ** then return the name of the first system call. Return NULL if zName
  37114. ** is the last system call or if zName is not the name of a valid
  37115. ** system call.
  37116. */
  37117. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  37118. int i = -1;
  37119. UNUSED_PARAMETER(p);
  37120. if( zName ){
  37121. for(i=0; i<ArraySize(aSyscall)-1; i++){
  37122. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  37123. }
  37124. }
  37125. for(i++; i<ArraySize(aSyscall); i++){
  37126. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  37127. }
  37128. return 0;
  37129. }
  37130. #ifdef SQLITE_WIN32_MALLOC
  37131. /*
  37132. ** If a Win32 native heap has been configured, this function will attempt to
  37133. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  37134. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  37135. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  37136. ** largest committed free block in the heap, in bytes.
  37137. */
  37138. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  37139. int rc = SQLITE_OK;
  37140. UINT nLargest = 0;
  37141. HANDLE hHeap;
  37142. winMemAssertMagic();
  37143. hHeap = winMemGetHeap();
  37144. assert( hHeap!=0 );
  37145. assert( hHeap!=INVALID_HANDLE_VALUE );
  37146. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37147. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  37148. #endif
  37149. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37150. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  37151. DWORD lastErrno = osGetLastError();
  37152. if( lastErrno==NO_ERROR ){
  37153. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  37154. (void*)hHeap);
  37155. rc = SQLITE_NOMEM_BKPT;
  37156. }else{
  37157. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  37158. osGetLastError(), (void*)hHeap);
  37159. rc = SQLITE_ERROR;
  37160. }
  37161. }
  37162. #else
  37163. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  37164. (void*)hHeap);
  37165. rc = SQLITE_NOTFOUND;
  37166. #endif
  37167. if( pnLargest ) *pnLargest = nLargest;
  37168. return rc;
  37169. }
  37170. /*
  37171. ** If a Win32 native heap has been configured, this function will attempt to
  37172. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  37173. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  37174. ** be returned and no changes will be made to the Win32 native heap.
  37175. */
  37176. SQLITE_API int sqlite3_win32_reset_heap(){
  37177. int rc;
  37178. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  37179. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  37180. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  37181. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  37182. sqlite3_mutex_enter(pMaster);
  37183. sqlite3_mutex_enter(pMem);
  37184. winMemAssertMagic();
  37185. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  37186. /*
  37187. ** At this point, there should be no outstanding memory allocations on
  37188. ** the heap. Also, since both the master and memsys locks are currently
  37189. ** being held by us, no other function (i.e. from another thread) should
  37190. ** be able to even access the heap. Attempt to destroy and recreate our
  37191. ** isolated Win32 native heap now.
  37192. */
  37193. assert( winMemGetHeap()!=NULL );
  37194. assert( winMemGetOwned() );
  37195. assert( sqlite3_memory_used()==0 );
  37196. winMemShutdown(winMemGetDataPtr());
  37197. assert( winMemGetHeap()==NULL );
  37198. assert( !winMemGetOwned() );
  37199. assert( sqlite3_memory_used()==0 );
  37200. rc = winMemInit(winMemGetDataPtr());
  37201. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  37202. assert( rc!=SQLITE_OK || winMemGetOwned() );
  37203. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  37204. }else{
  37205. /*
  37206. ** The Win32 native heap cannot be modified because it may be in use.
  37207. */
  37208. rc = SQLITE_BUSY;
  37209. }
  37210. sqlite3_mutex_leave(pMem);
  37211. sqlite3_mutex_leave(pMaster);
  37212. return rc;
  37213. }
  37214. #endif /* SQLITE_WIN32_MALLOC */
  37215. /*
  37216. ** This function outputs the specified (ANSI) string to the Win32 debugger
  37217. ** (if available).
  37218. */
  37219. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  37220. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  37221. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  37222. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  37223. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  37224. #ifdef SQLITE_ENABLE_API_ARMOR
  37225. if( !zBuf ){
  37226. (void)SQLITE_MISUSE_BKPT;
  37227. return;
  37228. }
  37229. #endif
  37230. #if defined(SQLITE_WIN32_HAS_ANSI)
  37231. if( nMin>0 ){
  37232. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  37233. memcpy(zDbgBuf, zBuf, nMin);
  37234. osOutputDebugStringA(zDbgBuf);
  37235. }else{
  37236. osOutputDebugStringA(zBuf);
  37237. }
  37238. #elif defined(SQLITE_WIN32_HAS_WIDE)
  37239. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  37240. if ( osMultiByteToWideChar(
  37241. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  37242. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  37243. return;
  37244. }
  37245. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  37246. #else
  37247. if( nMin>0 ){
  37248. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  37249. memcpy(zDbgBuf, zBuf, nMin);
  37250. fprintf(stderr, "%s", zDbgBuf);
  37251. }else{
  37252. fprintf(stderr, "%s", zBuf);
  37253. }
  37254. #endif
  37255. }
  37256. /*
  37257. ** The following routine suspends the current thread for at least ms
  37258. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  37259. */
  37260. #if SQLITE_OS_WINRT
  37261. static HANDLE sleepObj = NULL;
  37262. #endif
  37263. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  37264. #if SQLITE_OS_WINRT
  37265. if ( sleepObj==NULL ){
  37266. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  37267. SYNCHRONIZE);
  37268. }
  37269. assert( sleepObj!=NULL );
  37270. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  37271. #else
  37272. osSleep(milliseconds);
  37273. #endif
  37274. }
  37275. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  37276. SQLITE_THREADSAFE>0
  37277. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  37278. DWORD rc;
  37279. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  37280. TRUE))==WAIT_IO_COMPLETION ){}
  37281. return rc;
  37282. }
  37283. #endif
  37284. /*
  37285. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  37286. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  37287. **
  37288. ** Here is an interesting observation: Win95, Win98, and WinME lack
  37289. ** the LockFileEx() API. But we can still statically link against that
  37290. ** API as long as we don't call it when running Win95/98/ME. A call to
  37291. ** this routine is used to determine if the host is Win95/98/ME or
  37292. ** WinNT/2K/XP so that we will know whether or not we can safely call
  37293. ** the LockFileEx() API.
  37294. */
  37295. #if !SQLITE_WIN32_GETVERSIONEX
  37296. # define osIsNT() (1)
  37297. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  37298. # define osIsNT() (1)
  37299. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  37300. # define osIsNT() (0)
  37301. #else
  37302. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  37303. #endif
  37304. /*
  37305. ** This function determines if the machine is running a version of Windows
  37306. ** based on the NT kernel.
  37307. */
  37308. SQLITE_API int sqlite3_win32_is_nt(void){
  37309. #if SQLITE_OS_WINRT
  37310. /*
  37311. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  37312. ** kernel.
  37313. */
  37314. return 1;
  37315. #elif SQLITE_WIN32_GETVERSIONEX
  37316. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  37317. #if defined(SQLITE_WIN32_HAS_ANSI)
  37318. OSVERSIONINFOA sInfo;
  37319. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  37320. osGetVersionExA(&sInfo);
  37321. osInterlockedCompareExchange(&sqlite3_os_type,
  37322. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  37323. #elif defined(SQLITE_WIN32_HAS_WIDE)
  37324. OSVERSIONINFOW sInfo;
  37325. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  37326. osGetVersionExW(&sInfo);
  37327. osInterlockedCompareExchange(&sqlite3_os_type,
  37328. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  37329. #endif
  37330. }
  37331. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  37332. #elif SQLITE_TEST
  37333. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  37334. #else
  37335. /*
  37336. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  37337. ** deprecated are always assumed to be based on the NT kernel.
  37338. */
  37339. return 1;
  37340. #endif
  37341. }
  37342. #ifdef SQLITE_WIN32_MALLOC
  37343. /*
  37344. ** Allocate nBytes of memory.
  37345. */
  37346. static void *winMemMalloc(int nBytes){
  37347. HANDLE hHeap;
  37348. void *p;
  37349. winMemAssertMagic();
  37350. hHeap = winMemGetHeap();
  37351. assert( hHeap!=0 );
  37352. assert( hHeap!=INVALID_HANDLE_VALUE );
  37353. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37354. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  37355. #endif
  37356. assert( nBytes>=0 );
  37357. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  37358. if( !p ){
  37359. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  37360. nBytes, osGetLastError(), (void*)hHeap);
  37361. }
  37362. return p;
  37363. }
  37364. /*
  37365. ** Free memory.
  37366. */
  37367. static void winMemFree(void *pPrior){
  37368. HANDLE hHeap;
  37369. winMemAssertMagic();
  37370. hHeap = winMemGetHeap();
  37371. assert( hHeap!=0 );
  37372. assert( hHeap!=INVALID_HANDLE_VALUE );
  37373. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37374. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  37375. #endif
  37376. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  37377. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  37378. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  37379. pPrior, osGetLastError(), (void*)hHeap);
  37380. }
  37381. }
  37382. /*
  37383. ** Change the size of an existing memory allocation
  37384. */
  37385. static void *winMemRealloc(void *pPrior, int nBytes){
  37386. HANDLE hHeap;
  37387. void *p;
  37388. winMemAssertMagic();
  37389. hHeap = winMemGetHeap();
  37390. assert( hHeap!=0 );
  37391. assert( hHeap!=INVALID_HANDLE_VALUE );
  37392. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37393. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  37394. #endif
  37395. assert( nBytes>=0 );
  37396. if( !pPrior ){
  37397. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  37398. }else{
  37399. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  37400. }
  37401. if( !p ){
  37402. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  37403. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  37404. (void*)hHeap);
  37405. }
  37406. return p;
  37407. }
  37408. /*
  37409. ** Return the size of an outstanding allocation, in bytes.
  37410. */
  37411. static int winMemSize(void *p){
  37412. HANDLE hHeap;
  37413. SIZE_T n;
  37414. winMemAssertMagic();
  37415. hHeap = winMemGetHeap();
  37416. assert( hHeap!=0 );
  37417. assert( hHeap!=INVALID_HANDLE_VALUE );
  37418. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37419. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  37420. #endif
  37421. if( !p ) return 0;
  37422. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  37423. if( n==(SIZE_T)-1 ){
  37424. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  37425. p, osGetLastError(), (void*)hHeap);
  37426. return 0;
  37427. }
  37428. return (int)n;
  37429. }
  37430. /*
  37431. ** Round up a request size to the next valid allocation size.
  37432. */
  37433. static int winMemRoundup(int n){
  37434. return n;
  37435. }
  37436. /*
  37437. ** Initialize this module.
  37438. */
  37439. static int winMemInit(void *pAppData){
  37440. winMemData *pWinMemData = (winMemData *)pAppData;
  37441. if( !pWinMemData ) return SQLITE_ERROR;
  37442. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  37443. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  37444. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  37445. if( !pWinMemData->hHeap ){
  37446. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  37447. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  37448. if( dwMaximumSize==0 ){
  37449. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  37450. }else if( dwInitialSize>dwMaximumSize ){
  37451. dwInitialSize = dwMaximumSize;
  37452. }
  37453. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  37454. dwInitialSize, dwMaximumSize);
  37455. if( !pWinMemData->hHeap ){
  37456. sqlite3_log(SQLITE_NOMEM,
  37457. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  37458. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  37459. dwMaximumSize);
  37460. return SQLITE_NOMEM_BKPT;
  37461. }
  37462. pWinMemData->bOwned = TRUE;
  37463. assert( pWinMemData->bOwned );
  37464. }
  37465. #else
  37466. pWinMemData->hHeap = osGetProcessHeap();
  37467. if( !pWinMemData->hHeap ){
  37468. sqlite3_log(SQLITE_NOMEM,
  37469. "failed to GetProcessHeap (%lu)", osGetLastError());
  37470. return SQLITE_NOMEM_BKPT;
  37471. }
  37472. pWinMemData->bOwned = FALSE;
  37473. assert( !pWinMemData->bOwned );
  37474. #endif
  37475. assert( pWinMemData->hHeap!=0 );
  37476. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  37477. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37478. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  37479. #endif
  37480. return SQLITE_OK;
  37481. }
  37482. /*
  37483. ** Deinitialize this module.
  37484. */
  37485. static void winMemShutdown(void *pAppData){
  37486. winMemData *pWinMemData = (winMemData *)pAppData;
  37487. if( !pWinMemData ) return;
  37488. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  37489. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  37490. if( pWinMemData->hHeap ){
  37491. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  37492. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  37493. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  37494. #endif
  37495. if( pWinMemData->bOwned ){
  37496. if( !osHeapDestroy(pWinMemData->hHeap) ){
  37497. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  37498. osGetLastError(), (void*)pWinMemData->hHeap);
  37499. }
  37500. pWinMemData->bOwned = FALSE;
  37501. }
  37502. pWinMemData->hHeap = NULL;
  37503. }
  37504. }
  37505. /*
  37506. ** Populate the low-level memory allocation function pointers in
  37507. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  37508. ** arguments specify the block of memory to manage.
  37509. **
  37510. ** This routine is only called by sqlite3_config(), and therefore
  37511. ** is not required to be threadsafe (it is not).
  37512. */
  37513. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  37514. static const sqlite3_mem_methods winMemMethods = {
  37515. winMemMalloc,
  37516. winMemFree,
  37517. winMemRealloc,
  37518. winMemSize,
  37519. winMemRoundup,
  37520. winMemInit,
  37521. winMemShutdown,
  37522. &win_mem_data
  37523. };
  37524. return &winMemMethods;
  37525. }
  37526. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  37527. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  37528. }
  37529. #endif /* SQLITE_WIN32_MALLOC */
  37530. /*
  37531. ** Convert a UTF-8 string to Microsoft Unicode.
  37532. **
  37533. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37534. */
  37535. static LPWSTR winUtf8ToUnicode(const char *zText){
  37536. int nChar;
  37537. LPWSTR zWideText;
  37538. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  37539. if( nChar==0 ){
  37540. return 0;
  37541. }
  37542. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  37543. if( zWideText==0 ){
  37544. return 0;
  37545. }
  37546. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  37547. nChar);
  37548. if( nChar==0 ){
  37549. sqlite3_free(zWideText);
  37550. zWideText = 0;
  37551. }
  37552. return zWideText;
  37553. }
  37554. /*
  37555. ** Convert a Microsoft Unicode string to UTF-8.
  37556. **
  37557. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37558. */
  37559. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  37560. int nByte;
  37561. char *zText;
  37562. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  37563. if( nByte == 0 ){
  37564. return 0;
  37565. }
  37566. zText = sqlite3MallocZero( nByte );
  37567. if( zText==0 ){
  37568. return 0;
  37569. }
  37570. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  37571. 0, 0);
  37572. if( nByte == 0 ){
  37573. sqlite3_free(zText);
  37574. zText = 0;
  37575. }
  37576. return zText;
  37577. }
  37578. /*
  37579. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  37580. ** code page.
  37581. **
  37582. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37583. */
  37584. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  37585. int nByte;
  37586. LPWSTR zMbcsText;
  37587. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37588. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  37589. 0)*sizeof(WCHAR);
  37590. if( nByte==0 ){
  37591. return 0;
  37592. }
  37593. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  37594. if( zMbcsText==0 ){
  37595. return 0;
  37596. }
  37597. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  37598. nByte);
  37599. if( nByte==0 ){
  37600. sqlite3_free(zMbcsText);
  37601. zMbcsText = 0;
  37602. }
  37603. return zMbcsText;
  37604. }
  37605. /*
  37606. ** Convert a Microsoft Unicode string to a multi-byte character string,
  37607. ** using the ANSI or OEM code page.
  37608. **
  37609. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37610. */
  37611. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  37612. int nByte;
  37613. char *zText;
  37614. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37615. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  37616. if( nByte == 0 ){
  37617. return 0;
  37618. }
  37619. zText = sqlite3MallocZero( nByte );
  37620. if( zText==0 ){
  37621. return 0;
  37622. }
  37623. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  37624. nByte, 0, 0);
  37625. if( nByte == 0 ){
  37626. sqlite3_free(zText);
  37627. zText = 0;
  37628. }
  37629. return zText;
  37630. }
  37631. /*
  37632. ** Convert a multi-byte character string to UTF-8.
  37633. **
  37634. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37635. */
  37636. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  37637. char *zTextUtf8;
  37638. LPWSTR zTmpWide;
  37639. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  37640. if( zTmpWide==0 ){
  37641. return 0;
  37642. }
  37643. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  37644. sqlite3_free(zTmpWide);
  37645. return zTextUtf8;
  37646. }
  37647. /*
  37648. ** Convert a UTF-8 string to a multi-byte character string.
  37649. **
  37650. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37651. */
  37652. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  37653. char *zTextMbcs;
  37654. LPWSTR zTmpWide;
  37655. zTmpWide = winUtf8ToUnicode(zText);
  37656. if( zTmpWide==0 ){
  37657. return 0;
  37658. }
  37659. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  37660. sqlite3_free(zTmpWide);
  37661. return zTextMbcs;
  37662. }
  37663. /*
  37664. ** This is a public wrapper for the winUtf8ToUnicode() function.
  37665. */
  37666. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  37667. #ifdef SQLITE_ENABLE_API_ARMOR
  37668. if( !zText ){
  37669. (void)SQLITE_MISUSE_BKPT;
  37670. return 0;
  37671. }
  37672. #endif
  37673. #ifndef SQLITE_OMIT_AUTOINIT
  37674. if( sqlite3_initialize() ) return 0;
  37675. #endif
  37676. return winUtf8ToUnicode(zText);
  37677. }
  37678. /*
  37679. ** This is a public wrapper for the winUnicodeToUtf8() function.
  37680. */
  37681. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  37682. #ifdef SQLITE_ENABLE_API_ARMOR
  37683. if( !zWideText ){
  37684. (void)SQLITE_MISUSE_BKPT;
  37685. return 0;
  37686. }
  37687. #endif
  37688. #ifndef SQLITE_OMIT_AUTOINIT
  37689. if( sqlite3_initialize() ) return 0;
  37690. #endif
  37691. return winUnicodeToUtf8(zWideText);
  37692. }
  37693. /*
  37694. ** This is a public wrapper for the winMbcsToUtf8() function.
  37695. */
  37696. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  37697. #ifdef SQLITE_ENABLE_API_ARMOR
  37698. if( !zText ){
  37699. (void)SQLITE_MISUSE_BKPT;
  37700. return 0;
  37701. }
  37702. #endif
  37703. #ifndef SQLITE_OMIT_AUTOINIT
  37704. if( sqlite3_initialize() ) return 0;
  37705. #endif
  37706. return winMbcsToUtf8(zText, osAreFileApisANSI());
  37707. }
  37708. /*
  37709. ** This is a public wrapper for the winMbcsToUtf8() function.
  37710. */
  37711. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  37712. #ifdef SQLITE_ENABLE_API_ARMOR
  37713. if( !zText ){
  37714. (void)SQLITE_MISUSE_BKPT;
  37715. return 0;
  37716. }
  37717. #endif
  37718. #ifndef SQLITE_OMIT_AUTOINIT
  37719. if( sqlite3_initialize() ) return 0;
  37720. #endif
  37721. return winMbcsToUtf8(zText, useAnsi);
  37722. }
  37723. /*
  37724. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37725. */
  37726. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  37727. #ifdef SQLITE_ENABLE_API_ARMOR
  37728. if( !zText ){
  37729. (void)SQLITE_MISUSE_BKPT;
  37730. return 0;
  37731. }
  37732. #endif
  37733. #ifndef SQLITE_OMIT_AUTOINIT
  37734. if( sqlite3_initialize() ) return 0;
  37735. #endif
  37736. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  37737. }
  37738. /*
  37739. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37740. */
  37741. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  37742. #ifdef SQLITE_ENABLE_API_ARMOR
  37743. if( !zText ){
  37744. (void)SQLITE_MISUSE_BKPT;
  37745. return 0;
  37746. }
  37747. #endif
  37748. #ifndef SQLITE_OMIT_AUTOINIT
  37749. if( sqlite3_initialize() ) return 0;
  37750. #endif
  37751. return winUtf8ToMbcs(zText, useAnsi);
  37752. }
  37753. /*
  37754. ** This function sets the data directory or the temporary directory based on
  37755. ** the provided arguments. The type argument must be 1 in order to set the
  37756. ** data directory or 2 in order to set the temporary directory. The zValue
  37757. ** argument is the name of the directory to use. The return value will be
  37758. ** SQLITE_OK if successful.
  37759. */
  37760. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  37761. char **ppDirectory = 0;
  37762. #ifndef SQLITE_OMIT_AUTOINIT
  37763. int rc = sqlite3_initialize();
  37764. if( rc ) return rc;
  37765. #endif
  37766. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  37767. ppDirectory = &sqlite3_data_directory;
  37768. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  37769. ppDirectory = &sqlite3_temp_directory;
  37770. }
  37771. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  37772. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  37773. );
  37774. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  37775. if( ppDirectory ){
  37776. char *zValueUtf8 = 0;
  37777. if( zValue && zValue[0] ){
  37778. zValueUtf8 = winUnicodeToUtf8(zValue);
  37779. if ( zValueUtf8==0 ){
  37780. return SQLITE_NOMEM_BKPT;
  37781. }
  37782. }
  37783. sqlite3_free(*ppDirectory);
  37784. *ppDirectory = zValueUtf8;
  37785. return SQLITE_OK;
  37786. }
  37787. return SQLITE_ERROR;
  37788. }
  37789. /*
  37790. ** The return value of winGetLastErrorMsg
  37791. ** is zero if the error message fits in the buffer, or non-zero
  37792. ** otherwise (if the message was truncated).
  37793. */
  37794. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  37795. /* FormatMessage returns 0 on failure. Otherwise it
  37796. ** returns the number of TCHARs written to the output
  37797. ** buffer, excluding the terminating null char.
  37798. */
  37799. DWORD dwLen = 0;
  37800. char *zOut = 0;
  37801. if( osIsNT() ){
  37802. #if SQLITE_OS_WINRT
  37803. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  37804. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  37805. FORMAT_MESSAGE_IGNORE_INSERTS,
  37806. NULL,
  37807. lastErrno,
  37808. 0,
  37809. zTempWide,
  37810. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  37811. 0);
  37812. #else
  37813. LPWSTR zTempWide = NULL;
  37814. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37815. FORMAT_MESSAGE_FROM_SYSTEM |
  37816. FORMAT_MESSAGE_IGNORE_INSERTS,
  37817. NULL,
  37818. lastErrno,
  37819. 0,
  37820. (LPWSTR) &zTempWide,
  37821. 0,
  37822. 0);
  37823. #endif
  37824. if( dwLen > 0 ){
  37825. /* allocate a buffer and convert to UTF8 */
  37826. sqlite3BeginBenignMalloc();
  37827. zOut = winUnicodeToUtf8(zTempWide);
  37828. sqlite3EndBenignMalloc();
  37829. #if !SQLITE_OS_WINRT
  37830. /* free the system buffer allocated by FormatMessage */
  37831. osLocalFree(zTempWide);
  37832. #endif
  37833. }
  37834. }
  37835. #ifdef SQLITE_WIN32_HAS_ANSI
  37836. else{
  37837. char *zTemp = NULL;
  37838. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37839. FORMAT_MESSAGE_FROM_SYSTEM |
  37840. FORMAT_MESSAGE_IGNORE_INSERTS,
  37841. NULL,
  37842. lastErrno,
  37843. 0,
  37844. (LPSTR) &zTemp,
  37845. 0,
  37846. 0);
  37847. if( dwLen > 0 ){
  37848. /* allocate a buffer and convert to UTF8 */
  37849. sqlite3BeginBenignMalloc();
  37850. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  37851. sqlite3EndBenignMalloc();
  37852. /* free the system buffer allocated by FormatMessage */
  37853. osLocalFree(zTemp);
  37854. }
  37855. }
  37856. #endif
  37857. if( 0 == dwLen ){
  37858. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  37859. }else{
  37860. /* copy a maximum of nBuf chars to output buffer */
  37861. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  37862. /* free the UTF8 buffer */
  37863. sqlite3_free(zOut);
  37864. }
  37865. return 0;
  37866. }
  37867. /*
  37868. **
  37869. ** This function - winLogErrorAtLine() - is only ever called via the macro
  37870. ** winLogError().
  37871. **
  37872. ** This routine is invoked after an error occurs in an OS function.
  37873. ** It logs a message using sqlite3_log() containing the current value of
  37874. ** error code and, if possible, the human-readable equivalent from
  37875. ** FormatMessage.
  37876. **
  37877. ** The first argument passed to the macro should be the error code that
  37878. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  37879. ** The two subsequent arguments should be the name of the OS function that
  37880. ** failed and the associated file-system path, if any.
  37881. */
  37882. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  37883. static int winLogErrorAtLine(
  37884. int errcode, /* SQLite error code */
  37885. DWORD lastErrno, /* Win32 last error */
  37886. const char *zFunc, /* Name of OS function that failed */
  37887. const char *zPath, /* File path associated with error */
  37888. int iLine /* Source line number where error occurred */
  37889. ){
  37890. char zMsg[500]; /* Human readable error text */
  37891. int i; /* Loop counter */
  37892. zMsg[0] = 0;
  37893. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  37894. assert( errcode!=SQLITE_OK );
  37895. if( zPath==0 ) zPath = "";
  37896. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  37897. zMsg[i] = 0;
  37898. sqlite3_log(errcode,
  37899. "os_win.c:%d: (%lu) %s(%s) - %s",
  37900. iLine, lastErrno, zFunc, zPath, zMsg
  37901. );
  37902. return errcode;
  37903. }
  37904. /*
  37905. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  37906. ** will be retried following a locking error - probably caused by
  37907. ** antivirus software. Also the initial delay before the first retry.
  37908. ** The delay increases linearly with each retry.
  37909. */
  37910. #ifndef SQLITE_WIN32_IOERR_RETRY
  37911. # define SQLITE_WIN32_IOERR_RETRY 10
  37912. #endif
  37913. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  37914. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  37915. #endif
  37916. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  37917. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  37918. /*
  37919. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  37920. ** error code obtained via GetLastError() is eligible to be retried. It
  37921. ** must accept the error code DWORD as its only argument and should return
  37922. ** non-zero if the error code is transient in nature and the operation
  37923. ** responsible for generating the original error might succeed upon being
  37924. ** retried. The argument to this macro should be a variable.
  37925. **
  37926. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  37927. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  37928. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  37929. ** may be used to include additional error codes in the set that should
  37930. ** result in the failing I/O operation being retried by the caller. If
  37931. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  37932. ** identical to those of the "winIoerrCanRetry1" macro.
  37933. */
  37934. #if !defined(winIoerrCanRetry1)
  37935. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  37936. ((a)==ERROR_SHARING_VIOLATION) || \
  37937. ((a)==ERROR_LOCK_VIOLATION) || \
  37938. ((a)==ERROR_DEV_NOT_EXIST) || \
  37939. ((a)==ERROR_NETNAME_DELETED) || \
  37940. ((a)==ERROR_SEM_TIMEOUT) || \
  37941. ((a)==ERROR_NETWORK_UNREACHABLE))
  37942. #endif
  37943. /*
  37944. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  37945. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  37946. ** to give up with an error.
  37947. */
  37948. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  37949. DWORD e = osGetLastError();
  37950. if( *pnRetry>=winIoerrRetry ){
  37951. if( pError ){
  37952. *pError = e;
  37953. }
  37954. return 0;
  37955. }
  37956. if( winIoerrCanRetry1(e) ){
  37957. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37958. ++*pnRetry;
  37959. return 1;
  37960. }
  37961. #if defined(winIoerrCanRetry2)
  37962. else if( winIoerrCanRetry2(e) ){
  37963. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37964. ++*pnRetry;
  37965. return 1;
  37966. }
  37967. #endif
  37968. if( pError ){
  37969. *pError = e;
  37970. }
  37971. return 0;
  37972. }
  37973. /*
  37974. ** Log a I/O error retry episode.
  37975. */
  37976. static void winLogIoerr(int nRetry, int lineno){
  37977. if( nRetry ){
  37978. sqlite3_log(SQLITE_NOTICE,
  37979. "delayed %dms for lock/sharing conflict at line %d",
  37980. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  37981. );
  37982. }
  37983. }
  37984. /*
  37985. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  37986. ** corresponding section in "date.c" cannot use it.
  37987. */
  37988. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  37989. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  37990. /*
  37991. ** The MSVC CRT on Windows CE may not have a localtime() function.
  37992. ** So define a substitute.
  37993. */
  37994. /* # include <time.h> */
  37995. struct tm *__cdecl localtime(const time_t *t)
  37996. {
  37997. static struct tm y;
  37998. FILETIME uTm, lTm;
  37999. SYSTEMTIME pTm;
  38000. sqlite3_int64 t64;
  38001. t64 = *t;
  38002. t64 = (t64 + 11644473600)*10000000;
  38003. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  38004. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  38005. osFileTimeToLocalFileTime(&uTm,&lTm);
  38006. osFileTimeToSystemTime(&lTm,&pTm);
  38007. y.tm_year = pTm.wYear - 1900;
  38008. y.tm_mon = pTm.wMonth - 1;
  38009. y.tm_wday = pTm.wDayOfWeek;
  38010. y.tm_mday = pTm.wDay;
  38011. y.tm_hour = pTm.wHour;
  38012. y.tm_min = pTm.wMinute;
  38013. y.tm_sec = pTm.wSecond;
  38014. return &y;
  38015. }
  38016. #endif
  38017. #if SQLITE_OS_WINCE
  38018. /*************************************************************************
  38019. ** This section contains code for WinCE only.
  38020. */
  38021. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  38022. /*
  38023. ** Acquire a lock on the handle h
  38024. */
  38025. static void winceMutexAcquire(HANDLE h){
  38026. DWORD dwErr;
  38027. do {
  38028. dwErr = osWaitForSingleObject(h, INFINITE);
  38029. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  38030. }
  38031. /*
  38032. ** Release a lock acquired by winceMutexAcquire()
  38033. */
  38034. #define winceMutexRelease(h) ReleaseMutex(h)
  38035. /*
  38036. ** Create the mutex and shared memory used for locking in the file
  38037. ** descriptor pFile
  38038. */
  38039. static int winceCreateLock(const char *zFilename, winFile *pFile){
  38040. LPWSTR zTok;
  38041. LPWSTR zName;
  38042. DWORD lastErrno;
  38043. BOOL bLogged = FALSE;
  38044. BOOL bInit = TRUE;
  38045. zName = winUtf8ToUnicode(zFilename);
  38046. if( zName==0 ){
  38047. /* out of memory */
  38048. return SQLITE_IOERR_NOMEM_BKPT;
  38049. }
  38050. /* Initialize the local lockdata */
  38051. memset(&pFile->local, 0, sizeof(pFile->local));
  38052. /* Replace the backslashes from the filename and lowercase it
  38053. ** to derive a mutex name. */
  38054. zTok = osCharLowerW(zName);
  38055. for (;*zTok;zTok++){
  38056. if (*zTok == '\\') *zTok = '_';
  38057. }
  38058. /* Create/open the named mutex */
  38059. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  38060. if (!pFile->hMutex){
  38061. pFile->lastErrno = osGetLastError();
  38062. sqlite3_free(zName);
  38063. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  38064. "winceCreateLock1", zFilename);
  38065. }
  38066. /* Acquire the mutex before continuing */
  38067. winceMutexAcquire(pFile->hMutex);
  38068. /* Since the names of named mutexes, semaphores, file mappings etc are
  38069. ** case-sensitive, take advantage of that by uppercasing the mutex name
  38070. ** and using that as the shared filemapping name.
  38071. */
  38072. osCharUpperW(zName);
  38073. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  38074. PAGE_READWRITE, 0, sizeof(winceLock),
  38075. zName);
  38076. /* Set a flag that indicates we're the first to create the memory so it
  38077. ** must be zero-initialized */
  38078. lastErrno = osGetLastError();
  38079. if (lastErrno == ERROR_ALREADY_EXISTS){
  38080. bInit = FALSE;
  38081. }
  38082. sqlite3_free(zName);
  38083. /* If we succeeded in making the shared memory handle, map it. */
  38084. if( pFile->hShared ){
  38085. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  38086. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  38087. /* If mapping failed, close the shared memory handle and erase it */
  38088. if( !pFile->shared ){
  38089. pFile->lastErrno = osGetLastError();
  38090. winLogError(SQLITE_IOERR, pFile->lastErrno,
  38091. "winceCreateLock2", zFilename);
  38092. bLogged = TRUE;
  38093. osCloseHandle(pFile->hShared);
  38094. pFile->hShared = NULL;
  38095. }
  38096. }
  38097. /* If shared memory could not be created, then close the mutex and fail */
  38098. if( pFile->hShared==NULL ){
  38099. if( !bLogged ){
  38100. pFile->lastErrno = lastErrno;
  38101. winLogError(SQLITE_IOERR, pFile->lastErrno,
  38102. "winceCreateLock3", zFilename);
  38103. bLogged = TRUE;
  38104. }
  38105. winceMutexRelease(pFile->hMutex);
  38106. osCloseHandle(pFile->hMutex);
  38107. pFile->hMutex = NULL;
  38108. return SQLITE_IOERR;
  38109. }
  38110. /* Initialize the shared memory if we're supposed to */
  38111. if( bInit ){
  38112. memset(pFile->shared, 0, sizeof(winceLock));
  38113. }
  38114. winceMutexRelease(pFile->hMutex);
  38115. return SQLITE_OK;
  38116. }
  38117. /*
  38118. ** Destroy the part of winFile that deals with wince locks
  38119. */
  38120. static void winceDestroyLock(winFile *pFile){
  38121. if (pFile->hMutex){
  38122. /* Acquire the mutex */
  38123. winceMutexAcquire(pFile->hMutex);
  38124. /* The following blocks should probably assert in debug mode, but they
  38125. are to cleanup in case any locks remained open */
  38126. if (pFile->local.nReaders){
  38127. pFile->shared->nReaders --;
  38128. }
  38129. if (pFile->local.bReserved){
  38130. pFile->shared->bReserved = FALSE;
  38131. }
  38132. if (pFile->local.bPending){
  38133. pFile->shared->bPending = FALSE;
  38134. }
  38135. if (pFile->local.bExclusive){
  38136. pFile->shared->bExclusive = FALSE;
  38137. }
  38138. /* De-reference and close our copy of the shared memory handle */
  38139. osUnmapViewOfFile(pFile->shared);
  38140. osCloseHandle(pFile->hShared);
  38141. /* Done with the mutex */
  38142. winceMutexRelease(pFile->hMutex);
  38143. osCloseHandle(pFile->hMutex);
  38144. pFile->hMutex = NULL;
  38145. }
  38146. }
  38147. /*
  38148. ** An implementation of the LockFile() API of Windows for CE
  38149. */
  38150. static BOOL winceLockFile(
  38151. LPHANDLE phFile,
  38152. DWORD dwFileOffsetLow,
  38153. DWORD dwFileOffsetHigh,
  38154. DWORD nNumberOfBytesToLockLow,
  38155. DWORD nNumberOfBytesToLockHigh
  38156. ){
  38157. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  38158. BOOL bReturn = FALSE;
  38159. UNUSED_PARAMETER(dwFileOffsetHigh);
  38160. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  38161. if (!pFile->hMutex) return TRUE;
  38162. winceMutexAcquire(pFile->hMutex);
  38163. /* Wanting an exclusive lock? */
  38164. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  38165. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  38166. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  38167. pFile->shared->bExclusive = TRUE;
  38168. pFile->local.bExclusive = TRUE;
  38169. bReturn = TRUE;
  38170. }
  38171. }
  38172. /* Want a read-only lock? */
  38173. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  38174. nNumberOfBytesToLockLow == 1){
  38175. if (pFile->shared->bExclusive == 0){
  38176. pFile->local.nReaders ++;
  38177. if (pFile->local.nReaders == 1){
  38178. pFile->shared->nReaders ++;
  38179. }
  38180. bReturn = TRUE;
  38181. }
  38182. }
  38183. /* Want a pending lock? */
  38184. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  38185. && nNumberOfBytesToLockLow == 1){
  38186. /* If no pending lock has been acquired, then acquire it */
  38187. if (pFile->shared->bPending == 0) {
  38188. pFile->shared->bPending = TRUE;
  38189. pFile->local.bPending = TRUE;
  38190. bReturn = TRUE;
  38191. }
  38192. }
  38193. /* Want a reserved lock? */
  38194. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  38195. && nNumberOfBytesToLockLow == 1){
  38196. if (pFile->shared->bReserved == 0) {
  38197. pFile->shared->bReserved = TRUE;
  38198. pFile->local.bReserved = TRUE;
  38199. bReturn = TRUE;
  38200. }
  38201. }
  38202. winceMutexRelease(pFile->hMutex);
  38203. return bReturn;
  38204. }
  38205. /*
  38206. ** An implementation of the UnlockFile API of Windows for CE
  38207. */
  38208. static BOOL winceUnlockFile(
  38209. LPHANDLE phFile,
  38210. DWORD dwFileOffsetLow,
  38211. DWORD dwFileOffsetHigh,
  38212. DWORD nNumberOfBytesToUnlockLow,
  38213. DWORD nNumberOfBytesToUnlockHigh
  38214. ){
  38215. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  38216. BOOL bReturn = FALSE;
  38217. UNUSED_PARAMETER(dwFileOffsetHigh);
  38218. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  38219. if (!pFile->hMutex) return TRUE;
  38220. winceMutexAcquire(pFile->hMutex);
  38221. /* Releasing a reader lock or an exclusive lock */
  38222. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  38223. /* Did we have an exclusive lock? */
  38224. if (pFile->local.bExclusive){
  38225. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  38226. pFile->local.bExclusive = FALSE;
  38227. pFile->shared->bExclusive = FALSE;
  38228. bReturn = TRUE;
  38229. }
  38230. /* Did we just have a reader lock? */
  38231. else if (pFile->local.nReaders){
  38232. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  38233. || nNumberOfBytesToUnlockLow == 1);
  38234. pFile->local.nReaders --;
  38235. if (pFile->local.nReaders == 0)
  38236. {
  38237. pFile->shared->nReaders --;
  38238. }
  38239. bReturn = TRUE;
  38240. }
  38241. }
  38242. /* Releasing a pending lock */
  38243. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  38244. && nNumberOfBytesToUnlockLow == 1){
  38245. if (pFile->local.bPending){
  38246. pFile->local.bPending = FALSE;
  38247. pFile->shared->bPending = FALSE;
  38248. bReturn = TRUE;
  38249. }
  38250. }
  38251. /* Releasing a reserved lock */
  38252. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  38253. && nNumberOfBytesToUnlockLow == 1){
  38254. if (pFile->local.bReserved) {
  38255. pFile->local.bReserved = FALSE;
  38256. pFile->shared->bReserved = FALSE;
  38257. bReturn = TRUE;
  38258. }
  38259. }
  38260. winceMutexRelease(pFile->hMutex);
  38261. return bReturn;
  38262. }
  38263. /*
  38264. ** End of the special code for wince
  38265. *****************************************************************************/
  38266. #endif /* SQLITE_OS_WINCE */
  38267. /*
  38268. ** Lock a file region.
  38269. */
  38270. static BOOL winLockFile(
  38271. LPHANDLE phFile,
  38272. DWORD flags,
  38273. DWORD offsetLow,
  38274. DWORD offsetHigh,
  38275. DWORD numBytesLow,
  38276. DWORD numBytesHigh
  38277. ){
  38278. #if SQLITE_OS_WINCE
  38279. /*
  38280. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  38281. ** API LockFile.
  38282. */
  38283. return winceLockFile(phFile, offsetLow, offsetHigh,
  38284. numBytesLow, numBytesHigh);
  38285. #else
  38286. if( osIsNT() ){
  38287. OVERLAPPED ovlp;
  38288. memset(&ovlp, 0, sizeof(OVERLAPPED));
  38289. ovlp.Offset = offsetLow;
  38290. ovlp.OffsetHigh = offsetHigh;
  38291. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  38292. }else{
  38293. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  38294. numBytesHigh);
  38295. }
  38296. #endif
  38297. }
  38298. /*
  38299. ** Unlock a file region.
  38300. */
  38301. static BOOL winUnlockFile(
  38302. LPHANDLE phFile,
  38303. DWORD offsetLow,
  38304. DWORD offsetHigh,
  38305. DWORD numBytesLow,
  38306. DWORD numBytesHigh
  38307. ){
  38308. #if SQLITE_OS_WINCE
  38309. /*
  38310. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  38311. ** API UnlockFile.
  38312. */
  38313. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  38314. numBytesLow, numBytesHigh);
  38315. #else
  38316. if( osIsNT() ){
  38317. OVERLAPPED ovlp;
  38318. memset(&ovlp, 0, sizeof(OVERLAPPED));
  38319. ovlp.Offset = offsetLow;
  38320. ovlp.OffsetHigh = offsetHigh;
  38321. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  38322. }else{
  38323. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  38324. numBytesHigh);
  38325. }
  38326. #endif
  38327. }
  38328. /*****************************************************************************
  38329. ** The next group of routines implement the I/O methods specified
  38330. ** by the sqlite3_io_methods object.
  38331. ******************************************************************************/
  38332. /*
  38333. ** Some Microsoft compilers lack this definition.
  38334. */
  38335. #ifndef INVALID_SET_FILE_POINTER
  38336. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  38337. #endif
  38338. /*
  38339. ** Move the current position of the file handle passed as the first
  38340. ** argument to offset iOffset within the file. If successful, return 0.
  38341. ** Otherwise, set pFile->lastErrno and return non-zero.
  38342. */
  38343. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  38344. #if !SQLITE_OS_WINRT
  38345. LONG upperBits; /* Most sig. 32 bits of new offset */
  38346. LONG lowerBits; /* Least sig. 32 bits of new offset */
  38347. DWORD dwRet; /* Value returned by SetFilePointer() */
  38348. DWORD lastErrno; /* Value returned by GetLastError() */
  38349. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  38350. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  38351. lowerBits = (LONG)(iOffset & 0xffffffff);
  38352. /* API oddity: If successful, SetFilePointer() returns a dword
  38353. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  38354. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  38355. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  38356. ** whether an error has actually occurred, it is also necessary to call
  38357. ** GetLastError().
  38358. */
  38359. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  38360. if( (dwRet==INVALID_SET_FILE_POINTER
  38361. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  38362. pFile->lastErrno = lastErrno;
  38363. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  38364. "winSeekFile", pFile->zPath);
  38365. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  38366. return 1;
  38367. }
  38368. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  38369. return 0;
  38370. #else
  38371. /*
  38372. ** Same as above, except that this implementation works for WinRT.
  38373. */
  38374. LARGE_INTEGER x; /* The new offset */
  38375. BOOL bRet; /* Value returned by SetFilePointerEx() */
  38376. x.QuadPart = iOffset;
  38377. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  38378. if(!bRet){
  38379. pFile->lastErrno = osGetLastError();
  38380. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  38381. "winSeekFile", pFile->zPath);
  38382. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  38383. return 1;
  38384. }
  38385. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  38386. return 0;
  38387. #endif
  38388. }
  38389. #if SQLITE_MAX_MMAP_SIZE>0
  38390. /* Forward references to VFS helper methods used for memory mapped files */
  38391. static int winMapfile(winFile*, sqlite3_int64);
  38392. static int winUnmapfile(winFile*);
  38393. #endif
  38394. /*
  38395. ** Close a file.
  38396. **
  38397. ** It is reported that an attempt to close a handle might sometimes
  38398. ** fail. This is a very unreasonable result, but Windows is notorious
  38399. ** for being unreasonable so I do not doubt that it might happen. If
  38400. ** the close fails, we pause for 100 milliseconds and try again. As
  38401. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  38402. ** giving up and returning an error.
  38403. */
  38404. #define MX_CLOSE_ATTEMPT 3
  38405. static int winClose(sqlite3_file *id){
  38406. int rc, cnt = 0;
  38407. winFile *pFile = (winFile*)id;
  38408. assert( id!=0 );
  38409. #ifndef SQLITE_OMIT_WAL
  38410. assert( pFile->pShm==0 );
  38411. #endif
  38412. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  38413. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  38414. osGetCurrentProcessId(), pFile, pFile->h));
  38415. #if SQLITE_MAX_MMAP_SIZE>0
  38416. winUnmapfile(pFile);
  38417. #endif
  38418. do{
  38419. rc = osCloseHandle(pFile->h);
  38420. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  38421. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  38422. #if SQLITE_OS_WINCE
  38423. #define WINCE_DELETION_ATTEMPTS 3
  38424. {
  38425. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  38426. if( pAppData==NULL || !pAppData->bNoLock ){
  38427. winceDestroyLock(pFile);
  38428. }
  38429. }
  38430. if( pFile->zDeleteOnClose ){
  38431. int cnt = 0;
  38432. while(
  38433. osDeleteFileW(pFile->zDeleteOnClose)==0
  38434. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  38435. && cnt++ < WINCE_DELETION_ATTEMPTS
  38436. ){
  38437. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  38438. }
  38439. sqlite3_free(pFile->zDeleteOnClose);
  38440. }
  38441. #endif
  38442. if( rc ){
  38443. pFile->h = NULL;
  38444. }
  38445. OpenCounter(-1);
  38446. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  38447. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  38448. return rc ? SQLITE_OK
  38449. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  38450. "winClose", pFile->zPath);
  38451. }
  38452. /*
  38453. ** Read data from a file into a buffer. Return SQLITE_OK if all
  38454. ** bytes were read successfully and SQLITE_IOERR if anything goes
  38455. ** wrong.
  38456. */
  38457. static int winRead(
  38458. sqlite3_file *id, /* File to read from */
  38459. void *pBuf, /* Write content into this buffer */
  38460. int amt, /* Number of bytes to read */
  38461. sqlite3_int64 offset /* Begin reading at this offset */
  38462. ){
  38463. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38464. OVERLAPPED overlapped; /* The offset for ReadFile. */
  38465. #endif
  38466. winFile *pFile = (winFile*)id; /* file handle */
  38467. DWORD nRead; /* Number of bytes actually read from file */
  38468. int nRetry = 0; /* Number of retrys */
  38469. assert( id!=0 );
  38470. assert( amt>0 );
  38471. assert( offset>=0 );
  38472. SimulateIOError(return SQLITE_IOERR_READ);
  38473. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  38474. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  38475. pFile->h, pBuf, amt, offset, pFile->locktype));
  38476. #if SQLITE_MAX_MMAP_SIZE>0
  38477. /* Deal with as much of this read request as possible by transfering
  38478. ** data from the memory mapping using memcpy(). */
  38479. if( offset<pFile->mmapSize ){
  38480. if( offset+amt <= pFile->mmapSize ){
  38481. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  38482. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38483. osGetCurrentProcessId(), pFile, pFile->h));
  38484. return SQLITE_OK;
  38485. }else{
  38486. int nCopy = (int)(pFile->mmapSize - offset);
  38487. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  38488. pBuf = &((u8 *)pBuf)[nCopy];
  38489. amt -= nCopy;
  38490. offset += nCopy;
  38491. }
  38492. }
  38493. #endif
  38494. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38495. if( winSeekFile(pFile, offset) ){
  38496. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  38497. osGetCurrentProcessId(), pFile, pFile->h));
  38498. return SQLITE_FULL;
  38499. }
  38500. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  38501. #else
  38502. memset(&overlapped, 0, sizeof(OVERLAPPED));
  38503. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38504. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38505. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  38506. osGetLastError()!=ERROR_HANDLE_EOF ){
  38507. #endif
  38508. DWORD lastErrno;
  38509. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  38510. pFile->lastErrno = lastErrno;
  38511. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  38512. osGetCurrentProcessId(), pFile, pFile->h));
  38513. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  38514. "winRead", pFile->zPath);
  38515. }
  38516. winLogIoerr(nRetry, __LINE__);
  38517. if( nRead<(DWORD)amt ){
  38518. /* Unread parts of the buffer must be zero-filled */
  38519. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  38520. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  38521. osGetCurrentProcessId(), pFile, pFile->h));
  38522. return SQLITE_IOERR_SHORT_READ;
  38523. }
  38524. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38525. osGetCurrentProcessId(), pFile, pFile->h));
  38526. return SQLITE_OK;
  38527. }
  38528. /*
  38529. ** Write data from a buffer into a file. Return SQLITE_OK on success
  38530. ** or some other error code on failure.
  38531. */
  38532. static int winWrite(
  38533. sqlite3_file *id, /* File to write into */
  38534. const void *pBuf, /* The bytes to be written */
  38535. int amt, /* Number of bytes to write */
  38536. sqlite3_int64 offset /* Offset into the file to begin writing at */
  38537. ){
  38538. int rc = 0; /* True if error has occurred, else false */
  38539. winFile *pFile = (winFile*)id; /* File handle */
  38540. int nRetry = 0; /* Number of retries */
  38541. assert( amt>0 );
  38542. assert( pFile );
  38543. SimulateIOError(return SQLITE_IOERR_WRITE);
  38544. SimulateDiskfullError(return SQLITE_FULL);
  38545. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  38546. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  38547. pFile->h, pBuf, amt, offset, pFile->locktype));
  38548. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  38549. /* Deal with as much of this write request as possible by transfering
  38550. ** data from the memory mapping using memcpy(). */
  38551. if( offset<pFile->mmapSize ){
  38552. if( offset+amt <= pFile->mmapSize ){
  38553. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  38554. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38555. osGetCurrentProcessId(), pFile, pFile->h));
  38556. return SQLITE_OK;
  38557. }else{
  38558. int nCopy = (int)(pFile->mmapSize - offset);
  38559. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  38560. pBuf = &((u8 *)pBuf)[nCopy];
  38561. amt -= nCopy;
  38562. offset += nCopy;
  38563. }
  38564. }
  38565. #endif
  38566. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38567. rc = winSeekFile(pFile, offset);
  38568. if( rc==0 ){
  38569. #else
  38570. {
  38571. #endif
  38572. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38573. OVERLAPPED overlapped; /* The offset for WriteFile. */
  38574. #endif
  38575. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  38576. int nRem = amt; /* Number of bytes yet to be written */
  38577. DWORD nWrite; /* Bytes written by each WriteFile() call */
  38578. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  38579. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38580. memset(&overlapped, 0, sizeof(OVERLAPPED));
  38581. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38582. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38583. #endif
  38584. while( nRem>0 ){
  38585. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38586. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  38587. #else
  38588. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  38589. #endif
  38590. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  38591. break;
  38592. }
  38593. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  38594. if( nWrite==0 || nWrite>(DWORD)nRem ){
  38595. lastErrno = osGetLastError();
  38596. break;
  38597. }
  38598. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38599. offset += nWrite;
  38600. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38601. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38602. #endif
  38603. aRem += nWrite;
  38604. nRem -= nWrite;
  38605. }
  38606. if( nRem>0 ){
  38607. pFile->lastErrno = lastErrno;
  38608. rc = 1;
  38609. }
  38610. }
  38611. if( rc ){
  38612. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  38613. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  38614. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  38615. osGetCurrentProcessId(), pFile, pFile->h));
  38616. return winLogError(SQLITE_FULL, pFile->lastErrno,
  38617. "winWrite1", pFile->zPath);
  38618. }
  38619. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  38620. osGetCurrentProcessId(), pFile, pFile->h));
  38621. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  38622. "winWrite2", pFile->zPath);
  38623. }else{
  38624. winLogIoerr(nRetry, __LINE__);
  38625. }
  38626. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38627. osGetCurrentProcessId(), pFile, pFile->h));
  38628. return SQLITE_OK;
  38629. }
  38630. /*
  38631. ** Truncate an open file to a specified size
  38632. */
  38633. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  38634. winFile *pFile = (winFile*)id; /* File handle object */
  38635. int rc = SQLITE_OK; /* Return code for this function */
  38636. DWORD lastErrno;
  38637. assert( pFile );
  38638. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  38639. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  38640. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  38641. /* If the user has configured a chunk-size for this file, truncate the
  38642. ** file so that it consists of an integer number of chunks (i.e. the
  38643. ** actual file size after the operation may be larger than the requested
  38644. ** size).
  38645. */
  38646. if( pFile->szChunk>0 ){
  38647. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  38648. }
  38649. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  38650. if( winSeekFile(pFile, nByte) ){
  38651. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38652. "winTruncate1", pFile->zPath);
  38653. }else if( 0==osSetEndOfFile(pFile->h) &&
  38654. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  38655. pFile->lastErrno = lastErrno;
  38656. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38657. "winTruncate2", pFile->zPath);
  38658. }
  38659. #if SQLITE_MAX_MMAP_SIZE>0
  38660. /* If the file was truncated to a size smaller than the currently
  38661. ** mapped region, reduce the effective mapping size as well. SQLite will
  38662. ** use read() and write() to access data beyond this point from now on.
  38663. */
  38664. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  38665. pFile->mmapSize = nByte;
  38666. }
  38667. #endif
  38668. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  38669. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  38670. return rc;
  38671. }
  38672. #ifdef SQLITE_TEST
  38673. /*
  38674. ** Count the number of fullsyncs and normal syncs. This is used to test
  38675. ** that syncs and fullsyncs are occuring at the right times.
  38676. */
  38677. SQLITE_API int sqlite3_sync_count = 0;
  38678. SQLITE_API int sqlite3_fullsync_count = 0;
  38679. #endif
  38680. /*
  38681. ** Make sure all writes to a particular file are committed to disk.
  38682. */
  38683. static int winSync(sqlite3_file *id, int flags){
  38684. #ifndef SQLITE_NO_SYNC
  38685. /*
  38686. ** Used only when SQLITE_NO_SYNC is not defined.
  38687. */
  38688. BOOL rc;
  38689. #endif
  38690. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  38691. defined(SQLITE_HAVE_OS_TRACE)
  38692. /*
  38693. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  38694. ** OSTRACE() macros.
  38695. */
  38696. winFile *pFile = (winFile*)id;
  38697. #else
  38698. UNUSED_PARAMETER(id);
  38699. #endif
  38700. assert( pFile );
  38701. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  38702. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  38703. || (flags&0x0F)==SQLITE_SYNC_FULL
  38704. );
  38705. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  38706. ** line is to test that doing so does not cause any problems.
  38707. */
  38708. SimulateDiskfullError( return SQLITE_FULL );
  38709. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  38710. osGetCurrentProcessId(), pFile, pFile->h, flags,
  38711. pFile->locktype));
  38712. #ifndef SQLITE_TEST
  38713. UNUSED_PARAMETER(flags);
  38714. #else
  38715. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  38716. sqlite3_fullsync_count++;
  38717. }
  38718. sqlite3_sync_count++;
  38719. #endif
  38720. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  38721. ** no-op
  38722. */
  38723. #ifdef SQLITE_NO_SYNC
  38724. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38725. osGetCurrentProcessId(), pFile, pFile->h));
  38726. return SQLITE_OK;
  38727. #else
  38728. #if SQLITE_MAX_MMAP_SIZE>0
  38729. if( pFile->pMapRegion ){
  38730. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  38731. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38732. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  38733. pFile, pFile->pMapRegion));
  38734. }else{
  38735. pFile->lastErrno = osGetLastError();
  38736. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38737. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  38738. pFile, pFile->pMapRegion));
  38739. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  38740. "winSync1", pFile->zPath);
  38741. }
  38742. }
  38743. #endif
  38744. rc = osFlushFileBuffers(pFile->h);
  38745. SimulateIOError( rc=FALSE );
  38746. if( rc ){
  38747. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38748. osGetCurrentProcessId(), pFile, pFile->h));
  38749. return SQLITE_OK;
  38750. }else{
  38751. pFile->lastErrno = osGetLastError();
  38752. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  38753. osGetCurrentProcessId(), pFile, pFile->h));
  38754. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  38755. "winSync2", pFile->zPath);
  38756. }
  38757. #endif
  38758. }
  38759. /*
  38760. ** Determine the current size of a file in bytes
  38761. */
  38762. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  38763. winFile *pFile = (winFile*)id;
  38764. int rc = SQLITE_OK;
  38765. assert( id!=0 );
  38766. assert( pSize!=0 );
  38767. SimulateIOError(return SQLITE_IOERR_FSTAT);
  38768. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  38769. #if SQLITE_OS_WINRT
  38770. {
  38771. FILE_STANDARD_INFO info;
  38772. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  38773. &info, sizeof(info)) ){
  38774. *pSize = info.EndOfFile.QuadPart;
  38775. }else{
  38776. pFile->lastErrno = osGetLastError();
  38777. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38778. "winFileSize", pFile->zPath);
  38779. }
  38780. }
  38781. #else
  38782. {
  38783. DWORD upperBits;
  38784. DWORD lowerBits;
  38785. DWORD lastErrno;
  38786. lowerBits = osGetFileSize(pFile->h, &upperBits);
  38787. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  38788. if( (lowerBits == INVALID_FILE_SIZE)
  38789. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  38790. pFile->lastErrno = lastErrno;
  38791. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38792. "winFileSize", pFile->zPath);
  38793. }
  38794. }
  38795. #endif
  38796. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  38797. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  38798. return rc;
  38799. }
  38800. /*
  38801. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  38802. */
  38803. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  38804. # define LOCKFILE_FAIL_IMMEDIATELY 1
  38805. #endif
  38806. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  38807. # define LOCKFILE_EXCLUSIVE_LOCK 2
  38808. #endif
  38809. /*
  38810. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  38811. ** When the LockFile function was used, it was always expected to fail
  38812. ** immediately if the lock could not be obtained. Also, it always expected to
  38813. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  38814. ** and reflect those expectations; therefore, they should not be changed.
  38815. */
  38816. #ifndef SQLITE_LOCKFILE_FLAGS
  38817. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  38818. LOCKFILE_EXCLUSIVE_LOCK)
  38819. #endif
  38820. /*
  38821. ** Currently, SQLite never calls the LockFileEx function without wanting the
  38822. ** call to fail immediately if the lock cannot be obtained.
  38823. */
  38824. #ifndef SQLITE_LOCKFILEEX_FLAGS
  38825. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  38826. #endif
  38827. /*
  38828. ** Acquire a reader lock.
  38829. ** Different API routines are called depending on whether or not this
  38830. ** is Win9x or WinNT.
  38831. */
  38832. static int winGetReadLock(winFile *pFile){
  38833. int res;
  38834. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38835. if( osIsNT() ){
  38836. #if SQLITE_OS_WINCE
  38837. /*
  38838. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  38839. ** API LockFileEx.
  38840. */
  38841. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  38842. #else
  38843. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  38844. SHARED_SIZE, 0);
  38845. #endif
  38846. }
  38847. #ifdef SQLITE_WIN32_HAS_ANSI
  38848. else{
  38849. int lk;
  38850. sqlite3_randomness(sizeof(lk), &lk);
  38851. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  38852. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38853. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38854. }
  38855. #endif
  38856. if( res == 0 ){
  38857. pFile->lastErrno = osGetLastError();
  38858. /* No need to log a failure to lock */
  38859. }
  38860. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  38861. return res;
  38862. }
  38863. /*
  38864. ** Undo a readlock
  38865. */
  38866. static int winUnlockReadLock(winFile *pFile){
  38867. int res;
  38868. DWORD lastErrno;
  38869. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38870. if( osIsNT() ){
  38871. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  38872. }
  38873. #ifdef SQLITE_WIN32_HAS_ANSI
  38874. else{
  38875. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38876. }
  38877. #endif
  38878. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  38879. pFile->lastErrno = lastErrno;
  38880. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  38881. "winUnlockReadLock", pFile->zPath);
  38882. }
  38883. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  38884. return res;
  38885. }
  38886. /*
  38887. ** Lock the file with the lock specified by parameter locktype - one
  38888. ** of the following:
  38889. **
  38890. ** (1) SHARED_LOCK
  38891. ** (2) RESERVED_LOCK
  38892. ** (3) PENDING_LOCK
  38893. ** (4) EXCLUSIVE_LOCK
  38894. **
  38895. ** Sometimes when requesting one lock state, additional lock states
  38896. ** are inserted in between. The locking might fail on one of the later
  38897. ** transitions leaving the lock state different from what it started but
  38898. ** still short of its goal. The following chart shows the allowed
  38899. ** transitions and the inserted intermediate states:
  38900. **
  38901. ** UNLOCKED -> SHARED
  38902. ** SHARED -> RESERVED
  38903. ** SHARED -> (PENDING) -> EXCLUSIVE
  38904. ** RESERVED -> (PENDING) -> EXCLUSIVE
  38905. ** PENDING -> EXCLUSIVE
  38906. **
  38907. ** This routine will only increase a lock. The winUnlock() routine
  38908. ** erases all locks at once and returns us immediately to locking level 0.
  38909. ** It is not possible to lower the locking level one step at a time. You
  38910. ** must go straight to locking level 0.
  38911. */
  38912. static int winLock(sqlite3_file *id, int locktype){
  38913. int rc = SQLITE_OK; /* Return code from subroutines */
  38914. int res = 1; /* Result of a Windows lock call */
  38915. int newLocktype; /* Set pFile->locktype to this value before exiting */
  38916. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  38917. winFile *pFile = (winFile*)id;
  38918. DWORD lastErrno = NO_ERROR;
  38919. assert( id!=0 );
  38920. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  38921. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  38922. /* If there is already a lock of this type or more restrictive on the
  38923. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  38924. ** sqlite3OsEnterMutex() hasn't been called yet.
  38925. */
  38926. if( pFile->locktype>=locktype ){
  38927. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  38928. return SQLITE_OK;
  38929. }
  38930. /* Do not allow any kind of write-lock on a read-only database
  38931. */
  38932. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  38933. return SQLITE_IOERR_LOCK;
  38934. }
  38935. /* Make sure the locking sequence is correct
  38936. */
  38937. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  38938. assert( locktype!=PENDING_LOCK );
  38939. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  38940. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  38941. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  38942. ** the PENDING_LOCK byte is temporary.
  38943. */
  38944. newLocktype = pFile->locktype;
  38945. if( pFile->locktype==NO_LOCK
  38946. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  38947. ){
  38948. int cnt = 3;
  38949. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38950. PENDING_BYTE, 0, 1, 0))==0 ){
  38951. /* Try 3 times to get the pending lock. This is needed to work
  38952. ** around problems caused by indexing and/or anti-virus software on
  38953. ** Windows systems.
  38954. ** If you are using this code as a model for alternative VFSes, do not
  38955. ** copy this retry logic. It is a hack intended for Windows only.
  38956. */
  38957. lastErrno = osGetLastError();
  38958. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  38959. pFile->h, cnt, res));
  38960. if( lastErrno==ERROR_INVALID_HANDLE ){
  38961. pFile->lastErrno = lastErrno;
  38962. rc = SQLITE_IOERR_LOCK;
  38963. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  38964. pFile->h, cnt, sqlite3ErrName(rc)));
  38965. return rc;
  38966. }
  38967. if( cnt ) sqlite3_win32_sleep(1);
  38968. }
  38969. gotPendingLock = res;
  38970. if( !res ){
  38971. lastErrno = osGetLastError();
  38972. }
  38973. }
  38974. /* Acquire a shared lock
  38975. */
  38976. if( locktype==SHARED_LOCK && res ){
  38977. assert( pFile->locktype==NO_LOCK );
  38978. res = winGetReadLock(pFile);
  38979. if( res ){
  38980. newLocktype = SHARED_LOCK;
  38981. }else{
  38982. lastErrno = osGetLastError();
  38983. }
  38984. }
  38985. /* Acquire a RESERVED lock
  38986. */
  38987. if( locktype==RESERVED_LOCK && res ){
  38988. assert( pFile->locktype==SHARED_LOCK );
  38989. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  38990. if( res ){
  38991. newLocktype = RESERVED_LOCK;
  38992. }else{
  38993. lastErrno = osGetLastError();
  38994. }
  38995. }
  38996. /* Acquire a PENDING lock
  38997. */
  38998. if( locktype==EXCLUSIVE_LOCK && res ){
  38999. newLocktype = PENDING_LOCK;
  39000. gotPendingLock = 0;
  39001. }
  39002. /* Acquire an EXCLUSIVE lock
  39003. */
  39004. if( locktype==EXCLUSIVE_LOCK && res ){
  39005. assert( pFile->locktype>=SHARED_LOCK );
  39006. res = winUnlockReadLock(pFile);
  39007. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  39008. SHARED_SIZE, 0);
  39009. if( res ){
  39010. newLocktype = EXCLUSIVE_LOCK;
  39011. }else{
  39012. lastErrno = osGetLastError();
  39013. winGetReadLock(pFile);
  39014. }
  39015. }
  39016. /* If we are holding a PENDING lock that ought to be released, then
  39017. ** release it now.
  39018. */
  39019. if( gotPendingLock && locktype==SHARED_LOCK ){
  39020. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  39021. }
  39022. /* Update the state of the lock has held in the file descriptor then
  39023. ** return the appropriate result code.
  39024. */
  39025. if( res ){
  39026. rc = SQLITE_OK;
  39027. }else{
  39028. pFile->lastErrno = lastErrno;
  39029. rc = SQLITE_BUSY;
  39030. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  39031. pFile->h, locktype, newLocktype));
  39032. }
  39033. pFile->locktype = (u8)newLocktype;
  39034. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  39035. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  39036. return rc;
  39037. }
  39038. /*
  39039. ** This routine checks if there is a RESERVED lock held on the specified
  39040. ** file by this or any other process. If such a lock is held, return
  39041. ** non-zero, otherwise zero.
  39042. */
  39043. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  39044. int res;
  39045. winFile *pFile = (winFile*)id;
  39046. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  39047. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  39048. assert( id!=0 );
  39049. if( pFile->locktype>=RESERVED_LOCK ){
  39050. res = 1;
  39051. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  39052. }else{
  39053. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  39054. if( res ){
  39055. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  39056. }
  39057. res = !res;
  39058. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  39059. }
  39060. *pResOut = res;
  39061. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  39062. pFile->h, pResOut, *pResOut));
  39063. return SQLITE_OK;
  39064. }
  39065. /*
  39066. ** Lower the locking level on file descriptor id to locktype. locktype
  39067. ** must be either NO_LOCK or SHARED_LOCK.
  39068. **
  39069. ** If the locking level of the file descriptor is already at or below
  39070. ** the requested locking level, this routine is a no-op.
  39071. **
  39072. ** It is not possible for this routine to fail if the second argument
  39073. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  39074. ** might return SQLITE_IOERR;
  39075. */
  39076. static int winUnlock(sqlite3_file *id, int locktype){
  39077. int type;
  39078. winFile *pFile = (winFile*)id;
  39079. int rc = SQLITE_OK;
  39080. assert( pFile!=0 );
  39081. assert( locktype<=SHARED_LOCK );
  39082. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  39083. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  39084. type = pFile->locktype;
  39085. if( type>=EXCLUSIVE_LOCK ){
  39086. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  39087. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  39088. /* This should never happen. We should always be able to
  39089. ** reacquire the read lock */
  39090. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  39091. "winUnlock", pFile->zPath);
  39092. }
  39093. }
  39094. if( type>=RESERVED_LOCK ){
  39095. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  39096. }
  39097. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  39098. winUnlockReadLock(pFile);
  39099. }
  39100. if( type>=PENDING_LOCK ){
  39101. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  39102. }
  39103. pFile->locktype = (u8)locktype;
  39104. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  39105. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  39106. return rc;
  39107. }
  39108. /******************************************************************************
  39109. ****************************** No-op Locking **********************************
  39110. **
  39111. ** Of the various locking implementations available, this is by far the
  39112. ** simplest: locking is ignored. No attempt is made to lock the database
  39113. ** file for reading or writing.
  39114. **
  39115. ** This locking mode is appropriate for use on read-only databases
  39116. ** (ex: databases that are burned into CD-ROM, for example.) It can
  39117. ** also be used if the application employs some external mechanism to
  39118. ** prevent simultaneous access of the same database by two or more
  39119. ** database connections. But there is a serious risk of database
  39120. ** corruption if this locking mode is used in situations where multiple
  39121. ** database connections are accessing the same database file at the same
  39122. ** time and one or more of those connections are writing.
  39123. */
  39124. static int winNolockLock(sqlite3_file *id, int locktype){
  39125. UNUSED_PARAMETER(id);
  39126. UNUSED_PARAMETER(locktype);
  39127. return SQLITE_OK;
  39128. }
  39129. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  39130. UNUSED_PARAMETER(id);
  39131. UNUSED_PARAMETER(pResOut);
  39132. return SQLITE_OK;
  39133. }
  39134. static int winNolockUnlock(sqlite3_file *id, int locktype){
  39135. UNUSED_PARAMETER(id);
  39136. UNUSED_PARAMETER(locktype);
  39137. return SQLITE_OK;
  39138. }
  39139. /******************* End of the no-op lock implementation *********************
  39140. ******************************************************************************/
  39141. /*
  39142. ** If *pArg is initially negative then this is a query. Set *pArg to
  39143. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  39144. **
  39145. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  39146. */
  39147. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  39148. if( *pArg<0 ){
  39149. *pArg = (pFile->ctrlFlags & mask)!=0;
  39150. }else if( (*pArg)==0 ){
  39151. pFile->ctrlFlags &= ~mask;
  39152. }else{
  39153. pFile->ctrlFlags |= mask;
  39154. }
  39155. }
  39156. /* Forward references to VFS helper methods used for temporary files */
  39157. static int winGetTempname(sqlite3_vfs *, char **);
  39158. static int winIsDir(const void *);
  39159. static BOOL winIsDriveLetterAndColon(const char *);
  39160. /*
  39161. ** Control and query of the open file handle.
  39162. */
  39163. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  39164. winFile *pFile = (winFile*)id;
  39165. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  39166. switch( op ){
  39167. case SQLITE_FCNTL_LOCKSTATE: {
  39168. *(int*)pArg = pFile->locktype;
  39169. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39170. return SQLITE_OK;
  39171. }
  39172. case SQLITE_FCNTL_LAST_ERRNO: {
  39173. *(int*)pArg = (int)pFile->lastErrno;
  39174. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39175. return SQLITE_OK;
  39176. }
  39177. case SQLITE_FCNTL_CHUNK_SIZE: {
  39178. pFile->szChunk = *(int *)pArg;
  39179. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39180. return SQLITE_OK;
  39181. }
  39182. case SQLITE_FCNTL_SIZE_HINT: {
  39183. if( pFile->szChunk>0 ){
  39184. sqlite3_int64 oldSz;
  39185. int rc = winFileSize(id, &oldSz);
  39186. if( rc==SQLITE_OK ){
  39187. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  39188. if( newSz>oldSz ){
  39189. SimulateIOErrorBenign(1);
  39190. rc = winTruncate(id, newSz);
  39191. SimulateIOErrorBenign(0);
  39192. }
  39193. }
  39194. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  39195. return rc;
  39196. }
  39197. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39198. return SQLITE_OK;
  39199. }
  39200. case SQLITE_FCNTL_PERSIST_WAL: {
  39201. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  39202. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39203. return SQLITE_OK;
  39204. }
  39205. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  39206. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  39207. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39208. return SQLITE_OK;
  39209. }
  39210. case SQLITE_FCNTL_VFSNAME: {
  39211. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  39212. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39213. return SQLITE_OK;
  39214. }
  39215. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  39216. int *a = (int*)pArg;
  39217. if( a[0]>0 ){
  39218. winIoerrRetry = a[0];
  39219. }else{
  39220. a[0] = winIoerrRetry;
  39221. }
  39222. if( a[1]>0 ){
  39223. winIoerrRetryDelay = a[1];
  39224. }else{
  39225. a[1] = winIoerrRetryDelay;
  39226. }
  39227. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39228. return SQLITE_OK;
  39229. }
  39230. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  39231. LPHANDLE phFile = (LPHANDLE)pArg;
  39232. *phFile = pFile->h;
  39233. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  39234. return SQLITE_OK;
  39235. }
  39236. #ifdef SQLITE_TEST
  39237. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  39238. LPHANDLE phFile = (LPHANDLE)pArg;
  39239. HANDLE hOldFile = pFile->h;
  39240. pFile->h = *phFile;
  39241. *phFile = hOldFile;
  39242. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  39243. hOldFile, pFile->h));
  39244. return SQLITE_OK;
  39245. }
  39246. #endif
  39247. case SQLITE_FCNTL_TEMPFILENAME: {
  39248. char *zTFile = 0;
  39249. int rc = winGetTempname(pFile->pVfs, &zTFile);
  39250. if( rc==SQLITE_OK ){
  39251. *(char**)pArg = zTFile;
  39252. }
  39253. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  39254. return rc;
  39255. }
  39256. #if SQLITE_MAX_MMAP_SIZE>0
  39257. case SQLITE_FCNTL_MMAP_SIZE: {
  39258. i64 newLimit = *(i64*)pArg;
  39259. int rc = SQLITE_OK;
  39260. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  39261. newLimit = sqlite3GlobalConfig.mxMmap;
  39262. }
  39263. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  39264. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  39265. ** least a 64-bit type. */
  39266. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  39267. newLimit = (newLimit & 0x7FFFFFFF);
  39268. }
  39269. *(i64*)pArg = pFile->mmapSizeMax;
  39270. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  39271. pFile->mmapSizeMax = newLimit;
  39272. if( pFile->mmapSize>0 ){
  39273. winUnmapfile(pFile);
  39274. rc = winMapfile(pFile, -1);
  39275. }
  39276. }
  39277. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  39278. return rc;
  39279. }
  39280. #endif
  39281. }
  39282. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  39283. return SQLITE_NOTFOUND;
  39284. }
  39285. /*
  39286. ** Return the sector size in bytes of the underlying block device for
  39287. ** the specified file. This is almost always 512 bytes, but may be
  39288. ** larger for some devices.
  39289. **
  39290. ** SQLite code assumes this function cannot fail. It also assumes that
  39291. ** if two files are created in the same file-system directory (i.e.
  39292. ** a database and its journal file) that the sector size will be the
  39293. ** same for both.
  39294. */
  39295. static int winSectorSize(sqlite3_file *id){
  39296. (void)id;
  39297. return SQLITE_DEFAULT_SECTOR_SIZE;
  39298. }
  39299. /*
  39300. ** Return a vector of device characteristics.
  39301. */
  39302. static int winDeviceCharacteristics(sqlite3_file *id){
  39303. winFile *p = (winFile*)id;
  39304. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  39305. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  39306. }
  39307. /*
  39308. ** Windows will only let you create file view mappings
  39309. ** on allocation size granularity boundaries.
  39310. ** During sqlite3_os_init() we do a GetSystemInfo()
  39311. ** to get the granularity size.
  39312. */
  39313. static SYSTEM_INFO winSysInfo;
  39314. #ifndef SQLITE_OMIT_WAL
  39315. /*
  39316. ** Helper functions to obtain and relinquish the global mutex. The
  39317. ** global mutex is used to protect the winLockInfo objects used by
  39318. ** this file, all of which may be shared by multiple threads.
  39319. **
  39320. ** Function winShmMutexHeld() is used to assert() that the global mutex
  39321. ** is held when required. This function is only used as part of assert()
  39322. ** statements. e.g.
  39323. **
  39324. ** winShmEnterMutex()
  39325. ** assert( winShmMutexHeld() );
  39326. ** winShmLeaveMutex()
  39327. */
  39328. static void winShmEnterMutex(void){
  39329. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  39330. }
  39331. static void winShmLeaveMutex(void){
  39332. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  39333. }
  39334. #ifndef NDEBUG
  39335. static int winShmMutexHeld(void) {
  39336. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  39337. }
  39338. #endif
  39339. /*
  39340. ** Object used to represent a single file opened and mmapped to provide
  39341. ** shared memory. When multiple threads all reference the same
  39342. ** log-summary, each thread has its own winFile object, but they all
  39343. ** point to a single instance of this object. In other words, each
  39344. ** log-summary is opened only once per process.
  39345. **
  39346. ** winShmMutexHeld() must be true when creating or destroying
  39347. ** this object or while reading or writing the following fields:
  39348. **
  39349. ** nRef
  39350. ** pNext
  39351. **
  39352. ** The following fields are read-only after the object is created:
  39353. **
  39354. ** fid
  39355. ** zFilename
  39356. **
  39357. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  39358. ** winShmMutexHeld() is true when reading or writing any other field
  39359. ** in this structure.
  39360. **
  39361. */
  39362. struct winShmNode {
  39363. sqlite3_mutex *mutex; /* Mutex to access this object */
  39364. char *zFilename; /* Name of the file */
  39365. winFile hFile; /* File handle from winOpen */
  39366. int szRegion; /* Size of shared-memory regions */
  39367. int nRegion; /* Size of array apRegion */
  39368. struct ShmRegion {
  39369. HANDLE hMap; /* File handle from CreateFileMapping */
  39370. void *pMap;
  39371. } *aRegion;
  39372. DWORD lastErrno; /* The Windows errno from the last I/O error */
  39373. int nRef; /* Number of winShm objects pointing to this */
  39374. winShm *pFirst; /* All winShm objects pointing to this */
  39375. winShmNode *pNext; /* Next in list of all winShmNode objects */
  39376. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  39377. u8 nextShmId; /* Next available winShm.id value */
  39378. #endif
  39379. };
  39380. /*
  39381. ** A global array of all winShmNode objects.
  39382. **
  39383. ** The winShmMutexHeld() must be true while reading or writing this list.
  39384. */
  39385. static winShmNode *winShmNodeList = 0;
  39386. /*
  39387. ** Structure used internally by this VFS to record the state of an
  39388. ** open shared memory connection.
  39389. **
  39390. ** The following fields are initialized when this object is created and
  39391. ** are read-only thereafter:
  39392. **
  39393. ** winShm.pShmNode
  39394. ** winShm.id
  39395. **
  39396. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  39397. ** while accessing any read/write fields.
  39398. */
  39399. struct winShm {
  39400. winShmNode *pShmNode; /* The underlying winShmNode object */
  39401. winShm *pNext; /* Next winShm with the same winShmNode */
  39402. u8 hasMutex; /* True if holding the winShmNode mutex */
  39403. u16 sharedMask; /* Mask of shared locks held */
  39404. u16 exclMask; /* Mask of exclusive locks held */
  39405. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  39406. u8 id; /* Id of this connection with its winShmNode */
  39407. #endif
  39408. };
  39409. /*
  39410. ** Constants used for locking
  39411. */
  39412. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  39413. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  39414. /*
  39415. ** Apply advisory locks for all n bytes beginning at ofst.
  39416. */
  39417. #define WINSHM_UNLCK 1
  39418. #define WINSHM_RDLCK 2
  39419. #define WINSHM_WRLCK 3
  39420. static int winShmSystemLock(
  39421. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  39422. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  39423. int ofst, /* Offset to first byte to be locked/unlocked */
  39424. int nByte /* Number of bytes to lock or unlock */
  39425. ){
  39426. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  39427. /* Access to the winShmNode object is serialized by the caller */
  39428. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  39429. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  39430. pFile->hFile.h, lockType, ofst, nByte));
  39431. /* Release/Acquire the system-level lock */
  39432. if( lockType==WINSHM_UNLCK ){
  39433. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  39434. }else{
  39435. /* Initialize the locking parameters */
  39436. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  39437. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  39438. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  39439. }
  39440. if( rc!= 0 ){
  39441. rc = SQLITE_OK;
  39442. }else{
  39443. pFile->lastErrno = osGetLastError();
  39444. rc = SQLITE_BUSY;
  39445. }
  39446. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  39447. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  39448. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  39449. return rc;
  39450. }
  39451. /* Forward references to VFS methods */
  39452. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  39453. static int winDelete(sqlite3_vfs *,const char*,int);
  39454. /*
  39455. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  39456. **
  39457. ** This is not a VFS shared-memory method; it is a utility function called
  39458. ** by VFS shared-memory methods.
  39459. */
  39460. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  39461. winShmNode **pp;
  39462. winShmNode *p;
  39463. assert( winShmMutexHeld() );
  39464. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  39465. osGetCurrentProcessId(), deleteFlag));
  39466. pp = &winShmNodeList;
  39467. while( (p = *pp)!=0 ){
  39468. if( p->nRef==0 ){
  39469. int i;
  39470. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  39471. for(i=0; i<p->nRegion; i++){
  39472. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  39473. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  39474. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  39475. UNUSED_VARIABLE_VALUE(bRc);
  39476. bRc = osCloseHandle(p->aRegion[i].hMap);
  39477. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  39478. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  39479. UNUSED_VARIABLE_VALUE(bRc);
  39480. }
  39481. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  39482. SimulateIOErrorBenign(1);
  39483. winClose((sqlite3_file *)&p->hFile);
  39484. SimulateIOErrorBenign(0);
  39485. }
  39486. if( deleteFlag ){
  39487. SimulateIOErrorBenign(1);
  39488. sqlite3BeginBenignMalloc();
  39489. winDelete(pVfs, p->zFilename, 0);
  39490. sqlite3EndBenignMalloc();
  39491. SimulateIOErrorBenign(0);
  39492. }
  39493. *pp = p->pNext;
  39494. sqlite3_free(p->aRegion);
  39495. sqlite3_free(p);
  39496. }else{
  39497. pp = &p->pNext;
  39498. }
  39499. }
  39500. }
  39501. /*
  39502. ** Open the shared-memory area associated with database file pDbFd.
  39503. **
  39504. ** When opening a new shared-memory file, if no other instances of that
  39505. ** file are currently open, in this process or in other processes, then
  39506. ** the file must be truncated to zero length or have its header cleared.
  39507. */
  39508. static int winOpenSharedMemory(winFile *pDbFd){
  39509. struct winShm *p; /* The connection to be opened */
  39510. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  39511. int rc; /* Result code */
  39512. struct winShmNode *pNew; /* Newly allocated winShmNode */
  39513. int nName; /* Size of zName in bytes */
  39514. assert( pDbFd->pShm==0 ); /* Not previously opened */
  39515. /* Allocate space for the new sqlite3_shm object. Also speculatively
  39516. ** allocate space for a new winShmNode and filename.
  39517. */
  39518. p = sqlite3MallocZero( sizeof(*p) );
  39519. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  39520. nName = sqlite3Strlen30(pDbFd->zPath);
  39521. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  39522. if( pNew==0 ){
  39523. sqlite3_free(p);
  39524. return SQLITE_IOERR_NOMEM_BKPT;
  39525. }
  39526. pNew->zFilename = (char*)&pNew[1];
  39527. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  39528. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  39529. /* Look to see if there is an existing winShmNode that can be used.
  39530. ** If no matching winShmNode currently exists, create a new one.
  39531. */
  39532. winShmEnterMutex();
  39533. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  39534. /* TBD need to come up with better match here. Perhaps
  39535. ** use FILE_ID_BOTH_DIR_INFO Structure.
  39536. */
  39537. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  39538. }
  39539. if( pShmNode ){
  39540. sqlite3_free(pNew);
  39541. }else{
  39542. pShmNode = pNew;
  39543. pNew = 0;
  39544. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  39545. pShmNode->pNext = winShmNodeList;
  39546. winShmNodeList = pShmNode;
  39547. if( sqlite3GlobalConfig.bCoreMutex ){
  39548. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  39549. if( pShmNode->mutex==0 ){
  39550. rc = SQLITE_IOERR_NOMEM_BKPT;
  39551. goto shm_open_err;
  39552. }
  39553. }
  39554. rc = winOpen(pDbFd->pVfs,
  39555. pShmNode->zFilename, /* Name of the file (UTF-8) */
  39556. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  39557. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  39558. 0);
  39559. if( SQLITE_OK!=rc ){
  39560. goto shm_open_err;
  39561. }
  39562. /* Check to see if another process is holding the dead-man switch.
  39563. ** If not, truncate the file to zero length.
  39564. */
  39565. if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  39566. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  39567. if( rc!=SQLITE_OK ){
  39568. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  39569. "winOpenShm", pDbFd->zPath);
  39570. }
  39571. }
  39572. if( rc==SQLITE_OK ){
  39573. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39574. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  39575. }
  39576. if( rc ) goto shm_open_err;
  39577. }
  39578. /* Make the new connection a child of the winShmNode */
  39579. p->pShmNode = pShmNode;
  39580. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  39581. p->id = pShmNode->nextShmId++;
  39582. #endif
  39583. pShmNode->nRef++;
  39584. pDbFd->pShm = p;
  39585. winShmLeaveMutex();
  39586. /* The reference count on pShmNode has already been incremented under
  39587. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  39588. ** new (struct winShm) object to the pShmNode has been set. All that is
  39589. ** left to do is to link the new object into the linked list starting
  39590. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  39591. ** mutex.
  39592. */
  39593. sqlite3_mutex_enter(pShmNode->mutex);
  39594. p->pNext = pShmNode->pFirst;
  39595. pShmNode->pFirst = p;
  39596. sqlite3_mutex_leave(pShmNode->mutex);
  39597. return SQLITE_OK;
  39598. /* Jump here on any error */
  39599. shm_open_err:
  39600. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39601. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  39602. sqlite3_free(p);
  39603. sqlite3_free(pNew);
  39604. winShmLeaveMutex();
  39605. return rc;
  39606. }
  39607. /*
  39608. ** Close a connection to shared-memory. Delete the underlying
  39609. ** storage if deleteFlag is true.
  39610. */
  39611. static int winShmUnmap(
  39612. sqlite3_file *fd, /* Database holding shared memory */
  39613. int deleteFlag /* Delete after closing if true */
  39614. ){
  39615. winFile *pDbFd; /* Database holding shared-memory */
  39616. winShm *p; /* The connection to be closed */
  39617. winShmNode *pShmNode; /* The underlying shared-memory file */
  39618. winShm **pp; /* For looping over sibling connections */
  39619. pDbFd = (winFile*)fd;
  39620. p = pDbFd->pShm;
  39621. if( p==0 ) return SQLITE_OK;
  39622. pShmNode = p->pShmNode;
  39623. /* Remove connection p from the set of connections associated
  39624. ** with pShmNode */
  39625. sqlite3_mutex_enter(pShmNode->mutex);
  39626. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  39627. *pp = p->pNext;
  39628. /* Free the connection p */
  39629. sqlite3_free(p);
  39630. pDbFd->pShm = 0;
  39631. sqlite3_mutex_leave(pShmNode->mutex);
  39632. /* If pShmNode->nRef has reached 0, then close the underlying
  39633. ** shared-memory file, too */
  39634. winShmEnterMutex();
  39635. assert( pShmNode->nRef>0 );
  39636. pShmNode->nRef--;
  39637. if( pShmNode->nRef==0 ){
  39638. winShmPurge(pDbFd->pVfs, deleteFlag);
  39639. }
  39640. winShmLeaveMutex();
  39641. return SQLITE_OK;
  39642. }
  39643. /*
  39644. ** Change the lock state for a shared-memory segment.
  39645. */
  39646. static int winShmLock(
  39647. sqlite3_file *fd, /* Database file holding the shared memory */
  39648. int ofst, /* First lock to acquire or release */
  39649. int n, /* Number of locks to acquire or release */
  39650. int flags /* What to do with the lock */
  39651. ){
  39652. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  39653. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  39654. winShm *pX; /* For looping over all siblings */
  39655. winShmNode *pShmNode = p->pShmNode;
  39656. int rc = SQLITE_OK; /* Result code */
  39657. u16 mask; /* Mask of locks to take or release */
  39658. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  39659. assert( n>=1 );
  39660. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  39661. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  39662. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  39663. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  39664. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  39665. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  39666. assert( n>1 || mask==(1<<ofst) );
  39667. sqlite3_mutex_enter(pShmNode->mutex);
  39668. if( flags & SQLITE_SHM_UNLOCK ){
  39669. u16 allMask = 0; /* Mask of locks held by siblings */
  39670. /* See if any siblings hold this same lock */
  39671. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39672. if( pX==p ) continue;
  39673. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  39674. allMask |= pX->sharedMask;
  39675. }
  39676. /* Unlock the system-level locks */
  39677. if( (mask & allMask)==0 ){
  39678. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  39679. }else{
  39680. rc = SQLITE_OK;
  39681. }
  39682. /* Undo the local locks */
  39683. if( rc==SQLITE_OK ){
  39684. p->exclMask &= ~mask;
  39685. p->sharedMask &= ~mask;
  39686. }
  39687. }else if( flags & SQLITE_SHM_SHARED ){
  39688. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  39689. /* Find out which shared locks are already held by sibling connections.
  39690. ** If any sibling already holds an exclusive lock, go ahead and return
  39691. ** SQLITE_BUSY.
  39692. */
  39693. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39694. if( (pX->exclMask & mask)!=0 ){
  39695. rc = SQLITE_BUSY;
  39696. break;
  39697. }
  39698. allShared |= pX->sharedMask;
  39699. }
  39700. /* Get shared locks at the system level, if necessary */
  39701. if( rc==SQLITE_OK ){
  39702. if( (allShared & mask)==0 ){
  39703. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  39704. }else{
  39705. rc = SQLITE_OK;
  39706. }
  39707. }
  39708. /* Get the local shared locks */
  39709. if( rc==SQLITE_OK ){
  39710. p->sharedMask |= mask;
  39711. }
  39712. }else{
  39713. /* Make sure no sibling connections hold locks that will block this
  39714. ** lock. If any do, return SQLITE_BUSY right away.
  39715. */
  39716. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39717. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  39718. rc = SQLITE_BUSY;
  39719. break;
  39720. }
  39721. }
  39722. /* Get the exclusive locks at the system level. Then if successful
  39723. ** also mark the local connection as being locked.
  39724. */
  39725. if( rc==SQLITE_OK ){
  39726. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  39727. if( rc==SQLITE_OK ){
  39728. assert( (p->sharedMask & mask)==0 );
  39729. p->exclMask |= mask;
  39730. }
  39731. }
  39732. }
  39733. sqlite3_mutex_leave(pShmNode->mutex);
  39734. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  39735. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  39736. sqlite3ErrName(rc)));
  39737. return rc;
  39738. }
  39739. /*
  39740. ** Implement a memory barrier or memory fence on shared memory.
  39741. **
  39742. ** All loads and stores begun before the barrier must complete before
  39743. ** any load or store begun after the barrier.
  39744. */
  39745. static void winShmBarrier(
  39746. sqlite3_file *fd /* Database holding the shared memory */
  39747. ){
  39748. UNUSED_PARAMETER(fd);
  39749. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  39750. winShmEnterMutex(); /* Also mutex, for redundancy */
  39751. winShmLeaveMutex();
  39752. }
  39753. /*
  39754. ** This function is called to obtain a pointer to region iRegion of the
  39755. ** shared-memory associated with the database file fd. Shared-memory regions
  39756. ** are numbered starting from zero. Each shared-memory region is szRegion
  39757. ** bytes in size.
  39758. **
  39759. ** If an error occurs, an error code is returned and *pp is set to NULL.
  39760. **
  39761. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  39762. ** region has not been allocated (by any client, including one running in a
  39763. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  39764. ** isWrite is non-zero and the requested shared-memory region has not yet
  39765. ** been allocated, it is allocated by this function.
  39766. **
  39767. ** If the shared-memory region has already been allocated or is allocated by
  39768. ** this call as described above, then it is mapped into this processes
  39769. ** address space (if it is not already), *pp is set to point to the mapped
  39770. ** memory and SQLITE_OK returned.
  39771. */
  39772. static int winShmMap(
  39773. sqlite3_file *fd, /* Handle open on database file */
  39774. int iRegion, /* Region to retrieve */
  39775. int szRegion, /* Size of regions */
  39776. int isWrite, /* True to extend file if necessary */
  39777. void volatile **pp /* OUT: Mapped memory */
  39778. ){
  39779. winFile *pDbFd = (winFile*)fd;
  39780. winShm *pShm = pDbFd->pShm;
  39781. winShmNode *pShmNode;
  39782. int rc = SQLITE_OK;
  39783. if( !pShm ){
  39784. rc = winOpenSharedMemory(pDbFd);
  39785. if( rc!=SQLITE_OK ) return rc;
  39786. pShm = pDbFd->pShm;
  39787. }
  39788. pShmNode = pShm->pShmNode;
  39789. sqlite3_mutex_enter(pShmNode->mutex);
  39790. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  39791. if( pShmNode->nRegion<=iRegion ){
  39792. struct ShmRegion *apNew; /* New aRegion[] array */
  39793. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  39794. sqlite3_int64 sz; /* Current size of wal-index file */
  39795. pShmNode->szRegion = szRegion;
  39796. /* The requested region is not mapped into this processes address space.
  39797. ** Check to see if it has been allocated (i.e. if the wal-index file is
  39798. ** large enough to contain the requested region).
  39799. */
  39800. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  39801. if( rc!=SQLITE_OK ){
  39802. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39803. "winShmMap1", pDbFd->zPath);
  39804. goto shmpage_out;
  39805. }
  39806. if( sz<nByte ){
  39807. /* The requested memory region does not exist. If isWrite is set to
  39808. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  39809. **
  39810. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  39811. ** the requested memory region.
  39812. */
  39813. if( !isWrite ) goto shmpage_out;
  39814. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  39815. if( rc!=SQLITE_OK ){
  39816. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39817. "winShmMap2", pDbFd->zPath);
  39818. goto shmpage_out;
  39819. }
  39820. }
  39821. /* Map the requested memory region into this processes address space. */
  39822. apNew = (struct ShmRegion *)sqlite3_realloc64(
  39823. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  39824. );
  39825. if( !apNew ){
  39826. rc = SQLITE_IOERR_NOMEM_BKPT;
  39827. goto shmpage_out;
  39828. }
  39829. pShmNode->aRegion = apNew;
  39830. while( pShmNode->nRegion<=iRegion ){
  39831. HANDLE hMap = NULL; /* file-mapping handle */
  39832. void *pMap = 0; /* Mapped memory region */
  39833. #if SQLITE_OS_WINRT
  39834. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  39835. NULL, PAGE_READWRITE, nByte, NULL
  39836. );
  39837. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39838. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  39839. NULL, PAGE_READWRITE, 0, nByte, NULL
  39840. );
  39841. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39842. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  39843. NULL, PAGE_READWRITE, 0, nByte, NULL
  39844. );
  39845. #endif
  39846. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  39847. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  39848. hMap ? "ok" : "failed"));
  39849. if( hMap ){
  39850. int iOffset = pShmNode->nRegion*szRegion;
  39851. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39852. #if SQLITE_OS_WINRT
  39853. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39854. iOffset - iOffsetShift, szRegion + iOffsetShift
  39855. );
  39856. #else
  39857. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39858. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  39859. );
  39860. #endif
  39861. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  39862. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  39863. szRegion, pMap ? "ok" : "failed"));
  39864. }
  39865. if( !pMap ){
  39866. pShmNode->lastErrno = osGetLastError();
  39867. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  39868. "winShmMap3", pDbFd->zPath);
  39869. if( hMap ) osCloseHandle(hMap);
  39870. goto shmpage_out;
  39871. }
  39872. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  39873. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  39874. pShmNode->nRegion++;
  39875. }
  39876. }
  39877. shmpage_out:
  39878. if( pShmNode->nRegion>iRegion ){
  39879. int iOffset = iRegion*szRegion;
  39880. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39881. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  39882. *pp = (void *)&p[iOffsetShift];
  39883. }else{
  39884. *pp = 0;
  39885. }
  39886. sqlite3_mutex_leave(pShmNode->mutex);
  39887. return rc;
  39888. }
  39889. #else
  39890. # define winShmMap 0
  39891. # define winShmLock 0
  39892. # define winShmBarrier 0
  39893. # define winShmUnmap 0
  39894. #endif /* #ifndef SQLITE_OMIT_WAL */
  39895. /*
  39896. ** Cleans up the mapped region of the specified file, if any.
  39897. */
  39898. #if SQLITE_MAX_MMAP_SIZE>0
  39899. static int winUnmapfile(winFile *pFile){
  39900. assert( pFile!=0 );
  39901. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  39902. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  39903. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  39904. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  39905. if( pFile->pMapRegion ){
  39906. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  39907. pFile->lastErrno = osGetLastError();
  39908. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  39909. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  39910. pFile->pMapRegion));
  39911. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39912. "winUnmapfile1", pFile->zPath);
  39913. }
  39914. pFile->pMapRegion = 0;
  39915. pFile->mmapSize = 0;
  39916. pFile->mmapSizeActual = 0;
  39917. }
  39918. if( pFile->hMap!=NULL ){
  39919. if( !osCloseHandle(pFile->hMap) ){
  39920. pFile->lastErrno = osGetLastError();
  39921. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  39922. osGetCurrentProcessId(), pFile, pFile->hMap));
  39923. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39924. "winUnmapfile2", pFile->zPath);
  39925. }
  39926. pFile->hMap = NULL;
  39927. }
  39928. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39929. osGetCurrentProcessId(), pFile));
  39930. return SQLITE_OK;
  39931. }
  39932. /*
  39933. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  39934. ** is already mapped, the existing mapping is replaced by the new). Or, if
  39935. ** there already exists a mapping for this file, and there are still
  39936. ** outstanding xFetch() references to it, this function is a no-op.
  39937. **
  39938. ** If parameter nByte is non-negative, then it is the requested size of
  39939. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  39940. ** requested size is the size of the file on disk. The actual size of the
  39941. ** created mapping is either the requested size or the value configured
  39942. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  39943. **
  39944. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  39945. ** recreated as a result of outstanding references) or an SQLite error
  39946. ** code otherwise.
  39947. */
  39948. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  39949. sqlite3_int64 nMap = nByte;
  39950. int rc;
  39951. assert( nMap>=0 || pFd->nFetchOut==0 );
  39952. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  39953. osGetCurrentProcessId(), pFd, nByte));
  39954. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  39955. if( nMap<0 ){
  39956. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  39957. if( rc ){
  39958. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  39959. osGetCurrentProcessId(), pFd));
  39960. return SQLITE_IOERR_FSTAT;
  39961. }
  39962. }
  39963. if( nMap>pFd->mmapSizeMax ){
  39964. nMap = pFd->mmapSizeMax;
  39965. }
  39966. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  39967. if( nMap==0 && pFd->mmapSize>0 ){
  39968. winUnmapfile(pFd);
  39969. }
  39970. if( nMap!=pFd->mmapSize ){
  39971. void *pNew = 0;
  39972. DWORD protect = PAGE_READONLY;
  39973. DWORD flags = FILE_MAP_READ;
  39974. winUnmapfile(pFd);
  39975. #ifdef SQLITE_MMAP_READWRITE
  39976. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  39977. protect = PAGE_READWRITE;
  39978. flags |= FILE_MAP_WRITE;
  39979. }
  39980. #endif
  39981. #if SQLITE_OS_WINRT
  39982. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  39983. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39984. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  39985. (DWORD)((nMap>>32) & 0xffffffff),
  39986. (DWORD)(nMap & 0xffffffff), NULL);
  39987. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39988. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  39989. (DWORD)((nMap>>32) & 0xffffffff),
  39990. (DWORD)(nMap & 0xffffffff), NULL);
  39991. #endif
  39992. if( pFd->hMap==NULL ){
  39993. pFd->lastErrno = osGetLastError();
  39994. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  39995. "winMapfile1", pFd->zPath);
  39996. /* Log the error, but continue normal operation using xRead/xWrite */
  39997. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  39998. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39999. return SQLITE_OK;
  40000. }
  40001. assert( (nMap % winSysInfo.dwPageSize)==0 );
  40002. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  40003. #if SQLITE_OS_WINRT
  40004. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  40005. #else
  40006. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  40007. #endif
  40008. if( pNew==NULL ){
  40009. osCloseHandle(pFd->hMap);
  40010. pFd->hMap = NULL;
  40011. pFd->lastErrno = osGetLastError();
  40012. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  40013. "winMapfile2", pFd->zPath);
  40014. /* Log the error, but continue normal operation using xRead/xWrite */
  40015. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  40016. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  40017. return SQLITE_OK;
  40018. }
  40019. pFd->pMapRegion = pNew;
  40020. pFd->mmapSize = nMap;
  40021. pFd->mmapSizeActual = nMap;
  40022. }
  40023. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  40024. osGetCurrentProcessId(), pFd));
  40025. return SQLITE_OK;
  40026. }
  40027. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  40028. /*
  40029. ** If possible, return a pointer to a mapping of file fd starting at offset
  40030. ** iOff. The mapping must be valid for at least nAmt bytes.
  40031. **
  40032. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  40033. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  40034. ** Finally, if an error does occur, return an SQLite error code. The final
  40035. ** value of *pp is undefined in this case.
  40036. **
  40037. ** If this function does return a pointer, the caller must eventually
  40038. ** release the reference by calling winUnfetch().
  40039. */
  40040. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  40041. #if SQLITE_MAX_MMAP_SIZE>0
  40042. winFile *pFd = (winFile*)fd; /* The underlying database file */
  40043. #endif
  40044. *pp = 0;
  40045. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  40046. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  40047. #if SQLITE_MAX_MMAP_SIZE>0
  40048. if( pFd->mmapSizeMax>0 ){
  40049. if( pFd->pMapRegion==0 ){
  40050. int rc = winMapfile(pFd, -1);
  40051. if( rc!=SQLITE_OK ){
  40052. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  40053. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  40054. return rc;
  40055. }
  40056. }
  40057. if( pFd->mmapSize >= iOff+nAmt ){
  40058. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  40059. pFd->nFetchOut++;
  40060. }
  40061. }
  40062. #endif
  40063. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  40064. osGetCurrentProcessId(), fd, pp, *pp));
  40065. return SQLITE_OK;
  40066. }
  40067. /*
  40068. ** If the third argument is non-NULL, then this function releases a
  40069. ** reference obtained by an earlier call to winFetch(). The second
  40070. ** argument passed to this function must be the same as the corresponding
  40071. ** argument that was passed to the winFetch() invocation.
  40072. **
  40073. ** Or, if the third argument is NULL, then this function is being called
  40074. ** to inform the VFS layer that, according to POSIX, any existing mapping
  40075. ** may now be invalid and should be unmapped.
  40076. */
  40077. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  40078. #if SQLITE_MAX_MMAP_SIZE>0
  40079. winFile *pFd = (winFile*)fd; /* The underlying database file */
  40080. /* If p==0 (unmap the entire file) then there must be no outstanding
  40081. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  40082. ** then there must be at least one outstanding. */
  40083. assert( (p==0)==(pFd->nFetchOut==0) );
  40084. /* If p!=0, it must match the iOff value. */
  40085. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  40086. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  40087. osGetCurrentProcessId(), pFd, iOff, p));
  40088. if( p ){
  40089. pFd->nFetchOut--;
  40090. }else{
  40091. /* FIXME: If Windows truly always prevents truncating or deleting a
  40092. ** file while a mapping is held, then the following winUnmapfile() call
  40093. ** is unnecessary can be omitted - potentially improving
  40094. ** performance. */
  40095. winUnmapfile(pFd);
  40096. }
  40097. assert( pFd->nFetchOut>=0 );
  40098. #endif
  40099. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  40100. osGetCurrentProcessId(), fd));
  40101. return SQLITE_OK;
  40102. }
  40103. /*
  40104. ** Here ends the implementation of all sqlite3_file methods.
  40105. **
  40106. ********************** End sqlite3_file Methods *******************************
  40107. ******************************************************************************/
  40108. /*
  40109. ** This vector defines all the methods that can operate on an
  40110. ** sqlite3_file for win32.
  40111. */
  40112. static const sqlite3_io_methods winIoMethod = {
  40113. 3, /* iVersion */
  40114. winClose, /* xClose */
  40115. winRead, /* xRead */
  40116. winWrite, /* xWrite */
  40117. winTruncate, /* xTruncate */
  40118. winSync, /* xSync */
  40119. winFileSize, /* xFileSize */
  40120. winLock, /* xLock */
  40121. winUnlock, /* xUnlock */
  40122. winCheckReservedLock, /* xCheckReservedLock */
  40123. winFileControl, /* xFileControl */
  40124. winSectorSize, /* xSectorSize */
  40125. winDeviceCharacteristics, /* xDeviceCharacteristics */
  40126. winShmMap, /* xShmMap */
  40127. winShmLock, /* xShmLock */
  40128. winShmBarrier, /* xShmBarrier */
  40129. winShmUnmap, /* xShmUnmap */
  40130. winFetch, /* xFetch */
  40131. winUnfetch /* xUnfetch */
  40132. };
  40133. /*
  40134. ** This vector defines all the methods that can operate on an
  40135. ** sqlite3_file for win32 without performing any locking.
  40136. */
  40137. static const sqlite3_io_methods winIoNolockMethod = {
  40138. 3, /* iVersion */
  40139. winClose, /* xClose */
  40140. winRead, /* xRead */
  40141. winWrite, /* xWrite */
  40142. winTruncate, /* xTruncate */
  40143. winSync, /* xSync */
  40144. winFileSize, /* xFileSize */
  40145. winNolockLock, /* xLock */
  40146. winNolockUnlock, /* xUnlock */
  40147. winNolockCheckReservedLock, /* xCheckReservedLock */
  40148. winFileControl, /* xFileControl */
  40149. winSectorSize, /* xSectorSize */
  40150. winDeviceCharacteristics, /* xDeviceCharacteristics */
  40151. winShmMap, /* xShmMap */
  40152. winShmLock, /* xShmLock */
  40153. winShmBarrier, /* xShmBarrier */
  40154. winShmUnmap, /* xShmUnmap */
  40155. winFetch, /* xFetch */
  40156. winUnfetch /* xUnfetch */
  40157. };
  40158. static winVfsAppData winAppData = {
  40159. &winIoMethod, /* pMethod */
  40160. 0, /* pAppData */
  40161. 0 /* bNoLock */
  40162. };
  40163. static winVfsAppData winNolockAppData = {
  40164. &winIoNolockMethod, /* pMethod */
  40165. 0, /* pAppData */
  40166. 1 /* bNoLock */
  40167. };
  40168. /****************************************************************************
  40169. **************************** sqlite3_vfs methods ****************************
  40170. **
  40171. ** This division contains the implementation of methods on the
  40172. ** sqlite3_vfs object.
  40173. */
  40174. #if defined(__CYGWIN__)
  40175. /*
  40176. ** Convert a filename from whatever the underlying operating system
  40177. ** supports for filenames into UTF-8. Space to hold the result is
  40178. ** obtained from malloc and must be freed by the calling function.
  40179. */
  40180. static char *winConvertToUtf8Filename(const void *zFilename){
  40181. char *zConverted = 0;
  40182. if( osIsNT() ){
  40183. zConverted = winUnicodeToUtf8(zFilename);
  40184. }
  40185. #ifdef SQLITE_WIN32_HAS_ANSI
  40186. else{
  40187. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  40188. }
  40189. #endif
  40190. /* caller will handle out of memory */
  40191. return zConverted;
  40192. }
  40193. #endif
  40194. /*
  40195. ** Convert a UTF-8 filename into whatever form the underlying
  40196. ** operating system wants filenames in. Space to hold the result
  40197. ** is obtained from malloc and must be freed by the calling
  40198. ** function.
  40199. */
  40200. static void *winConvertFromUtf8Filename(const char *zFilename){
  40201. void *zConverted = 0;
  40202. if( osIsNT() ){
  40203. zConverted = winUtf8ToUnicode(zFilename);
  40204. }
  40205. #ifdef SQLITE_WIN32_HAS_ANSI
  40206. else{
  40207. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  40208. }
  40209. #endif
  40210. /* caller will handle out of memory */
  40211. return zConverted;
  40212. }
  40213. /*
  40214. ** This function returns non-zero if the specified UTF-8 string buffer
  40215. ** ends with a directory separator character or one was successfully
  40216. ** added to it.
  40217. */
  40218. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  40219. if( zBuf ){
  40220. int nLen = sqlite3Strlen30(zBuf);
  40221. if( nLen>0 ){
  40222. if( winIsDirSep(zBuf[nLen-1]) ){
  40223. return 1;
  40224. }else if( nLen+1<nBuf ){
  40225. zBuf[nLen] = winGetDirSep();
  40226. zBuf[nLen+1] = '\0';
  40227. return 1;
  40228. }
  40229. }
  40230. }
  40231. return 0;
  40232. }
  40233. /*
  40234. ** Create a temporary file name and store the resulting pointer into pzBuf.
  40235. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  40236. */
  40237. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  40238. static char zChars[] =
  40239. "abcdefghijklmnopqrstuvwxyz"
  40240. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  40241. "0123456789";
  40242. size_t i, j;
  40243. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  40244. int nMax, nBuf, nDir, nLen;
  40245. char *zBuf;
  40246. /* It's odd to simulate an io-error here, but really this is just
  40247. ** using the io-error infrastructure to test that SQLite handles this
  40248. ** function failing.
  40249. */
  40250. SimulateIOError( return SQLITE_IOERR );
  40251. /* Allocate a temporary buffer to store the fully qualified file
  40252. ** name for the temporary file. If this fails, we cannot continue.
  40253. */
  40254. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  40255. zBuf = sqlite3MallocZero( nBuf );
  40256. if( !zBuf ){
  40257. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40258. return SQLITE_IOERR_NOMEM_BKPT;
  40259. }
  40260. /* Figure out the effective temporary directory. First, check if one
  40261. ** has been explicitly set by the application; otherwise, use the one
  40262. ** configured by the operating system.
  40263. */
  40264. nDir = nMax - (nPre + 15);
  40265. assert( nDir>0 );
  40266. if( sqlite3_temp_directory ){
  40267. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  40268. if( nDirLen>0 ){
  40269. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  40270. nDirLen++;
  40271. }
  40272. if( nDirLen>nDir ){
  40273. sqlite3_free(zBuf);
  40274. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  40275. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  40276. }
  40277. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  40278. }
  40279. }
  40280. #if defined(__CYGWIN__)
  40281. else{
  40282. static const char *azDirs[] = {
  40283. 0, /* getenv("SQLITE_TMPDIR") */
  40284. 0, /* getenv("TMPDIR") */
  40285. 0, /* getenv("TMP") */
  40286. 0, /* getenv("TEMP") */
  40287. 0, /* getenv("USERPROFILE") */
  40288. "/var/tmp",
  40289. "/usr/tmp",
  40290. "/tmp",
  40291. ".",
  40292. 0 /* List terminator */
  40293. };
  40294. unsigned int i;
  40295. const char *zDir = 0;
  40296. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  40297. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  40298. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  40299. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  40300. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  40301. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  40302. void *zConverted;
  40303. if( zDir==0 ) continue;
  40304. /* If the path starts with a drive letter followed by the colon
  40305. ** character, assume it is already a native Win32 path; otherwise,
  40306. ** it must be converted to a native Win32 path via the Cygwin API
  40307. ** prior to using it.
  40308. */
  40309. if( winIsDriveLetterAndColon(zDir) ){
  40310. zConverted = winConvertFromUtf8Filename(zDir);
  40311. if( !zConverted ){
  40312. sqlite3_free(zBuf);
  40313. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40314. return SQLITE_IOERR_NOMEM_BKPT;
  40315. }
  40316. if( winIsDir(zConverted) ){
  40317. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  40318. sqlite3_free(zConverted);
  40319. break;
  40320. }
  40321. sqlite3_free(zConverted);
  40322. }else{
  40323. zConverted = sqlite3MallocZero( nMax+1 );
  40324. if( !zConverted ){
  40325. sqlite3_free(zBuf);
  40326. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40327. return SQLITE_IOERR_NOMEM_BKPT;
  40328. }
  40329. if( cygwin_conv_path(
  40330. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  40331. zConverted, nMax+1)<0 ){
  40332. sqlite3_free(zConverted);
  40333. sqlite3_free(zBuf);
  40334. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  40335. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  40336. "winGetTempname2", zDir);
  40337. }
  40338. if( winIsDir(zConverted) ){
  40339. /* At this point, we know the candidate directory exists and should
  40340. ** be used. However, we may need to convert the string containing
  40341. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  40342. */
  40343. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  40344. if( !zUtf8 ){
  40345. sqlite3_free(zConverted);
  40346. sqlite3_free(zBuf);
  40347. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40348. return SQLITE_IOERR_NOMEM_BKPT;
  40349. }
  40350. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  40351. sqlite3_free(zUtf8);
  40352. sqlite3_free(zConverted);
  40353. break;
  40354. }
  40355. sqlite3_free(zConverted);
  40356. }
  40357. }
  40358. }
  40359. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  40360. else if( osIsNT() ){
  40361. char *zMulti;
  40362. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  40363. if( !zWidePath ){
  40364. sqlite3_free(zBuf);
  40365. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40366. return SQLITE_IOERR_NOMEM_BKPT;
  40367. }
  40368. if( osGetTempPathW(nMax, zWidePath)==0 ){
  40369. sqlite3_free(zWidePath);
  40370. sqlite3_free(zBuf);
  40371. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  40372. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  40373. "winGetTempname2", 0);
  40374. }
  40375. zMulti = winUnicodeToUtf8(zWidePath);
  40376. if( zMulti ){
  40377. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  40378. sqlite3_free(zMulti);
  40379. sqlite3_free(zWidePath);
  40380. }else{
  40381. sqlite3_free(zWidePath);
  40382. sqlite3_free(zBuf);
  40383. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40384. return SQLITE_IOERR_NOMEM_BKPT;
  40385. }
  40386. }
  40387. #ifdef SQLITE_WIN32_HAS_ANSI
  40388. else{
  40389. char *zUtf8;
  40390. char *zMbcsPath = sqlite3MallocZero( nMax );
  40391. if( !zMbcsPath ){
  40392. sqlite3_free(zBuf);
  40393. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40394. return SQLITE_IOERR_NOMEM_BKPT;
  40395. }
  40396. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  40397. sqlite3_free(zBuf);
  40398. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  40399. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  40400. "winGetTempname3", 0);
  40401. }
  40402. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  40403. if( zUtf8 ){
  40404. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  40405. sqlite3_free(zUtf8);
  40406. }else{
  40407. sqlite3_free(zBuf);
  40408. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  40409. return SQLITE_IOERR_NOMEM_BKPT;
  40410. }
  40411. }
  40412. #endif /* SQLITE_WIN32_HAS_ANSI */
  40413. #endif /* !SQLITE_OS_WINRT */
  40414. /*
  40415. ** Check to make sure the temporary directory ends with an appropriate
  40416. ** separator. If it does not and there is not enough space left to add
  40417. ** one, fail.
  40418. */
  40419. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  40420. sqlite3_free(zBuf);
  40421. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  40422. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  40423. }
  40424. /*
  40425. ** Check that the output buffer is large enough for the temporary file
  40426. ** name in the following format:
  40427. **
  40428. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  40429. **
  40430. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  40431. ** account for the space used by the 15 character random suffix and the
  40432. ** two trailing NUL characters. The final directory separator character
  40433. ** has already added if it was not already present.
  40434. */
  40435. nLen = sqlite3Strlen30(zBuf);
  40436. if( (nLen + nPre + 17) > nBuf ){
  40437. sqlite3_free(zBuf);
  40438. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  40439. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  40440. }
  40441. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  40442. j = sqlite3Strlen30(zBuf);
  40443. sqlite3_randomness(15, &zBuf[j]);
  40444. for(i=0; i<15; i++, j++){
  40445. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  40446. }
  40447. zBuf[j] = 0;
  40448. zBuf[j+1] = 0;
  40449. *pzBuf = zBuf;
  40450. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  40451. return SQLITE_OK;
  40452. }
  40453. /*
  40454. ** Return TRUE if the named file is really a directory. Return false if
  40455. ** it is something other than a directory, or if there is any kind of memory
  40456. ** allocation failure.
  40457. */
  40458. static int winIsDir(const void *zConverted){
  40459. DWORD attr;
  40460. int rc = 0;
  40461. DWORD lastErrno;
  40462. if( osIsNT() ){
  40463. int cnt = 0;
  40464. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40465. memset(&sAttrData, 0, sizeof(sAttrData));
  40466. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  40467. GetFileExInfoStandard,
  40468. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  40469. if( !rc ){
  40470. return 0; /* Invalid name? */
  40471. }
  40472. attr = sAttrData.dwFileAttributes;
  40473. #if SQLITE_OS_WINCE==0
  40474. }else{
  40475. attr = osGetFileAttributesA((char*)zConverted);
  40476. #endif
  40477. }
  40478. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  40479. }
  40480. /* forward reference */
  40481. static int winAccess(
  40482. sqlite3_vfs *pVfs, /* Not used on win32 */
  40483. const char *zFilename, /* Name of file to check */
  40484. int flags, /* Type of test to make on this file */
  40485. int *pResOut /* OUT: Result */
  40486. );
  40487. /*
  40488. ** Open a file.
  40489. */
  40490. static int winOpen(
  40491. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  40492. const char *zName, /* Name of the file (UTF-8) */
  40493. sqlite3_file *id, /* Write the SQLite file handle here */
  40494. int flags, /* Open mode flags */
  40495. int *pOutFlags /* Status return flags */
  40496. ){
  40497. HANDLE h;
  40498. DWORD lastErrno = 0;
  40499. DWORD dwDesiredAccess;
  40500. DWORD dwShareMode;
  40501. DWORD dwCreationDisposition;
  40502. DWORD dwFlagsAndAttributes = 0;
  40503. #if SQLITE_OS_WINCE
  40504. int isTemp = 0;
  40505. #endif
  40506. winVfsAppData *pAppData;
  40507. winFile *pFile = (winFile*)id;
  40508. void *zConverted; /* Filename in OS encoding */
  40509. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  40510. int cnt = 0;
  40511. /* If argument zPath is a NULL pointer, this function is required to open
  40512. ** a temporary file. Use this buffer to store the file name in.
  40513. */
  40514. char *zTmpname = 0; /* For temporary filename, if necessary. */
  40515. int rc = SQLITE_OK; /* Function Return Code */
  40516. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  40517. int eType = flags&0xFFFFFF00; /* Type of file to open */
  40518. #endif
  40519. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  40520. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  40521. int isCreate = (flags & SQLITE_OPEN_CREATE);
  40522. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  40523. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  40524. #ifndef NDEBUG
  40525. int isOpenJournal = (isCreate && (
  40526. eType==SQLITE_OPEN_MASTER_JOURNAL
  40527. || eType==SQLITE_OPEN_MAIN_JOURNAL
  40528. || eType==SQLITE_OPEN_WAL
  40529. ));
  40530. #endif
  40531. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  40532. zUtf8Name, id, flags, pOutFlags));
  40533. /* Check the following statements are true:
  40534. **
  40535. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  40536. ** (b) if CREATE is set, then READWRITE must also be set, and
  40537. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  40538. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  40539. */
  40540. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  40541. assert(isCreate==0 || isReadWrite);
  40542. assert(isExclusive==0 || isCreate);
  40543. assert(isDelete==0 || isCreate);
  40544. /* The main DB, main journal, WAL file and master journal are never
  40545. ** automatically deleted. Nor are they ever temporary files. */
  40546. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  40547. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  40548. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  40549. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  40550. /* Assert that the upper layer has set one of the "file-type" flags. */
  40551. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  40552. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  40553. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  40554. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  40555. );
  40556. assert( pFile!=0 );
  40557. memset(pFile, 0, sizeof(winFile));
  40558. pFile->h = INVALID_HANDLE_VALUE;
  40559. #if SQLITE_OS_WINRT
  40560. if( !zUtf8Name && !sqlite3_temp_directory ){
  40561. sqlite3_log(SQLITE_ERROR,
  40562. "sqlite3_temp_directory variable should be set for WinRT");
  40563. }
  40564. #endif
  40565. /* If the second argument to this function is NULL, generate a
  40566. ** temporary file name to use
  40567. */
  40568. if( !zUtf8Name ){
  40569. assert( isDelete && !isOpenJournal );
  40570. rc = winGetTempname(pVfs, &zTmpname);
  40571. if( rc!=SQLITE_OK ){
  40572. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  40573. return rc;
  40574. }
  40575. zUtf8Name = zTmpname;
  40576. }
  40577. /* Database filenames are double-zero terminated if they are not
  40578. ** URIs with parameters. Hence, they can always be passed into
  40579. ** sqlite3_uri_parameter().
  40580. */
  40581. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  40582. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  40583. /* Convert the filename to the system encoding. */
  40584. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  40585. if( zConverted==0 ){
  40586. sqlite3_free(zTmpname);
  40587. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  40588. return SQLITE_IOERR_NOMEM_BKPT;
  40589. }
  40590. if( winIsDir(zConverted) ){
  40591. sqlite3_free(zConverted);
  40592. sqlite3_free(zTmpname);
  40593. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  40594. return SQLITE_CANTOPEN_ISDIR;
  40595. }
  40596. if( isReadWrite ){
  40597. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  40598. }else{
  40599. dwDesiredAccess = GENERIC_READ;
  40600. }
  40601. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  40602. ** created. SQLite doesn't use it to indicate "exclusive access"
  40603. ** as it is usually understood.
  40604. */
  40605. if( isExclusive ){
  40606. /* Creates a new file, only if it does not already exist. */
  40607. /* If the file exists, it fails. */
  40608. dwCreationDisposition = CREATE_NEW;
  40609. }else if( isCreate ){
  40610. /* Open existing file, or create if it doesn't exist */
  40611. dwCreationDisposition = OPEN_ALWAYS;
  40612. }else{
  40613. /* Opens a file, only if it exists. */
  40614. dwCreationDisposition = OPEN_EXISTING;
  40615. }
  40616. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  40617. if( isDelete ){
  40618. #if SQLITE_OS_WINCE
  40619. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  40620. isTemp = 1;
  40621. #else
  40622. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  40623. | FILE_ATTRIBUTE_HIDDEN
  40624. | FILE_FLAG_DELETE_ON_CLOSE;
  40625. #endif
  40626. }else{
  40627. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  40628. }
  40629. /* Reports from the internet are that performance is always
  40630. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  40631. #if SQLITE_OS_WINCE
  40632. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  40633. #endif
  40634. if( osIsNT() ){
  40635. #if SQLITE_OS_WINRT
  40636. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  40637. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  40638. extendedParameters.dwFileAttributes =
  40639. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  40640. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  40641. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  40642. extendedParameters.lpSecurityAttributes = NULL;
  40643. extendedParameters.hTemplateFile = NULL;
  40644. do{
  40645. h = osCreateFile2((LPCWSTR)zConverted,
  40646. dwDesiredAccess,
  40647. dwShareMode,
  40648. dwCreationDisposition,
  40649. &extendedParameters);
  40650. if( h!=INVALID_HANDLE_VALUE ) break;
  40651. if( isReadWrite ){
  40652. int isRO = 0;
  40653. int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  40654. if( rc2==SQLITE_OK && isRO ) break;
  40655. }
  40656. }while( winRetryIoerr(&cnt, &lastErrno) );
  40657. #else
  40658. do{
  40659. h = osCreateFileW((LPCWSTR)zConverted,
  40660. dwDesiredAccess,
  40661. dwShareMode, NULL,
  40662. dwCreationDisposition,
  40663. dwFlagsAndAttributes,
  40664. NULL);
  40665. if( h!=INVALID_HANDLE_VALUE ) break;
  40666. if( isReadWrite ){
  40667. int isRO = 0;
  40668. int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  40669. if( rc2==SQLITE_OK && isRO ) break;
  40670. }
  40671. }while( winRetryIoerr(&cnt, &lastErrno) );
  40672. #endif
  40673. }
  40674. #ifdef SQLITE_WIN32_HAS_ANSI
  40675. else{
  40676. do{
  40677. h = osCreateFileA((LPCSTR)zConverted,
  40678. dwDesiredAccess,
  40679. dwShareMode, NULL,
  40680. dwCreationDisposition,
  40681. dwFlagsAndAttributes,
  40682. NULL);
  40683. if( h!=INVALID_HANDLE_VALUE ) break;
  40684. if( isReadWrite ){
  40685. int isRO = 0;
  40686. int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  40687. if( rc2==SQLITE_OK && isRO ) break;
  40688. }
  40689. }while( winRetryIoerr(&cnt, &lastErrno) );
  40690. }
  40691. #endif
  40692. winLogIoerr(cnt, __LINE__);
  40693. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  40694. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40695. if( h==INVALID_HANDLE_VALUE ){
  40696. sqlite3_free(zConverted);
  40697. sqlite3_free(zTmpname);
  40698. if( isReadWrite && !isExclusive ){
  40699. return winOpen(pVfs, zName, id,
  40700. ((flags|SQLITE_OPEN_READONLY) &
  40701. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  40702. pOutFlags);
  40703. }else{
  40704. pFile->lastErrno = lastErrno;
  40705. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  40706. return SQLITE_CANTOPEN_BKPT;
  40707. }
  40708. }
  40709. if( pOutFlags ){
  40710. if( isReadWrite ){
  40711. *pOutFlags = SQLITE_OPEN_READWRITE;
  40712. }else{
  40713. *pOutFlags = SQLITE_OPEN_READONLY;
  40714. }
  40715. }
  40716. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  40717. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  40718. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40719. pAppData = (winVfsAppData*)pVfs->pAppData;
  40720. #if SQLITE_OS_WINCE
  40721. {
  40722. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  40723. && ((pAppData==NULL) || !pAppData->bNoLock)
  40724. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  40725. ){
  40726. osCloseHandle(h);
  40727. sqlite3_free(zConverted);
  40728. sqlite3_free(zTmpname);
  40729. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  40730. return rc;
  40731. }
  40732. }
  40733. if( isTemp ){
  40734. pFile->zDeleteOnClose = zConverted;
  40735. }else
  40736. #endif
  40737. {
  40738. sqlite3_free(zConverted);
  40739. }
  40740. sqlite3_free(zTmpname);
  40741. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  40742. pFile->pVfs = pVfs;
  40743. pFile->h = h;
  40744. if( isReadonly ){
  40745. pFile->ctrlFlags |= WINFILE_RDONLY;
  40746. }
  40747. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  40748. pFile->ctrlFlags |= WINFILE_PSOW;
  40749. }
  40750. pFile->lastErrno = NO_ERROR;
  40751. pFile->zPath = zName;
  40752. #if SQLITE_MAX_MMAP_SIZE>0
  40753. pFile->hMap = NULL;
  40754. pFile->pMapRegion = 0;
  40755. pFile->mmapSize = 0;
  40756. pFile->mmapSizeActual = 0;
  40757. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  40758. #endif
  40759. OpenCounter(+1);
  40760. return rc;
  40761. }
  40762. /*
  40763. ** Delete the named file.
  40764. **
  40765. ** Note that Windows does not allow a file to be deleted if some other
  40766. ** process has it open. Sometimes a virus scanner or indexing program
  40767. ** will open a journal file shortly after it is created in order to do
  40768. ** whatever it does. While this other process is holding the
  40769. ** file open, we will be unable to delete it. To work around this
  40770. ** problem, we delay 100 milliseconds and try to delete again. Up
  40771. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  40772. ** up and returning an error.
  40773. */
  40774. static int winDelete(
  40775. sqlite3_vfs *pVfs, /* Not used on win32 */
  40776. const char *zFilename, /* Name of file to delete */
  40777. int syncDir /* Not used on win32 */
  40778. ){
  40779. int cnt = 0;
  40780. int rc;
  40781. DWORD attr;
  40782. DWORD lastErrno = 0;
  40783. void *zConverted;
  40784. UNUSED_PARAMETER(pVfs);
  40785. UNUSED_PARAMETER(syncDir);
  40786. SimulateIOError(return SQLITE_IOERR_DELETE);
  40787. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  40788. zConverted = winConvertFromUtf8Filename(zFilename);
  40789. if( zConverted==0 ){
  40790. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40791. return SQLITE_IOERR_NOMEM_BKPT;
  40792. }
  40793. if( osIsNT() ){
  40794. do {
  40795. #if SQLITE_OS_WINRT
  40796. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40797. memset(&sAttrData, 0, sizeof(sAttrData));
  40798. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  40799. &sAttrData) ){
  40800. attr = sAttrData.dwFileAttributes;
  40801. }else{
  40802. lastErrno = osGetLastError();
  40803. if( lastErrno==ERROR_FILE_NOT_FOUND
  40804. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40805. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40806. }else{
  40807. rc = SQLITE_ERROR;
  40808. }
  40809. break;
  40810. }
  40811. #else
  40812. attr = osGetFileAttributesW(zConverted);
  40813. #endif
  40814. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40815. lastErrno = osGetLastError();
  40816. if( lastErrno==ERROR_FILE_NOT_FOUND
  40817. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40818. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40819. }else{
  40820. rc = SQLITE_ERROR;
  40821. }
  40822. break;
  40823. }
  40824. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40825. rc = SQLITE_ERROR; /* Files only. */
  40826. break;
  40827. }
  40828. if ( osDeleteFileW(zConverted) ){
  40829. rc = SQLITE_OK; /* Deleted OK. */
  40830. break;
  40831. }
  40832. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40833. rc = SQLITE_ERROR; /* No more retries. */
  40834. break;
  40835. }
  40836. } while(1);
  40837. }
  40838. #ifdef SQLITE_WIN32_HAS_ANSI
  40839. else{
  40840. do {
  40841. attr = osGetFileAttributesA(zConverted);
  40842. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40843. lastErrno = osGetLastError();
  40844. if( lastErrno==ERROR_FILE_NOT_FOUND
  40845. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40846. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40847. }else{
  40848. rc = SQLITE_ERROR;
  40849. }
  40850. break;
  40851. }
  40852. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40853. rc = SQLITE_ERROR; /* Files only. */
  40854. break;
  40855. }
  40856. if ( osDeleteFileA(zConverted) ){
  40857. rc = SQLITE_OK; /* Deleted OK. */
  40858. break;
  40859. }
  40860. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40861. rc = SQLITE_ERROR; /* No more retries. */
  40862. break;
  40863. }
  40864. } while(1);
  40865. }
  40866. #endif
  40867. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  40868. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  40869. }else{
  40870. winLogIoerr(cnt, __LINE__);
  40871. }
  40872. sqlite3_free(zConverted);
  40873. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  40874. return rc;
  40875. }
  40876. /*
  40877. ** Check the existence and status of a file.
  40878. */
  40879. static int winAccess(
  40880. sqlite3_vfs *pVfs, /* Not used on win32 */
  40881. const char *zFilename, /* Name of file to check */
  40882. int flags, /* Type of test to make on this file */
  40883. int *pResOut /* OUT: Result */
  40884. ){
  40885. DWORD attr;
  40886. int rc = 0;
  40887. DWORD lastErrno = 0;
  40888. void *zConverted;
  40889. UNUSED_PARAMETER(pVfs);
  40890. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  40891. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  40892. zFilename, flags, pResOut));
  40893. zConverted = winConvertFromUtf8Filename(zFilename);
  40894. if( zConverted==0 ){
  40895. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40896. return SQLITE_IOERR_NOMEM_BKPT;
  40897. }
  40898. if( osIsNT() ){
  40899. int cnt = 0;
  40900. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40901. memset(&sAttrData, 0, sizeof(sAttrData));
  40902. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  40903. GetFileExInfoStandard,
  40904. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  40905. if( rc ){
  40906. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  40907. ** as if it does not exist.
  40908. */
  40909. if( flags==SQLITE_ACCESS_EXISTS
  40910. && sAttrData.nFileSizeHigh==0
  40911. && sAttrData.nFileSizeLow==0 ){
  40912. attr = INVALID_FILE_ATTRIBUTES;
  40913. }else{
  40914. attr = sAttrData.dwFileAttributes;
  40915. }
  40916. }else{
  40917. winLogIoerr(cnt, __LINE__);
  40918. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  40919. sqlite3_free(zConverted);
  40920. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  40921. zFilename);
  40922. }else{
  40923. attr = INVALID_FILE_ATTRIBUTES;
  40924. }
  40925. }
  40926. }
  40927. #ifdef SQLITE_WIN32_HAS_ANSI
  40928. else{
  40929. attr = osGetFileAttributesA((char*)zConverted);
  40930. }
  40931. #endif
  40932. sqlite3_free(zConverted);
  40933. switch( flags ){
  40934. case SQLITE_ACCESS_READ:
  40935. case SQLITE_ACCESS_EXISTS:
  40936. rc = attr!=INVALID_FILE_ATTRIBUTES;
  40937. break;
  40938. case SQLITE_ACCESS_READWRITE:
  40939. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  40940. (attr & FILE_ATTRIBUTE_READONLY)==0;
  40941. break;
  40942. default:
  40943. assert(!"Invalid flags argument");
  40944. }
  40945. *pResOut = rc;
  40946. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  40947. zFilename, pResOut, *pResOut));
  40948. return SQLITE_OK;
  40949. }
  40950. /*
  40951. ** Returns non-zero if the specified path name starts with a drive letter
  40952. ** followed by a colon character.
  40953. */
  40954. static BOOL winIsDriveLetterAndColon(
  40955. const char *zPathname
  40956. ){
  40957. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  40958. }
  40959. /*
  40960. ** Returns non-zero if the specified path name should be used verbatim. If
  40961. ** non-zero is returned from this function, the calling function must simply
  40962. ** use the provided path name verbatim -OR- resolve it into a full path name
  40963. ** using the GetFullPathName Win32 API function (if available).
  40964. */
  40965. static BOOL winIsVerbatimPathname(
  40966. const char *zPathname
  40967. ){
  40968. /*
  40969. ** If the path name starts with a forward slash or a backslash, it is either
  40970. ** a legal UNC name, a volume relative path, or an absolute path name in the
  40971. ** "Unix" format on Windows. There is no easy way to differentiate between
  40972. ** the final two cases; therefore, we return the safer return value of TRUE
  40973. ** so that callers of this function will simply use it verbatim.
  40974. */
  40975. if ( winIsDirSep(zPathname[0]) ){
  40976. return TRUE;
  40977. }
  40978. /*
  40979. ** If the path name starts with a letter and a colon it is either a volume
  40980. ** relative path or an absolute path. Callers of this function must not
  40981. ** attempt to treat it as a relative path name (i.e. they should simply use
  40982. ** it verbatim).
  40983. */
  40984. if ( winIsDriveLetterAndColon(zPathname) ){
  40985. return TRUE;
  40986. }
  40987. /*
  40988. ** If we get to this point, the path name should almost certainly be a purely
  40989. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  40990. */
  40991. return FALSE;
  40992. }
  40993. /*
  40994. ** Turn a relative pathname into a full pathname. Write the full
  40995. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  40996. ** bytes in size.
  40997. */
  40998. static int winFullPathname(
  40999. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  41000. const char *zRelative, /* Possibly relative input path */
  41001. int nFull, /* Size of output buffer in bytes */
  41002. char *zFull /* Output buffer */
  41003. ){
  41004. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  41005. DWORD nByte;
  41006. void *zConverted;
  41007. char *zOut;
  41008. #endif
  41009. /* If this path name begins with "/X:", where "X" is any alphabetic
  41010. ** character, discard the initial "/" from the pathname.
  41011. */
  41012. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  41013. zRelative++;
  41014. }
  41015. #if defined(__CYGWIN__)
  41016. SimulateIOError( return SQLITE_ERROR );
  41017. UNUSED_PARAMETER(nFull);
  41018. assert( nFull>=pVfs->mxPathname );
  41019. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  41020. /*
  41021. ** NOTE: We are dealing with a relative path name and the data
  41022. ** directory has been set. Therefore, use it as the basis
  41023. ** for converting the relative path name to an absolute
  41024. ** one by prepending the data directory and a slash.
  41025. */
  41026. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  41027. if( !zOut ){
  41028. return SQLITE_IOERR_NOMEM_BKPT;
  41029. }
  41030. if( cygwin_conv_path(
  41031. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  41032. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  41033. sqlite3_free(zOut);
  41034. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  41035. "winFullPathname1", zRelative);
  41036. }else{
  41037. char *zUtf8 = winConvertToUtf8Filename(zOut);
  41038. if( !zUtf8 ){
  41039. sqlite3_free(zOut);
  41040. return SQLITE_IOERR_NOMEM_BKPT;
  41041. }
  41042. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  41043. sqlite3_data_directory, winGetDirSep(), zUtf8);
  41044. sqlite3_free(zUtf8);
  41045. sqlite3_free(zOut);
  41046. }
  41047. }else{
  41048. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  41049. if( !zOut ){
  41050. return SQLITE_IOERR_NOMEM_BKPT;
  41051. }
  41052. if( cygwin_conv_path(
  41053. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  41054. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  41055. sqlite3_free(zOut);
  41056. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  41057. "winFullPathname2", zRelative);
  41058. }else{
  41059. char *zUtf8 = winConvertToUtf8Filename(zOut);
  41060. if( !zUtf8 ){
  41061. sqlite3_free(zOut);
  41062. return SQLITE_IOERR_NOMEM_BKPT;
  41063. }
  41064. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  41065. sqlite3_free(zUtf8);
  41066. sqlite3_free(zOut);
  41067. }
  41068. }
  41069. return SQLITE_OK;
  41070. #endif
  41071. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  41072. SimulateIOError( return SQLITE_ERROR );
  41073. /* WinCE has no concept of a relative pathname, or so I am told. */
  41074. /* WinRT has no way to convert a relative path to an absolute one. */
  41075. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  41076. /*
  41077. ** NOTE: We are dealing with a relative path name and the data
  41078. ** directory has been set. Therefore, use it as the basis
  41079. ** for converting the relative path name to an absolute
  41080. ** one by prepending the data directory and a backslash.
  41081. */
  41082. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  41083. sqlite3_data_directory, winGetDirSep(), zRelative);
  41084. }else{
  41085. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  41086. }
  41087. return SQLITE_OK;
  41088. #endif
  41089. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  41090. /* It's odd to simulate an io-error here, but really this is just
  41091. ** using the io-error infrastructure to test that SQLite handles this
  41092. ** function failing. This function could fail if, for example, the
  41093. ** current working directory has been unlinked.
  41094. */
  41095. SimulateIOError( return SQLITE_ERROR );
  41096. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  41097. /*
  41098. ** NOTE: We are dealing with a relative path name and the data
  41099. ** directory has been set. Therefore, use it as the basis
  41100. ** for converting the relative path name to an absolute
  41101. ** one by prepending the data directory and a backslash.
  41102. */
  41103. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  41104. sqlite3_data_directory, winGetDirSep(), zRelative);
  41105. return SQLITE_OK;
  41106. }
  41107. zConverted = winConvertFromUtf8Filename(zRelative);
  41108. if( zConverted==0 ){
  41109. return SQLITE_IOERR_NOMEM_BKPT;
  41110. }
  41111. if( osIsNT() ){
  41112. LPWSTR zTemp;
  41113. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  41114. if( nByte==0 ){
  41115. sqlite3_free(zConverted);
  41116. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  41117. "winFullPathname1", zRelative);
  41118. }
  41119. nByte += 3;
  41120. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  41121. if( zTemp==0 ){
  41122. sqlite3_free(zConverted);
  41123. return SQLITE_IOERR_NOMEM_BKPT;
  41124. }
  41125. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  41126. if( nByte==0 ){
  41127. sqlite3_free(zConverted);
  41128. sqlite3_free(zTemp);
  41129. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  41130. "winFullPathname2", zRelative);
  41131. }
  41132. sqlite3_free(zConverted);
  41133. zOut = winUnicodeToUtf8(zTemp);
  41134. sqlite3_free(zTemp);
  41135. }
  41136. #ifdef SQLITE_WIN32_HAS_ANSI
  41137. else{
  41138. char *zTemp;
  41139. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  41140. if( nByte==0 ){
  41141. sqlite3_free(zConverted);
  41142. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  41143. "winFullPathname3", zRelative);
  41144. }
  41145. nByte += 3;
  41146. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  41147. if( zTemp==0 ){
  41148. sqlite3_free(zConverted);
  41149. return SQLITE_IOERR_NOMEM_BKPT;
  41150. }
  41151. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  41152. if( nByte==0 ){
  41153. sqlite3_free(zConverted);
  41154. sqlite3_free(zTemp);
  41155. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  41156. "winFullPathname4", zRelative);
  41157. }
  41158. sqlite3_free(zConverted);
  41159. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  41160. sqlite3_free(zTemp);
  41161. }
  41162. #endif
  41163. if( zOut ){
  41164. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  41165. sqlite3_free(zOut);
  41166. return SQLITE_OK;
  41167. }else{
  41168. return SQLITE_IOERR_NOMEM_BKPT;
  41169. }
  41170. #endif
  41171. }
  41172. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  41173. /*
  41174. ** Interfaces for opening a shared library, finding entry points
  41175. ** within the shared library, and closing the shared library.
  41176. */
  41177. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  41178. HANDLE h;
  41179. #if defined(__CYGWIN__)
  41180. int nFull = pVfs->mxPathname+1;
  41181. char *zFull = sqlite3MallocZero( nFull );
  41182. void *zConverted = 0;
  41183. if( zFull==0 ){
  41184. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  41185. return 0;
  41186. }
  41187. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  41188. sqlite3_free(zFull);
  41189. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  41190. return 0;
  41191. }
  41192. zConverted = winConvertFromUtf8Filename(zFull);
  41193. sqlite3_free(zFull);
  41194. #else
  41195. void *zConverted = winConvertFromUtf8Filename(zFilename);
  41196. UNUSED_PARAMETER(pVfs);
  41197. #endif
  41198. if( zConverted==0 ){
  41199. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  41200. return 0;
  41201. }
  41202. if( osIsNT() ){
  41203. #if SQLITE_OS_WINRT
  41204. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  41205. #else
  41206. h = osLoadLibraryW((LPCWSTR)zConverted);
  41207. #endif
  41208. }
  41209. #ifdef SQLITE_WIN32_HAS_ANSI
  41210. else{
  41211. h = osLoadLibraryA((char*)zConverted);
  41212. }
  41213. #endif
  41214. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  41215. sqlite3_free(zConverted);
  41216. return (void*)h;
  41217. }
  41218. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  41219. UNUSED_PARAMETER(pVfs);
  41220. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  41221. }
  41222. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  41223. FARPROC proc;
  41224. UNUSED_PARAMETER(pVfs);
  41225. proc = osGetProcAddressA((HANDLE)pH, zSym);
  41226. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  41227. (void*)pH, zSym, (void*)proc));
  41228. return (void(*)(void))proc;
  41229. }
  41230. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  41231. UNUSED_PARAMETER(pVfs);
  41232. osFreeLibrary((HANDLE)pHandle);
  41233. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  41234. }
  41235. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  41236. #define winDlOpen 0
  41237. #define winDlError 0
  41238. #define winDlSym 0
  41239. #define winDlClose 0
  41240. #endif
  41241. /* State information for the randomness gatherer. */
  41242. typedef struct EntropyGatherer EntropyGatherer;
  41243. struct EntropyGatherer {
  41244. unsigned char *a; /* Gather entropy into this buffer */
  41245. int na; /* Size of a[] in bytes */
  41246. int i; /* XOR next input into a[i] */
  41247. int nXor; /* Number of XOR operations done */
  41248. };
  41249. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  41250. /* Mix sz bytes of entropy into p. */
  41251. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  41252. int j, k;
  41253. for(j=0, k=p->i; j<sz; j++){
  41254. p->a[k++] ^= x[j];
  41255. if( k>=p->na ) k = 0;
  41256. }
  41257. p->i = k;
  41258. p->nXor += sz;
  41259. }
  41260. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  41261. /*
  41262. ** Write up to nBuf bytes of randomness into zBuf.
  41263. */
  41264. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  41265. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  41266. UNUSED_PARAMETER(pVfs);
  41267. memset(zBuf, 0, nBuf);
  41268. return nBuf;
  41269. #else
  41270. EntropyGatherer e;
  41271. UNUSED_PARAMETER(pVfs);
  41272. memset(zBuf, 0, nBuf);
  41273. e.a = (unsigned char*)zBuf;
  41274. e.na = nBuf;
  41275. e.nXor = 0;
  41276. e.i = 0;
  41277. {
  41278. SYSTEMTIME x;
  41279. osGetSystemTime(&x);
  41280. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  41281. }
  41282. {
  41283. DWORD pid = osGetCurrentProcessId();
  41284. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  41285. }
  41286. #if SQLITE_OS_WINRT
  41287. {
  41288. ULONGLONG cnt = osGetTickCount64();
  41289. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  41290. }
  41291. #else
  41292. {
  41293. DWORD cnt = osGetTickCount();
  41294. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  41295. }
  41296. #endif /* SQLITE_OS_WINRT */
  41297. {
  41298. LARGE_INTEGER i;
  41299. osQueryPerformanceCounter(&i);
  41300. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  41301. }
  41302. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  41303. {
  41304. UUID id;
  41305. memset(&id, 0, sizeof(UUID));
  41306. osUuidCreate(&id);
  41307. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  41308. memset(&id, 0, sizeof(UUID));
  41309. osUuidCreateSequential(&id);
  41310. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  41311. }
  41312. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  41313. return e.nXor>nBuf ? nBuf : e.nXor;
  41314. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  41315. }
  41316. /*
  41317. ** Sleep for a little while. Return the amount of time slept.
  41318. */
  41319. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  41320. sqlite3_win32_sleep((microsec+999)/1000);
  41321. UNUSED_PARAMETER(pVfs);
  41322. return ((microsec+999)/1000)*1000;
  41323. }
  41324. /*
  41325. ** The following variable, if set to a non-zero value, is interpreted as
  41326. ** the number of seconds since 1970 and is used to set the result of
  41327. ** sqlite3OsCurrentTime() during testing.
  41328. */
  41329. #ifdef SQLITE_TEST
  41330. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  41331. #endif
  41332. /*
  41333. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  41334. ** the current time and date as a Julian Day number times 86_400_000. In
  41335. ** other words, write into *piNow the number of milliseconds since the Julian
  41336. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  41337. ** proleptic Gregorian calendar.
  41338. **
  41339. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  41340. ** cannot be found.
  41341. */
  41342. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  41343. /* FILETIME structure is a 64-bit value representing the number of
  41344. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  41345. */
  41346. FILETIME ft;
  41347. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  41348. #ifdef SQLITE_TEST
  41349. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  41350. #endif
  41351. /* 2^32 - to avoid use of LL and warnings in gcc */
  41352. static const sqlite3_int64 max32BitValue =
  41353. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  41354. (sqlite3_int64)294967296;
  41355. #if SQLITE_OS_WINCE
  41356. SYSTEMTIME time;
  41357. osGetSystemTime(&time);
  41358. /* if SystemTimeToFileTime() fails, it returns zero. */
  41359. if (!osSystemTimeToFileTime(&time,&ft)){
  41360. return SQLITE_ERROR;
  41361. }
  41362. #else
  41363. osGetSystemTimeAsFileTime( &ft );
  41364. #endif
  41365. *piNow = winFiletimeEpoch +
  41366. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  41367. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  41368. #ifdef SQLITE_TEST
  41369. if( sqlite3_current_time ){
  41370. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  41371. }
  41372. #endif
  41373. UNUSED_PARAMETER(pVfs);
  41374. return SQLITE_OK;
  41375. }
  41376. /*
  41377. ** Find the current time (in Universal Coordinated Time). Write the
  41378. ** current time and date as a Julian Day number into *prNow and
  41379. ** return 0. Return 1 if the time and date cannot be found.
  41380. */
  41381. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  41382. int rc;
  41383. sqlite3_int64 i;
  41384. rc = winCurrentTimeInt64(pVfs, &i);
  41385. if( !rc ){
  41386. *prNow = i/86400000.0;
  41387. }
  41388. return rc;
  41389. }
  41390. /*
  41391. ** The idea is that this function works like a combination of
  41392. ** GetLastError() and FormatMessage() on Windows (or errno and
  41393. ** strerror_r() on Unix). After an error is returned by an OS
  41394. ** function, SQLite calls this function with zBuf pointing to
  41395. ** a buffer of nBuf bytes. The OS layer should populate the
  41396. ** buffer with a nul-terminated UTF-8 encoded error message
  41397. ** describing the last IO error to have occurred within the calling
  41398. ** thread.
  41399. **
  41400. ** If the error message is too large for the supplied buffer,
  41401. ** it should be truncated. The return value of xGetLastError
  41402. ** is zero if the error message fits in the buffer, or non-zero
  41403. ** otherwise (if the message was truncated). If non-zero is returned,
  41404. ** then it is not necessary to include the nul-terminator character
  41405. ** in the output buffer.
  41406. **
  41407. ** Not supplying an error message will have no adverse effect
  41408. ** on SQLite. It is fine to have an implementation that never
  41409. ** returns an error message:
  41410. **
  41411. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  41412. ** assert(zBuf[0]=='\0');
  41413. ** return 0;
  41414. ** }
  41415. **
  41416. ** However if an error message is supplied, it will be incorporated
  41417. ** by sqlite into the error message available to the user using
  41418. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  41419. */
  41420. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  41421. DWORD e = osGetLastError();
  41422. UNUSED_PARAMETER(pVfs);
  41423. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  41424. return e;
  41425. }
  41426. /*
  41427. ** Initialize and deinitialize the operating system interface.
  41428. */
  41429. SQLITE_API int sqlite3_os_init(void){
  41430. static sqlite3_vfs winVfs = {
  41431. 3, /* iVersion */
  41432. sizeof(winFile), /* szOsFile */
  41433. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  41434. 0, /* pNext */
  41435. "win32", /* zName */
  41436. &winAppData, /* pAppData */
  41437. winOpen, /* xOpen */
  41438. winDelete, /* xDelete */
  41439. winAccess, /* xAccess */
  41440. winFullPathname, /* xFullPathname */
  41441. winDlOpen, /* xDlOpen */
  41442. winDlError, /* xDlError */
  41443. winDlSym, /* xDlSym */
  41444. winDlClose, /* xDlClose */
  41445. winRandomness, /* xRandomness */
  41446. winSleep, /* xSleep */
  41447. winCurrentTime, /* xCurrentTime */
  41448. winGetLastError, /* xGetLastError */
  41449. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  41450. winSetSystemCall, /* xSetSystemCall */
  41451. winGetSystemCall, /* xGetSystemCall */
  41452. winNextSystemCall, /* xNextSystemCall */
  41453. };
  41454. #if defined(SQLITE_WIN32_HAS_WIDE)
  41455. static sqlite3_vfs winLongPathVfs = {
  41456. 3, /* iVersion */
  41457. sizeof(winFile), /* szOsFile */
  41458. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  41459. 0, /* pNext */
  41460. "win32-longpath", /* zName */
  41461. &winAppData, /* pAppData */
  41462. winOpen, /* xOpen */
  41463. winDelete, /* xDelete */
  41464. winAccess, /* xAccess */
  41465. winFullPathname, /* xFullPathname */
  41466. winDlOpen, /* xDlOpen */
  41467. winDlError, /* xDlError */
  41468. winDlSym, /* xDlSym */
  41469. winDlClose, /* xDlClose */
  41470. winRandomness, /* xRandomness */
  41471. winSleep, /* xSleep */
  41472. winCurrentTime, /* xCurrentTime */
  41473. winGetLastError, /* xGetLastError */
  41474. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  41475. winSetSystemCall, /* xSetSystemCall */
  41476. winGetSystemCall, /* xGetSystemCall */
  41477. winNextSystemCall, /* xNextSystemCall */
  41478. };
  41479. #endif
  41480. static sqlite3_vfs winNolockVfs = {
  41481. 3, /* iVersion */
  41482. sizeof(winFile), /* szOsFile */
  41483. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  41484. 0, /* pNext */
  41485. "win32-none", /* zName */
  41486. &winNolockAppData, /* pAppData */
  41487. winOpen, /* xOpen */
  41488. winDelete, /* xDelete */
  41489. winAccess, /* xAccess */
  41490. winFullPathname, /* xFullPathname */
  41491. winDlOpen, /* xDlOpen */
  41492. winDlError, /* xDlError */
  41493. winDlSym, /* xDlSym */
  41494. winDlClose, /* xDlClose */
  41495. winRandomness, /* xRandomness */
  41496. winSleep, /* xSleep */
  41497. winCurrentTime, /* xCurrentTime */
  41498. winGetLastError, /* xGetLastError */
  41499. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  41500. winSetSystemCall, /* xSetSystemCall */
  41501. winGetSystemCall, /* xGetSystemCall */
  41502. winNextSystemCall, /* xNextSystemCall */
  41503. };
  41504. #if defined(SQLITE_WIN32_HAS_WIDE)
  41505. static sqlite3_vfs winLongPathNolockVfs = {
  41506. 3, /* iVersion */
  41507. sizeof(winFile), /* szOsFile */
  41508. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  41509. 0, /* pNext */
  41510. "win32-longpath-none", /* zName */
  41511. &winNolockAppData, /* pAppData */
  41512. winOpen, /* xOpen */
  41513. winDelete, /* xDelete */
  41514. winAccess, /* xAccess */
  41515. winFullPathname, /* xFullPathname */
  41516. winDlOpen, /* xDlOpen */
  41517. winDlError, /* xDlError */
  41518. winDlSym, /* xDlSym */
  41519. winDlClose, /* xDlClose */
  41520. winRandomness, /* xRandomness */
  41521. winSleep, /* xSleep */
  41522. winCurrentTime, /* xCurrentTime */
  41523. winGetLastError, /* xGetLastError */
  41524. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  41525. winSetSystemCall, /* xSetSystemCall */
  41526. winGetSystemCall, /* xGetSystemCall */
  41527. winNextSystemCall, /* xNextSystemCall */
  41528. };
  41529. #endif
  41530. /* Double-check that the aSyscall[] array has been constructed
  41531. ** correctly. See ticket [bb3a86e890c8e96ab] */
  41532. assert( ArraySize(aSyscall)==80 );
  41533. /* get memory map allocation granularity */
  41534. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  41535. #if SQLITE_OS_WINRT
  41536. osGetNativeSystemInfo(&winSysInfo);
  41537. #else
  41538. osGetSystemInfo(&winSysInfo);
  41539. #endif
  41540. assert( winSysInfo.dwAllocationGranularity>0 );
  41541. assert( winSysInfo.dwPageSize>0 );
  41542. sqlite3_vfs_register(&winVfs, 1);
  41543. #if defined(SQLITE_WIN32_HAS_WIDE)
  41544. sqlite3_vfs_register(&winLongPathVfs, 0);
  41545. #endif
  41546. sqlite3_vfs_register(&winNolockVfs, 0);
  41547. #if defined(SQLITE_WIN32_HAS_WIDE)
  41548. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  41549. #endif
  41550. return SQLITE_OK;
  41551. }
  41552. SQLITE_API int sqlite3_os_end(void){
  41553. #if SQLITE_OS_WINRT
  41554. if( sleepObj!=NULL ){
  41555. osCloseHandle(sleepObj);
  41556. sleepObj = NULL;
  41557. }
  41558. #endif
  41559. return SQLITE_OK;
  41560. }
  41561. #endif /* SQLITE_OS_WIN */
  41562. /************** End of os_win.c **********************************************/
  41563. /************** Begin file bitvec.c ******************************************/
  41564. /*
  41565. ** 2008 February 16
  41566. **
  41567. ** The author disclaims copyright to this source code. In place of
  41568. ** a legal notice, here is a blessing:
  41569. **
  41570. ** May you do good and not evil.
  41571. ** May you find forgiveness for yourself and forgive others.
  41572. ** May you share freely, never taking more than you give.
  41573. **
  41574. *************************************************************************
  41575. ** This file implements an object that represents a fixed-length
  41576. ** bitmap. Bits are numbered starting with 1.
  41577. **
  41578. ** A bitmap is used to record which pages of a database file have been
  41579. ** journalled during a transaction, or which pages have the "dont-write"
  41580. ** property. Usually only a few pages are meet either condition.
  41581. ** So the bitmap is usually sparse and has low cardinality.
  41582. ** But sometimes (for example when during a DROP of a large table) most
  41583. ** or all of the pages in a database can get journalled. In those cases,
  41584. ** the bitmap becomes dense with high cardinality. The algorithm needs
  41585. ** to handle both cases well.
  41586. **
  41587. ** The size of the bitmap is fixed when the object is created.
  41588. **
  41589. ** All bits are clear when the bitmap is created. Individual bits
  41590. ** may be set or cleared one at a time.
  41591. **
  41592. ** Test operations are about 100 times more common that set operations.
  41593. ** Clear operations are exceedingly rare. There are usually between
  41594. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  41595. ** sometimes grow into tens of thousands or larger. The size of the
  41596. ** Bitvec object is the number of pages in the database file at the
  41597. ** start of a transaction, and is thus usually less than a few thousand,
  41598. ** but can be as large as 2 billion for a really big database.
  41599. */
  41600. /* #include "sqliteInt.h" */
  41601. /* Size of the Bitvec structure in bytes. */
  41602. #define BITVEC_SZ 512
  41603. /* Round the union size down to the nearest pointer boundary, since that's how
  41604. ** it will be aligned within the Bitvec struct. */
  41605. #define BITVEC_USIZE \
  41606. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  41607. /* Type of the array "element" for the bitmap representation.
  41608. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  41609. ** Setting this to the "natural word" size of your CPU may improve
  41610. ** performance. */
  41611. #define BITVEC_TELEM u8
  41612. /* Size, in bits, of the bitmap element. */
  41613. #define BITVEC_SZELEM 8
  41614. /* Number of elements in a bitmap array. */
  41615. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  41616. /* Number of bits in the bitmap array. */
  41617. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  41618. /* Number of u32 values in hash table. */
  41619. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  41620. /* Maximum number of entries in hash table before
  41621. ** sub-dividing and re-hashing. */
  41622. #define BITVEC_MXHASH (BITVEC_NINT/2)
  41623. /* Hashing function for the aHash representation.
  41624. ** Empirical testing showed that the *37 multiplier
  41625. ** (an arbitrary prime)in the hash function provided
  41626. ** no fewer collisions than the no-op *1. */
  41627. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  41628. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  41629. /*
  41630. ** A bitmap is an instance of the following structure.
  41631. **
  41632. ** This bitmap records the existence of zero or more bits
  41633. ** with values between 1 and iSize, inclusive.
  41634. **
  41635. ** There are three possible representations of the bitmap.
  41636. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  41637. ** bitmap. The least significant bit is bit 1.
  41638. **
  41639. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  41640. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  41641. **
  41642. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  41643. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  41644. ** handles up to iDivisor separate values of i. apSub[0] holds
  41645. ** values between 1 and iDivisor. apSub[1] holds values between
  41646. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  41647. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  41648. ** to hold deal with values between 1 and iDivisor.
  41649. */
  41650. struct Bitvec {
  41651. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  41652. u32 nSet; /* Number of bits that are set - only valid for aHash
  41653. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  41654. ** this would be 125. */
  41655. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  41656. /* Should >=0 for apSub element. */
  41657. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  41658. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  41659. union {
  41660. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  41661. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  41662. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  41663. } u;
  41664. };
  41665. /*
  41666. ** Create a new bitmap object able to handle bits between 0 and iSize,
  41667. ** inclusive. Return a pointer to the new object. Return NULL if
  41668. ** malloc fails.
  41669. */
  41670. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  41671. Bitvec *p;
  41672. assert( sizeof(*p)==BITVEC_SZ );
  41673. p = sqlite3MallocZero( sizeof(*p) );
  41674. if( p ){
  41675. p->iSize = iSize;
  41676. }
  41677. return p;
  41678. }
  41679. /*
  41680. ** Check to see if the i-th bit is set. Return true or false.
  41681. ** If p is NULL (if the bitmap has not been created) or if
  41682. ** i is out of range, then return false.
  41683. */
  41684. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  41685. assert( p!=0 );
  41686. i--;
  41687. if( i>=p->iSize ) return 0;
  41688. while( p->iDivisor ){
  41689. u32 bin = i/p->iDivisor;
  41690. i = i%p->iDivisor;
  41691. p = p->u.apSub[bin];
  41692. if (!p) {
  41693. return 0;
  41694. }
  41695. }
  41696. if( p->iSize<=BITVEC_NBIT ){
  41697. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  41698. } else{
  41699. u32 h = BITVEC_HASH(i++);
  41700. while( p->u.aHash[h] ){
  41701. if( p->u.aHash[h]==i ) return 1;
  41702. h = (h+1) % BITVEC_NINT;
  41703. }
  41704. return 0;
  41705. }
  41706. }
  41707. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  41708. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  41709. }
  41710. /*
  41711. ** Set the i-th bit. Return 0 on success and an error code if
  41712. ** anything goes wrong.
  41713. **
  41714. ** This routine might cause sub-bitmaps to be allocated. Failing
  41715. ** to get the memory needed to hold the sub-bitmap is the only
  41716. ** that can go wrong with an insert, assuming p and i are valid.
  41717. **
  41718. ** The calling function must ensure that p is a valid Bitvec object
  41719. ** and that the value for "i" is within range of the Bitvec object.
  41720. ** Otherwise the behavior is undefined.
  41721. */
  41722. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  41723. u32 h;
  41724. if( p==0 ) return SQLITE_OK;
  41725. assert( i>0 );
  41726. assert( i<=p->iSize );
  41727. i--;
  41728. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  41729. u32 bin = i/p->iDivisor;
  41730. i = i%p->iDivisor;
  41731. if( p->u.apSub[bin]==0 ){
  41732. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  41733. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  41734. }
  41735. p = p->u.apSub[bin];
  41736. }
  41737. if( p->iSize<=BITVEC_NBIT ){
  41738. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  41739. return SQLITE_OK;
  41740. }
  41741. h = BITVEC_HASH(i++);
  41742. /* if there wasn't a hash collision, and this doesn't */
  41743. /* completely fill the hash, then just add it without */
  41744. /* worring about sub-dividing and re-hashing. */
  41745. if( !p->u.aHash[h] ){
  41746. if (p->nSet<(BITVEC_NINT-1)) {
  41747. goto bitvec_set_end;
  41748. } else {
  41749. goto bitvec_set_rehash;
  41750. }
  41751. }
  41752. /* there was a collision, check to see if it's already */
  41753. /* in hash, if not, try to find a spot for it */
  41754. do {
  41755. if( p->u.aHash[h]==i ) return SQLITE_OK;
  41756. h++;
  41757. if( h>=BITVEC_NINT ) h = 0;
  41758. } while( p->u.aHash[h] );
  41759. /* we didn't find it in the hash. h points to the first */
  41760. /* available free spot. check to see if this is going to */
  41761. /* make our hash too "full". */
  41762. bitvec_set_rehash:
  41763. if( p->nSet>=BITVEC_MXHASH ){
  41764. unsigned int j;
  41765. int rc;
  41766. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  41767. if( aiValues==0 ){
  41768. return SQLITE_NOMEM_BKPT;
  41769. }else{
  41770. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41771. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  41772. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  41773. rc = sqlite3BitvecSet(p, i);
  41774. for(j=0; j<BITVEC_NINT; j++){
  41775. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  41776. }
  41777. sqlite3StackFree(0, aiValues);
  41778. return rc;
  41779. }
  41780. }
  41781. bitvec_set_end:
  41782. p->nSet++;
  41783. p->u.aHash[h] = i;
  41784. return SQLITE_OK;
  41785. }
  41786. /*
  41787. ** Clear the i-th bit.
  41788. **
  41789. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  41790. ** that BitvecClear can use to rebuilt its hash table.
  41791. */
  41792. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  41793. if( p==0 ) return;
  41794. assert( i>0 );
  41795. i--;
  41796. while( p->iDivisor ){
  41797. u32 bin = i/p->iDivisor;
  41798. i = i%p->iDivisor;
  41799. p = p->u.apSub[bin];
  41800. if (!p) {
  41801. return;
  41802. }
  41803. }
  41804. if( p->iSize<=BITVEC_NBIT ){
  41805. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  41806. }else{
  41807. unsigned int j;
  41808. u32 *aiValues = pBuf;
  41809. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41810. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  41811. p->nSet = 0;
  41812. for(j=0; j<BITVEC_NINT; j++){
  41813. if( aiValues[j] && aiValues[j]!=(i+1) ){
  41814. u32 h = BITVEC_HASH(aiValues[j]-1);
  41815. p->nSet++;
  41816. while( p->u.aHash[h] ){
  41817. h++;
  41818. if( h>=BITVEC_NINT ) h = 0;
  41819. }
  41820. p->u.aHash[h] = aiValues[j];
  41821. }
  41822. }
  41823. }
  41824. }
  41825. /*
  41826. ** Destroy a bitmap object. Reclaim all memory used.
  41827. */
  41828. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  41829. if( p==0 ) return;
  41830. if( p->iDivisor ){
  41831. unsigned int i;
  41832. for(i=0; i<BITVEC_NPTR; i++){
  41833. sqlite3BitvecDestroy(p->u.apSub[i]);
  41834. }
  41835. }
  41836. sqlite3_free(p);
  41837. }
  41838. /*
  41839. ** Return the value of the iSize parameter specified when Bitvec *p
  41840. ** was created.
  41841. */
  41842. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  41843. return p->iSize;
  41844. }
  41845. #ifndef SQLITE_UNTESTABLE
  41846. /*
  41847. ** Let V[] be an array of unsigned characters sufficient to hold
  41848. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  41849. ** Then the following macros can be used to set, clear, or test
  41850. ** individual bits within V.
  41851. */
  41852. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  41853. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  41854. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  41855. /*
  41856. ** This routine runs an extensive test of the Bitvec code.
  41857. **
  41858. ** The input is an array of integers that acts as a program
  41859. ** to test the Bitvec. The integers are opcodes followed
  41860. ** by 0, 1, or 3 operands, depending on the opcode. Another
  41861. ** opcode follows immediately after the last operand.
  41862. **
  41863. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  41864. ** "halt" opcode and causes the test to end.
  41865. **
  41866. ** 0 Halt and return the number of errors
  41867. ** 1 N S X Set N bits beginning with S and incrementing by X
  41868. ** 2 N S X Clear N bits beginning with S and incrementing by X
  41869. ** 3 N Set N randomly chosen bits
  41870. ** 4 N Clear N randomly chosen bits
  41871. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  41872. **
  41873. ** The opcodes 1 through 4 perform set and clear operations are performed
  41874. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  41875. ** Opcode 5 works on the linear array only, not on the Bitvec.
  41876. ** Opcode 5 is used to deliberately induce a fault in order to
  41877. ** confirm that error detection works.
  41878. **
  41879. ** At the conclusion of the test the linear array is compared
  41880. ** against the Bitvec object. If there are any differences,
  41881. ** an error is returned. If they are the same, zero is returned.
  41882. **
  41883. ** If a memory allocation error occurs, return -1.
  41884. */
  41885. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  41886. Bitvec *pBitvec = 0;
  41887. unsigned char *pV = 0;
  41888. int rc = -1;
  41889. int i, nx, pc, op;
  41890. void *pTmpSpace;
  41891. /* Allocate the Bitvec to be tested and a linear array of
  41892. ** bits to act as the reference */
  41893. pBitvec = sqlite3BitvecCreate( sz );
  41894. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  41895. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  41896. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  41897. /* NULL pBitvec tests */
  41898. sqlite3BitvecSet(0, 1);
  41899. sqlite3BitvecClear(0, 1, pTmpSpace);
  41900. /* Run the program */
  41901. pc = 0;
  41902. while( (op = aOp[pc])!=0 ){
  41903. switch( op ){
  41904. case 1:
  41905. case 2:
  41906. case 5: {
  41907. nx = 4;
  41908. i = aOp[pc+2] - 1;
  41909. aOp[pc+2] += aOp[pc+3];
  41910. break;
  41911. }
  41912. case 3:
  41913. case 4:
  41914. default: {
  41915. nx = 2;
  41916. sqlite3_randomness(sizeof(i), &i);
  41917. break;
  41918. }
  41919. }
  41920. if( (--aOp[pc+1]) > 0 ) nx = 0;
  41921. pc += nx;
  41922. i = (i & 0x7fffffff)%sz;
  41923. if( (op & 1)!=0 ){
  41924. SETBIT(pV, (i+1));
  41925. if( op!=5 ){
  41926. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  41927. }
  41928. }else{
  41929. CLEARBIT(pV, (i+1));
  41930. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  41931. }
  41932. }
  41933. /* Test to make sure the linear array exactly matches the
  41934. ** Bitvec object. Start with the assumption that they do
  41935. ** match (rc==0). Change rc to non-zero if a discrepancy
  41936. ** is found.
  41937. */
  41938. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  41939. + sqlite3BitvecTest(pBitvec, 0)
  41940. + (sqlite3BitvecSize(pBitvec) - sz);
  41941. for(i=1; i<=sz; i++){
  41942. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  41943. rc = i;
  41944. break;
  41945. }
  41946. }
  41947. /* Free allocated structure */
  41948. bitvec_end:
  41949. sqlite3_free(pTmpSpace);
  41950. sqlite3_free(pV);
  41951. sqlite3BitvecDestroy(pBitvec);
  41952. return rc;
  41953. }
  41954. #endif /* SQLITE_UNTESTABLE */
  41955. /************** End of bitvec.c **********************************************/
  41956. /************** Begin file pcache.c ******************************************/
  41957. /*
  41958. ** 2008 August 05
  41959. **
  41960. ** The author disclaims copyright to this source code. In place of
  41961. ** a legal notice, here is a blessing:
  41962. **
  41963. ** May you do good and not evil.
  41964. ** May you find forgiveness for yourself and forgive others.
  41965. ** May you share freely, never taking more than you give.
  41966. **
  41967. *************************************************************************
  41968. ** This file implements that page cache.
  41969. */
  41970. /* #include "sqliteInt.h" */
  41971. /*
  41972. ** A complete page cache is an instance of this structure. Every
  41973. ** entry in the cache holds a single page of the database file. The
  41974. ** btree layer only operates on the cached copy of the database pages.
  41975. **
  41976. ** A page cache entry is "clean" if it exactly matches what is currently
  41977. ** on disk. A page is "dirty" if it has been modified and needs to be
  41978. ** persisted to disk.
  41979. **
  41980. ** pDirty, pDirtyTail, pSynced:
  41981. ** All dirty pages are linked into the doubly linked list using
  41982. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  41983. ** such that p was added to the list more recently than p->pDirtyNext.
  41984. ** PCache.pDirty points to the first (newest) element in the list and
  41985. ** pDirtyTail to the last (oldest).
  41986. **
  41987. ** The PCache.pSynced variable is used to optimize searching for a dirty
  41988. ** page to eject from the cache mid-transaction. It is better to eject
  41989. ** a page that does not require a journal sync than one that does.
  41990. ** Therefore, pSynced is maintained to that it *almost* always points
  41991. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  41992. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  41993. ** (so that the right page to eject can be found by following pDirtyPrev
  41994. ** pointers).
  41995. */
  41996. struct PCache {
  41997. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  41998. PgHdr *pSynced; /* Last synced page in dirty page list */
  41999. int nRefSum; /* Sum of ref counts over all pages */
  42000. int szCache; /* Configured cache size */
  42001. int szSpill; /* Size before spilling occurs */
  42002. int szPage; /* Size of every page in this cache */
  42003. int szExtra; /* Size of extra space for each page */
  42004. u8 bPurgeable; /* True if pages are on backing store */
  42005. u8 eCreate; /* eCreate value for for xFetch() */
  42006. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  42007. void *pStress; /* Argument to xStress */
  42008. sqlite3_pcache *pCache; /* Pluggable cache module */
  42009. };
  42010. /********************************** Test and Debug Logic **********************/
  42011. /*
  42012. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  42013. ** recompiling.
  42014. **
  42015. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  42016. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  42017. ** is displayed for many operations, resulting in a lot of output.
  42018. */
  42019. #if defined(SQLITE_DEBUG) && 0
  42020. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  42021. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  42022. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  42023. void pcacheDump(PCache *pCache){
  42024. int N;
  42025. int i, j;
  42026. sqlite3_pcache_page *pLower;
  42027. PgHdr *pPg;
  42028. unsigned char *a;
  42029. if( sqlite3PcacheTrace<2 ) return;
  42030. if( pCache->pCache==0 ) return;
  42031. N = sqlite3PcachePagecount(pCache);
  42032. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  42033. for(i=1; i<=N; i++){
  42034. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  42035. if( pLower==0 ) continue;
  42036. pPg = (PgHdr*)pLower->pExtra;
  42037. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  42038. a = (unsigned char *)pLower->pBuf;
  42039. for(j=0; j<12; j++) printf("%02x", a[j]);
  42040. printf("\n");
  42041. if( pPg->pPage==0 ){
  42042. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  42043. }
  42044. }
  42045. }
  42046. #else
  42047. # define pcacheTrace(X)
  42048. # define pcacheDump(X)
  42049. #endif
  42050. /*
  42051. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  42052. ** Return false if any invariant is violated.
  42053. **
  42054. ** This routine is for use inside of assert() statements only. For
  42055. ** example:
  42056. **
  42057. ** assert( sqlite3PcachePageSanity(pPg) );
  42058. */
  42059. #ifdef SQLITE_DEBUG
  42060. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  42061. PCache *pCache;
  42062. assert( pPg!=0 );
  42063. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  42064. pCache = pPg->pCache;
  42065. assert( pCache!=0 ); /* Every page has an associated PCache */
  42066. if( pPg->flags & PGHDR_CLEAN ){
  42067. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  42068. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  42069. assert( pCache->pDirtyTail!=pPg );
  42070. }
  42071. /* WRITEABLE pages must also be DIRTY */
  42072. if( pPg->flags & PGHDR_WRITEABLE ){
  42073. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  42074. }
  42075. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  42076. ** for example, when using the sqlite3PagerDontWrite() optimization:
  42077. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  42078. ** (2) Page X moved to freelist, WRITEABLE is cleared
  42079. ** (3) Page X reused, WRITEABLE is set again
  42080. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  42081. ** in step 3, and page might be written into the database without first
  42082. ** syncing the rollback journal, which might cause corruption on a power
  42083. ** loss.
  42084. **
  42085. ** Another example is when the database page size is smaller than the
  42086. ** disk sector size. When any page of a sector is journalled, all pages
  42087. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  42088. ** in case they are later modified, since all pages in the same sector
  42089. ** must be journalled and synced before any of those pages can be safely
  42090. ** written.
  42091. */
  42092. return 1;
  42093. }
  42094. #endif /* SQLITE_DEBUG */
  42095. /********************************** Linked List Management ********************/
  42096. /* Allowed values for second argument to pcacheManageDirtyList() */
  42097. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  42098. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  42099. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  42100. /*
  42101. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  42102. ** argument determines what operation to do. The 0x01 bit means first
  42103. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  42104. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  42105. */
  42106. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  42107. PCache *p = pPage->pCache;
  42108. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  42109. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  42110. pPage->pgno));
  42111. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  42112. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  42113. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  42114. /* Update the PCache1.pSynced variable if necessary. */
  42115. if( p->pSynced==pPage ){
  42116. p->pSynced = pPage->pDirtyPrev;
  42117. }
  42118. if( pPage->pDirtyNext ){
  42119. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  42120. }else{
  42121. assert( pPage==p->pDirtyTail );
  42122. p->pDirtyTail = pPage->pDirtyPrev;
  42123. }
  42124. if( pPage->pDirtyPrev ){
  42125. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  42126. }else{
  42127. /* If there are now no dirty pages in the cache, set eCreate to 2.
  42128. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  42129. ** searching for a dirty page to eject from the cache when it might
  42130. ** otherwise have to. */
  42131. assert( pPage==p->pDirty );
  42132. p->pDirty = pPage->pDirtyNext;
  42133. assert( p->bPurgeable || p->eCreate==2 );
  42134. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  42135. assert( p->bPurgeable==0 || p->eCreate==1 );
  42136. p->eCreate = 2;
  42137. }
  42138. }
  42139. }
  42140. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  42141. pPage->pDirtyPrev = 0;
  42142. pPage->pDirtyNext = p->pDirty;
  42143. if( pPage->pDirtyNext ){
  42144. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  42145. pPage->pDirtyNext->pDirtyPrev = pPage;
  42146. }else{
  42147. p->pDirtyTail = pPage;
  42148. if( p->bPurgeable ){
  42149. assert( p->eCreate==2 );
  42150. p->eCreate = 1;
  42151. }
  42152. }
  42153. p->pDirty = pPage;
  42154. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  42155. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  42156. ** optimization, as if pSynced points to a page with the NEED_SYNC
  42157. ** flag set sqlite3PcacheFetchStress() searches through all newer
  42158. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  42159. if( !p->pSynced
  42160. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  42161. ){
  42162. p->pSynced = pPage;
  42163. }
  42164. }
  42165. pcacheDump(p);
  42166. }
  42167. /*
  42168. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  42169. ** being used for an in-memory database, this function is a no-op.
  42170. */
  42171. static void pcacheUnpin(PgHdr *p){
  42172. if( p->pCache->bPurgeable ){
  42173. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  42174. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  42175. pcacheDump(p->pCache);
  42176. }
  42177. }
  42178. /*
  42179. ** Compute the number of pages of cache requested. p->szCache is the
  42180. ** cache size requested by the "PRAGMA cache_size" statement.
  42181. */
  42182. static int numberOfCachePages(PCache *p){
  42183. if( p->szCache>=0 ){
  42184. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  42185. ** suggested cache size is set to N. */
  42186. return p->szCache;
  42187. }else{
  42188. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  42189. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  42190. ** bytes of memory. */
  42191. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  42192. }
  42193. }
  42194. /*************************************************** General Interfaces ******
  42195. **
  42196. ** Initialize and shutdown the page cache subsystem. Neither of these
  42197. ** functions are threadsafe.
  42198. */
  42199. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  42200. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  42201. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  42202. ** built-in default page cache is used instead of the application defined
  42203. ** page cache. */
  42204. sqlite3PCacheSetDefault();
  42205. }
  42206. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  42207. }
  42208. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  42209. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  42210. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  42211. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  42212. }
  42213. }
  42214. /*
  42215. ** Return the size in bytes of a PCache object.
  42216. */
  42217. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  42218. /*
  42219. ** Create a new PCache object. Storage space to hold the object
  42220. ** has already been allocated and is passed in as the p pointer.
  42221. ** The caller discovers how much space needs to be allocated by
  42222. ** calling sqlite3PcacheSize().
  42223. **
  42224. ** szExtra is some extra space allocated for each page. The first
  42225. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  42226. ** but remaining content will be uninitialized. Though it is opaque
  42227. ** to this module, the extra space really ends up being the MemPage
  42228. ** structure in the pager.
  42229. */
  42230. SQLITE_PRIVATE int sqlite3PcacheOpen(
  42231. int szPage, /* Size of every page */
  42232. int szExtra, /* Extra space associated with each page */
  42233. int bPurgeable, /* True if pages are on backing store */
  42234. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  42235. void *pStress, /* Argument to xStress */
  42236. PCache *p /* Preallocated space for the PCache */
  42237. ){
  42238. memset(p, 0, sizeof(PCache));
  42239. p->szPage = 1;
  42240. p->szExtra = szExtra;
  42241. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  42242. p->bPurgeable = bPurgeable;
  42243. p->eCreate = 2;
  42244. p->xStress = xStress;
  42245. p->pStress = pStress;
  42246. p->szCache = 100;
  42247. p->szSpill = 1;
  42248. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  42249. return sqlite3PcacheSetPageSize(p, szPage);
  42250. }
  42251. /*
  42252. ** Change the page size for PCache object. The caller must ensure that there
  42253. ** are no outstanding page references when this function is called.
  42254. */
  42255. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  42256. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  42257. if( pCache->szPage ){
  42258. sqlite3_pcache *pNew;
  42259. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  42260. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  42261. pCache->bPurgeable
  42262. );
  42263. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  42264. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  42265. if( pCache->pCache ){
  42266. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  42267. }
  42268. pCache->pCache = pNew;
  42269. pCache->szPage = szPage;
  42270. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  42271. }
  42272. return SQLITE_OK;
  42273. }
  42274. /*
  42275. ** Try to obtain a page from the cache.
  42276. **
  42277. ** This routine returns a pointer to an sqlite3_pcache_page object if
  42278. ** such an object is already in cache, or if a new one is created.
  42279. ** This routine returns a NULL pointer if the object was not in cache
  42280. ** and could not be created.
  42281. **
  42282. ** The createFlags should be 0 to check for existing pages and should
  42283. ** be 3 (not 1, but 3) to try to create a new page.
  42284. **
  42285. ** If the createFlag is 0, then NULL is always returned if the page
  42286. ** is not already in the cache. If createFlag is 1, then a new page
  42287. ** is created only if that can be done without spilling dirty pages
  42288. ** and without exceeding the cache size limit.
  42289. **
  42290. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  42291. ** initialize the sqlite3_pcache_page object and convert it into a
  42292. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  42293. ** routines are split this way for performance reasons. When separated
  42294. ** they can both (usually) operate without having to push values to
  42295. ** the stack on entry and pop them back off on exit, which saves a
  42296. ** lot of pushing and popping.
  42297. */
  42298. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  42299. PCache *pCache, /* Obtain the page from this cache */
  42300. Pgno pgno, /* Page number to obtain */
  42301. int createFlag /* If true, create page if it does not exist already */
  42302. ){
  42303. int eCreate;
  42304. sqlite3_pcache_page *pRes;
  42305. assert( pCache!=0 );
  42306. assert( pCache->pCache!=0 );
  42307. assert( createFlag==3 || createFlag==0 );
  42308. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  42309. /* eCreate defines what to do if the page does not exist.
  42310. ** 0 Do not allocate a new page. (createFlag==0)
  42311. ** 1 Allocate a new page if doing so is inexpensive.
  42312. ** (createFlag==1 AND bPurgeable AND pDirty)
  42313. ** 2 Allocate a new page even it doing so is difficult.
  42314. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  42315. */
  42316. eCreate = createFlag & pCache->eCreate;
  42317. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  42318. assert( createFlag==0 || pCache->eCreate==eCreate );
  42319. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  42320. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  42321. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  42322. createFlag?" create":"",pRes));
  42323. return pRes;
  42324. }
  42325. /*
  42326. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  42327. ** page because no clean pages are available for reuse and the cache
  42328. ** size limit has been reached, then this routine can be invoked to
  42329. ** try harder to allocate a page. This routine might invoke the stress
  42330. ** callback to spill dirty pages to the journal. It will then try to
  42331. ** allocate the new page and will only fail to allocate a new page on
  42332. ** an OOM error.
  42333. **
  42334. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  42335. */
  42336. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  42337. PCache *pCache, /* Obtain the page from this cache */
  42338. Pgno pgno, /* Page number to obtain */
  42339. sqlite3_pcache_page **ppPage /* Write result here */
  42340. ){
  42341. PgHdr *pPg;
  42342. if( pCache->eCreate==2 ) return 0;
  42343. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  42344. /* Find a dirty page to write-out and recycle. First try to find a
  42345. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  42346. ** cleared), but if that is not possible settle for any other
  42347. ** unreferenced dirty page.
  42348. **
  42349. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  42350. ** flag is currently referenced, then the following may leave pSynced
  42351. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  42352. ** cleared). This is Ok, as pSynced is just an optimization. */
  42353. for(pPg=pCache->pSynced;
  42354. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  42355. pPg=pPg->pDirtyPrev
  42356. );
  42357. pCache->pSynced = pPg;
  42358. if( !pPg ){
  42359. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  42360. }
  42361. if( pPg ){
  42362. int rc;
  42363. #ifdef SQLITE_LOG_CACHE_SPILL
  42364. sqlite3_log(SQLITE_FULL,
  42365. "spill page %d making room for %d - cache used: %d/%d",
  42366. pPg->pgno, pgno,
  42367. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  42368. numberOfCachePages(pCache));
  42369. #endif
  42370. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  42371. rc = pCache->xStress(pCache->pStress, pPg);
  42372. pcacheDump(pCache);
  42373. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  42374. return rc;
  42375. }
  42376. }
  42377. }
  42378. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  42379. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  42380. }
  42381. /*
  42382. ** This is a helper routine for sqlite3PcacheFetchFinish()
  42383. **
  42384. ** In the uncommon case where the page being fetched has not been
  42385. ** initialized, this routine is invoked to do the initialization.
  42386. ** This routine is broken out into a separate function since it
  42387. ** requires extra stack manipulation that can be avoided in the common
  42388. ** case.
  42389. */
  42390. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  42391. PCache *pCache, /* Obtain the page from this cache */
  42392. Pgno pgno, /* Page number obtained */
  42393. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  42394. ){
  42395. PgHdr *pPgHdr;
  42396. assert( pPage!=0 );
  42397. pPgHdr = (PgHdr*)pPage->pExtra;
  42398. assert( pPgHdr->pPage==0 );
  42399. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  42400. pPgHdr->pPage = pPage;
  42401. pPgHdr->pData = pPage->pBuf;
  42402. pPgHdr->pExtra = (void *)&pPgHdr[1];
  42403. memset(pPgHdr->pExtra, 0, 8);
  42404. pPgHdr->pCache = pCache;
  42405. pPgHdr->pgno = pgno;
  42406. pPgHdr->flags = PGHDR_CLEAN;
  42407. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  42408. }
  42409. /*
  42410. ** This routine converts the sqlite3_pcache_page object returned by
  42411. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  42412. ** must be called after sqlite3PcacheFetch() in order to get a usable
  42413. ** result.
  42414. */
  42415. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  42416. PCache *pCache, /* Obtain the page from this cache */
  42417. Pgno pgno, /* Page number obtained */
  42418. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  42419. ){
  42420. PgHdr *pPgHdr;
  42421. assert( pPage!=0 );
  42422. pPgHdr = (PgHdr *)pPage->pExtra;
  42423. if( !pPgHdr->pPage ){
  42424. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  42425. }
  42426. pCache->nRefSum++;
  42427. pPgHdr->nRef++;
  42428. assert( sqlite3PcachePageSanity(pPgHdr) );
  42429. return pPgHdr;
  42430. }
  42431. /*
  42432. ** Decrement the reference count on a page. If the page is clean and the
  42433. ** reference count drops to 0, then it is made eligible for recycling.
  42434. */
  42435. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  42436. assert( p->nRef>0 );
  42437. p->pCache->nRefSum--;
  42438. if( (--p->nRef)==0 ){
  42439. if( p->flags&PGHDR_CLEAN ){
  42440. pcacheUnpin(p);
  42441. }else{
  42442. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  42443. }
  42444. }
  42445. }
  42446. /*
  42447. ** Increase the reference count of a supplied page by 1.
  42448. */
  42449. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  42450. assert(p->nRef>0);
  42451. assert( sqlite3PcachePageSanity(p) );
  42452. p->nRef++;
  42453. p->pCache->nRefSum++;
  42454. }
  42455. /*
  42456. ** Drop a page from the cache. There must be exactly one reference to the
  42457. ** page. This function deletes that reference, so after it returns the
  42458. ** page pointed to by p is invalid.
  42459. */
  42460. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  42461. assert( p->nRef==1 );
  42462. assert( sqlite3PcachePageSanity(p) );
  42463. if( p->flags&PGHDR_DIRTY ){
  42464. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  42465. }
  42466. p->pCache->nRefSum--;
  42467. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  42468. }
  42469. /*
  42470. ** Make sure the page is marked as dirty. If it isn't dirty already,
  42471. ** make it so.
  42472. */
  42473. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  42474. assert( p->nRef>0 );
  42475. assert( sqlite3PcachePageSanity(p) );
  42476. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  42477. p->flags &= ~PGHDR_DONT_WRITE;
  42478. if( p->flags & PGHDR_CLEAN ){
  42479. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  42480. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  42481. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  42482. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  42483. }
  42484. assert( sqlite3PcachePageSanity(p) );
  42485. }
  42486. }
  42487. /*
  42488. ** Make sure the page is marked as clean. If it isn't clean already,
  42489. ** make it so.
  42490. */
  42491. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  42492. assert( sqlite3PcachePageSanity(p) );
  42493. if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
  42494. assert( (p->flags & PGHDR_CLEAN)==0 );
  42495. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  42496. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  42497. p->flags |= PGHDR_CLEAN;
  42498. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  42499. assert( sqlite3PcachePageSanity(p) );
  42500. if( p->nRef==0 ){
  42501. pcacheUnpin(p);
  42502. }
  42503. }
  42504. }
  42505. /*
  42506. ** Make every page in the cache clean.
  42507. */
  42508. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  42509. PgHdr *p;
  42510. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  42511. while( (p = pCache->pDirty)!=0 ){
  42512. sqlite3PcacheMakeClean(p);
  42513. }
  42514. }
  42515. /*
  42516. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  42517. */
  42518. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  42519. PgHdr *p;
  42520. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  42521. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  42522. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  42523. }
  42524. pCache->pSynced = pCache->pDirtyTail;
  42525. }
  42526. /*
  42527. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  42528. */
  42529. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  42530. PgHdr *p;
  42531. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  42532. p->flags &= ~PGHDR_NEED_SYNC;
  42533. }
  42534. pCache->pSynced = pCache->pDirtyTail;
  42535. }
  42536. /*
  42537. ** Change the page number of page p to newPgno.
  42538. */
  42539. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  42540. PCache *pCache = p->pCache;
  42541. assert( p->nRef>0 );
  42542. assert( newPgno>0 );
  42543. assert( sqlite3PcachePageSanity(p) );
  42544. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  42545. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  42546. p->pgno = newPgno;
  42547. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  42548. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  42549. }
  42550. }
  42551. /*
  42552. ** Drop every cache entry whose page number is greater than "pgno". The
  42553. ** caller must ensure that there are no outstanding references to any pages
  42554. ** other than page 1 with a page number greater than pgno.
  42555. **
  42556. ** If there is a reference to page 1 and the pgno parameter passed to this
  42557. ** function is 0, then the data area associated with page 1 is zeroed, but
  42558. ** the page object is not dropped.
  42559. */
  42560. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  42561. if( pCache->pCache ){
  42562. PgHdr *p;
  42563. PgHdr *pNext;
  42564. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  42565. for(p=pCache->pDirty; p; p=pNext){
  42566. pNext = p->pDirtyNext;
  42567. /* This routine never gets call with a positive pgno except right
  42568. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  42569. ** it must be that pgno==0.
  42570. */
  42571. assert( p->pgno>0 );
  42572. if( p->pgno>pgno ){
  42573. assert( p->flags&PGHDR_DIRTY );
  42574. sqlite3PcacheMakeClean(p);
  42575. }
  42576. }
  42577. if( pgno==0 && pCache->nRefSum ){
  42578. sqlite3_pcache_page *pPage1;
  42579. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  42580. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  42581. ** pCache->nRefSum>0 */
  42582. memset(pPage1->pBuf, 0, pCache->szPage);
  42583. pgno = 1;
  42584. }
  42585. }
  42586. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  42587. }
  42588. }
  42589. /*
  42590. ** Close a cache.
  42591. */
  42592. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  42593. assert( pCache->pCache!=0 );
  42594. pcacheTrace(("%p.CLOSE\n",pCache));
  42595. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  42596. }
  42597. /*
  42598. ** Discard the contents of the cache.
  42599. */
  42600. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  42601. sqlite3PcacheTruncate(pCache, 0);
  42602. }
  42603. /*
  42604. ** Merge two lists of pages connected by pDirty and in pgno order.
  42605. ** Do not bother fixing the pDirtyPrev pointers.
  42606. */
  42607. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  42608. PgHdr result, *pTail;
  42609. pTail = &result;
  42610. assert( pA!=0 && pB!=0 );
  42611. for(;;){
  42612. if( pA->pgno<pB->pgno ){
  42613. pTail->pDirty = pA;
  42614. pTail = pA;
  42615. pA = pA->pDirty;
  42616. if( pA==0 ){
  42617. pTail->pDirty = pB;
  42618. break;
  42619. }
  42620. }else{
  42621. pTail->pDirty = pB;
  42622. pTail = pB;
  42623. pB = pB->pDirty;
  42624. if( pB==0 ){
  42625. pTail->pDirty = pA;
  42626. break;
  42627. }
  42628. }
  42629. }
  42630. return result.pDirty;
  42631. }
  42632. /*
  42633. ** Sort the list of pages in accending order by pgno. Pages are
  42634. ** connected by pDirty pointers. The pDirtyPrev pointers are
  42635. ** corrupted by this sort.
  42636. **
  42637. ** Since there cannot be more than 2^31 distinct pages in a database,
  42638. ** there cannot be more than 31 buckets required by the merge sorter.
  42639. ** One extra bucket is added to catch overflow in case something
  42640. ** ever changes to make the previous sentence incorrect.
  42641. */
  42642. #define N_SORT_BUCKET 32
  42643. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  42644. PgHdr *a[N_SORT_BUCKET], *p;
  42645. int i;
  42646. memset(a, 0, sizeof(a));
  42647. while( pIn ){
  42648. p = pIn;
  42649. pIn = p->pDirty;
  42650. p->pDirty = 0;
  42651. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  42652. if( a[i]==0 ){
  42653. a[i] = p;
  42654. break;
  42655. }else{
  42656. p = pcacheMergeDirtyList(a[i], p);
  42657. a[i] = 0;
  42658. }
  42659. }
  42660. if( NEVER(i==N_SORT_BUCKET-1) ){
  42661. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  42662. ** the input list. But that is impossible.
  42663. */
  42664. a[i] = pcacheMergeDirtyList(a[i], p);
  42665. }
  42666. }
  42667. p = a[0];
  42668. for(i=1; i<N_SORT_BUCKET; i++){
  42669. if( a[i]==0 ) continue;
  42670. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  42671. }
  42672. return p;
  42673. }
  42674. /*
  42675. ** Return a list of all dirty pages in the cache, sorted by page number.
  42676. */
  42677. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  42678. PgHdr *p;
  42679. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  42680. p->pDirty = p->pDirtyNext;
  42681. }
  42682. return pcacheSortDirtyList(pCache->pDirty);
  42683. }
  42684. /*
  42685. ** Return the total number of references to all pages held by the cache.
  42686. **
  42687. ** This is not the total number of pages referenced, but the sum of the
  42688. ** reference count for all pages.
  42689. */
  42690. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  42691. return pCache->nRefSum;
  42692. }
  42693. /*
  42694. ** Return the number of references to the page supplied as an argument.
  42695. */
  42696. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  42697. return p->nRef;
  42698. }
  42699. /*
  42700. ** Return the total number of pages in the cache.
  42701. */
  42702. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  42703. assert( pCache->pCache!=0 );
  42704. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  42705. }
  42706. #ifdef SQLITE_TEST
  42707. /*
  42708. ** Get the suggested cache-size value.
  42709. */
  42710. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  42711. return numberOfCachePages(pCache);
  42712. }
  42713. #endif
  42714. /*
  42715. ** Set the suggested cache-size value.
  42716. */
  42717. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  42718. assert( pCache->pCache!=0 );
  42719. pCache->szCache = mxPage;
  42720. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  42721. numberOfCachePages(pCache));
  42722. }
  42723. /*
  42724. ** Set the suggested cache-spill value. Make no changes if if the
  42725. ** argument is zero. Return the effective cache-spill size, which will
  42726. ** be the larger of the szSpill and szCache.
  42727. */
  42728. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  42729. int res;
  42730. assert( p->pCache!=0 );
  42731. if( mxPage ){
  42732. if( mxPage<0 ){
  42733. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  42734. }
  42735. p->szSpill = mxPage;
  42736. }
  42737. res = numberOfCachePages(p);
  42738. if( res<p->szSpill ) res = p->szSpill;
  42739. return res;
  42740. }
  42741. /*
  42742. ** Free up as much memory as possible from the page cache.
  42743. */
  42744. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  42745. assert( pCache->pCache!=0 );
  42746. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  42747. }
  42748. /*
  42749. ** Return the size of the header added by this middleware layer
  42750. ** in the page-cache hierarchy.
  42751. */
  42752. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  42753. /*
  42754. ** Return the number of dirty pages currently in the cache, as a percentage
  42755. ** of the configured cache size.
  42756. */
  42757. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  42758. PgHdr *pDirty;
  42759. int nDirty = 0;
  42760. int nCache = numberOfCachePages(pCache);
  42761. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  42762. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  42763. }
  42764. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  42765. /*
  42766. ** For all dirty pages currently in the cache, invoke the specified
  42767. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  42768. ** defined.
  42769. */
  42770. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  42771. PgHdr *pDirty;
  42772. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  42773. xIter(pDirty);
  42774. }
  42775. }
  42776. #endif
  42777. /************** End of pcache.c **********************************************/
  42778. /************** Begin file pcache1.c *****************************************/
  42779. /*
  42780. ** 2008 November 05
  42781. **
  42782. ** The author disclaims copyright to this source code. In place of
  42783. ** a legal notice, here is a blessing:
  42784. **
  42785. ** May you do good and not evil.
  42786. ** May you find forgiveness for yourself and forgive others.
  42787. ** May you share freely, never taking more than you give.
  42788. **
  42789. *************************************************************************
  42790. **
  42791. ** This file implements the default page cache implementation (the
  42792. ** sqlite3_pcache interface). It also contains part of the implementation
  42793. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  42794. ** If the default page cache implementation is overridden, then neither of
  42795. ** these two features are available.
  42796. **
  42797. ** A Page cache line looks like this:
  42798. **
  42799. ** -------------------------------------------------------------
  42800. ** | database page content | PgHdr1 | MemPage | PgHdr |
  42801. ** -------------------------------------------------------------
  42802. **
  42803. ** The database page content is up front (so that buffer overreads tend to
  42804. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  42805. ** is the extension added by the btree.c module containing information such
  42806. ** as the database page number and how that database page is used. PgHdr
  42807. ** is added by the pcache.c layer and contains information used to keep track
  42808. ** of which pages are "dirty". PgHdr1 is an extension added by this
  42809. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  42810. ** PgHdr1 contains information needed to look up a page by its page number.
  42811. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  42812. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  42813. **
  42814. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  42815. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  42816. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  42817. ** size can vary according to architecture, compile-time options, and
  42818. ** SQLite library version number.
  42819. **
  42820. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  42821. ** using a separate memory allocation from the database page content. This
  42822. ** seeks to overcome the "clownshoe" problem (also called "internal
  42823. ** fragmentation" in academic literature) of allocating a few bytes more
  42824. ** than a power of two with the memory allocator rounding up to the next
  42825. ** power of two, and leaving the rounded-up space unused.
  42826. **
  42827. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  42828. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  42829. **
  42830. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  42831. ** The btree.c module deals with pointers to MemPage objects.
  42832. **
  42833. ** SOURCE OF PAGE CACHE MEMORY:
  42834. **
  42835. ** Memory for a page might come from any of three sources:
  42836. **
  42837. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  42838. ** (2) Global page-cache memory provided using sqlite3_config() with
  42839. ** SQLITE_CONFIG_PAGECACHE.
  42840. ** (3) PCache-local bulk allocation.
  42841. **
  42842. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  42843. ** that is allocated when the page cache is created. The size of the local
  42844. ** bulk allocation can be adjusted using
  42845. **
  42846. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  42847. **
  42848. ** If N is positive, then N pages worth of memory are allocated using a single
  42849. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  42850. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  42851. ** for as many pages as can be accomodated.
  42852. **
  42853. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  42854. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  42855. ** memory allocator (1).
  42856. **
  42857. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  42858. ** show that method (3) with N==100 provides about a 5% performance boost for
  42859. ** common workloads.
  42860. */
  42861. /* #include "sqliteInt.h" */
  42862. typedef struct PCache1 PCache1;
  42863. typedef struct PgHdr1 PgHdr1;
  42864. typedef struct PgFreeslot PgFreeslot;
  42865. typedef struct PGroup PGroup;
  42866. /*
  42867. ** Each cache entry is represented by an instance of the following
  42868. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  42869. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  42870. ** in memory.
  42871. */
  42872. struct PgHdr1 {
  42873. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  42874. unsigned int iKey; /* Key value (page number) */
  42875. u8 isBulkLocal; /* This page from bulk local storage */
  42876. u8 isAnchor; /* This is the PGroup.lru element */
  42877. PgHdr1 *pNext; /* Next in hash table chain */
  42878. PCache1 *pCache; /* Cache that currently owns this page */
  42879. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  42880. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  42881. };
  42882. /*
  42883. ** A page is pinned if it is no on the LRU list
  42884. */
  42885. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  42886. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  42887. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  42888. ** of one or more PCaches that are able to recycle each other's unpinned
  42889. ** pages when they are under memory pressure. A PGroup is an instance of
  42890. ** the following object.
  42891. **
  42892. ** This page cache implementation works in one of two modes:
  42893. **
  42894. ** (1) Every PCache is the sole member of its own PGroup. There is
  42895. ** one PGroup per PCache.
  42896. **
  42897. ** (2) There is a single global PGroup that all PCaches are a member
  42898. ** of.
  42899. **
  42900. ** Mode 1 uses more memory (since PCache instances are not able to rob
  42901. ** unused pages from other PCaches) but it also operates without a mutex,
  42902. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  42903. ** threadsafe, but recycles pages more efficiently.
  42904. **
  42905. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  42906. ** PGroup which is the pcache1.grp global variable and its mutex is
  42907. ** SQLITE_MUTEX_STATIC_LRU.
  42908. */
  42909. struct PGroup {
  42910. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  42911. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  42912. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  42913. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  42914. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  42915. PgHdr1 lru; /* The beginning and end of the LRU list */
  42916. };
  42917. /* Each page cache is an instance of the following object. Every
  42918. ** open database file (including each in-memory database and each
  42919. ** temporary or transient database) has a single page cache which
  42920. ** is an instance of this object.
  42921. **
  42922. ** Pointers to structures of this type are cast and returned as
  42923. ** opaque sqlite3_pcache* handles.
  42924. */
  42925. struct PCache1 {
  42926. /* Cache configuration parameters. Page size (szPage) and the purgeable
  42927. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  42928. ** cache is created and are never changed thereafter. nMax may be
  42929. ** modified at any time by a call to the pcache1Cachesize() method.
  42930. ** The PGroup mutex must be held when accessing nMax.
  42931. */
  42932. PGroup *pGroup; /* PGroup this cache belongs to */
  42933. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  42934. int szPage; /* Size of database content section */
  42935. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  42936. int szAlloc; /* Total size of one pcache line */
  42937. int bPurgeable; /* True if cache is purgeable */
  42938. unsigned int nMin; /* Minimum number of pages reserved */
  42939. unsigned int nMax; /* Configured "cache_size" value */
  42940. unsigned int n90pct; /* nMax*9/10 */
  42941. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  42942. /* Hash table of all pages. The following variables may only be accessed
  42943. ** when the accessor is holding the PGroup mutex.
  42944. */
  42945. unsigned int nRecyclable; /* Number of pages in the LRU list */
  42946. unsigned int nPage; /* Total number of pages in apHash */
  42947. unsigned int nHash; /* Number of slots in apHash[] */
  42948. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  42949. PgHdr1 *pFree; /* List of unused pcache-local pages */
  42950. void *pBulk; /* Bulk memory used by pcache-local */
  42951. };
  42952. /*
  42953. ** Free slots in the allocator used to divide up the global page cache
  42954. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  42955. */
  42956. struct PgFreeslot {
  42957. PgFreeslot *pNext; /* Next free slot */
  42958. };
  42959. /*
  42960. ** Global data used by this cache.
  42961. */
  42962. static SQLITE_WSD struct PCacheGlobal {
  42963. PGroup grp; /* The global PGroup for mode (2) */
  42964. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  42965. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  42966. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  42967. ** The nFreeSlot and pFree values do require mutex protection.
  42968. */
  42969. int isInit; /* True if initialized */
  42970. int separateCache; /* Use a new PGroup for each PCache */
  42971. int nInitPage; /* Initial bulk allocation size */
  42972. int szSlot; /* Size of each free slot */
  42973. int nSlot; /* The number of pcache slots */
  42974. int nReserve; /* Try to keep nFreeSlot above this */
  42975. void *pStart, *pEnd; /* Bounds of global page cache memory */
  42976. /* Above requires no mutex. Use mutex below for variable that follow. */
  42977. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  42978. PgFreeslot *pFree; /* Free page blocks */
  42979. int nFreeSlot; /* Number of unused pcache slots */
  42980. /* The following value requires a mutex to change. We skip the mutex on
  42981. ** reading because (1) most platforms read a 32-bit integer atomically and
  42982. ** (2) even if an incorrect value is read, no great harm is done since this
  42983. ** is really just an optimization. */
  42984. int bUnderPressure; /* True if low on PAGECACHE memory */
  42985. } pcache1_g;
  42986. /*
  42987. ** All code in this file should access the global structure above via the
  42988. ** alias "pcache1". This ensures that the WSD emulation is used when
  42989. ** compiling for systems that do not support real WSD.
  42990. */
  42991. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  42992. /*
  42993. ** Macros to enter and leave the PCache LRU mutex.
  42994. */
  42995. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  42996. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  42997. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  42998. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  42999. #else
  43000. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  43001. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  43002. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  43003. #endif
  43004. /******************************************************************************/
  43005. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  43006. /*
  43007. ** This function is called during initialization if a static buffer is
  43008. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  43009. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  43010. ** enough to contain 'n' buffers of 'sz' bytes each.
  43011. **
  43012. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  43013. ** to be serialized already. There is no need for further mutexing.
  43014. */
  43015. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  43016. if( pcache1.isInit ){
  43017. PgFreeslot *p;
  43018. if( pBuf==0 ) sz = n = 0;
  43019. if( n==0 ) sz = 0;
  43020. sz = ROUNDDOWN8(sz);
  43021. pcache1.szSlot = sz;
  43022. pcache1.nSlot = pcache1.nFreeSlot = n;
  43023. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  43024. pcache1.pStart = pBuf;
  43025. pcache1.pFree = 0;
  43026. pcache1.bUnderPressure = 0;
  43027. while( n-- ){
  43028. p = (PgFreeslot*)pBuf;
  43029. p->pNext = pcache1.pFree;
  43030. pcache1.pFree = p;
  43031. pBuf = (void*)&((char*)pBuf)[sz];
  43032. }
  43033. pcache1.pEnd = pBuf;
  43034. }
  43035. }
  43036. /*
  43037. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  43038. ** true if pCache->pFree ends up containing one or more free pages.
  43039. */
  43040. static int pcache1InitBulk(PCache1 *pCache){
  43041. i64 szBulk;
  43042. char *zBulk;
  43043. if( pcache1.nInitPage==0 ) return 0;
  43044. /* Do not bother with a bulk allocation if the cache size very small */
  43045. if( pCache->nMax<3 ) return 0;
  43046. sqlite3BeginBenignMalloc();
  43047. if( pcache1.nInitPage>0 ){
  43048. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  43049. }else{
  43050. szBulk = -1024 * (i64)pcache1.nInitPage;
  43051. }
  43052. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  43053. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  43054. }
  43055. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  43056. sqlite3EndBenignMalloc();
  43057. if( zBulk ){
  43058. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  43059. do{
  43060. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  43061. pX->page.pBuf = zBulk;
  43062. pX->page.pExtra = &pX[1];
  43063. pX->isBulkLocal = 1;
  43064. pX->isAnchor = 0;
  43065. pX->pNext = pCache->pFree;
  43066. pCache->pFree = pX;
  43067. zBulk += pCache->szAlloc;
  43068. }while( --nBulk );
  43069. }
  43070. return pCache->pFree!=0;
  43071. }
  43072. /*
  43073. ** Malloc function used within this file to allocate space from the buffer
  43074. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  43075. ** such buffer exists or there is no space left in it, this function falls
  43076. ** back to sqlite3Malloc().
  43077. **
  43078. ** Multiple threads can run this routine at the same time. Global variables
  43079. ** in pcache1 need to be protected via mutex.
  43080. */
  43081. static void *pcache1Alloc(int nByte){
  43082. void *p = 0;
  43083. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  43084. if( nByte<=pcache1.szSlot ){
  43085. sqlite3_mutex_enter(pcache1.mutex);
  43086. p = (PgHdr1 *)pcache1.pFree;
  43087. if( p ){
  43088. pcache1.pFree = pcache1.pFree->pNext;
  43089. pcache1.nFreeSlot--;
  43090. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  43091. assert( pcache1.nFreeSlot>=0 );
  43092. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  43093. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  43094. }
  43095. sqlite3_mutex_leave(pcache1.mutex);
  43096. }
  43097. if( p==0 ){
  43098. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  43099. ** it from sqlite3Malloc instead.
  43100. */
  43101. p = sqlite3Malloc(nByte);
  43102. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  43103. if( p ){
  43104. int sz = sqlite3MallocSize(p);
  43105. sqlite3_mutex_enter(pcache1.mutex);
  43106. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  43107. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  43108. sqlite3_mutex_leave(pcache1.mutex);
  43109. }
  43110. #endif
  43111. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  43112. }
  43113. return p;
  43114. }
  43115. /*
  43116. ** Free an allocated buffer obtained from pcache1Alloc().
  43117. */
  43118. static void pcache1Free(void *p){
  43119. if( p==0 ) return;
  43120. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  43121. PgFreeslot *pSlot;
  43122. sqlite3_mutex_enter(pcache1.mutex);
  43123. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  43124. pSlot = (PgFreeslot*)p;
  43125. pSlot->pNext = pcache1.pFree;
  43126. pcache1.pFree = pSlot;
  43127. pcache1.nFreeSlot++;
  43128. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  43129. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  43130. sqlite3_mutex_leave(pcache1.mutex);
  43131. }else{
  43132. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  43133. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  43134. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  43135. {
  43136. int nFreed = 0;
  43137. nFreed = sqlite3MallocSize(p);
  43138. sqlite3_mutex_enter(pcache1.mutex);
  43139. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  43140. sqlite3_mutex_leave(pcache1.mutex);
  43141. }
  43142. #endif
  43143. sqlite3_free(p);
  43144. }
  43145. }
  43146. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43147. /*
  43148. ** Return the size of a pcache allocation
  43149. */
  43150. static int pcache1MemSize(void *p){
  43151. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  43152. return pcache1.szSlot;
  43153. }else{
  43154. int iSize;
  43155. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  43156. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  43157. iSize = sqlite3MallocSize(p);
  43158. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  43159. return iSize;
  43160. }
  43161. }
  43162. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  43163. /*
  43164. ** Allocate a new page object initially associated with cache pCache.
  43165. */
  43166. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  43167. PgHdr1 *p = 0;
  43168. void *pPg;
  43169. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  43170. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  43171. p = pCache->pFree;
  43172. pCache->pFree = p->pNext;
  43173. p->pNext = 0;
  43174. }else{
  43175. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43176. /* The group mutex must be released before pcache1Alloc() is called. This
  43177. ** is because it might call sqlite3_release_memory(), which assumes that
  43178. ** this mutex is not held. */
  43179. assert( pcache1.separateCache==0 );
  43180. assert( pCache->pGroup==&pcache1.grp );
  43181. pcache1LeaveMutex(pCache->pGroup);
  43182. #endif
  43183. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  43184. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  43185. pPg = pcache1Alloc(pCache->szPage);
  43186. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  43187. if( !pPg || !p ){
  43188. pcache1Free(pPg);
  43189. sqlite3_free(p);
  43190. pPg = 0;
  43191. }
  43192. #else
  43193. pPg = pcache1Alloc(pCache->szAlloc);
  43194. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  43195. #endif
  43196. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  43197. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43198. pcache1EnterMutex(pCache->pGroup);
  43199. #endif
  43200. if( pPg==0 ) return 0;
  43201. p->page.pBuf = pPg;
  43202. p->page.pExtra = &p[1];
  43203. p->isBulkLocal = 0;
  43204. p->isAnchor = 0;
  43205. }
  43206. (*pCache->pnPurgeable)++;
  43207. return p;
  43208. }
  43209. /*
  43210. ** Free a page object allocated by pcache1AllocPage().
  43211. */
  43212. static void pcache1FreePage(PgHdr1 *p){
  43213. PCache1 *pCache;
  43214. assert( p!=0 );
  43215. pCache = p->pCache;
  43216. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  43217. if( p->isBulkLocal ){
  43218. p->pNext = pCache->pFree;
  43219. pCache->pFree = p;
  43220. }else{
  43221. pcache1Free(p->page.pBuf);
  43222. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  43223. sqlite3_free(p);
  43224. #endif
  43225. }
  43226. (*pCache->pnPurgeable)--;
  43227. }
  43228. /*
  43229. ** Malloc function used by SQLite to obtain space from the buffer configured
  43230. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  43231. ** exists, this function falls back to sqlite3Malloc().
  43232. */
  43233. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  43234. return pcache1Alloc(sz);
  43235. }
  43236. /*
  43237. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  43238. */
  43239. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  43240. pcache1Free(p);
  43241. }
  43242. /*
  43243. ** Return true if it desirable to avoid allocating a new page cache
  43244. ** entry.
  43245. **
  43246. ** If memory was allocated specifically to the page cache using
  43247. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  43248. ** it is desirable to avoid allocating a new page cache entry because
  43249. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  43250. ** for all page cache needs and we should not need to spill the
  43251. ** allocation onto the heap.
  43252. **
  43253. ** Or, the heap is used for all page cache memory but the heap is
  43254. ** under memory pressure, then again it is desirable to avoid
  43255. ** allocating a new page cache entry in order to avoid stressing
  43256. ** the heap even further.
  43257. */
  43258. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  43259. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  43260. return pcache1.bUnderPressure;
  43261. }else{
  43262. return sqlite3HeapNearlyFull();
  43263. }
  43264. }
  43265. /******************************************************************************/
  43266. /******** General Implementation Functions ************************************/
  43267. /*
  43268. ** This function is used to resize the hash table used by the cache passed
  43269. ** as the first argument.
  43270. **
  43271. ** The PCache mutex must be held when this function is called.
  43272. */
  43273. static void pcache1ResizeHash(PCache1 *p){
  43274. PgHdr1 **apNew;
  43275. unsigned int nNew;
  43276. unsigned int i;
  43277. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  43278. nNew = p->nHash*2;
  43279. if( nNew<256 ){
  43280. nNew = 256;
  43281. }
  43282. pcache1LeaveMutex(p->pGroup);
  43283. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  43284. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  43285. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  43286. pcache1EnterMutex(p->pGroup);
  43287. if( apNew ){
  43288. for(i=0; i<p->nHash; i++){
  43289. PgHdr1 *pPage;
  43290. PgHdr1 *pNext = p->apHash[i];
  43291. while( (pPage = pNext)!=0 ){
  43292. unsigned int h = pPage->iKey % nNew;
  43293. pNext = pPage->pNext;
  43294. pPage->pNext = apNew[h];
  43295. apNew[h] = pPage;
  43296. }
  43297. }
  43298. sqlite3_free(p->apHash);
  43299. p->apHash = apNew;
  43300. p->nHash = nNew;
  43301. }
  43302. }
  43303. /*
  43304. ** This function is used internally to remove the page pPage from the
  43305. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  43306. ** LRU list, then this function is a no-op.
  43307. **
  43308. ** The PGroup mutex must be held when this function is called.
  43309. */
  43310. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  43311. assert( pPage!=0 );
  43312. assert( PAGE_IS_UNPINNED(pPage) );
  43313. assert( pPage->pLruNext );
  43314. assert( pPage->pLruPrev );
  43315. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  43316. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  43317. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  43318. pPage->pLruNext = 0;
  43319. pPage->pLruPrev = 0;
  43320. assert( pPage->isAnchor==0 );
  43321. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  43322. pPage->pCache->nRecyclable--;
  43323. return pPage;
  43324. }
  43325. /*
  43326. ** Remove the page supplied as an argument from the hash table
  43327. ** (PCache1.apHash structure) that it is currently stored in.
  43328. ** Also free the page if freePage is true.
  43329. **
  43330. ** The PGroup mutex must be held when this function is called.
  43331. */
  43332. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  43333. unsigned int h;
  43334. PCache1 *pCache = pPage->pCache;
  43335. PgHdr1 **pp;
  43336. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  43337. h = pPage->iKey % pCache->nHash;
  43338. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  43339. *pp = (*pp)->pNext;
  43340. pCache->nPage--;
  43341. if( freeFlag ) pcache1FreePage(pPage);
  43342. }
  43343. /*
  43344. ** If there are currently more than nMaxPage pages allocated, try
  43345. ** to recycle pages to reduce the number allocated to nMaxPage.
  43346. */
  43347. static void pcache1EnforceMaxPage(PCache1 *pCache){
  43348. PGroup *pGroup = pCache->pGroup;
  43349. PgHdr1 *p;
  43350. assert( sqlite3_mutex_held(pGroup->mutex) );
  43351. while( pGroup->nPurgeable>pGroup->nMaxPage
  43352. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  43353. ){
  43354. assert( p->pCache->pGroup==pGroup );
  43355. assert( PAGE_IS_UNPINNED(p) );
  43356. pcache1PinPage(p);
  43357. pcache1RemoveFromHash(p, 1);
  43358. }
  43359. if( pCache->nPage==0 && pCache->pBulk ){
  43360. sqlite3_free(pCache->pBulk);
  43361. pCache->pBulk = pCache->pFree = 0;
  43362. }
  43363. }
  43364. /*
  43365. ** Discard all pages from cache pCache with a page number (key value)
  43366. ** greater than or equal to iLimit. Any pinned pages that meet this
  43367. ** criteria are unpinned before they are discarded.
  43368. **
  43369. ** The PCache mutex must be held when this function is called.
  43370. */
  43371. static void pcache1TruncateUnsafe(
  43372. PCache1 *pCache, /* The cache to truncate */
  43373. unsigned int iLimit /* Drop pages with this pgno or larger */
  43374. ){
  43375. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  43376. unsigned int h, iStop;
  43377. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  43378. assert( pCache->iMaxKey >= iLimit );
  43379. assert( pCache->nHash > 0 );
  43380. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  43381. /* If we are just shaving the last few pages off the end of the
  43382. ** cache, then there is no point in scanning the entire hash table.
  43383. ** Only scan those hash slots that might contain pages that need to
  43384. ** be removed. */
  43385. h = iLimit % pCache->nHash;
  43386. iStop = pCache->iMaxKey % pCache->nHash;
  43387. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  43388. }else{
  43389. /* This is the general case where many pages are being removed.
  43390. ** It is necessary to scan the entire hash table */
  43391. h = pCache->nHash/2;
  43392. iStop = h - 1;
  43393. }
  43394. for(;;){
  43395. PgHdr1 **pp;
  43396. PgHdr1 *pPage;
  43397. assert( h<pCache->nHash );
  43398. pp = &pCache->apHash[h];
  43399. while( (pPage = *pp)!=0 ){
  43400. if( pPage->iKey>=iLimit ){
  43401. pCache->nPage--;
  43402. *pp = pPage->pNext;
  43403. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  43404. pcache1FreePage(pPage);
  43405. }else{
  43406. pp = &pPage->pNext;
  43407. TESTONLY( if( nPage>=0 ) nPage++; )
  43408. }
  43409. }
  43410. if( h==iStop ) break;
  43411. h = (h+1) % pCache->nHash;
  43412. }
  43413. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  43414. }
  43415. /******************************************************************************/
  43416. /******** sqlite3_pcache Methods **********************************************/
  43417. /*
  43418. ** Implementation of the sqlite3_pcache.xInit method.
  43419. */
  43420. static int pcache1Init(void *NotUsed){
  43421. UNUSED_PARAMETER(NotUsed);
  43422. assert( pcache1.isInit==0 );
  43423. memset(&pcache1, 0, sizeof(pcache1));
  43424. /*
  43425. ** The pcache1.separateCache variable is true if each PCache has its own
  43426. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  43427. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  43428. **
  43429. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  43430. **
  43431. ** * Use a unified cache in single-threaded applications that have
  43432. ** configured a start-time buffer for use as page-cache memory using
  43433. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  43434. ** pBuf argument.
  43435. **
  43436. ** * Otherwise use separate caches (mode-1)
  43437. */
  43438. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  43439. pcache1.separateCache = 0;
  43440. #elif SQLITE_THREADSAFE
  43441. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  43442. || sqlite3GlobalConfig.bCoreMutex>0;
  43443. #else
  43444. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  43445. #endif
  43446. #if SQLITE_THREADSAFE
  43447. if( sqlite3GlobalConfig.bCoreMutex ){
  43448. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  43449. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  43450. }
  43451. #endif
  43452. if( pcache1.separateCache
  43453. && sqlite3GlobalConfig.nPage!=0
  43454. && sqlite3GlobalConfig.pPage==0
  43455. ){
  43456. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  43457. }else{
  43458. pcache1.nInitPage = 0;
  43459. }
  43460. pcache1.grp.mxPinned = 10;
  43461. pcache1.isInit = 1;
  43462. return SQLITE_OK;
  43463. }
  43464. /*
  43465. ** Implementation of the sqlite3_pcache.xShutdown method.
  43466. ** Note that the static mutex allocated in xInit does
  43467. ** not need to be freed.
  43468. */
  43469. static void pcache1Shutdown(void *NotUsed){
  43470. UNUSED_PARAMETER(NotUsed);
  43471. assert( pcache1.isInit!=0 );
  43472. memset(&pcache1, 0, sizeof(pcache1));
  43473. }
  43474. /* forward declaration */
  43475. static void pcache1Destroy(sqlite3_pcache *p);
  43476. /*
  43477. ** Implementation of the sqlite3_pcache.xCreate method.
  43478. **
  43479. ** Allocate a new cache.
  43480. */
  43481. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  43482. PCache1 *pCache; /* The newly created page cache */
  43483. PGroup *pGroup; /* The group the new page cache will belong to */
  43484. int sz; /* Bytes of memory required to allocate the new cache */
  43485. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  43486. assert( szExtra < 300 );
  43487. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  43488. pCache = (PCache1 *)sqlite3MallocZero(sz);
  43489. if( pCache ){
  43490. if( pcache1.separateCache ){
  43491. pGroup = (PGroup*)&pCache[1];
  43492. pGroup->mxPinned = 10;
  43493. }else{
  43494. pGroup = &pcache1.grp;
  43495. }
  43496. if( pGroup->lru.isAnchor==0 ){
  43497. pGroup->lru.isAnchor = 1;
  43498. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  43499. }
  43500. pCache->pGroup = pGroup;
  43501. pCache->szPage = szPage;
  43502. pCache->szExtra = szExtra;
  43503. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  43504. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  43505. pcache1EnterMutex(pGroup);
  43506. pcache1ResizeHash(pCache);
  43507. if( bPurgeable ){
  43508. pCache->nMin = 10;
  43509. pGroup->nMinPage += pCache->nMin;
  43510. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  43511. pCache->pnPurgeable = &pGroup->nPurgeable;
  43512. }else{
  43513. static unsigned int dummyCurrentPage;
  43514. pCache->pnPurgeable = &dummyCurrentPage;
  43515. }
  43516. pcache1LeaveMutex(pGroup);
  43517. if( pCache->nHash==0 ){
  43518. pcache1Destroy((sqlite3_pcache*)pCache);
  43519. pCache = 0;
  43520. }
  43521. }
  43522. return (sqlite3_pcache *)pCache;
  43523. }
  43524. /*
  43525. ** Implementation of the sqlite3_pcache.xCachesize method.
  43526. **
  43527. ** Configure the cache_size limit for a cache.
  43528. */
  43529. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  43530. PCache1 *pCache = (PCache1 *)p;
  43531. if( pCache->bPurgeable ){
  43532. PGroup *pGroup = pCache->pGroup;
  43533. pcache1EnterMutex(pGroup);
  43534. pGroup->nMaxPage += (nMax - pCache->nMax);
  43535. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  43536. pCache->nMax = nMax;
  43537. pCache->n90pct = pCache->nMax*9/10;
  43538. pcache1EnforceMaxPage(pCache);
  43539. pcache1LeaveMutex(pGroup);
  43540. }
  43541. }
  43542. /*
  43543. ** Implementation of the sqlite3_pcache.xShrink method.
  43544. **
  43545. ** Free up as much memory as possible.
  43546. */
  43547. static void pcache1Shrink(sqlite3_pcache *p){
  43548. PCache1 *pCache = (PCache1*)p;
  43549. if( pCache->bPurgeable ){
  43550. PGroup *pGroup = pCache->pGroup;
  43551. int savedMaxPage;
  43552. pcache1EnterMutex(pGroup);
  43553. savedMaxPage = pGroup->nMaxPage;
  43554. pGroup->nMaxPage = 0;
  43555. pcache1EnforceMaxPage(pCache);
  43556. pGroup->nMaxPage = savedMaxPage;
  43557. pcache1LeaveMutex(pGroup);
  43558. }
  43559. }
  43560. /*
  43561. ** Implementation of the sqlite3_pcache.xPagecount method.
  43562. */
  43563. static int pcache1Pagecount(sqlite3_pcache *p){
  43564. int n;
  43565. PCache1 *pCache = (PCache1*)p;
  43566. pcache1EnterMutex(pCache->pGroup);
  43567. n = pCache->nPage;
  43568. pcache1LeaveMutex(pCache->pGroup);
  43569. return n;
  43570. }
  43571. /*
  43572. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  43573. ** in the header of the pcache1Fetch() procedure.
  43574. **
  43575. ** This steps are broken out into a separate procedure because they are
  43576. ** usually not needed, and by avoiding the stack initialization required
  43577. ** for these steps, the main pcache1Fetch() procedure can run faster.
  43578. */
  43579. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  43580. PCache1 *pCache,
  43581. unsigned int iKey,
  43582. int createFlag
  43583. ){
  43584. unsigned int nPinned;
  43585. PGroup *pGroup = pCache->pGroup;
  43586. PgHdr1 *pPage = 0;
  43587. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  43588. assert( pCache->nPage >= pCache->nRecyclable );
  43589. nPinned = pCache->nPage - pCache->nRecyclable;
  43590. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  43591. assert( pCache->n90pct == pCache->nMax*9/10 );
  43592. if( createFlag==1 && (
  43593. nPinned>=pGroup->mxPinned
  43594. || nPinned>=pCache->n90pct
  43595. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  43596. )){
  43597. return 0;
  43598. }
  43599. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  43600. assert( pCache->nHash>0 && pCache->apHash );
  43601. /* Step 4. Try to recycle a page. */
  43602. if( pCache->bPurgeable
  43603. && !pGroup->lru.pLruPrev->isAnchor
  43604. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  43605. ){
  43606. PCache1 *pOther;
  43607. pPage = pGroup->lru.pLruPrev;
  43608. assert( PAGE_IS_UNPINNED(pPage) );
  43609. pcache1RemoveFromHash(pPage, 0);
  43610. pcache1PinPage(pPage);
  43611. pOther = pPage->pCache;
  43612. if( pOther->szAlloc != pCache->szAlloc ){
  43613. pcache1FreePage(pPage);
  43614. pPage = 0;
  43615. }else{
  43616. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  43617. }
  43618. }
  43619. /* Step 5. If a usable page buffer has still not been found,
  43620. ** attempt to allocate a new one.
  43621. */
  43622. if( !pPage ){
  43623. pPage = pcache1AllocPage(pCache, createFlag==1);
  43624. }
  43625. if( pPage ){
  43626. unsigned int h = iKey % pCache->nHash;
  43627. pCache->nPage++;
  43628. pPage->iKey = iKey;
  43629. pPage->pNext = pCache->apHash[h];
  43630. pPage->pCache = pCache;
  43631. pPage->pLruPrev = 0;
  43632. pPage->pLruNext = 0;
  43633. *(void **)pPage->page.pExtra = 0;
  43634. pCache->apHash[h] = pPage;
  43635. if( iKey>pCache->iMaxKey ){
  43636. pCache->iMaxKey = iKey;
  43637. }
  43638. }
  43639. return pPage;
  43640. }
  43641. /*
  43642. ** Implementation of the sqlite3_pcache.xFetch method.
  43643. **
  43644. ** Fetch a page by key value.
  43645. **
  43646. ** Whether or not a new page may be allocated by this function depends on
  43647. ** the value of the createFlag argument. 0 means do not allocate a new
  43648. ** page. 1 means allocate a new page if space is easily available. 2
  43649. ** means to try really hard to allocate a new page.
  43650. **
  43651. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  43652. ** database) there is really no difference between createFlag 1 and 2. So
  43653. ** the calling function (pcache.c) will never have a createFlag of 1 on
  43654. ** a non-purgeable cache.
  43655. **
  43656. ** There are three different approaches to obtaining space for a page,
  43657. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  43658. **
  43659. ** 1. Regardless of the value of createFlag, the cache is searched for a
  43660. ** copy of the requested page. If one is found, it is returned.
  43661. **
  43662. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  43663. ** returned.
  43664. **
  43665. ** 3. If createFlag is 1, and the page is not already in the cache, then
  43666. ** return NULL (do not allocate a new page) if any of the following
  43667. ** conditions are true:
  43668. **
  43669. ** (a) the number of pages pinned by the cache is greater than
  43670. ** PCache1.nMax, or
  43671. **
  43672. ** (b) the number of pages pinned by the cache is greater than
  43673. ** the sum of nMax for all purgeable caches, less the sum of
  43674. ** nMin for all other purgeable caches, or
  43675. **
  43676. ** 4. If none of the first three conditions apply and the cache is marked
  43677. ** as purgeable, and if one of the following is true:
  43678. **
  43679. ** (a) The number of pages allocated for the cache is already
  43680. ** PCache1.nMax, or
  43681. **
  43682. ** (b) The number of pages allocated for all purgeable caches is
  43683. ** already equal to or greater than the sum of nMax for all
  43684. ** purgeable caches,
  43685. **
  43686. ** (c) The system is under memory pressure and wants to avoid
  43687. ** unnecessary pages cache entry allocations
  43688. **
  43689. ** then attempt to recycle a page from the LRU list. If it is the right
  43690. ** size, return the recycled buffer. Otherwise, free the buffer and
  43691. ** proceed to step 5.
  43692. **
  43693. ** 5. Otherwise, allocate and return a new page buffer.
  43694. **
  43695. ** There are two versions of this routine. pcache1FetchWithMutex() is
  43696. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  43697. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  43698. ** invokes the appropriate routine.
  43699. */
  43700. static PgHdr1 *pcache1FetchNoMutex(
  43701. sqlite3_pcache *p,
  43702. unsigned int iKey,
  43703. int createFlag
  43704. ){
  43705. PCache1 *pCache = (PCache1 *)p;
  43706. PgHdr1 *pPage = 0;
  43707. /* Step 1: Search the hash table for an existing entry. */
  43708. pPage = pCache->apHash[iKey % pCache->nHash];
  43709. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  43710. /* Step 2: If the page was found in the hash table, then return it.
  43711. ** If the page was not in the hash table and createFlag is 0, abort.
  43712. ** Otherwise (page not in hash and createFlag!=0) continue with
  43713. ** subsequent steps to try to create the page. */
  43714. if( pPage ){
  43715. if( PAGE_IS_UNPINNED(pPage) ){
  43716. return pcache1PinPage(pPage);
  43717. }else{
  43718. return pPage;
  43719. }
  43720. }else if( createFlag ){
  43721. /* Steps 3, 4, and 5 implemented by this subroutine */
  43722. return pcache1FetchStage2(pCache, iKey, createFlag);
  43723. }else{
  43724. return 0;
  43725. }
  43726. }
  43727. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43728. static PgHdr1 *pcache1FetchWithMutex(
  43729. sqlite3_pcache *p,
  43730. unsigned int iKey,
  43731. int createFlag
  43732. ){
  43733. PCache1 *pCache = (PCache1 *)p;
  43734. PgHdr1 *pPage;
  43735. pcache1EnterMutex(pCache->pGroup);
  43736. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  43737. assert( pPage==0 || pCache->iMaxKey>=iKey );
  43738. pcache1LeaveMutex(pCache->pGroup);
  43739. return pPage;
  43740. }
  43741. #endif
  43742. static sqlite3_pcache_page *pcache1Fetch(
  43743. sqlite3_pcache *p,
  43744. unsigned int iKey,
  43745. int createFlag
  43746. ){
  43747. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  43748. PCache1 *pCache = (PCache1 *)p;
  43749. #endif
  43750. assert( offsetof(PgHdr1,page)==0 );
  43751. assert( pCache->bPurgeable || createFlag!=1 );
  43752. assert( pCache->bPurgeable || pCache->nMin==0 );
  43753. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  43754. assert( pCache->nMin==0 || pCache->bPurgeable );
  43755. assert( pCache->nHash>0 );
  43756. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43757. if( pCache->pGroup->mutex ){
  43758. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  43759. }else
  43760. #endif
  43761. {
  43762. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  43763. }
  43764. }
  43765. /*
  43766. ** Implementation of the sqlite3_pcache.xUnpin method.
  43767. **
  43768. ** Mark a page as unpinned (eligible for asynchronous recycling).
  43769. */
  43770. static void pcache1Unpin(
  43771. sqlite3_pcache *p,
  43772. sqlite3_pcache_page *pPg,
  43773. int reuseUnlikely
  43774. ){
  43775. PCache1 *pCache = (PCache1 *)p;
  43776. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43777. PGroup *pGroup = pCache->pGroup;
  43778. assert( pPage->pCache==pCache );
  43779. pcache1EnterMutex(pGroup);
  43780. /* It is an error to call this function if the page is already
  43781. ** part of the PGroup LRU list.
  43782. */
  43783. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  43784. assert( PAGE_IS_PINNED(pPage) );
  43785. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  43786. pcache1RemoveFromHash(pPage, 1);
  43787. }else{
  43788. /* Add the page to the PGroup LRU list. */
  43789. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  43790. pPage->pLruPrev = &pGroup->lru;
  43791. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  43792. *ppFirst = pPage;
  43793. pCache->nRecyclable++;
  43794. }
  43795. pcache1LeaveMutex(pCache->pGroup);
  43796. }
  43797. /*
  43798. ** Implementation of the sqlite3_pcache.xRekey method.
  43799. */
  43800. static void pcache1Rekey(
  43801. sqlite3_pcache *p,
  43802. sqlite3_pcache_page *pPg,
  43803. unsigned int iOld,
  43804. unsigned int iNew
  43805. ){
  43806. PCache1 *pCache = (PCache1 *)p;
  43807. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43808. PgHdr1 **pp;
  43809. unsigned int h;
  43810. assert( pPage->iKey==iOld );
  43811. assert( pPage->pCache==pCache );
  43812. pcache1EnterMutex(pCache->pGroup);
  43813. h = iOld%pCache->nHash;
  43814. pp = &pCache->apHash[h];
  43815. while( (*pp)!=pPage ){
  43816. pp = &(*pp)->pNext;
  43817. }
  43818. *pp = pPage->pNext;
  43819. h = iNew%pCache->nHash;
  43820. pPage->iKey = iNew;
  43821. pPage->pNext = pCache->apHash[h];
  43822. pCache->apHash[h] = pPage;
  43823. if( iNew>pCache->iMaxKey ){
  43824. pCache->iMaxKey = iNew;
  43825. }
  43826. pcache1LeaveMutex(pCache->pGroup);
  43827. }
  43828. /*
  43829. ** Implementation of the sqlite3_pcache.xTruncate method.
  43830. **
  43831. ** Discard all unpinned pages in the cache with a page number equal to
  43832. ** or greater than parameter iLimit. Any pinned pages with a page number
  43833. ** equal to or greater than iLimit are implicitly unpinned.
  43834. */
  43835. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  43836. PCache1 *pCache = (PCache1 *)p;
  43837. pcache1EnterMutex(pCache->pGroup);
  43838. if( iLimit<=pCache->iMaxKey ){
  43839. pcache1TruncateUnsafe(pCache, iLimit);
  43840. pCache->iMaxKey = iLimit-1;
  43841. }
  43842. pcache1LeaveMutex(pCache->pGroup);
  43843. }
  43844. /*
  43845. ** Implementation of the sqlite3_pcache.xDestroy method.
  43846. **
  43847. ** Destroy a cache allocated using pcache1Create().
  43848. */
  43849. static void pcache1Destroy(sqlite3_pcache *p){
  43850. PCache1 *pCache = (PCache1 *)p;
  43851. PGroup *pGroup = pCache->pGroup;
  43852. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  43853. pcache1EnterMutex(pGroup);
  43854. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  43855. assert( pGroup->nMaxPage >= pCache->nMax );
  43856. pGroup->nMaxPage -= pCache->nMax;
  43857. assert( pGroup->nMinPage >= pCache->nMin );
  43858. pGroup->nMinPage -= pCache->nMin;
  43859. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  43860. pcache1EnforceMaxPage(pCache);
  43861. pcache1LeaveMutex(pGroup);
  43862. sqlite3_free(pCache->pBulk);
  43863. sqlite3_free(pCache->apHash);
  43864. sqlite3_free(pCache);
  43865. }
  43866. /*
  43867. ** This function is called during initialization (sqlite3_initialize()) to
  43868. ** install the default pluggable cache module, assuming the user has not
  43869. ** already provided an alternative.
  43870. */
  43871. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  43872. static const sqlite3_pcache_methods2 defaultMethods = {
  43873. 1, /* iVersion */
  43874. 0, /* pArg */
  43875. pcache1Init, /* xInit */
  43876. pcache1Shutdown, /* xShutdown */
  43877. pcache1Create, /* xCreate */
  43878. pcache1Cachesize, /* xCachesize */
  43879. pcache1Pagecount, /* xPagecount */
  43880. pcache1Fetch, /* xFetch */
  43881. pcache1Unpin, /* xUnpin */
  43882. pcache1Rekey, /* xRekey */
  43883. pcache1Truncate, /* xTruncate */
  43884. pcache1Destroy, /* xDestroy */
  43885. pcache1Shrink /* xShrink */
  43886. };
  43887. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  43888. }
  43889. /*
  43890. ** Return the size of the header on each page of this PCACHE implementation.
  43891. */
  43892. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  43893. /*
  43894. ** Return the global mutex used by this PCACHE implementation. The
  43895. ** sqlite3_status() routine needs access to this mutex.
  43896. */
  43897. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  43898. return pcache1.mutex;
  43899. }
  43900. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43901. /*
  43902. ** This function is called to free superfluous dynamically allocated memory
  43903. ** held by the pager system. Memory in use by any SQLite pager allocated
  43904. ** by the current thread may be sqlite3_free()ed.
  43905. **
  43906. ** nReq is the number of bytes of memory required. Once this much has
  43907. ** been released, the function returns. The return value is the total number
  43908. ** of bytes of memory released.
  43909. */
  43910. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  43911. int nFree = 0;
  43912. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  43913. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  43914. if( sqlite3GlobalConfig.pPage==0 ){
  43915. PgHdr1 *p;
  43916. pcache1EnterMutex(&pcache1.grp);
  43917. while( (nReq<0 || nFree<nReq)
  43918. && (p=pcache1.grp.lru.pLruPrev)!=0
  43919. && p->isAnchor==0
  43920. ){
  43921. nFree += pcache1MemSize(p->page.pBuf);
  43922. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  43923. nFree += sqlite3MemSize(p);
  43924. #endif
  43925. assert( PAGE_IS_UNPINNED(p) );
  43926. pcache1PinPage(p);
  43927. pcache1RemoveFromHash(p, 1);
  43928. }
  43929. pcache1LeaveMutex(&pcache1.grp);
  43930. }
  43931. return nFree;
  43932. }
  43933. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  43934. #ifdef SQLITE_TEST
  43935. /*
  43936. ** This function is used by test procedures to inspect the internal state
  43937. ** of the global cache.
  43938. */
  43939. SQLITE_PRIVATE void sqlite3PcacheStats(
  43940. int *pnCurrent, /* OUT: Total number of pages cached */
  43941. int *pnMax, /* OUT: Global maximum cache size */
  43942. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  43943. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  43944. ){
  43945. PgHdr1 *p;
  43946. int nRecyclable = 0;
  43947. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  43948. assert( PAGE_IS_UNPINNED(p) );
  43949. nRecyclable++;
  43950. }
  43951. *pnCurrent = pcache1.grp.nPurgeable;
  43952. *pnMax = (int)pcache1.grp.nMaxPage;
  43953. *pnMin = (int)pcache1.grp.nMinPage;
  43954. *pnRecyclable = nRecyclable;
  43955. }
  43956. #endif
  43957. /************** End of pcache1.c *********************************************/
  43958. /************** Begin file rowset.c ******************************************/
  43959. /*
  43960. ** 2008 December 3
  43961. **
  43962. ** The author disclaims copyright to this source code. In place of
  43963. ** a legal notice, here is a blessing:
  43964. **
  43965. ** May you do good and not evil.
  43966. ** May you find forgiveness for yourself and forgive others.
  43967. ** May you share freely, never taking more than you give.
  43968. **
  43969. *************************************************************************
  43970. **
  43971. ** This module implements an object we call a "RowSet".
  43972. **
  43973. ** The RowSet object is a collection of rowids. Rowids
  43974. ** are inserted into the RowSet in an arbitrary order. Inserts
  43975. ** can be intermixed with tests to see if a given rowid has been
  43976. ** previously inserted into the RowSet.
  43977. **
  43978. ** After all inserts are finished, it is possible to extract the
  43979. ** elements of the RowSet in sorted order. Once this extraction
  43980. ** process has started, no new elements may be inserted.
  43981. **
  43982. ** Hence, the primitive operations for a RowSet are:
  43983. **
  43984. ** CREATE
  43985. ** INSERT
  43986. ** TEST
  43987. ** SMALLEST
  43988. ** DESTROY
  43989. **
  43990. ** The CREATE and DESTROY primitives are the constructor and destructor,
  43991. ** obviously. The INSERT primitive adds a new element to the RowSet.
  43992. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  43993. ** extracts the least value from the RowSet.
  43994. **
  43995. ** The INSERT primitive might allocate additional memory. Memory is
  43996. ** allocated in chunks so most INSERTs do no allocation. There is an
  43997. ** upper bound on the size of allocated memory. No memory is freed
  43998. ** until DESTROY.
  43999. **
  44000. ** The TEST primitive includes a "batch" number. The TEST primitive
  44001. ** will only see elements that were inserted before the last change
  44002. ** in the batch number. In other words, if an INSERT occurs between
  44003. ** two TESTs where the TESTs have the same batch nubmer, then the
  44004. ** value added by the INSERT will not be visible to the second TEST.
  44005. ** The initial batch number is zero, so if the very first TEST contains
  44006. ** a non-zero batch number, it will see all prior INSERTs.
  44007. **
  44008. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  44009. ** that is attempted.
  44010. **
  44011. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  44012. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  44013. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  44014. ** The cost of a TEST using the same batch number is O(logN). The cost
  44015. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  44016. ** primitives are constant time. The cost of DESTROY is O(N).
  44017. **
  44018. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  44019. ** be possible, but the feature was not used, so it was removed in order
  44020. ** to simplify the code.
  44021. */
  44022. /* #include "sqliteInt.h" */
  44023. /*
  44024. ** Target size for allocation chunks.
  44025. */
  44026. #define ROWSET_ALLOCATION_SIZE 1024
  44027. /*
  44028. ** The number of rowset entries per allocation chunk.
  44029. */
  44030. #define ROWSET_ENTRY_PER_CHUNK \
  44031. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  44032. /*
  44033. ** Each entry in a RowSet is an instance of the following object.
  44034. **
  44035. ** This same object is reused to store a linked list of trees of RowSetEntry
  44036. ** objects. In that alternative use, pRight points to the next entry
  44037. ** in the list, pLeft points to the tree, and v is unused. The
  44038. ** RowSet.pForest value points to the head of this forest list.
  44039. */
  44040. struct RowSetEntry {
  44041. i64 v; /* ROWID value for this entry */
  44042. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  44043. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  44044. };
  44045. /*
  44046. ** RowSetEntry objects are allocated in large chunks (instances of the
  44047. ** following structure) to reduce memory allocation overhead. The
  44048. ** chunks are kept on a linked list so that they can be deallocated
  44049. ** when the RowSet is destroyed.
  44050. */
  44051. struct RowSetChunk {
  44052. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  44053. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  44054. };
  44055. /*
  44056. ** A RowSet in an instance of the following structure.
  44057. **
  44058. ** A typedef of this structure if found in sqliteInt.h.
  44059. */
  44060. struct RowSet {
  44061. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  44062. sqlite3 *db; /* The database connection */
  44063. struct RowSetEntry *pEntry; /* List of entries using pRight */
  44064. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  44065. struct RowSetEntry *pFresh; /* Source of new entry objects */
  44066. struct RowSetEntry *pForest; /* List of binary trees of entries */
  44067. u16 nFresh; /* Number of objects on pFresh */
  44068. u16 rsFlags; /* Various flags */
  44069. int iBatch; /* Current insert batch */
  44070. };
  44071. /*
  44072. ** Allowed values for RowSet.rsFlags
  44073. */
  44074. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  44075. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  44076. /*
  44077. ** Turn bulk memory into a RowSet object. N bytes of memory
  44078. ** are available at pSpace. The db pointer is used as a memory context
  44079. ** for any subsequent allocations that need to occur.
  44080. ** Return a pointer to the new RowSet object.
  44081. **
  44082. ** It must be the case that N is sufficient to make a Rowset. If not
  44083. ** an assertion fault occurs.
  44084. **
  44085. ** If N is larger than the minimum, use the surplus as an initial
  44086. ** allocation of entries available to be filled.
  44087. */
  44088. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  44089. RowSet *p;
  44090. assert( N >= ROUND8(sizeof(*p)) );
  44091. p = pSpace;
  44092. p->pChunk = 0;
  44093. p->db = db;
  44094. p->pEntry = 0;
  44095. p->pLast = 0;
  44096. p->pForest = 0;
  44097. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  44098. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  44099. p->rsFlags = ROWSET_SORTED;
  44100. p->iBatch = 0;
  44101. return p;
  44102. }
  44103. /*
  44104. ** Deallocate all chunks from a RowSet. This frees all memory that
  44105. ** the RowSet has allocated over its lifetime. This routine is
  44106. ** the destructor for the RowSet.
  44107. */
  44108. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  44109. struct RowSetChunk *pChunk, *pNextChunk;
  44110. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  44111. pNextChunk = pChunk->pNextChunk;
  44112. sqlite3DbFree(p->db, pChunk);
  44113. }
  44114. p->pChunk = 0;
  44115. p->nFresh = 0;
  44116. p->pEntry = 0;
  44117. p->pLast = 0;
  44118. p->pForest = 0;
  44119. p->rsFlags = ROWSET_SORTED;
  44120. }
  44121. /*
  44122. ** Allocate a new RowSetEntry object that is associated with the
  44123. ** given RowSet. Return a pointer to the new and completely uninitialized
  44124. ** objected.
  44125. **
  44126. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  44127. ** routine returns NULL.
  44128. */
  44129. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  44130. assert( p!=0 );
  44131. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  44132. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  44133. ** is more efficient to pull a preallocated entry from the pool */
  44134. struct RowSetChunk *pNew;
  44135. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  44136. if( pNew==0 ){
  44137. return 0;
  44138. }
  44139. pNew->pNextChunk = p->pChunk;
  44140. p->pChunk = pNew;
  44141. p->pFresh = pNew->aEntry;
  44142. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  44143. }
  44144. p->nFresh--;
  44145. return p->pFresh++;
  44146. }
  44147. /*
  44148. ** Insert a new value into a RowSet.
  44149. **
  44150. ** The mallocFailed flag of the database connection is set if a
  44151. ** memory allocation fails.
  44152. */
  44153. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  44154. struct RowSetEntry *pEntry; /* The new entry */
  44155. struct RowSetEntry *pLast; /* The last prior entry */
  44156. /* This routine is never called after sqlite3RowSetNext() */
  44157. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  44158. pEntry = rowSetEntryAlloc(p);
  44159. if( pEntry==0 ) return;
  44160. pEntry->v = rowid;
  44161. pEntry->pRight = 0;
  44162. pLast = p->pLast;
  44163. if( pLast ){
  44164. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  44165. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  44166. ** where possible */
  44167. p->rsFlags &= ~ROWSET_SORTED;
  44168. }
  44169. pLast->pRight = pEntry;
  44170. }else{
  44171. p->pEntry = pEntry;
  44172. }
  44173. p->pLast = pEntry;
  44174. }
  44175. /*
  44176. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  44177. **
  44178. ** The input lists are connected via pRight pointers and are
  44179. ** assumed to each already be in sorted order.
  44180. */
  44181. static struct RowSetEntry *rowSetEntryMerge(
  44182. struct RowSetEntry *pA, /* First sorted list to be merged */
  44183. struct RowSetEntry *pB /* Second sorted list to be merged */
  44184. ){
  44185. struct RowSetEntry head;
  44186. struct RowSetEntry *pTail;
  44187. pTail = &head;
  44188. assert( pA!=0 && pB!=0 );
  44189. for(;;){
  44190. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  44191. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  44192. if( pA->v<=pB->v ){
  44193. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  44194. pA = pA->pRight;
  44195. if( pA==0 ){
  44196. pTail->pRight = pB;
  44197. break;
  44198. }
  44199. }else{
  44200. pTail = pTail->pRight = pB;
  44201. pB = pB->pRight;
  44202. if( pB==0 ){
  44203. pTail->pRight = pA;
  44204. break;
  44205. }
  44206. }
  44207. }
  44208. return head.pRight;
  44209. }
  44210. /*
  44211. ** Sort all elements on the list of RowSetEntry objects into order of
  44212. ** increasing v.
  44213. */
  44214. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  44215. unsigned int i;
  44216. struct RowSetEntry *pNext, *aBucket[40];
  44217. memset(aBucket, 0, sizeof(aBucket));
  44218. while( pIn ){
  44219. pNext = pIn->pRight;
  44220. pIn->pRight = 0;
  44221. for(i=0; aBucket[i]; i++){
  44222. pIn = rowSetEntryMerge(aBucket[i], pIn);
  44223. aBucket[i] = 0;
  44224. }
  44225. aBucket[i] = pIn;
  44226. pIn = pNext;
  44227. }
  44228. pIn = aBucket[0];
  44229. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  44230. if( aBucket[i]==0 ) continue;
  44231. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  44232. }
  44233. return pIn;
  44234. }
  44235. /*
  44236. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  44237. ** Convert this tree into a linked list connected by the pRight pointers
  44238. ** and return pointers to the first and last elements of the new list.
  44239. */
  44240. static void rowSetTreeToList(
  44241. struct RowSetEntry *pIn, /* Root of the input tree */
  44242. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  44243. struct RowSetEntry **ppLast /* Write tail of the output list here */
  44244. ){
  44245. assert( pIn!=0 );
  44246. if( pIn->pLeft ){
  44247. struct RowSetEntry *p;
  44248. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  44249. p->pRight = pIn;
  44250. }else{
  44251. *ppFirst = pIn;
  44252. }
  44253. if( pIn->pRight ){
  44254. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  44255. }else{
  44256. *ppLast = pIn;
  44257. }
  44258. assert( (*ppLast)->pRight==0 );
  44259. }
  44260. /*
  44261. ** Convert a sorted list of elements (connected by pRight) into a binary
  44262. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  44263. ** node taken from the head of *ppList. A depth of 2 means a tree with
  44264. ** three nodes. And so forth.
  44265. **
  44266. ** Use as many entries from the input list as required and update the
  44267. ** *ppList to point to the unused elements of the list. If the input
  44268. ** list contains too few elements, then construct an incomplete tree
  44269. ** and leave *ppList set to NULL.
  44270. **
  44271. ** Return a pointer to the root of the constructed binary tree.
  44272. */
  44273. static struct RowSetEntry *rowSetNDeepTree(
  44274. struct RowSetEntry **ppList,
  44275. int iDepth
  44276. ){
  44277. struct RowSetEntry *p; /* Root of the new tree */
  44278. struct RowSetEntry *pLeft; /* Left subtree */
  44279. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  44280. /* Prevent unnecessary deep recursion when we run out of entries */
  44281. return 0;
  44282. }
  44283. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  44284. /* This branch causes a *balanced* tree to be generated. A valid tree
  44285. ** is still generated without this branch, but the tree is wildly
  44286. ** unbalanced and inefficient. */
  44287. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  44288. p = *ppList;
  44289. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  44290. /* It is safe to always return here, but the resulting tree
  44291. ** would be unbalanced */
  44292. return pLeft;
  44293. }
  44294. p->pLeft = pLeft;
  44295. *ppList = p->pRight;
  44296. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  44297. }else{
  44298. p = *ppList;
  44299. *ppList = p->pRight;
  44300. p->pLeft = p->pRight = 0;
  44301. }
  44302. return p;
  44303. }
  44304. /*
  44305. ** Convert a sorted list of elements into a binary tree. Make the tree
  44306. ** as deep as it needs to be in order to contain the entire list.
  44307. */
  44308. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  44309. int iDepth; /* Depth of the tree so far */
  44310. struct RowSetEntry *p; /* Current tree root */
  44311. struct RowSetEntry *pLeft; /* Left subtree */
  44312. assert( pList!=0 );
  44313. p = pList;
  44314. pList = p->pRight;
  44315. p->pLeft = p->pRight = 0;
  44316. for(iDepth=1; pList; iDepth++){
  44317. pLeft = p;
  44318. p = pList;
  44319. pList = p->pRight;
  44320. p->pLeft = pLeft;
  44321. p->pRight = rowSetNDeepTree(&pList, iDepth);
  44322. }
  44323. return p;
  44324. }
  44325. /*
  44326. ** Extract the smallest element from the RowSet.
  44327. ** Write the element into *pRowid. Return 1 on success. Return
  44328. ** 0 if the RowSet is already empty.
  44329. **
  44330. ** After this routine has been called, the sqlite3RowSetInsert()
  44331. ** routine may not be called again.
  44332. **
  44333. ** This routine may not be called after sqlite3RowSetTest() has
  44334. ** been used. Older versions of RowSet allowed that, but as the
  44335. ** capability was not used by the code generator, it was removed
  44336. ** for code economy.
  44337. */
  44338. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  44339. assert( p!=0 );
  44340. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  44341. /* Merge the forest into a single sorted list on first call */
  44342. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  44343. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  44344. p->pEntry = rowSetEntrySort(p->pEntry);
  44345. }
  44346. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  44347. }
  44348. /* Return the next entry on the list */
  44349. if( p->pEntry ){
  44350. *pRowid = p->pEntry->v;
  44351. p->pEntry = p->pEntry->pRight;
  44352. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  44353. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  44354. sqlite3RowSetClear(p);
  44355. }
  44356. return 1;
  44357. }else{
  44358. return 0;
  44359. }
  44360. }
  44361. /*
  44362. ** Check to see if element iRowid was inserted into the rowset as
  44363. ** part of any insert batch prior to iBatch. Return 1 or 0.
  44364. **
  44365. ** If this is the first test of a new batch and if there exist entries
  44366. ** on pRowSet->pEntry, then sort those entries into the forest at
  44367. ** pRowSet->pForest so that they can be tested.
  44368. */
  44369. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  44370. struct RowSetEntry *p, *pTree;
  44371. /* This routine is never called after sqlite3RowSetNext() */
  44372. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  44373. /* Sort entries into the forest on the first test of a new batch.
  44374. ** To save unnecessary work, only do this when the batch number changes.
  44375. */
  44376. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  44377. p = pRowSet->pEntry;
  44378. if( p ){
  44379. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  44380. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  44381. /* Only sort the current set of entiries if they need it */
  44382. p = rowSetEntrySort(p);
  44383. }
  44384. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  44385. ppPrevTree = &pTree->pRight;
  44386. if( pTree->pLeft==0 ){
  44387. pTree->pLeft = rowSetListToTree(p);
  44388. break;
  44389. }else{
  44390. struct RowSetEntry *pAux, *pTail;
  44391. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  44392. pTree->pLeft = 0;
  44393. p = rowSetEntryMerge(pAux, p);
  44394. }
  44395. }
  44396. if( pTree==0 ){
  44397. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  44398. if( pTree ){
  44399. pTree->v = 0;
  44400. pTree->pRight = 0;
  44401. pTree->pLeft = rowSetListToTree(p);
  44402. }
  44403. }
  44404. pRowSet->pEntry = 0;
  44405. pRowSet->pLast = 0;
  44406. pRowSet->rsFlags |= ROWSET_SORTED;
  44407. }
  44408. pRowSet->iBatch = iBatch;
  44409. }
  44410. /* Test to see if the iRowid value appears anywhere in the forest.
  44411. ** Return 1 if it does and 0 if not.
  44412. */
  44413. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  44414. p = pTree->pLeft;
  44415. while( p ){
  44416. if( p->v<iRowid ){
  44417. p = p->pRight;
  44418. }else if( p->v>iRowid ){
  44419. p = p->pLeft;
  44420. }else{
  44421. return 1;
  44422. }
  44423. }
  44424. }
  44425. return 0;
  44426. }
  44427. /************** End of rowset.c **********************************************/
  44428. /************** Begin file pager.c *******************************************/
  44429. /*
  44430. ** 2001 September 15
  44431. **
  44432. ** The author disclaims copyright to this source code. In place of
  44433. ** a legal notice, here is a blessing:
  44434. **
  44435. ** May you do good and not evil.
  44436. ** May you find forgiveness for yourself and forgive others.
  44437. ** May you share freely, never taking more than you give.
  44438. **
  44439. *************************************************************************
  44440. ** This is the implementation of the page cache subsystem or "pager".
  44441. **
  44442. ** The pager is used to access a database disk file. It implements
  44443. ** atomic commit and rollback through the use of a journal file that
  44444. ** is separate from the database file. The pager also implements file
  44445. ** locking to prevent two processes from writing the same database
  44446. ** file simultaneously, or one process from reading the database while
  44447. ** another is writing.
  44448. */
  44449. #ifndef SQLITE_OMIT_DISKIO
  44450. /* #include "sqliteInt.h" */
  44451. /************** Include wal.h in the middle of pager.c ***********************/
  44452. /************** Begin file wal.h *********************************************/
  44453. /*
  44454. ** 2010 February 1
  44455. **
  44456. ** The author disclaims copyright to this source code. In place of
  44457. ** a legal notice, here is a blessing:
  44458. **
  44459. ** May you do good and not evil.
  44460. ** May you find forgiveness for yourself and forgive others.
  44461. ** May you share freely, never taking more than you give.
  44462. **
  44463. *************************************************************************
  44464. ** This header file defines the interface to the write-ahead logging
  44465. ** system. Refer to the comments below and the header comment attached to
  44466. ** the implementation of each function in log.c for further details.
  44467. */
  44468. #ifndef SQLITE_WAL_H
  44469. #define SQLITE_WAL_H
  44470. /* #include "sqliteInt.h" */
  44471. /* Macros for extracting appropriate sync flags for either transaction
  44472. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  44473. */
  44474. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  44475. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  44476. #ifdef SQLITE_OMIT_WAL
  44477. # define sqlite3WalOpen(x,y,z) 0
  44478. # define sqlite3WalLimit(x,y)
  44479. # define sqlite3WalClose(v,w,x,y,z) 0
  44480. # define sqlite3WalBeginReadTransaction(y,z) 0
  44481. # define sqlite3WalEndReadTransaction(z)
  44482. # define sqlite3WalDbsize(y) 0
  44483. # define sqlite3WalBeginWriteTransaction(y) 0
  44484. # define sqlite3WalEndWriteTransaction(x) 0
  44485. # define sqlite3WalUndo(x,y,z) 0
  44486. # define sqlite3WalSavepoint(y,z)
  44487. # define sqlite3WalSavepointUndo(y,z) 0
  44488. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  44489. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  44490. # define sqlite3WalCallback(z) 0
  44491. # define sqlite3WalExclusiveMode(y,z) 0
  44492. # define sqlite3WalHeapMemory(z) 0
  44493. # define sqlite3WalFramesize(z) 0
  44494. # define sqlite3WalFindFrame(x,y,z) 0
  44495. # define sqlite3WalFile(x) 0
  44496. #else
  44497. #define WAL_SAVEPOINT_NDATA 4
  44498. /* Connection to a write-ahead log (WAL) file.
  44499. ** There is one object of this type for each pager.
  44500. */
  44501. typedef struct Wal Wal;
  44502. /* Open and close a connection to a write-ahead log. */
  44503. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  44504. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  44505. /* Set the limiting size of a WAL file. */
  44506. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  44507. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  44508. ** snapshot is like a read-transaction. It is the state of the database
  44509. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  44510. ** preserves the current state even if the other threads or processes
  44511. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  44512. ** transaction and releases the lock.
  44513. */
  44514. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  44515. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  44516. /* Read a page from the write-ahead log, if it is present. */
  44517. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  44518. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  44519. /* If the WAL is not empty, return the size of the database. */
  44520. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  44521. /* Obtain or release the WRITER lock. */
  44522. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  44523. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  44524. /* Undo any frames written (but not committed) to the log */
  44525. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  44526. /* Return an integer that records the current (uncommitted) write
  44527. ** position in the WAL */
  44528. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  44529. /* Move the write position of the WAL back to iFrame. Called in
  44530. ** response to a ROLLBACK TO command. */
  44531. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  44532. /* Write a frame or frames to the log. */
  44533. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  44534. /* Copy pages from the log to the database file */
  44535. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  44536. Wal *pWal, /* Write-ahead log connection */
  44537. sqlite3 *db, /* Check this handle's interrupt flag */
  44538. int eMode, /* One of PASSIVE, FULL and RESTART */
  44539. int (*xBusy)(void*), /* Function to call when busy */
  44540. void *pBusyArg, /* Context argument for xBusyHandler */
  44541. int sync_flags, /* Flags to sync db file with (or 0) */
  44542. int nBuf, /* Size of buffer nBuf */
  44543. u8 *zBuf, /* Temporary buffer to use */
  44544. int *pnLog, /* OUT: Number of frames in WAL */
  44545. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  44546. );
  44547. /* Return the value to pass to a sqlite3_wal_hook callback, the
  44548. ** number of frames in the WAL at the point of the last commit since
  44549. ** sqlite3WalCallback() was called. If no commits have occurred since
  44550. ** the last call, then return 0.
  44551. */
  44552. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  44553. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  44554. ** by the pager layer on the database file.
  44555. */
  44556. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  44557. /* Return true if the argument is non-NULL and the WAL module is using
  44558. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  44559. ** WAL module is using shared-memory, return false.
  44560. */
  44561. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  44562. #ifdef SQLITE_ENABLE_SNAPSHOT
  44563. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  44564. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  44565. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  44566. #endif
  44567. #ifdef SQLITE_ENABLE_ZIPVFS
  44568. /* If the WAL file is not empty, return the number of bytes of content
  44569. ** stored in each frame (i.e. the db page-size when the WAL was created).
  44570. */
  44571. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  44572. #endif
  44573. /* Return the sqlite3_file object for the WAL file */
  44574. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  44575. #endif /* ifndef SQLITE_OMIT_WAL */
  44576. #endif /* SQLITE_WAL_H */
  44577. /************** End of wal.h *************************************************/
  44578. /************** Continuing where we left off in pager.c **********************/
  44579. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  44580. **
  44581. ** This comment block describes invariants that hold when using a rollback
  44582. ** journal. These invariants do not apply for journal_mode=WAL,
  44583. ** journal_mode=MEMORY, or journal_mode=OFF.
  44584. **
  44585. ** Within this comment block, a page is deemed to have been synced
  44586. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  44587. ** Otherwise, the page is not synced until the xSync method of the VFS
  44588. ** is called successfully on the file containing the page.
  44589. **
  44590. ** Definition: A page of the database file is said to be "overwriteable" if
  44591. ** one or more of the following are true about the page:
  44592. **
  44593. ** (a) The original content of the page as it was at the beginning of
  44594. ** the transaction has been written into the rollback journal and
  44595. ** synced.
  44596. **
  44597. ** (b) The page was a freelist leaf page at the start of the transaction.
  44598. **
  44599. ** (c) The page number is greater than the largest page that existed in
  44600. ** the database file at the start of the transaction.
  44601. **
  44602. ** (1) A page of the database file is never overwritten unless one of the
  44603. ** following are true:
  44604. **
  44605. ** (a) The page and all other pages on the same sector are overwriteable.
  44606. **
  44607. ** (b) The atomic page write optimization is enabled, and the entire
  44608. ** transaction other than the update of the transaction sequence
  44609. ** number consists of a single page change.
  44610. **
  44611. ** (2) The content of a page written into the rollback journal exactly matches
  44612. ** both the content in the database when the rollback journal was written
  44613. ** and the content in the database at the beginning of the current
  44614. ** transaction.
  44615. **
  44616. ** (3) Writes to the database file are an integer multiple of the page size
  44617. ** in length and are aligned on a page boundary.
  44618. **
  44619. ** (4) Reads from the database file are either aligned on a page boundary and
  44620. ** an integer multiple of the page size in length or are taken from the
  44621. ** first 100 bytes of the database file.
  44622. **
  44623. ** (5) All writes to the database file are synced prior to the rollback journal
  44624. ** being deleted, truncated, or zeroed.
  44625. **
  44626. ** (6) If a master journal file is used, then all writes to the database file
  44627. ** are synced prior to the master journal being deleted.
  44628. **
  44629. ** Definition: Two databases (or the same database at two points it time)
  44630. ** are said to be "logically equivalent" if they give the same answer to
  44631. ** all queries. Note in particular the content of freelist leaf
  44632. ** pages can be changed arbitrarily without affecting the logical equivalence
  44633. ** of the database.
  44634. **
  44635. ** (7) At any time, if any subset, including the empty set and the total set,
  44636. ** of the unsynced changes to a rollback journal are removed and the
  44637. ** journal is rolled back, the resulting database file will be logically
  44638. ** equivalent to the database file at the beginning of the transaction.
  44639. **
  44640. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  44641. ** is called to restore the database file to the same size it was at
  44642. ** the beginning of the transaction. (In some VFSes, the xTruncate
  44643. ** method is a no-op, but that does not change the fact the SQLite will
  44644. ** invoke it.)
  44645. **
  44646. ** (9) Whenever the database file is modified, at least one bit in the range
  44647. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  44648. ** the EXCLUSIVE lock, thus signaling other connections on the same
  44649. ** database to flush their caches.
  44650. **
  44651. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  44652. ** than one billion transactions.
  44653. **
  44654. ** (11) A database file is well-formed at the beginning and at the conclusion
  44655. ** of every transaction.
  44656. **
  44657. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  44658. ** the database file.
  44659. **
  44660. ** (13) A SHARED lock is held on the database file while reading any
  44661. ** content out of the database file.
  44662. **
  44663. ******************************************************************************/
  44664. /*
  44665. ** Macros for troubleshooting. Normally turned off
  44666. */
  44667. #if 0
  44668. int sqlite3PagerTrace=1; /* True to enable tracing */
  44669. #define sqlite3DebugPrintf printf
  44670. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  44671. #else
  44672. #define PAGERTRACE(X)
  44673. #endif
  44674. /*
  44675. ** The following two macros are used within the PAGERTRACE() macros above
  44676. ** to print out file-descriptors.
  44677. **
  44678. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  44679. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  44680. ** struct as its argument.
  44681. */
  44682. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  44683. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  44684. /*
  44685. ** The Pager.eState variable stores the current 'state' of a pager. A
  44686. ** pager may be in any one of the seven states shown in the following
  44687. ** state diagram.
  44688. **
  44689. ** OPEN <------+------+
  44690. ** | | |
  44691. ** V | |
  44692. ** +---------> READER-------+ |
  44693. ** | | |
  44694. ** | V |
  44695. ** |<-------WRITER_LOCKED------> ERROR
  44696. ** | | ^
  44697. ** | V |
  44698. ** |<------WRITER_CACHEMOD-------->|
  44699. ** | | |
  44700. ** | V |
  44701. ** |<-------WRITER_DBMOD---------->|
  44702. ** | | |
  44703. ** | V |
  44704. ** +<------WRITER_FINISHED-------->+
  44705. **
  44706. **
  44707. ** List of state transitions and the C [function] that performs each:
  44708. **
  44709. ** OPEN -> READER [sqlite3PagerSharedLock]
  44710. ** READER -> OPEN [pager_unlock]
  44711. **
  44712. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  44713. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  44714. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  44715. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  44716. ** WRITER_*** -> READER [pager_end_transaction]
  44717. **
  44718. ** WRITER_*** -> ERROR [pager_error]
  44719. ** ERROR -> OPEN [pager_unlock]
  44720. **
  44721. **
  44722. ** OPEN:
  44723. **
  44724. ** The pager starts up in this state. Nothing is guaranteed in this
  44725. ** state - the file may or may not be locked and the database size is
  44726. ** unknown. The database may not be read or written.
  44727. **
  44728. ** * No read or write transaction is active.
  44729. ** * Any lock, or no lock at all, may be held on the database file.
  44730. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  44731. **
  44732. ** READER:
  44733. **
  44734. ** In this state all the requirements for reading the database in
  44735. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  44736. ** was) in exclusive-locking mode, a user-level read transaction is
  44737. ** open. The database size is known in this state.
  44738. **
  44739. ** A connection running with locking_mode=normal enters this state when
  44740. ** it opens a read-transaction on the database and returns to state
  44741. ** OPEN after the read-transaction is completed. However a connection
  44742. ** running in locking_mode=exclusive (including temp databases) remains in
  44743. ** this state even after the read-transaction is closed. The only way
  44744. ** a locking_mode=exclusive connection can transition from READER to OPEN
  44745. ** is via the ERROR state (see below).
  44746. **
  44747. ** * A read transaction may be active (but a write-transaction cannot).
  44748. ** * A SHARED or greater lock is held on the database file.
  44749. ** * The dbSize variable may be trusted (even if a user-level read
  44750. ** transaction is not active). The dbOrigSize and dbFileSize variables
  44751. ** may not be trusted at this point.
  44752. ** * If the database is a WAL database, then the WAL connection is open.
  44753. ** * Even if a read-transaction is not open, it is guaranteed that
  44754. ** there is no hot-journal in the file-system.
  44755. **
  44756. ** WRITER_LOCKED:
  44757. **
  44758. ** The pager moves to this state from READER when a write-transaction
  44759. ** is first opened on the database. In WRITER_LOCKED state, all locks
  44760. ** required to start a write-transaction are held, but no actual
  44761. ** modifications to the cache or database have taken place.
  44762. **
  44763. ** In rollback mode, a RESERVED or (if the transaction was opened with
  44764. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  44765. ** moving to this state, but the journal file is not written to or opened
  44766. ** to in this state. If the transaction is committed or rolled back while
  44767. ** in WRITER_LOCKED state, all that is required is to unlock the database
  44768. ** file.
  44769. **
  44770. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  44771. ** If the connection is running with locking_mode=exclusive, an attempt
  44772. ** is made to obtain an EXCLUSIVE lock on the database file.
  44773. **
  44774. ** * A write transaction is active.
  44775. ** * If the connection is open in rollback-mode, a RESERVED or greater
  44776. ** lock is held on the database file.
  44777. ** * If the connection is open in WAL-mode, a WAL write transaction
  44778. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  44779. ** called).
  44780. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  44781. ** * The contents of the pager cache have not been modified.
  44782. ** * The journal file may or may not be open.
  44783. ** * Nothing (not even the first header) has been written to the journal.
  44784. **
  44785. ** WRITER_CACHEMOD:
  44786. **
  44787. ** A pager moves from WRITER_LOCKED state to this state when a page is
  44788. ** first modified by the upper layer. In rollback mode the journal file
  44789. ** is opened (if it is not already open) and a header written to the
  44790. ** start of it. The database file on disk has not been modified.
  44791. **
  44792. ** * A write transaction is active.
  44793. ** * A RESERVED or greater lock is held on the database file.
  44794. ** * The journal file is open and the first header has been written
  44795. ** to it, but the header has not been synced to disk.
  44796. ** * The contents of the page cache have been modified.
  44797. **
  44798. ** WRITER_DBMOD:
  44799. **
  44800. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  44801. ** when it modifies the contents of the database file. WAL connections
  44802. ** never enter this state (since they do not modify the database file,
  44803. ** just the log file).
  44804. **
  44805. ** * A write transaction is active.
  44806. ** * An EXCLUSIVE or greater lock is held on the database file.
  44807. ** * The journal file is open and the first header has been written
  44808. ** and synced to disk.
  44809. ** * The contents of the page cache have been modified (and possibly
  44810. ** written to disk).
  44811. **
  44812. ** WRITER_FINISHED:
  44813. **
  44814. ** It is not possible for a WAL connection to enter this state.
  44815. **
  44816. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  44817. ** state after the entire transaction has been successfully written into the
  44818. ** database file. In this state the transaction may be committed simply
  44819. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  44820. ** not possible to modify the database further. At this point, the upper
  44821. ** layer must either commit or rollback the transaction.
  44822. **
  44823. ** * A write transaction is active.
  44824. ** * An EXCLUSIVE or greater lock is held on the database file.
  44825. ** * All writing and syncing of journal and database data has finished.
  44826. ** If no error occurred, all that remains is to finalize the journal to
  44827. ** commit the transaction. If an error did occur, the caller will need
  44828. ** to rollback the transaction.
  44829. **
  44830. ** ERROR:
  44831. **
  44832. ** The ERROR state is entered when an IO or disk-full error (including
  44833. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  44834. ** difficult to be sure that the in-memory pager state (cache contents,
  44835. ** db size etc.) are consistent with the contents of the file-system.
  44836. **
  44837. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  44838. ** cannot.
  44839. **
  44840. ** For example, if an IO error occurs while performing a rollback,
  44841. ** the contents of the page-cache may be left in an inconsistent state.
  44842. ** At this point it would be dangerous to change back to READER state
  44843. ** (as usually happens after a rollback). Any subsequent readers might
  44844. ** report database corruption (due to the inconsistent cache), and if
  44845. ** they upgrade to writers, they may inadvertently corrupt the database
  44846. ** file. To avoid this hazard, the pager switches into the ERROR state
  44847. ** instead of READER following such an error.
  44848. **
  44849. ** Once it has entered the ERROR state, any attempt to use the pager
  44850. ** to read or write data returns an error. Eventually, once all
  44851. ** outstanding transactions have been abandoned, the pager is able to
  44852. ** transition back to OPEN state, discarding the contents of the
  44853. ** page-cache and any other in-memory state at the same time. Everything
  44854. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  44855. ** when a read-transaction is next opened on the pager (transitioning
  44856. ** the pager into READER state). At that point the system has recovered
  44857. ** from the error.
  44858. **
  44859. ** Specifically, the pager jumps into the ERROR state if:
  44860. **
  44861. ** 1. An error occurs while attempting a rollback. This happens in
  44862. ** function sqlite3PagerRollback().
  44863. **
  44864. ** 2. An error occurs while attempting to finalize a journal file
  44865. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  44866. **
  44867. ** 3. An error occurs while attempting to write to the journal or
  44868. ** database file in function pagerStress() in order to free up
  44869. ** memory.
  44870. **
  44871. ** In other cases, the error is returned to the b-tree layer. The b-tree
  44872. ** layer then attempts a rollback operation. If the error condition
  44873. ** persists, the pager enters the ERROR state via condition (1) above.
  44874. **
  44875. ** Condition (3) is necessary because it can be triggered by a read-only
  44876. ** statement executed within a transaction. In this case, if the error
  44877. ** code were simply returned to the user, the b-tree layer would not
  44878. ** automatically attempt a rollback, as it assumes that an error in a
  44879. ** read-only statement cannot leave the pager in an internally inconsistent
  44880. ** state.
  44881. **
  44882. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  44883. ** * There are one or more outstanding references to pages (after the
  44884. ** last reference is dropped the pager should move back to OPEN state).
  44885. ** * The pager is not an in-memory pager.
  44886. **
  44887. **
  44888. ** Notes:
  44889. **
  44890. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  44891. ** connection is open in WAL mode. A WAL connection is always in one
  44892. ** of the first four states.
  44893. **
  44894. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  44895. ** state. There are two exceptions: immediately after exclusive-mode has
  44896. ** been turned on (and before any read or write transactions are
  44897. ** executed), and when the pager is leaving the "error state".
  44898. **
  44899. ** * See also: assert_pager_state().
  44900. */
  44901. #define PAGER_OPEN 0
  44902. #define PAGER_READER 1
  44903. #define PAGER_WRITER_LOCKED 2
  44904. #define PAGER_WRITER_CACHEMOD 3
  44905. #define PAGER_WRITER_DBMOD 4
  44906. #define PAGER_WRITER_FINISHED 5
  44907. #define PAGER_ERROR 6
  44908. /*
  44909. ** The Pager.eLock variable is almost always set to one of the
  44910. ** following locking-states, according to the lock currently held on
  44911. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  44912. ** This variable is kept up to date as locks are taken and released by
  44913. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  44914. **
  44915. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  44916. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  44917. ** the operation was successful. In these circumstances pagerLockDb() and
  44918. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  44919. ** when unlocking the file, and only updated when locking the file if the
  44920. ** VFS call is successful. This way, the Pager.eLock variable may be set
  44921. ** to a less exclusive (lower) value than the lock that is actually held
  44922. ** at the system level, but it is never set to a more exclusive value.
  44923. **
  44924. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  44925. ** be a few redundant xLock() calls or a lock may be held for longer than
  44926. ** required, but nothing really goes wrong.
  44927. **
  44928. ** The exception is when the database file is unlocked as the pager moves
  44929. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  44930. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  44931. ** transition, by the same pager or any other). If the call to xUnlock()
  44932. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  44933. ** can confuse the call to xCheckReservedLock() call made later as part
  44934. ** of hot-journal detection.
  44935. **
  44936. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  44937. ** lock held by this process or any others". So xCheckReservedLock may
  44938. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  44939. ** doesn't know it because of a previous error in xUnlock). If this happens
  44940. ** a hot-journal may be mistaken for a journal being created by an active
  44941. ** transaction in another process, causing SQLite to read from the database
  44942. ** without rolling it back.
  44943. **
  44944. ** To work around this, if a call to xUnlock() fails when unlocking the
  44945. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  44946. ** is only changed back to a real locking state after a successful call
  44947. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  44948. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  44949. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  44950. ** lock on the database file before attempting to roll it back. See function
  44951. ** PagerSharedLock() for more detail.
  44952. **
  44953. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  44954. ** PAGER_OPEN state.
  44955. */
  44956. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  44957. /*
  44958. ** A macro used for invoking the codec if there is one
  44959. */
  44960. #ifdef SQLITE_HAS_CODEC
  44961. # define CODEC1(P,D,N,X,E) \
  44962. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  44963. # define CODEC2(P,D,N,X,E,O) \
  44964. if( P->xCodec==0 ){ O=(char*)D; }else \
  44965. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  44966. #else
  44967. # define CODEC1(P,D,N,X,E) /* NO-OP */
  44968. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  44969. #endif
  44970. /*
  44971. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  44972. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  44973. ** This could conceivably cause corruption following a power failure on
  44974. ** such a system. This is currently an undocumented limit.
  44975. */
  44976. #define MAX_SECTOR_SIZE 0x10000
  44977. /*
  44978. ** An instance of the following structure is allocated for each active
  44979. ** savepoint and statement transaction in the system. All such structures
  44980. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  44981. ** resized using sqlite3Realloc().
  44982. **
  44983. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  44984. ** set to 0. If a journal-header is written into the main journal while
  44985. ** the savepoint is active, then iHdrOffset is set to the byte offset
  44986. ** immediately following the last journal record written into the main
  44987. ** journal before the journal-header. This is required during savepoint
  44988. ** rollback (see pagerPlaybackSavepoint()).
  44989. */
  44990. typedef struct PagerSavepoint PagerSavepoint;
  44991. struct PagerSavepoint {
  44992. i64 iOffset; /* Starting offset in main journal */
  44993. i64 iHdrOffset; /* See above */
  44994. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  44995. Pgno nOrig; /* Original number of pages in file */
  44996. Pgno iSubRec; /* Index of first record in sub-journal */
  44997. #ifndef SQLITE_OMIT_WAL
  44998. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  44999. #endif
  45000. };
  45001. /*
  45002. ** Bits of the Pager.doNotSpill flag. See further description below.
  45003. */
  45004. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  45005. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  45006. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  45007. /*
  45008. ** An open page cache is an instance of struct Pager. A description of
  45009. ** some of the more important member variables follows:
  45010. **
  45011. ** eState
  45012. **
  45013. ** The current 'state' of the pager object. See the comment and state
  45014. ** diagram above for a description of the pager state.
  45015. **
  45016. ** eLock
  45017. **
  45018. ** For a real on-disk database, the current lock held on the database file -
  45019. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  45020. **
  45021. ** For a temporary or in-memory database (neither of which require any
  45022. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  45023. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  45024. ** logic into thinking that it already has all the locks it will ever
  45025. ** need (and no reason to release them).
  45026. **
  45027. ** In some (obscure) circumstances, this variable may also be set to
  45028. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  45029. ** details.
  45030. **
  45031. ** changeCountDone
  45032. **
  45033. ** This boolean variable is used to make sure that the change-counter
  45034. ** (the 4-byte header field at byte offset 24 of the database file) is
  45035. ** not updated more often than necessary.
  45036. **
  45037. ** It is set to true when the change-counter field is updated, which
  45038. ** can only happen if an exclusive lock is held on the database file.
  45039. ** It is cleared (set to false) whenever an exclusive lock is
  45040. ** relinquished on the database file. Each time a transaction is committed,
  45041. ** The changeCountDone flag is inspected. If it is true, the work of
  45042. ** updating the change-counter is omitted for the current transaction.
  45043. **
  45044. ** This mechanism means that when running in exclusive mode, a connection
  45045. ** need only update the change-counter once, for the first transaction
  45046. ** committed.
  45047. **
  45048. ** setMaster
  45049. **
  45050. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  45051. ** (or may not) specify a master-journal name to be written into the
  45052. ** journal file before it is synced to disk.
  45053. **
  45054. ** Whether or not a journal file contains a master-journal pointer affects
  45055. ** the way in which the journal file is finalized after the transaction is
  45056. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  45057. ** If a journal file does not contain a master-journal pointer, it is
  45058. ** finalized by overwriting the first journal header with zeroes. If
  45059. ** it does contain a master-journal pointer the journal file is finalized
  45060. ** by truncating it to zero bytes, just as if the connection were
  45061. ** running in "journal_mode=truncate" mode.
  45062. **
  45063. ** Journal files that contain master journal pointers cannot be finalized
  45064. ** simply by overwriting the first journal-header with zeroes, as the
  45065. ** master journal pointer could interfere with hot-journal rollback of any
  45066. ** subsequently interrupted transaction that reuses the journal file.
  45067. **
  45068. ** The flag is cleared as soon as the journal file is finalized (either
  45069. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  45070. ** journal file from being successfully finalized, the setMaster flag
  45071. ** is cleared anyway (and the pager will move to ERROR state).
  45072. **
  45073. ** doNotSpill
  45074. **
  45075. ** This variables control the behavior of cache-spills (calls made by
  45076. ** the pcache module to the pagerStress() routine to write cached data
  45077. ** to the file-system in order to free up memory).
  45078. **
  45079. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  45080. ** writing to the database from pagerStress() is disabled altogether.
  45081. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  45082. ** comes up during savepoint rollback that requires the pcache module
  45083. ** to allocate a new page to prevent the journal file from being written
  45084. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  45085. ** case is a user preference.
  45086. **
  45087. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  45088. ** pagerStress() is permitted, but syncing the journal file is not.
  45089. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  45090. ** is larger than the database page-size in order to prevent a journal sync
  45091. ** from happening in between the journalling of two pages on the same sector.
  45092. **
  45093. ** subjInMemory
  45094. **
  45095. ** This is a boolean variable. If true, then any required sub-journal
  45096. ** is opened as an in-memory journal file. If false, then in-memory
  45097. ** sub-journals are only used for in-memory pager files.
  45098. **
  45099. ** This variable is updated by the upper layer each time a new
  45100. ** write-transaction is opened.
  45101. **
  45102. ** dbSize, dbOrigSize, dbFileSize
  45103. **
  45104. ** Variable dbSize is set to the number of pages in the database file.
  45105. ** It is valid in PAGER_READER and higher states (all states except for
  45106. ** OPEN and ERROR).
  45107. **
  45108. ** dbSize is set based on the size of the database file, which may be
  45109. ** larger than the size of the database (the value stored at offset
  45110. ** 28 of the database header by the btree). If the size of the file
  45111. ** is not an integer multiple of the page-size, the value stored in
  45112. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  45113. ** Except, any file that is greater than 0 bytes in size is considered
  45114. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  45115. ** to dbSize==1).
  45116. **
  45117. ** During a write-transaction, if pages with page-numbers greater than
  45118. ** dbSize are modified in the cache, dbSize is updated accordingly.
  45119. ** Similarly, if the database is truncated using PagerTruncateImage(),
  45120. ** dbSize is updated.
  45121. **
  45122. ** Variables dbOrigSize and dbFileSize are valid in states
  45123. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  45124. ** variable at the start of the transaction. It is used during rollback,
  45125. ** and to determine whether or not pages need to be journalled before
  45126. ** being modified.
  45127. **
  45128. ** Throughout a write-transaction, dbFileSize contains the size of
  45129. ** the file on disk in pages. It is set to a copy of dbSize when the
  45130. ** write-transaction is first opened, and updated when VFS calls are made
  45131. ** to write or truncate the database file on disk.
  45132. **
  45133. ** The only reason the dbFileSize variable is required is to suppress
  45134. ** unnecessary calls to xTruncate() after committing a transaction. If,
  45135. ** when a transaction is committed, the dbFileSize variable indicates
  45136. ** that the database file is larger than the database image (Pager.dbSize),
  45137. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  45138. ** to measure the database file on disk, and then truncates it if required.
  45139. ** dbFileSize is not used when rolling back a transaction. In this case
  45140. ** pager_truncate() is called unconditionally (which means there may be
  45141. ** a call to xFilesize() that is not strictly required). In either case,
  45142. ** pager_truncate() may cause the file to become smaller or larger.
  45143. **
  45144. ** dbHintSize
  45145. **
  45146. ** The dbHintSize variable is used to limit the number of calls made to
  45147. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  45148. **
  45149. ** dbHintSize is set to a copy of the dbSize variable when a
  45150. ** write-transaction is opened (at the same time as dbFileSize and
  45151. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  45152. ** dbHintSize is increased to the number of pages that correspond to the
  45153. ** size-hint passed to the method call. See pager_write_pagelist() for
  45154. ** details.
  45155. **
  45156. ** errCode
  45157. **
  45158. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  45159. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  45160. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  45161. ** sub-codes.
  45162. **
  45163. ** syncFlags, walSyncFlags
  45164. **
  45165. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  45166. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  45167. ** and contains the flags used to sync the checkpoint operations in the
  45168. ** lower two bits, and sync flags used for transaction commits in the WAL
  45169. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  45170. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  45171. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  45172. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  45173. ** meaning that the 0x04 and 0x08 bits are both zero.
  45174. */
  45175. struct Pager {
  45176. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  45177. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  45178. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  45179. u8 useJournal; /* Use a rollback journal on this file */
  45180. u8 noSync; /* Do not sync the journal if true */
  45181. u8 fullSync; /* Do extra syncs of the journal for robustness */
  45182. u8 extraSync; /* sync directory after journal delete */
  45183. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  45184. u8 walSyncFlags; /* See description above */
  45185. u8 tempFile; /* zFilename is a temporary or immutable file */
  45186. u8 noLock; /* Do not lock (except in WAL mode) */
  45187. u8 readOnly; /* True for a read-only database */
  45188. u8 memDb; /* True to inhibit all file I/O */
  45189. /**************************************************************************
  45190. ** The following block contains those class members that change during
  45191. ** routine operation. Class members not in this block are either fixed
  45192. ** when the pager is first created or else only change when there is a
  45193. ** significant mode change (such as changing the page_size, locking_mode,
  45194. ** or the journal_mode). From another view, these class members describe
  45195. ** the "state" of the pager, while other class members describe the
  45196. ** "configuration" of the pager.
  45197. */
  45198. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  45199. u8 eLock; /* Current lock held on database file */
  45200. u8 changeCountDone; /* Set after incrementing the change-counter */
  45201. u8 setMaster; /* True if a m-j name has been written to jrnl */
  45202. u8 doNotSpill; /* Do not spill the cache when non-zero */
  45203. u8 subjInMemory; /* True to use in-memory sub-journals */
  45204. u8 bUseFetch; /* True to use xFetch() */
  45205. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  45206. Pgno dbSize; /* Number of pages in the database */
  45207. Pgno dbOrigSize; /* dbSize before the current transaction */
  45208. Pgno dbFileSize; /* Number of pages in the database file */
  45209. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  45210. int errCode; /* One of several kinds of errors */
  45211. int nRec; /* Pages journalled since last j-header written */
  45212. u32 cksumInit; /* Quasi-random value added to every checksum */
  45213. u32 nSubRec; /* Number of records written to sub-journal */
  45214. Bitvec *pInJournal; /* One bit for each page in the database file */
  45215. sqlite3_file *fd; /* File descriptor for database */
  45216. sqlite3_file *jfd; /* File descriptor for main journal */
  45217. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  45218. i64 journalOff; /* Current write offset in the journal file */
  45219. i64 journalHdr; /* Byte offset to previous journal header */
  45220. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  45221. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  45222. int nSavepoint; /* Number of elements in aSavepoint[] */
  45223. u32 iDataVersion; /* Changes whenever database content changes */
  45224. char dbFileVers[16]; /* Changes whenever database file changes */
  45225. int nMmapOut; /* Number of mmap pages currently outstanding */
  45226. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  45227. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  45228. /*
  45229. ** End of the routinely-changing class members
  45230. ***************************************************************************/
  45231. u16 nExtra; /* Add this many bytes to each in-memory page */
  45232. i16 nReserve; /* Number of unused bytes at end of each page */
  45233. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  45234. u32 sectorSize; /* Assumed sector size during rollback */
  45235. int pageSize; /* Number of bytes in a page */
  45236. Pgno mxPgno; /* Maximum allowed size of the database */
  45237. i64 journalSizeLimit; /* Size limit for persistent journal files */
  45238. char *zFilename; /* Name of the database file */
  45239. char *zJournal; /* Name of the journal file */
  45240. int (*xBusyHandler)(void*); /* Function to call when busy */
  45241. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  45242. int aStat[3]; /* Total cache hits, misses and writes */
  45243. #ifdef SQLITE_TEST
  45244. int nRead; /* Database pages read */
  45245. #endif
  45246. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  45247. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  45248. #ifdef SQLITE_HAS_CODEC
  45249. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  45250. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  45251. void (*xCodecFree)(void*); /* Destructor for the codec */
  45252. void *pCodec; /* First argument to xCodec... methods */
  45253. #endif
  45254. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  45255. PCache *pPCache; /* Pointer to page cache object */
  45256. #ifndef SQLITE_OMIT_WAL
  45257. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  45258. char *zWal; /* File name for write-ahead log */
  45259. #endif
  45260. };
  45261. /*
  45262. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  45263. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  45264. ** or CACHE_WRITE to sqlite3_db_status().
  45265. */
  45266. #define PAGER_STAT_HIT 0
  45267. #define PAGER_STAT_MISS 1
  45268. #define PAGER_STAT_WRITE 2
  45269. /*
  45270. ** The following global variables hold counters used for
  45271. ** testing purposes only. These variables do not exist in
  45272. ** a non-testing build. These variables are not thread-safe.
  45273. */
  45274. #ifdef SQLITE_TEST
  45275. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  45276. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  45277. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  45278. # define PAGER_INCR(v) v++
  45279. #else
  45280. # define PAGER_INCR(v)
  45281. #endif
  45282. /*
  45283. ** Journal files begin with the following magic string. The data
  45284. ** was obtained from /dev/random. It is used only as a sanity check.
  45285. **
  45286. ** Since version 2.8.0, the journal format contains additional sanity
  45287. ** checking information. If the power fails while the journal is being
  45288. ** written, semi-random garbage data might appear in the journal
  45289. ** file after power is restored. If an attempt is then made
  45290. ** to roll the journal back, the database could be corrupted. The additional
  45291. ** sanity checking data is an attempt to discover the garbage in the
  45292. ** journal and ignore it.
  45293. **
  45294. ** The sanity checking information for the new journal format consists
  45295. ** of a 32-bit checksum on each page of data. The checksum covers both
  45296. ** the page number and the pPager->pageSize bytes of data for the page.
  45297. ** This cksum is initialized to a 32-bit random value that appears in the
  45298. ** journal file right after the header. The random initializer is important,
  45299. ** because garbage data that appears at the end of a journal is likely
  45300. ** data that was once in other files that have now been deleted. If the
  45301. ** garbage data came from an obsolete journal file, the checksums might
  45302. ** be correct. But by initializing the checksum to random value which
  45303. ** is different for every journal, we minimize that risk.
  45304. */
  45305. static const unsigned char aJournalMagic[] = {
  45306. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  45307. };
  45308. /*
  45309. ** The size of the of each page record in the journal is given by
  45310. ** the following macro.
  45311. */
  45312. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  45313. /*
  45314. ** The journal header size for this pager. This is usually the same
  45315. ** size as a single disk sector. See also setSectorSize().
  45316. */
  45317. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  45318. /*
  45319. ** The macro MEMDB is true if we are dealing with an in-memory database.
  45320. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  45321. ** the value of MEMDB will be a constant and the compiler will optimize
  45322. ** out code that would never execute.
  45323. */
  45324. #ifdef SQLITE_OMIT_MEMORYDB
  45325. # define MEMDB 0
  45326. #else
  45327. # define MEMDB pPager->memDb
  45328. #endif
  45329. /*
  45330. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  45331. ** interfaces to access the database using memory-mapped I/O.
  45332. */
  45333. #if SQLITE_MAX_MMAP_SIZE>0
  45334. # define USEFETCH(x) ((x)->bUseFetch)
  45335. #else
  45336. # define USEFETCH(x) 0
  45337. #endif
  45338. /*
  45339. ** The maximum legal page number is (2^31 - 1).
  45340. */
  45341. #define PAGER_MAX_PGNO 2147483647
  45342. /*
  45343. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  45344. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  45345. **
  45346. ** This is so that expressions can be written as:
  45347. **
  45348. ** if( isOpen(pPager->jfd) ){ ...
  45349. **
  45350. ** instead of
  45351. **
  45352. ** if( pPager->jfd->pMethods ){ ...
  45353. */
  45354. #define isOpen(pFd) ((pFd)->pMethods!=0)
  45355. /*
  45356. ** Return true if this pager uses a write-ahead log to read page pgno.
  45357. ** Return false if the pager reads pgno directly from the database.
  45358. */
  45359. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
  45360. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
  45361. u32 iRead = 0;
  45362. int rc;
  45363. if( pPager->pWal==0 ) return 0;
  45364. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  45365. return rc || iRead;
  45366. }
  45367. #endif
  45368. #ifndef SQLITE_OMIT_WAL
  45369. # define pagerUseWal(x) ((x)->pWal!=0)
  45370. #else
  45371. # define pagerUseWal(x) 0
  45372. # define pagerRollbackWal(x) 0
  45373. # define pagerWalFrames(v,w,x,y) 0
  45374. # define pagerOpenWalIfPresent(z) SQLITE_OK
  45375. # define pagerBeginReadTransaction(z) SQLITE_OK
  45376. #endif
  45377. #ifndef NDEBUG
  45378. /*
  45379. ** Usage:
  45380. **
  45381. ** assert( assert_pager_state(pPager) );
  45382. **
  45383. ** This function runs many asserts to try to find inconsistencies in
  45384. ** the internal state of the Pager object.
  45385. */
  45386. static int assert_pager_state(Pager *p){
  45387. Pager *pPager = p;
  45388. /* State must be valid. */
  45389. assert( p->eState==PAGER_OPEN
  45390. || p->eState==PAGER_READER
  45391. || p->eState==PAGER_WRITER_LOCKED
  45392. || p->eState==PAGER_WRITER_CACHEMOD
  45393. || p->eState==PAGER_WRITER_DBMOD
  45394. || p->eState==PAGER_WRITER_FINISHED
  45395. || p->eState==PAGER_ERROR
  45396. );
  45397. /* Regardless of the current state, a temp-file connection always behaves
  45398. ** as if it has an exclusive lock on the database file. It never updates
  45399. ** the change-counter field, so the changeCountDone flag is always set.
  45400. */
  45401. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  45402. assert( p->tempFile==0 || pPager->changeCountDone );
  45403. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  45404. ** And if the journal-mode is "OFF", the journal file must not be open.
  45405. */
  45406. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  45407. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  45408. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  45409. ** this means an in-memory pager performs no IO at all, it cannot encounter
  45410. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  45411. ** a journal file. (although the in-memory journal implementation may
  45412. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  45413. ** is therefore not possible for an in-memory pager to enter the ERROR
  45414. ** state.
  45415. */
  45416. if( MEMDB ){
  45417. assert( !isOpen(p->fd) );
  45418. assert( p->noSync );
  45419. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  45420. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  45421. );
  45422. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  45423. assert( pagerUseWal(p)==0 );
  45424. }
  45425. /* If changeCountDone is set, a RESERVED lock or greater must be held
  45426. ** on the file.
  45427. */
  45428. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  45429. assert( p->eLock!=PENDING_LOCK );
  45430. switch( p->eState ){
  45431. case PAGER_OPEN:
  45432. assert( !MEMDB );
  45433. assert( pPager->errCode==SQLITE_OK );
  45434. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  45435. break;
  45436. case PAGER_READER:
  45437. assert( pPager->errCode==SQLITE_OK );
  45438. assert( p->eLock!=UNKNOWN_LOCK );
  45439. assert( p->eLock>=SHARED_LOCK );
  45440. break;
  45441. case PAGER_WRITER_LOCKED:
  45442. assert( p->eLock!=UNKNOWN_LOCK );
  45443. assert( pPager->errCode==SQLITE_OK );
  45444. if( !pagerUseWal(pPager) ){
  45445. assert( p->eLock>=RESERVED_LOCK );
  45446. }
  45447. assert( pPager->dbSize==pPager->dbOrigSize );
  45448. assert( pPager->dbOrigSize==pPager->dbFileSize );
  45449. assert( pPager->dbOrigSize==pPager->dbHintSize );
  45450. assert( pPager->setMaster==0 );
  45451. break;
  45452. case PAGER_WRITER_CACHEMOD:
  45453. assert( p->eLock!=UNKNOWN_LOCK );
  45454. assert( pPager->errCode==SQLITE_OK );
  45455. if( !pagerUseWal(pPager) ){
  45456. /* It is possible that if journal_mode=wal here that neither the
  45457. ** journal file nor the WAL file are open. This happens during
  45458. ** a rollback transaction that switches from journal_mode=off
  45459. ** to journal_mode=wal.
  45460. */
  45461. assert( p->eLock>=RESERVED_LOCK );
  45462. assert( isOpen(p->jfd)
  45463. || p->journalMode==PAGER_JOURNALMODE_OFF
  45464. || p->journalMode==PAGER_JOURNALMODE_WAL
  45465. );
  45466. }
  45467. assert( pPager->dbOrigSize==pPager->dbFileSize );
  45468. assert( pPager->dbOrigSize==pPager->dbHintSize );
  45469. break;
  45470. case PAGER_WRITER_DBMOD:
  45471. assert( p->eLock==EXCLUSIVE_LOCK );
  45472. assert( pPager->errCode==SQLITE_OK );
  45473. assert( !pagerUseWal(pPager) );
  45474. assert( p->eLock>=EXCLUSIVE_LOCK );
  45475. assert( isOpen(p->jfd)
  45476. || p->journalMode==PAGER_JOURNALMODE_OFF
  45477. || p->journalMode==PAGER_JOURNALMODE_WAL
  45478. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  45479. );
  45480. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  45481. break;
  45482. case PAGER_WRITER_FINISHED:
  45483. assert( p->eLock==EXCLUSIVE_LOCK );
  45484. assert( pPager->errCode==SQLITE_OK );
  45485. assert( !pagerUseWal(pPager) );
  45486. assert( isOpen(p->jfd)
  45487. || p->journalMode==PAGER_JOURNALMODE_OFF
  45488. || p->journalMode==PAGER_JOURNALMODE_WAL
  45489. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  45490. );
  45491. break;
  45492. case PAGER_ERROR:
  45493. /* There must be at least one outstanding reference to the pager if
  45494. ** in ERROR state. Otherwise the pager should have already dropped
  45495. ** back to OPEN state.
  45496. */
  45497. assert( pPager->errCode!=SQLITE_OK );
  45498. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  45499. break;
  45500. }
  45501. return 1;
  45502. }
  45503. #endif /* ifndef NDEBUG */
  45504. #ifdef SQLITE_DEBUG
  45505. /*
  45506. ** Return a pointer to a human readable string in a static buffer
  45507. ** containing the state of the Pager object passed as an argument. This
  45508. ** is intended to be used within debuggers. For example, as an alternative
  45509. ** to "print *pPager" in gdb:
  45510. **
  45511. ** (gdb) printf "%s", print_pager_state(pPager)
  45512. */
  45513. static char *print_pager_state(Pager *p){
  45514. static char zRet[1024];
  45515. sqlite3_snprintf(1024, zRet,
  45516. "Filename: %s\n"
  45517. "State: %s errCode=%d\n"
  45518. "Lock: %s\n"
  45519. "Locking mode: locking_mode=%s\n"
  45520. "Journal mode: journal_mode=%s\n"
  45521. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  45522. "Journal: journalOff=%lld journalHdr=%lld\n"
  45523. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  45524. , p->zFilename
  45525. , p->eState==PAGER_OPEN ? "OPEN" :
  45526. p->eState==PAGER_READER ? "READER" :
  45527. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  45528. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  45529. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  45530. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  45531. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  45532. , (int)p->errCode
  45533. , p->eLock==NO_LOCK ? "NO_LOCK" :
  45534. p->eLock==RESERVED_LOCK ? "RESERVED" :
  45535. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  45536. p->eLock==SHARED_LOCK ? "SHARED" :
  45537. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  45538. , p->exclusiveMode ? "exclusive" : "normal"
  45539. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  45540. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  45541. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  45542. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  45543. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  45544. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  45545. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  45546. , p->journalOff, p->journalHdr
  45547. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  45548. );
  45549. return zRet;
  45550. }
  45551. #endif
  45552. /* Forward references to the various page getters */
  45553. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  45554. static int getPageError(Pager*,Pgno,DbPage**,int);
  45555. #if SQLITE_MAX_MMAP_SIZE>0
  45556. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  45557. #endif
  45558. /*
  45559. ** Set the Pager.xGet method for the appropriate routine used to fetch
  45560. ** content from the pager.
  45561. */
  45562. static void setGetterMethod(Pager *pPager){
  45563. if( pPager->errCode ){
  45564. pPager->xGet = getPageError;
  45565. #if SQLITE_MAX_MMAP_SIZE>0
  45566. }else if( USEFETCH(pPager)
  45567. #ifdef SQLITE_HAS_CODEC
  45568. && pPager->xCodec==0
  45569. #endif
  45570. ){
  45571. pPager->xGet = getPageMMap;
  45572. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  45573. }else{
  45574. pPager->xGet = getPageNormal;
  45575. }
  45576. }
  45577. /*
  45578. ** Return true if it is necessary to write page *pPg into the sub-journal.
  45579. ** A page needs to be written into the sub-journal if there exists one
  45580. ** or more open savepoints for which:
  45581. **
  45582. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  45583. ** * The bit corresponding to the page-number is not set in
  45584. ** PagerSavepoint.pInSavepoint.
  45585. */
  45586. static int subjRequiresPage(PgHdr *pPg){
  45587. Pager *pPager = pPg->pPager;
  45588. PagerSavepoint *p;
  45589. Pgno pgno = pPg->pgno;
  45590. int i;
  45591. for(i=0; i<pPager->nSavepoint; i++){
  45592. p = &pPager->aSavepoint[i];
  45593. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  45594. return 1;
  45595. }
  45596. }
  45597. return 0;
  45598. }
  45599. #ifdef SQLITE_DEBUG
  45600. /*
  45601. ** Return true if the page is already in the journal file.
  45602. */
  45603. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  45604. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  45605. }
  45606. #endif
  45607. /*
  45608. ** Read a 32-bit integer from the given file descriptor. Store the integer
  45609. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  45610. ** error code is something goes wrong.
  45611. **
  45612. ** All values are stored on disk as big-endian.
  45613. */
  45614. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  45615. unsigned char ac[4];
  45616. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  45617. if( rc==SQLITE_OK ){
  45618. *pRes = sqlite3Get4byte(ac);
  45619. }
  45620. return rc;
  45621. }
  45622. /*
  45623. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  45624. */
  45625. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  45626. /*
  45627. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  45628. ** on success or an error code is something goes wrong.
  45629. */
  45630. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  45631. char ac[4];
  45632. put32bits(ac, val);
  45633. return sqlite3OsWrite(fd, ac, 4, offset);
  45634. }
  45635. /*
  45636. ** Unlock the database file to level eLock, which must be either NO_LOCK
  45637. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  45638. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  45639. **
  45640. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45641. ** called, do not modify it. See the comment above the #define of
  45642. ** UNKNOWN_LOCK for an explanation of this.
  45643. */
  45644. static int pagerUnlockDb(Pager *pPager, int eLock){
  45645. int rc = SQLITE_OK;
  45646. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  45647. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  45648. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  45649. if( isOpen(pPager->fd) ){
  45650. assert( pPager->eLock>=eLock );
  45651. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  45652. if( pPager->eLock!=UNKNOWN_LOCK ){
  45653. pPager->eLock = (u8)eLock;
  45654. }
  45655. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  45656. }
  45657. return rc;
  45658. }
  45659. /*
  45660. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  45661. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  45662. ** Pager.eLock variable to the new locking state.
  45663. **
  45664. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45665. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  45666. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  45667. ** of this.
  45668. */
  45669. static int pagerLockDb(Pager *pPager, int eLock){
  45670. int rc = SQLITE_OK;
  45671. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  45672. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  45673. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  45674. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  45675. pPager->eLock = (u8)eLock;
  45676. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  45677. }
  45678. }
  45679. return rc;
  45680. }
  45681. /*
  45682. ** This function determines whether or not the atomic-write or
  45683. ** atomic-batch-write optimizations can be used with this pager. The
  45684. ** atomic-write optimization can be used if:
  45685. **
  45686. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  45687. ** a database page may be written atomically, and
  45688. ** (b) the value returned by OsSectorSize() is less than or equal
  45689. ** to the page size.
  45690. **
  45691. ** If it can be used, then the value returned is the size of the journal
  45692. ** file when it contains rollback data for exactly one page.
  45693. **
  45694. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  45695. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  45696. ** returned in this case.
  45697. **
  45698. ** If neither optimization can be used, 0 is returned.
  45699. */
  45700. static int jrnlBufferSize(Pager *pPager){
  45701. assert( !MEMDB );
  45702. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  45703. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  45704. int dc; /* Device characteristics */
  45705. assert( isOpen(pPager->fd) );
  45706. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45707. #else
  45708. UNUSED_PARAMETER(pPager);
  45709. #endif
  45710. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  45711. if( dc&SQLITE_IOCAP_BATCH_ATOMIC ){
  45712. return -1;
  45713. }
  45714. #endif
  45715. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45716. {
  45717. int nSector = pPager->sectorSize;
  45718. int szPage = pPager->pageSize;
  45719. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  45720. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  45721. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  45722. return 0;
  45723. }
  45724. }
  45725. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  45726. #endif
  45727. return 0;
  45728. }
  45729. /*
  45730. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  45731. ** on the cache using a hash function. This is used for testing
  45732. ** and debugging only.
  45733. */
  45734. #ifdef SQLITE_CHECK_PAGES
  45735. /*
  45736. ** Return a 32-bit hash of the page data for pPage.
  45737. */
  45738. static u32 pager_datahash(int nByte, unsigned char *pData){
  45739. u32 hash = 0;
  45740. int i;
  45741. for(i=0; i<nByte; i++){
  45742. hash = (hash*1039) + pData[i];
  45743. }
  45744. return hash;
  45745. }
  45746. static u32 pager_pagehash(PgHdr *pPage){
  45747. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  45748. }
  45749. static void pager_set_pagehash(PgHdr *pPage){
  45750. pPage->pageHash = pager_pagehash(pPage);
  45751. }
  45752. /*
  45753. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  45754. ** is defined, and NDEBUG is not defined, an assert() statement checks
  45755. ** that the page is either dirty or still matches the calculated page-hash.
  45756. */
  45757. #define CHECK_PAGE(x) checkPage(x)
  45758. static void checkPage(PgHdr *pPg){
  45759. Pager *pPager = pPg->pPager;
  45760. assert( pPager->eState!=PAGER_ERROR );
  45761. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  45762. }
  45763. #else
  45764. #define pager_datahash(X,Y) 0
  45765. #define pager_pagehash(X) 0
  45766. #define pager_set_pagehash(X)
  45767. #define CHECK_PAGE(x)
  45768. #endif /* SQLITE_CHECK_PAGES */
  45769. /*
  45770. ** When this is called the journal file for pager pPager must be open.
  45771. ** This function attempts to read a master journal file name from the
  45772. ** end of the file and, if successful, copies it into memory supplied
  45773. ** by the caller. See comments above writeMasterJournal() for the format
  45774. ** used to store a master journal file name at the end of a journal file.
  45775. **
  45776. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  45777. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  45778. ** enough space to write the master journal name). If the master journal
  45779. ** name in the journal is longer than nMaster bytes (including a
  45780. ** nul-terminator), then this is handled as if no master journal name
  45781. ** were present in the journal.
  45782. **
  45783. ** If a master journal file name is present at the end of the journal
  45784. ** file, then it is copied into the buffer pointed to by zMaster. A
  45785. ** nul-terminator byte is appended to the buffer following the master
  45786. ** journal file name.
  45787. **
  45788. ** If it is determined that no master journal file name is present
  45789. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  45790. **
  45791. ** If an error occurs while reading from the journal file, an SQLite
  45792. ** error code is returned.
  45793. */
  45794. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  45795. int rc; /* Return code */
  45796. u32 len; /* Length in bytes of master journal name */
  45797. i64 szJ; /* Total size in bytes of journal file pJrnl */
  45798. u32 cksum; /* MJ checksum value read from journal */
  45799. u32 u; /* Unsigned loop counter */
  45800. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  45801. zMaster[0] = '\0';
  45802. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  45803. || szJ<16
  45804. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  45805. || len>=nMaster
  45806. || len>szJ-16
  45807. || len==0
  45808. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  45809. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  45810. || memcmp(aMagic, aJournalMagic, 8)
  45811. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  45812. ){
  45813. return rc;
  45814. }
  45815. /* See if the checksum matches the master journal name */
  45816. for(u=0; u<len; u++){
  45817. cksum -= zMaster[u];
  45818. }
  45819. if( cksum ){
  45820. /* If the checksum doesn't add up, then one or more of the disk sectors
  45821. ** containing the master journal filename is corrupted. This means
  45822. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  45823. ** master-journal filename.
  45824. */
  45825. len = 0;
  45826. }
  45827. zMaster[len] = '\0';
  45828. return SQLITE_OK;
  45829. }
  45830. /*
  45831. ** Return the offset of the sector boundary at or immediately
  45832. ** following the value in pPager->journalOff, assuming a sector
  45833. ** size of pPager->sectorSize bytes.
  45834. **
  45835. ** i.e for a sector size of 512:
  45836. **
  45837. ** Pager.journalOff Return value
  45838. ** ---------------------------------------
  45839. ** 0 0
  45840. ** 512 512
  45841. ** 100 512
  45842. ** 2000 2048
  45843. **
  45844. */
  45845. static i64 journalHdrOffset(Pager *pPager){
  45846. i64 offset = 0;
  45847. i64 c = pPager->journalOff;
  45848. if( c ){
  45849. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  45850. }
  45851. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  45852. assert( offset>=c );
  45853. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  45854. return offset;
  45855. }
  45856. /*
  45857. ** The journal file must be open when this function is called.
  45858. **
  45859. ** This function is a no-op if the journal file has not been written to
  45860. ** within the current transaction (i.e. if Pager.journalOff==0).
  45861. **
  45862. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  45863. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  45864. ** zero the 28-byte header at the start of the journal file. In either case,
  45865. ** if the pager is not in no-sync mode, sync the journal file immediately
  45866. ** after writing or truncating it.
  45867. **
  45868. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  45869. ** following the truncation or zeroing described above the size of the
  45870. ** journal file in bytes is larger than this value, then truncate the
  45871. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  45872. ** not need to be synced following this operation.
  45873. **
  45874. ** If an IO error occurs, abandon processing and return the IO error code.
  45875. ** Otherwise, return SQLITE_OK.
  45876. */
  45877. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  45878. int rc = SQLITE_OK; /* Return code */
  45879. assert( isOpen(pPager->jfd) );
  45880. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  45881. if( pPager->journalOff ){
  45882. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  45883. IOTRACE(("JZEROHDR %p\n", pPager))
  45884. if( doTruncate || iLimit==0 ){
  45885. rc = sqlite3OsTruncate(pPager->jfd, 0);
  45886. }else{
  45887. static const char zeroHdr[28] = {0};
  45888. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  45889. }
  45890. if( rc==SQLITE_OK && !pPager->noSync ){
  45891. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  45892. }
  45893. /* At this point the transaction is committed but the write lock
  45894. ** is still held on the file. If there is a size limit configured for
  45895. ** the persistent journal and the journal file currently consumes more
  45896. ** space than that limit allows for, truncate it now. There is no need
  45897. ** to sync the file following this operation.
  45898. */
  45899. if( rc==SQLITE_OK && iLimit>0 ){
  45900. i64 sz;
  45901. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  45902. if( rc==SQLITE_OK && sz>iLimit ){
  45903. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  45904. }
  45905. }
  45906. }
  45907. return rc;
  45908. }
  45909. /*
  45910. ** The journal file must be open when this routine is called. A journal
  45911. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  45912. ** current location.
  45913. **
  45914. ** The format for the journal header is as follows:
  45915. ** - 8 bytes: Magic identifying journal format.
  45916. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  45917. ** - 4 bytes: Random number used for page hash.
  45918. ** - 4 bytes: Initial database page count.
  45919. ** - 4 bytes: Sector size used by the process that wrote this journal.
  45920. ** - 4 bytes: Database page size.
  45921. **
  45922. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  45923. */
  45924. static int writeJournalHdr(Pager *pPager){
  45925. int rc = SQLITE_OK; /* Return code */
  45926. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  45927. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  45928. u32 nWrite; /* Bytes of header sector written */
  45929. int ii; /* Loop counter */
  45930. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  45931. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  45932. nHeader = JOURNAL_HDR_SZ(pPager);
  45933. }
  45934. /* If there are active savepoints and any of them were created
  45935. ** since the most recent journal header was written, update the
  45936. ** PagerSavepoint.iHdrOffset fields now.
  45937. */
  45938. for(ii=0; ii<pPager->nSavepoint; ii++){
  45939. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  45940. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  45941. }
  45942. }
  45943. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  45944. /*
  45945. ** Write the nRec Field - the number of page records that follow this
  45946. ** journal header. Normally, zero is written to this value at this time.
  45947. ** After the records are added to the journal (and the journal synced,
  45948. ** if in full-sync mode), the zero is overwritten with the true number
  45949. ** of records (see syncJournal()).
  45950. **
  45951. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  45952. ** reading the journal this value tells SQLite to assume that the
  45953. ** rest of the journal file contains valid page records. This assumption
  45954. ** is dangerous, as if a failure occurred whilst writing to the journal
  45955. ** file it may contain some garbage data. There are two scenarios
  45956. ** where this risk can be ignored:
  45957. **
  45958. ** * When the pager is in no-sync mode. Corruption can follow a
  45959. ** power failure in this case anyway.
  45960. **
  45961. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  45962. ** that garbage data is never appended to the journal file.
  45963. */
  45964. assert( isOpen(pPager->fd) || pPager->noSync );
  45965. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  45966. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  45967. ){
  45968. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  45969. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  45970. }else{
  45971. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  45972. }
  45973. /* The random check-hash initializer */
  45974. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  45975. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  45976. /* The initial database size */
  45977. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  45978. /* The assumed sector size for this process */
  45979. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  45980. /* The page size */
  45981. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  45982. /* Initializing the tail of the buffer is not necessary. Everything
  45983. ** works find if the following memset() is omitted. But initializing
  45984. ** the memory prevents valgrind from complaining, so we are willing to
  45985. ** take the performance hit.
  45986. */
  45987. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  45988. nHeader-(sizeof(aJournalMagic)+20));
  45989. /* In theory, it is only necessary to write the 28 bytes that the
  45990. ** journal header consumes to the journal file here. Then increment the
  45991. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  45992. ** record is written to the following sector (leaving a gap in the file
  45993. ** that will be implicitly filled in by the OS).
  45994. **
  45995. ** However it has been discovered that on some systems this pattern can
  45996. ** be significantly slower than contiguously writing data to the file,
  45997. ** even if that means explicitly writing data to the block of
  45998. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  45999. ** is done.
  46000. **
  46001. ** The loop is required here in case the sector-size is larger than the
  46002. ** database page size. Since the zHeader buffer is only Pager.pageSize
  46003. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  46004. ** to populate the entire journal header sector.
  46005. */
  46006. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  46007. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  46008. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  46009. assert( pPager->journalHdr <= pPager->journalOff );
  46010. pPager->journalOff += nHeader;
  46011. }
  46012. return rc;
  46013. }
  46014. /*
  46015. ** The journal file must be open when this is called. A journal header file
  46016. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  46017. ** file. The current location in the journal file is given by
  46018. ** pPager->journalOff. See comments above function writeJournalHdr() for
  46019. ** a description of the journal header format.
  46020. **
  46021. ** If the header is read successfully, *pNRec is set to the number of
  46022. ** page records following this header and *pDbSize is set to the size of the
  46023. ** database before the transaction began, in pages. Also, pPager->cksumInit
  46024. ** is set to the value read from the journal header. SQLITE_OK is returned
  46025. ** in this case.
  46026. **
  46027. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  46028. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  46029. ** cannot be read from the journal file an error code is returned.
  46030. */
  46031. static int readJournalHdr(
  46032. Pager *pPager, /* Pager object */
  46033. int isHot,
  46034. i64 journalSize, /* Size of the open journal file in bytes */
  46035. u32 *pNRec, /* OUT: Value read from the nRec field */
  46036. u32 *pDbSize /* OUT: Value of original database size field */
  46037. ){
  46038. int rc; /* Return code */
  46039. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  46040. i64 iHdrOff; /* Offset of journal header being read */
  46041. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  46042. /* Advance Pager.journalOff to the start of the next sector. If the
  46043. ** journal file is too small for there to be a header stored at this
  46044. ** point, return SQLITE_DONE.
  46045. */
  46046. pPager->journalOff = journalHdrOffset(pPager);
  46047. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  46048. return SQLITE_DONE;
  46049. }
  46050. iHdrOff = pPager->journalOff;
  46051. /* Read in the first 8 bytes of the journal header. If they do not match
  46052. ** the magic string found at the start of each journal header, return
  46053. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  46054. ** proceed.
  46055. */
  46056. if( isHot || iHdrOff!=pPager->journalHdr ){
  46057. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  46058. if( rc ){
  46059. return rc;
  46060. }
  46061. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  46062. return SQLITE_DONE;
  46063. }
  46064. }
  46065. /* Read the first three 32-bit fields of the journal header: The nRec
  46066. ** field, the checksum-initializer and the database size at the start
  46067. ** of the transaction. Return an error code if anything goes wrong.
  46068. */
  46069. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  46070. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  46071. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  46072. ){
  46073. return rc;
  46074. }
  46075. if( pPager->journalOff==0 ){
  46076. u32 iPageSize; /* Page-size field of journal header */
  46077. u32 iSectorSize; /* Sector-size field of journal header */
  46078. /* Read the page-size and sector-size journal header fields. */
  46079. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  46080. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  46081. ){
  46082. return rc;
  46083. }
  46084. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  46085. ** journal header to zero. In this case, assume that the Pager.pageSize
  46086. ** variable is already set to the correct page size.
  46087. */
  46088. if( iPageSize==0 ){
  46089. iPageSize = pPager->pageSize;
  46090. }
  46091. /* Check that the values read from the page-size and sector-size fields
  46092. ** are within range. To be 'in range', both values need to be a power
  46093. ** of two greater than or equal to 512 or 32, and not greater than their
  46094. ** respective compile time maximum limits.
  46095. */
  46096. if( iPageSize<512 || iSectorSize<32
  46097. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  46098. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  46099. ){
  46100. /* If the either the page-size or sector-size in the journal-header is
  46101. ** invalid, then the process that wrote the journal-header must have
  46102. ** crashed before the header was synced. In this case stop reading
  46103. ** the journal file here.
  46104. */
  46105. return SQLITE_DONE;
  46106. }
  46107. /* Update the page-size to match the value read from the journal.
  46108. ** Use a testcase() macro to make sure that malloc failure within
  46109. ** PagerSetPagesize() is tested.
  46110. */
  46111. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  46112. testcase( rc!=SQLITE_OK );
  46113. /* Update the assumed sector-size to match the value used by
  46114. ** the process that created this journal. If this journal was
  46115. ** created by a process other than this one, then this routine
  46116. ** is being called from within pager_playback(). The local value
  46117. ** of Pager.sectorSize is restored at the end of that routine.
  46118. */
  46119. pPager->sectorSize = iSectorSize;
  46120. }
  46121. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  46122. return rc;
  46123. }
  46124. /*
  46125. ** Write the supplied master journal name into the journal file for pager
  46126. ** pPager at the current location. The master journal name must be the last
  46127. ** thing written to a journal file. If the pager is in full-sync mode, the
  46128. ** journal file descriptor is advanced to the next sector boundary before
  46129. ** anything is written. The format is:
  46130. **
  46131. ** + 4 bytes: PAGER_MJ_PGNO.
  46132. ** + N bytes: Master journal filename in utf-8.
  46133. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  46134. ** + 4 bytes: Master journal name checksum.
  46135. ** + 8 bytes: aJournalMagic[].
  46136. **
  46137. ** The master journal page checksum is the sum of the bytes in the master
  46138. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  46139. **
  46140. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  46141. ** this call is a no-op.
  46142. */
  46143. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  46144. int rc; /* Return code */
  46145. int nMaster; /* Length of string zMaster */
  46146. i64 iHdrOff; /* Offset of header in journal file */
  46147. i64 jrnlSize; /* Size of journal file on disk */
  46148. u32 cksum = 0; /* Checksum of string zMaster */
  46149. assert( pPager->setMaster==0 );
  46150. assert( !pagerUseWal(pPager) );
  46151. if( !zMaster
  46152. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  46153. || !isOpen(pPager->jfd)
  46154. ){
  46155. return SQLITE_OK;
  46156. }
  46157. pPager->setMaster = 1;
  46158. assert( pPager->journalHdr <= pPager->journalOff );
  46159. /* Calculate the length in bytes and the checksum of zMaster */
  46160. for(nMaster=0; zMaster[nMaster]; nMaster++){
  46161. cksum += zMaster[nMaster];
  46162. }
  46163. /* If in full-sync mode, advance to the next disk sector before writing
  46164. ** the master journal name. This is in case the previous page written to
  46165. ** the journal has already been synced.
  46166. */
  46167. if( pPager->fullSync ){
  46168. pPager->journalOff = journalHdrOffset(pPager);
  46169. }
  46170. iHdrOff = pPager->journalOff;
  46171. /* Write the master journal data to the end of the journal file. If
  46172. ** an error occurs, return the error code to the caller.
  46173. */
  46174. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  46175. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  46176. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  46177. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  46178. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  46179. iHdrOff+4+nMaster+8)))
  46180. ){
  46181. return rc;
  46182. }
  46183. pPager->journalOff += (nMaster+20);
  46184. /* If the pager is in peristent-journal mode, then the physical
  46185. ** journal-file may extend past the end of the master-journal name
  46186. ** and 8 bytes of magic data just written to the file. This is
  46187. ** dangerous because the code to rollback a hot-journal file
  46188. ** will not be able to find the master-journal name to determine
  46189. ** whether or not the journal is hot.
  46190. **
  46191. ** Easiest thing to do in this scenario is to truncate the journal
  46192. ** file to the required size.
  46193. */
  46194. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  46195. && jrnlSize>pPager->journalOff
  46196. ){
  46197. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  46198. }
  46199. return rc;
  46200. }
  46201. /*
  46202. ** Discard the entire contents of the in-memory page-cache.
  46203. */
  46204. static void pager_reset(Pager *pPager){
  46205. pPager->iDataVersion++;
  46206. sqlite3BackupRestart(pPager->pBackup);
  46207. sqlite3PcacheClear(pPager->pPCache);
  46208. }
  46209. /*
  46210. ** Return the pPager->iDataVersion value
  46211. */
  46212. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  46213. assert( pPager->eState>PAGER_OPEN );
  46214. return pPager->iDataVersion;
  46215. }
  46216. /*
  46217. ** Free all structures in the Pager.aSavepoint[] array and set both
  46218. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  46219. ** if it is open and the pager is not in exclusive mode.
  46220. */
  46221. static void releaseAllSavepoints(Pager *pPager){
  46222. int ii; /* Iterator for looping through Pager.aSavepoint */
  46223. for(ii=0; ii<pPager->nSavepoint; ii++){
  46224. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  46225. }
  46226. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  46227. sqlite3OsClose(pPager->sjfd);
  46228. }
  46229. sqlite3_free(pPager->aSavepoint);
  46230. pPager->aSavepoint = 0;
  46231. pPager->nSavepoint = 0;
  46232. pPager->nSubRec = 0;
  46233. }
  46234. /*
  46235. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  46236. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  46237. ** or SQLITE_NOMEM if a malloc failure occurs.
  46238. */
  46239. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  46240. int ii; /* Loop counter */
  46241. int rc = SQLITE_OK; /* Result code */
  46242. for(ii=0; ii<pPager->nSavepoint; ii++){
  46243. PagerSavepoint *p = &pPager->aSavepoint[ii];
  46244. if( pgno<=p->nOrig ){
  46245. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  46246. testcase( rc==SQLITE_NOMEM );
  46247. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  46248. }
  46249. }
  46250. return rc;
  46251. }
  46252. /*
  46253. ** This function is a no-op if the pager is in exclusive mode and not
  46254. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  46255. ** state.
  46256. **
  46257. ** If the pager is not in exclusive-access mode, the database file is
  46258. ** completely unlocked. If the file is unlocked and the file-system does
  46259. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  46260. ** closed (if it is open).
  46261. **
  46262. ** If the pager is in ERROR state when this function is called, the
  46263. ** contents of the pager cache are discarded before switching back to
  46264. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  46265. ** or not, any journal file left in the file-system will be treated
  46266. ** as a hot-journal and rolled back the next time a read-transaction
  46267. ** is opened (by this or by any other connection).
  46268. */
  46269. static void pager_unlock(Pager *pPager){
  46270. assert( pPager->eState==PAGER_READER
  46271. || pPager->eState==PAGER_OPEN
  46272. || pPager->eState==PAGER_ERROR
  46273. );
  46274. sqlite3BitvecDestroy(pPager->pInJournal);
  46275. pPager->pInJournal = 0;
  46276. releaseAllSavepoints(pPager);
  46277. if( pagerUseWal(pPager) ){
  46278. assert( !isOpen(pPager->jfd) );
  46279. sqlite3WalEndReadTransaction(pPager->pWal);
  46280. pPager->eState = PAGER_OPEN;
  46281. }else if( !pPager->exclusiveMode ){
  46282. int rc; /* Error code returned by pagerUnlockDb() */
  46283. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  46284. /* If the operating system support deletion of open files, then
  46285. ** close the journal file when dropping the database lock. Otherwise
  46286. ** another connection with journal_mode=delete might delete the file
  46287. ** out from under us.
  46288. */
  46289. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  46290. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  46291. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  46292. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  46293. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  46294. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  46295. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  46296. || 1!=(pPager->journalMode & 5)
  46297. ){
  46298. sqlite3OsClose(pPager->jfd);
  46299. }
  46300. /* If the pager is in the ERROR state and the call to unlock the database
  46301. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  46302. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  46303. ** is necessary.
  46304. */
  46305. rc = pagerUnlockDb(pPager, NO_LOCK);
  46306. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  46307. pPager->eLock = UNKNOWN_LOCK;
  46308. }
  46309. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  46310. ** without clearing the error code. This is intentional - the error
  46311. ** code is cleared and the cache reset in the block below.
  46312. */
  46313. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  46314. pPager->changeCountDone = 0;
  46315. pPager->eState = PAGER_OPEN;
  46316. }
  46317. /* If Pager.errCode is set, the contents of the pager cache cannot be
  46318. ** trusted. Now that there are no outstanding references to the pager,
  46319. ** it can safely move back to PAGER_OPEN state. This happens in both
  46320. ** normal and exclusive-locking mode.
  46321. */
  46322. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  46323. if( pPager->errCode ){
  46324. if( pPager->tempFile==0 ){
  46325. pager_reset(pPager);
  46326. pPager->changeCountDone = 0;
  46327. pPager->eState = PAGER_OPEN;
  46328. }else{
  46329. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  46330. }
  46331. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  46332. pPager->errCode = SQLITE_OK;
  46333. setGetterMethod(pPager);
  46334. }
  46335. pPager->journalOff = 0;
  46336. pPager->journalHdr = 0;
  46337. pPager->setMaster = 0;
  46338. }
  46339. /*
  46340. ** This function is called whenever an IOERR or FULL error that requires
  46341. ** the pager to transition into the ERROR state may ahve occurred.
  46342. ** The first argument is a pointer to the pager structure, the second
  46343. ** the error-code about to be returned by a pager API function. The
  46344. ** value returned is a copy of the second argument to this function.
  46345. **
  46346. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  46347. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  46348. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  46349. ** all major API calls on the Pager will immediately return Pager.errCode.
  46350. **
  46351. ** The ERROR state indicates that the contents of the pager-cache
  46352. ** cannot be trusted. This state can be cleared by completely discarding
  46353. ** the contents of the pager-cache. If a transaction was active when
  46354. ** the persistent error occurred, then the rollback journal may need
  46355. ** to be replayed to restore the contents of the database file (as if
  46356. ** it were a hot-journal).
  46357. */
  46358. static int pager_error(Pager *pPager, int rc){
  46359. int rc2 = rc & 0xff;
  46360. assert( rc==SQLITE_OK || !MEMDB );
  46361. assert(
  46362. pPager->errCode==SQLITE_FULL ||
  46363. pPager->errCode==SQLITE_OK ||
  46364. (pPager->errCode & 0xff)==SQLITE_IOERR
  46365. );
  46366. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  46367. pPager->errCode = rc;
  46368. pPager->eState = PAGER_ERROR;
  46369. setGetterMethod(pPager);
  46370. }
  46371. return rc;
  46372. }
  46373. static int pager_truncate(Pager *pPager, Pgno nPage);
  46374. /*
  46375. ** The write transaction open on pPager is being committed (bCommit==1)
  46376. ** or rolled back (bCommit==0).
  46377. **
  46378. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  46379. **
  46380. ** Rules:
  46381. **
  46382. ** * For non-TEMP databases, always sync to disk. This is necessary
  46383. ** for transactions to be durable.
  46384. **
  46385. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  46386. ** file has been created already (via a spill on pagerStress()) and
  46387. ** when the number of dirty pages in memory exceeds 25% of the total
  46388. ** cache size.
  46389. */
  46390. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  46391. if( pPager->tempFile==0 ) return 1;
  46392. if( !bCommit ) return 0;
  46393. if( !isOpen(pPager->fd) ) return 0;
  46394. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  46395. }
  46396. /*
  46397. ** This routine ends a transaction. A transaction is usually ended by
  46398. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  46399. ** after rollback of a hot-journal, or if an error occurs while opening
  46400. ** the journal file or writing the very first journal-header of a
  46401. ** database transaction.
  46402. **
  46403. ** This routine is never called in PAGER_ERROR state. If it is called
  46404. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  46405. ** exclusive than a RESERVED lock, it is a no-op.
  46406. **
  46407. ** Otherwise, any active savepoints are released.
  46408. **
  46409. ** If the journal file is open, then it is "finalized". Once a journal
  46410. ** file has been finalized it is not possible to use it to roll back a
  46411. ** transaction. Nor will it be considered to be a hot-journal by this
  46412. ** or any other database connection. Exactly how a journal is finalized
  46413. ** depends on whether or not the pager is running in exclusive mode and
  46414. ** the current journal-mode (Pager.journalMode value), as follows:
  46415. **
  46416. ** journalMode==MEMORY
  46417. ** Journal file descriptor is simply closed. This destroys an
  46418. ** in-memory journal.
  46419. **
  46420. ** journalMode==TRUNCATE
  46421. ** Journal file is truncated to zero bytes in size.
  46422. **
  46423. ** journalMode==PERSIST
  46424. ** The first 28 bytes of the journal file are zeroed. This invalidates
  46425. ** the first journal header in the file, and hence the entire journal
  46426. ** file. An invalid journal file cannot be rolled back.
  46427. **
  46428. ** journalMode==DELETE
  46429. ** The journal file is closed and deleted using sqlite3OsDelete().
  46430. **
  46431. ** If the pager is running in exclusive mode, this method of finalizing
  46432. ** the journal file is never used. Instead, if the journalMode is
  46433. ** DELETE and the pager is in exclusive mode, the method described under
  46434. ** journalMode==PERSIST is used instead.
  46435. **
  46436. ** After the journal is finalized, the pager moves to PAGER_READER state.
  46437. ** If running in non-exclusive rollback mode, the lock on the file is
  46438. ** downgraded to a SHARED_LOCK.
  46439. **
  46440. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  46441. ** any of the IO operations to finalize the journal file or unlock the
  46442. ** database then the IO error code is returned to the user. If the
  46443. ** operation to finalize the journal file fails, then the code still
  46444. ** tries to unlock the database file if not in exclusive mode. If the
  46445. ** unlock operation fails as well, then the first error code related
  46446. ** to the first error encountered (the journal finalization one) is
  46447. ** returned.
  46448. */
  46449. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  46450. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  46451. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  46452. /* Do nothing if the pager does not have an open write transaction
  46453. ** or at least a RESERVED lock. This function may be called when there
  46454. ** is no write-transaction active but a RESERVED or greater lock is
  46455. ** held under two circumstances:
  46456. **
  46457. ** 1. After a successful hot-journal rollback, it is called with
  46458. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  46459. **
  46460. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  46461. ** lock switches back to locking_mode=normal and then executes a
  46462. ** read-transaction, this function is called with eState==PAGER_READER
  46463. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  46464. */
  46465. assert( assert_pager_state(pPager) );
  46466. assert( pPager->eState!=PAGER_ERROR );
  46467. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  46468. return SQLITE_OK;
  46469. }
  46470. releaseAllSavepoints(pPager);
  46471. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  46472. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  46473. );
  46474. if( isOpen(pPager->jfd) ){
  46475. assert( !pagerUseWal(pPager) );
  46476. /* Finalize the journal file. */
  46477. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  46478. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  46479. sqlite3OsClose(pPager->jfd);
  46480. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  46481. if( pPager->journalOff==0 ){
  46482. rc = SQLITE_OK;
  46483. }else{
  46484. rc = sqlite3OsTruncate(pPager->jfd, 0);
  46485. if( rc==SQLITE_OK && pPager->fullSync ){
  46486. /* Make sure the new file size is written into the inode right away.
  46487. ** Otherwise the journal might resurrect following a power loss and
  46488. ** cause the last transaction to roll back. See
  46489. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  46490. */
  46491. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  46492. }
  46493. }
  46494. pPager->journalOff = 0;
  46495. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  46496. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  46497. ){
  46498. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  46499. pPager->journalOff = 0;
  46500. }else{
  46501. /* This branch may be executed with Pager.journalMode==MEMORY if
  46502. ** a hot-journal was just rolled back. In this case the journal
  46503. ** file should be closed and deleted. If this connection writes to
  46504. ** the database file, it will do so using an in-memory journal.
  46505. */
  46506. int bDelete = !pPager->tempFile;
  46507. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  46508. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  46509. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  46510. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  46511. );
  46512. sqlite3OsClose(pPager->jfd);
  46513. if( bDelete ){
  46514. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  46515. }
  46516. }
  46517. }
  46518. #ifdef SQLITE_CHECK_PAGES
  46519. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  46520. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  46521. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  46522. if( p ){
  46523. p->pageHash = 0;
  46524. sqlite3PagerUnrefNotNull(p);
  46525. }
  46526. }
  46527. #endif
  46528. sqlite3BitvecDestroy(pPager->pInJournal);
  46529. pPager->pInJournal = 0;
  46530. pPager->nRec = 0;
  46531. if( rc==SQLITE_OK ){
  46532. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  46533. sqlite3PcacheCleanAll(pPager->pPCache);
  46534. }else{
  46535. sqlite3PcacheClearWritable(pPager->pPCache);
  46536. }
  46537. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  46538. }
  46539. if( pagerUseWal(pPager) ){
  46540. /* Drop the WAL write-lock, if any. Also, if the connection was in
  46541. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  46542. ** lock held on the database file.
  46543. */
  46544. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  46545. assert( rc2==SQLITE_OK );
  46546. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  46547. /* This branch is taken when committing a transaction in rollback-journal
  46548. ** mode if the database file on disk is larger than the database image.
  46549. ** At this point the journal has been finalized and the transaction
  46550. ** successfully committed, but the EXCLUSIVE lock is still held on the
  46551. ** file. So it is safe to truncate the database file to its minimum
  46552. ** required size. */
  46553. assert( pPager->eLock==EXCLUSIVE_LOCK );
  46554. rc = pager_truncate(pPager, pPager->dbSize);
  46555. }
  46556. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  46557. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  46558. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  46559. }
  46560. if( !pPager->exclusiveMode
  46561. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  46562. ){
  46563. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  46564. pPager->changeCountDone = 0;
  46565. }
  46566. pPager->eState = PAGER_READER;
  46567. pPager->setMaster = 0;
  46568. return (rc==SQLITE_OK?rc2:rc);
  46569. }
  46570. /*
  46571. ** Execute a rollback if a transaction is active and unlock the
  46572. ** database file.
  46573. **
  46574. ** If the pager has already entered the ERROR state, do not attempt
  46575. ** the rollback at this time. Instead, pager_unlock() is called. The
  46576. ** call to pager_unlock() will discard all in-memory pages, unlock
  46577. ** the database file and move the pager back to OPEN state. If this
  46578. ** means that there is a hot-journal left in the file-system, the next
  46579. ** connection to obtain a shared lock on the pager (which may be this one)
  46580. ** will roll it back.
  46581. **
  46582. ** If the pager has not already entered the ERROR state, but an IO or
  46583. ** malloc error occurs during a rollback, then this will itself cause
  46584. ** the pager to enter the ERROR state. Which will be cleared by the
  46585. ** call to pager_unlock(), as described above.
  46586. */
  46587. static void pagerUnlockAndRollback(Pager *pPager){
  46588. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  46589. assert( assert_pager_state(pPager) );
  46590. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  46591. sqlite3BeginBenignMalloc();
  46592. sqlite3PagerRollback(pPager);
  46593. sqlite3EndBenignMalloc();
  46594. }else if( !pPager->exclusiveMode ){
  46595. assert( pPager->eState==PAGER_READER );
  46596. pager_end_transaction(pPager, 0, 0);
  46597. }
  46598. }
  46599. pager_unlock(pPager);
  46600. }
  46601. /*
  46602. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  46603. ** of data. Compute and return a checksum based ont the contents of the
  46604. ** page of data and the current value of pPager->cksumInit.
  46605. **
  46606. ** This is not a real checksum. It is really just the sum of the
  46607. ** random initial value (pPager->cksumInit) and every 200th byte
  46608. ** of the page data, starting with byte offset (pPager->pageSize%200).
  46609. ** Each byte is interpreted as an 8-bit unsigned integer.
  46610. **
  46611. ** Changing the formula used to compute this checksum results in an
  46612. ** incompatible journal file format.
  46613. **
  46614. ** If journal corruption occurs due to a power failure, the most likely
  46615. ** scenario is that one end or the other of the record will be changed.
  46616. ** It is much less likely that the two ends of the journal record will be
  46617. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  46618. ** though fast and simple, catches the mostly likely kind of corruption.
  46619. */
  46620. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  46621. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  46622. int i = pPager->pageSize-200; /* Loop counter */
  46623. while( i>0 ){
  46624. cksum += aData[i];
  46625. i -= 200;
  46626. }
  46627. return cksum;
  46628. }
  46629. /*
  46630. ** Report the current page size and number of reserved bytes back
  46631. ** to the codec.
  46632. */
  46633. #ifdef SQLITE_HAS_CODEC
  46634. static void pagerReportSize(Pager *pPager){
  46635. if( pPager->xCodecSizeChng ){
  46636. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  46637. (int)pPager->nReserve);
  46638. }
  46639. }
  46640. #else
  46641. # define pagerReportSize(X) /* No-op if we do not support a codec */
  46642. #endif
  46643. #ifdef SQLITE_HAS_CODEC
  46644. /*
  46645. ** Make sure the number of reserved bits is the same in the destination
  46646. ** pager as it is in the source. This comes up when a VACUUM changes the
  46647. ** number of reserved bits to the "optimal" amount.
  46648. */
  46649. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  46650. if( pDest->nReserve!=pSrc->nReserve ){
  46651. pDest->nReserve = pSrc->nReserve;
  46652. pagerReportSize(pDest);
  46653. }
  46654. }
  46655. #endif
  46656. /*
  46657. ** Read a single page from either the journal file (if isMainJrnl==1) or
  46658. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  46659. ** The page begins at offset *pOffset into the file. The *pOffset
  46660. ** value is increased to the start of the next page in the journal.
  46661. **
  46662. ** The main rollback journal uses checksums - the statement journal does
  46663. ** not.
  46664. **
  46665. ** If the page number of the page record read from the (sub-)journal file
  46666. ** is greater than the current value of Pager.dbSize, then playback is
  46667. ** skipped and SQLITE_OK is returned.
  46668. **
  46669. ** If pDone is not NULL, then it is a record of pages that have already
  46670. ** been played back. If the page at *pOffset has already been played back
  46671. ** (if the corresponding pDone bit is set) then skip the playback.
  46672. ** Make sure the pDone bit corresponding to the *pOffset page is set
  46673. ** prior to returning.
  46674. **
  46675. ** If the page record is successfully read from the (sub-)journal file
  46676. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  46677. ** while reading the record from the (sub-)journal file or while writing
  46678. ** to the database file, then the IO error code is returned. If data
  46679. ** is successfully read from the (sub-)journal file but appears to be
  46680. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  46681. ** two circumstances:
  46682. **
  46683. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  46684. ** * If the record is being rolled back from the main journal file
  46685. ** and the checksum field does not match the record content.
  46686. **
  46687. ** Neither of these two scenarios are possible during a savepoint rollback.
  46688. **
  46689. ** If this is a savepoint rollback, then memory may have to be dynamically
  46690. ** allocated by this function. If this is the case and an allocation fails,
  46691. ** SQLITE_NOMEM is returned.
  46692. */
  46693. static int pager_playback_one_page(
  46694. Pager *pPager, /* The pager being played back */
  46695. i64 *pOffset, /* Offset of record to playback */
  46696. Bitvec *pDone, /* Bitvec of pages already played back */
  46697. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  46698. int isSavepnt /* True for a savepoint rollback */
  46699. ){
  46700. int rc;
  46701. PgHdr *pPg; /* An existing page in the cache */
  46702. Pgno pgno; /* The page number of a page in journal */
  46703. u32 cksum; /* Checksum used for sanity checking */
  46704. char *aData; /* Temporary storage for the page */
  46705. sqlite3_file *jfd; /* The file descriptor for the journal file */
  46706. int isSynced; /* True if journal page is synced */
  46707. #ifdef SQLITE_HAS_CODEC
  46708. /* The jrnlEnc flag is true if Journal pages should be passed through
  46709. ** the codec. It is false for pure in-memory journals. */
  46710. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  46711. #endif
  46712. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  46713. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  46714. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  46715. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  46716. aData = pPager->pTmpSpace;
  46717. assert( aData ); /* Temp storage must have already been allocated */
  46718. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  46719. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  46720. ** or savepoint rollback done at the request of the caller) or this is
  46721. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  46722. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  46723. ** only reads from the main journal, not the sub-journal.
  46724. */
  46725. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  46726. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  46727. );
  46728. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  46729. /* Read the page number and page data from the journal or sub-journal
  46730. ** file. Return an error code to the caller if an IO error occurs.
  46731. */
  46732. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  46733. rc = read32bits(jfd, *pOffset, &pgno);
  46734. if( rc!=SQLITE_OK ) return rc;
  46735. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  46736. if( rc!=SQLITE_OK ) return rc;
  46737. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  46738. /* Sanity checking on the page. This is more important that I originally
  46739. ** thought. If a power failure occurs while the journal is being written,
  46740. ** it could cause invalid data to be written into the journal. We need to
  46741. ** detect this invalid data (with high probability) and ignore it.
  46742. */
  46743. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  46744. assert( !isSavepnt );
  46745. return SQLITE_DONE;
  46746. }
  46747. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  46748. return SQLITE_OK;
  46749. }
  46750. if( isMainJrnl ){
  46751. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  46752. if( rc ) return rc;
  46753. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  46754. return SQLITE_DONE;
  46755. }
  46756. }
  46757. /* If this page has already been played back before during the current
  46758. ** rollback, then don't bother to play it back again.
  46759. */
  46760. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  46761. return rc;
  46762. }
  46763. /* When playing back page 1, restore the nReserve setting
  46764. */
  46765. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  46766. pPager->nReserve = ((u8*)aData)[20];
  46767. pagerReportSize(pPager);
  46768. }
  46769. /* If the pager is in CACHEMOD state, then there must be a copy of this
  46770. ** page in the pager cache. In this case just update the pager cache,
  46771. ** not the database file. The page is left marked dirty in this case.
  46772. **
  46773. ** An exception to the above rule: If the database is in no-sync mode
  46774. ** and a page is moved during an incremental vacuum then the page may
  46775. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  46776. ** during a Movepage() call, then the page may not be in the cache
  46777. ** either. So the condition described in the above paragraph is not
  46778. ** assert()able.
  46779. **
  46780. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  46781. ** pager cache if it exists and the main file. The page is then marked
  46782. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  46783. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  46784. ** if the pager is in OPEN state.
  46785. **
  46786. ** Ticket #1171: The statement journal might contain page content that is
  46787. ** different from the page content at the start of the transaction.
  46788. ** This occurs when a page is changed prior to the start of a statement
  46789. ** then changed again within the statement. When rolling back such a
  46790. ** statement we must not write to the original database unless we know
  46791. ** for certain that original page contents are synced into the main rollback
  46792. ** journal. Otherwise, a power loss might leave modified data in the
  46793. ** database file without an entry in the rollback journal that can
  46794. ** restore the database to its original form. Two conditions must be
  46795. ** met before writing to the database files. (1) the database must be
  46796. ** locked. (2) we know that the original page content is fully synced
  46797. ** in the main journal either because the page is not in cache or else
  46798. ** the page is marked as needSync==0.
  46799. **
  46800. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  46801. ** is possible to fail a statement on a database that does not yet exist.
  46802. ** Do not attempt to write if database file has never been opened.
  46803. */
  46804. if( pagerUseWal(pPager) ){
  46805. pPg = 0;
  46806. }else{
  46807. pPg = sqlite3PagerLookup(pPager, pgno);
  46808. }
  46809. assert( pPg || !MEMDB );
  46810. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  46811. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  46812. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  46813. (isMainJrnl?"main-journal":"sub-journal")
  46814. ));
  46815. if( isMainJrnl ){
  46816. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  46817. }else{
  46818. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  46819. }
  46820. if( isOpen(pPager->fd)
  46821. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46822. && isSynced
  46823. ){
  46824. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  46825. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  46826. assert( !pagerUseWal(pPager) );
  46827. /* Write the data read from the journal back into the database file.
  46828. ** This is usually safe even for an encrypted database - as the data
  46829. ** was encrypted before it was written to the journal file. The exception
  46830. ** is if the data was just read from an in-memory sub-journal. In that
  46831. ** case it must be encrypted here before it is copied into the database
  46832. ** file. */
  46833. #ifdef SQLITE_HAS_CODEC
  46834. if( !jrnlEnc ){
  46835. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  46836. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46837. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46838. }else
  46839. #endif
  46840. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46841. if( pgno>pPager->dbFileSize ){
  46842. pPager->dbFileSize = pgno;
  46843. }
  46844. if( pPager->pBackup ){
  46845. #ifdef SQLITE_HAS_CODEC
  46846. if( jrnlEnc ){
  46847. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46848. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46849. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  46850. }else
  46851. #endif
  46852. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46853. }
  46854. }else if( !isMainJrnl && pPg==0 ){
  46855. /* If this is a rollback of a savepoint and data was not written to
  46856. ** the database and the page is not in-memory, there is a potential
  46857. ** problem. When the page is next fetched by the b-tree layer, it
  46858. ** will be read from the database file, which may or may not be
  46859. ** current.
  46860. **
  46861. ** There are a couple of different ways this can happen. All are quite
  46862. ** obscure. When running in synchronous mode, this can only happen
  46863. ** if the page is on the free-list at the start of the transaction, then
  46864. ** populated, then moved using sqlite3PagerMovepage().
  46865. **
  46866. ** The solution is to add an in-memory page to the cache containing
  46867. ** the data just read from the sub-journal. Mark the page as dirty
  46868. ** and if the pager requires a journal-sync, then mark the page as
  46869. ** requiring a journal-sync before it is written.
  46870. */
  46871. assert( isSavepnt );
  46872. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  46873. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  46874. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  46875. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  46876. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  46877. if( rc!=SQLITE_OK ) return rc;
  46878. sqlite3PcacheMakeDirty(pPg);
  46879. }
  46880. if( pPg ){
  46881. /* No page should ever be explicitly rolled back that is in use, except
  46882. ** for page 1 which is held in use in order to keep the lock on the
  46883. ** database active. However such a page may be rolled back as a result
  46884. ** of an internal error resulting in an automatic call to
  46885. ** sqlite3PagerRollback().
  46886. */
  46887. void *pData;
  46888. pData = pPg->pData;
  46889. memcpy(pData, (u8*)aData, pPager->pageSize);
  46890. pPager->xReiniter(pPg);
  46891. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  46892. ** that call was dangerous and had no detectable benefit since the cache
  46893. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  46894. ** has been removed. */
  46895. pager_set_pagehash(pPg);
  46896. /* If this was page 1, then restore the value of Pager.dbFileVers.
  46897. ** Do this before any decoding. */
  46898. if( pgno==1 ){
  46899. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  46900. }
  46901. /* Decode the page just read from disk */
  46902. #if SQLITE_HAS_CODEC
  46903. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  46904. #endif
  46905. sqlite3PcacheRelease(pPg);
  46906. }
  46907. return rc;
  46908. }
  46909. /*
  46910. ** Parameter zMaster is the name of a master journal file. A single journal
  46911. ** file that referred to the master journal file has just been rolled back.
  46912. ** This routine checks if it is possible to delete the master journal file,
  46913. ** and does so if it is.
  46914. **
  46915. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  46916. ** available for use within this function.
  46917. **
  46918. ** When a master journal file is created, it is populated with the names
  46919. ** of all of its child journals, one after another, formatted as utf-8
  46920. ** encoded text. The end of each child journal file is marked with a
  46921. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  46922. ** file for a transaction involving two databases might be:
  46923. **
  46924. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  46925. **
  46926. ** A master journal file may only be deleted once all of its child
  46927. ** journals have been rolled back.
  46928. **
  46929. ** This function reads the contents of the master-journal file into
  46930. ** memory and loops through each of the child journal names. For
  46931. ** each child journal, it checks if:
  46932. **
  46933. ** * if the child journal exists, and if so
  46934. ** * if the child journal contains a reference to master journal
  46935. ** file zMaster
  46936. **
  46937. ** If a child journal can be found that matches both of the criteria
  46938. ** above, this function returns without doing anything. Otherwise, if
  46939. ** no such child journal can be found, file zMaster is deleted from
  46940. ** the file-system using sqlite3OsDelete().
  46941. **
  46942. ** If an IO error within this function, an error code is returned. This
  46943. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  46944. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  46945. ** occur, SQLITE_OK is returned.
  46946. **
  46947. ** TODO: This function allocates a single block of memory to load
  46948. ** the entire contents of the master journal file. This could be
  46949. ** a couple of kilobytes or so - potentially larger than the page
  46950. ** size.
  46951. */
  46952. static int pager_delmaster(Pager *pPager, const char *zMaster){
  46953. sqlite3_vfs *pVfs = pPager->pVfs;
  46954. int rc; /* Return code */
  46955. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  46956. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  46957. char *zMasterJournal = 0; /* Contents of master journal file */
  46958. i64 nMasterJournal; /* Size of master journal file */
  46959. char *zJournal; /* Pointer to one journal within MJ file */
  46960. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  46961. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  46962. /* Allocate space for both the pJournal and pMaster file descriptors.
  46963. ** If successful, open the master journal file for reading.
  46964. */
  46965. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  46966. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  46967. if( !pMaster ){
  46968. rc = SQLITE_NOMEM_BKPT;
  46969. }else{
  46970. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  46971. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  46972. }
  46973. if( rc!=SQLITE_OK ) goto delmaster_out;
  46974. /* Load the entire master journal file into space obtained from
  46975. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  46976. ** sufficient space (in zMasterPtr) to hold the names of master
  46977. ** journal files extracted from regular rollback-journals.
  46978. */
  46979. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  46980. if( rc!=SQLITE_OK ) goto delmaster_out;
  46981. nMasterPtr = pVfs->mxPathname+1;
  46982. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  46983. if( !zMasterJournal ){
  46984. rc = SQLITE_NOMEM_BKPT;
  46985. goto delmaster_out;
  46986. }
  46987. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  46988. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  46989. if( rc!=SQLITE_OK ) goto delmaster_out;
  46990. zMasterJournal[nMasterJournal] = 0;
  46991. zJournal = zMasterJournal;
  46992. while( (zJournal-zMasterJournal)<nMasterJournal ){
  46993. int exists;
  46994. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  46995. if( rc!=SQLITE_OK ){
  46996. goto delmaster_out;
  46997. }
  46998. if( exists ){
  46999. /* One of the journals pointed to by the master journal exists.
  47000. ** Open it and check if it points at the master journal. If
  47001. ** so, return without deleting the master journal file.
  47002. */
  47003. int c;
  47004. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  47005. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  47006. if( rc!=SQLITE_OK ){
  47007. goto delmaster_out;
  47008. }
  47009. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  47010. sqlite3OsClose(pJournal);
  47011. if( rc!=SQLITE_OK ){
  47012. goto delmaster_out;
  47013. }
  47014. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  47015. if( c ){
  47016. /* We have a match. Do not delete the master journal file. */
  47017. goto delmaster_out;
  47018. }
  47019. }
  47020. zJournal += (sqlite3Strlen30(zJournal)+1);
  47021. }
  47022. sqlite3OsClose(pMaster);
  47023. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  47024. delmaster_out:
  47025. sqlite3_free(zMasterJournal);
  47026. if( pMaster ){
  47027. sqlite3OsClose(pMaster);
  47028. assert( !isOpen(pJournal) );
  47029. sqlite3_free(pMaster);
  47030. }
  47031. return rc;
  47032. }
  47033. /*
  47034. ** This function is used to change the actual size of the database
  47035. ** file in the file-system. This only happens when committing a transaction,
  47036. ** or rolling back a transaction (including rolling back a hot-journal).
  47037. **
  47038. ** If the main database file is not open, or the pager is not in either
  47039. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  47040. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  47041. ** If the file on disk is currently larger than nPage pages, then use the VFS
  47042. ** xTruncate() method to truncate it.
  47043. **
  47044. ** Or, it might be the case that the file on disk is smaller than
  47045. ** nPage pages. Some operating system implementations can get confused if
  47046. ** you try to truncate a file to some size that is larger than it
  47047. ** currently is, so detect this case and write a single zero byte to
  47048. ** the end of the new file instead.
  47049. **
  47050. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  47051. ** the database file, return the error code to the caller.
  47052. */
  47053. static int pager_truncate(Pager *pPager, Pgno nPage){
  47054. int rc = SQLITE_OK;
  47055. assert( pPager->eState!=PAGER_ERROR );
  47056. assert( pPager->eState!=PAGER_READER );
  47057. if( isOpen(pPager->fd)
  47058. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  47059. ){
  47060. i64 currentSize, newSize;
  47061. int szPage = pPager->pageSize;
  47062. assert( pPager->eLock==EXCLUSIVE_LOCK );
  47063. /* TODO: Is it safe to use Pager.dbFileSize here? */
  47064. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  47065. newSize = szPage*(i64)nPage;
  47066. if( rc==SQLITE_OK && currentSize!=newSize ){
  47067. if( currentSize>newSize ){
  47068. rc = sqlite3OsTruncate(pPager->fd, newSize);
  47069. }else if( (currentSize+szPage)<=newSize ){
  47070. char *pTmp = pPager->pTmpSpace;
  47071. memset(pTmp, 0, szPage);
  47072. testcase( (newSize-szPage) == currentSize );
  47073. testcase( (newSize-szPage) > currentSize );
  47074. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  47075. }
  47076. if( rc==SQLITE_OK ){
  47077. pPager->dbFileSize = nPage;
  47078. }
  47079. }
  47080. }
  47081. return rc;
  47082. }
  47083. /*
  47084. ** Return a sanitized version of the sector-size of OS file pFile. The
  47085. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  47086. */
  47087. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  47088. int iRet = sqlite3OsSectorSize(pFile);
  47089. if( iRet<32 ){
  47090. iRet = 512;
  47091. }else if( iRet>MAX_SECTOR_SIZE ){
  47092. assert( MAX_SECTOR_SIZE>=512 );
  47093. iRet = MAX_SECTOR_SIZE;
  47094. }
  47095. return iRet;
  47096. }
  47097. /*
  47098. ** Set the value of the Pager.sectorSize variable for the given
  47099. ** pager based on the value returned by the xSectorSize method
  47100. ** of the open database file. The sector size will be used
  47101. ** to determine the size and alignment of journal header and
  47102. ** master journal pointers within created journal files.
  47103. **
  47104. ** For temporary files the effective sector size is always 512 bytes.
  47105. **
  47106. ** Otherwise, for non-temporary files, the effective sector size is
  47107. ** the value returned by the xSectorSize() method rounded up to 32 if
  47108. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  47109. ** is greater than MAX_SECTOR_SIZE.
  47110. **
  47111. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  47112. ** the effective sector size to its minimum value (512). The purpose of
  47113. ** pPager->sectorSize is to define the "blast radius" of bytes that
  47114. ** might change if a crash occurs while writing to a single byte in
  47115. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  47116. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  47117. ** size. For backwards compatibility of the rollback journal file format,
  47118. ** we cannot reduce the effective sector size below 512.
  47119. */
  47120. static void setSectorSize(Pager *pPager){
  47121. assert( isOpen(pPager->fd) || pPager->tempFile );
  47122. if( pPager->tempFile
  47123. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  47124. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  47125. ){
  47126. /* Sector size doesn't matter for temporary files. Also, the file
  47127. ** may not have been opened yet, in which case the OsSectorSize()
  47128. ** call will segfault. */
  47129. pPager->sectorSize = 512;
  47130. }else{
  47131. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  47132. }
  47133. }
  47134. /*
  47135. ** Playback the journal and thus restore the database file to
  47136. ** the state it was in before we started making changes.
  47137. **
  47138. ** The journal file format is as follows:
  47139. **
  47140. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  47141. ** (2) 4 byte big-endian integer which is the number of valid page records
  47142. ** in the journal. If this value is 0xffffffff, then compute the
  47143. ** number of page records from the journal size.
  47144. ** (3) 4 byte big-endian integer which is the initial value for the
  47145. ** sanity checksum.
  47146. ** (4) 4 byte integer which is the number of pages to truncate the
  47147. ** database to during a rollback.
  47148. ** (5) 4 byte big-endian integer which is the sector size. The header
  47149. ** is this many bytes in size.
  47150. ** (6) 4 byte big-endian integer which is the page size.
  47151. ** (7) zero padding out to the next sector size.
  47152. ** (8) Zero or more pages instances, each as follows:
  47153. ** + 4 byte page number.
  47154. ** + pPager->pageSize bytes of data.
  47155. ** + 4 byte checksum
  47156. **
  47157. ** When we speak of the journal header, we mean the first 7 items above.
  47158. ** Each entry in the journal is an instance of the 8th item.
  47159. **
  47160. ** Call the value from the second bullet "nRec". nRec is the number of
  47161. ** valid page entries in the journal. In most cases, you can compute the
  47162. ** value of nRec from the size of the journal file. But if a power
  47163. ** failure occurred while the journal was being written, it could be the
  47164. ** case that the size of the journal file had already been increased but
  47165. ** the extra entries had not yet made it safely to disk. In such a case,
  47166. ** the value of nRec computed from the file size would be too large. For
  47167. ** that reason, we always use the nRec value in the header.
  47168. **
  47169. ** If the nRec value is 0xffffffff it means that nRec should be computed
  47170. ** from the file size. This value is used when the user selects the
  47171. ** no-sync option for the journal. A power failure could lead to corruption
  47172. ** in this case. But for things like temporary table (which will be
  47173. ** deleted when the power is restored) we don't care.
  47174. **
  47175. ** If the file opened as the journal file is not a well-formed
  47176. ** journal file then all pages up to the first corrupted page are rolled
  47177. ** back (or no pages if the journal header is corrupted). The journal file
  47178. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  47179. ** been encountered.
  47180. **
  47181. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  47182. ** and an error code is returned.
  47183. **
  47184. ** The isHot parameter indicates that we are trying to rollback a journal
  47185. ** that might be a hot journal. Or, it could be that the journal is
  47186. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  47187. ** If the journal really is hot, reset the pager cache prior rolling
  47188. ** back any content. If the journal is merely persistent, no reset is
  47189. ** needed.
  47190. */
  47191. static int pager_playback(Pager *pPager, int isHot){
  47192. sqlite3_vfs *pVfs = pPager->pVfs;
  47193. i64 szJ; /* Size of the journal file in bytes */
  47194. u32 nRec; /* Number of Records in the journal */
  47195. u32 u; /* Unsigned loop counter */
  47196. Pgno mxPg = 0; /* Size of the original file in pages */
  47197. int rc; /* Result code of a subroutine */
  47198. int res = 1; /* Value returned by sqlite3OsAccess() */
  47199. char *zMaster = 0; /* Name of master journal file if any */
  47200. int needPagerReset; /* True to reset page prior to first page rollback */
  47201. int nPlayback = 0; /* Total number of pages restored from journal */
  47202. u32 savedPageSize = pPager->pageSize;
  47203. /* Figure out how many records are in the journal. Abort early if
  47204. ** the journal is empty.
  47205. */
  47206. assert( isOpen(pPager->jfd) );
  47207. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  47208. if( rc!=SQLITE_OK ){
  47209. goto end_playback;
  47210. }
  47211. /* Read the master journal name from the journal, if it is present.
  47212. ** If a master journal file name is specified, but the file is not
  47213. ** present on disk, then the journal is not hot and does not need to be
  47214. ** played back.
  47215. **
  47216. ** TODO: Technically the following is an error because it assumes that
  47217. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  47218. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  47219. ** mxPathname is 512, which is the same as the minimum allowable value
  47220. ** for pageSize.
  47221. */
  47222. zMaster = pPager->pTmpSpace;
  47223. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  47224. if( rc==SQLITE_OK && zMaster[0] ){
  47225. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  47226. }
  47227. zMaster = 0;
  47228. if( rc!=SQLITE_OK || !res ){
  47229. goto end_playback;
  47230. }
  47231. pPager->journalOff = 0;
  47232. needPagerReset = isHot;
  47233. /* This loop terminates either when a readJournalHdr() or
  47234. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  47235. ** occurs.
  47236. */
  47237. while( 1 ){
  47238. /* Read the next journal header from the journal file. If there are
  47239. ** not enough bytes left in the journal file for a complete header, or
  47240. ** it is corrupted, then a process must have failed while writing it.
  47241. ** This indicates nothing more needs to be rolled back.
  47242. */
  47243. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  47244. if( rc!=SQLITE_OK ){
  47245. if( rc==SQLITE_DONE ){
  47246. rc = SQLITE_OK;
  47247. }
  47248. goto end_playback;
  47249. }
  47250. /* If nRec is 0xffffffff, then this journal was created by a process
  47251. ** working in no-sync mode. This means that the rest of the journal
  47252. ** file consists of pages, there are no more journal headers. Compute
  47253. ** the value of nRec based on this assumption.
  47254. */
  47255. if( nRec==0xffffffff ){
  47256. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  47257. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  47258. }
  47259. /* If nRec is 0 and this rollback is of a transaction created by this
  47260. ** process and if this is the final header in the journal, then it means
  47261. ** that this part of the journal was being filled but has not yet been
  47262. ** synced to disk. Compute the number of pages based on the remaining
  47263. ** size of the file.
  47264. **
  47265. ** The third term of the test was added to fix ticket #2565.
  47266. ** When rolling back a hot journal, nRec==0 always means that the next
  47267. ** chunk of the journal contains zero pages to be rolled back. But
  47268. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  47269. ** the journal, it means that the journal might contain additional
  47270. ** pages that need to be rolled back and that the number of pages
  47271. ** should be computed based on the journal file size.
  47272. */
  47273. if( nRec==0 && !isHot &&
  47274. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  47275. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  47276. }
  47277. /* If this is the first header read from the journal, truncate the
  47278. ** database file back to its original size.
  47279. */
  47280. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  47281. rc = pager_truncate(pPager, mxPg);
  47282. if( rc!=SQLITE_OK ){
  47283. goto end_playback;
  47284. }
  47285. pPager->dbSize = mxPg;
  47286. }
  47287. /* Copy original pages out of the journal and back into the
  47288. ** database file and/or page cache.
  47289. */
  47290. for(u=0; u<nRec; u++){
  47291. if( needPagerReset ){
  47292. pager_reset(pPager);
  47293. needPagerReset = 0;
  47294. }
  47295. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  47296. if( rc==SQLITE_OK ){
  47297. nPlayback++;
  47298. }else{
  47299. if( rc==SQLITE_DONE ){
  47300. pPager->journalOff = szJ;
  47301. break;
  47302. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  47303. /* If the journal has been truncated, simply stop reading and
  47304. ** processing the journal. This might happen if the journal was
  47305. ** not completely written and synced prior to a crash. In that
  47306. ** case, the database should have never been written in the
  47307. ** first place so it is OK to simply abandon the rollback. */
  47308. rc = SQLITE_OK;
  47309. goto end_playback;
  47310. }else{
  47311. /* If we are unable to rollback, quit and return the error
  47312. ** code. This will cause the pager to enter the error state
  47313. ** so that no further harm will be done. Perhaps the next
  47314. ** process to come along will be able to rollback the database.
  47315. */
  47316. goto end_playback;
  47317. }
  47318. }
  47319. }
  47320. }
  47321. /*NOTREACHED*/
  47322. assert( 0 );
  47323. end_playback:
  47324. if( rc==SQLITE_OK ){
  47325. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  47326. }
  47327. /* Following a rollback, the database file should be back in its original
  47328. ** state prior to the start of the transaction, so invoke the
  47329. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  47330. ** assertion that the transaction counter was modified.
  47331. */
  47332. #ifdef SQLITE_DEBUG
  47333. if( pPager->fd->pMethods ){
  47334. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  47335. }
  47336. #endif
  47337. /* If this playback is happening automatically as a result of an IO or
  47338. ** malloc error that occurred after the change-counter was updated but
  47339. ** before the transaction was committed, then the change-counter
  47340. ** modification may just have been reverted. If this happens in exclusive
  47341. ** mode, then subsequent transactions performed by the connection will not
  47342. ** update the change-counter at all. This may lead to cache inconsistency
  47343. ** problems for other processes at some point in the future. So, just
  47344. ** in case this has happened, clear the changeCountDone flag now.
  47345. */
  47346. pPager->changeCountDone = pPager->tempFile;
  47347. if( rc==SQLITE_OK ){
  47348. zMaster = pPager->pTmpSpace;
  47349. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  47350. testcase( rc!=SQLITE_OK );
  47351. }
  47352. if( rc==SQLITE_OK
  47353. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  47354. ){
  47355. rc = sqlite3PagerSync(pPager, 0);
  47356. }
  47357. if( rc==SQLITE_OK ){
  47358. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  47359. testcase( rc!=SQLITE_OK );
  47360. }
  47361. if( rc==SQLITE_OK && zMaster[0] && res ){
  47362. /* If there was a master journal and this routine will return success,
  47363. ** see if it is possible to delete the master journal.
  47364. */
  47365. rc = pager_delmaster(pPager, zMaster);
  47366. testcase( rc!=SQLITE_OK );
  47367. }
  47368. if( isHot && nPlayback ){
  47369. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  47370. nPlayback, pPager->zJournal);
  47371. }
  47372. /* The Pager.sectorSize variable may have been updated while rolling
  47373. ** back a journal created by a process with a different sector size
  47374. ** value. Reset it to the correct value for this process.
  47375. */
  47376. setSectorSize(pPager);
  47377. return rc;
  47378. }
  47379. /*
  47380. ** Read the content for page pPg out of the database file (or out of
  47381. ** the WAL if that is where the most recent copy if found) into
  47382. ** pPg->pData. A shared lock or greater must be held on the database
  47383. ** file before this function is called.
  47384. **
  47385. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  47386. ** the value read from the database file.
  47387. **
  47388. ** If an IO error occurs, then the IO error is returned to the caller.
  47389. ** Otherwise, SQLITE_OK is returned.
  47390. */
  47391. static int readDbPage(PgHdr *pPg){
  47392. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  47393. int rc = SQLITE_OK; /* Return code */
  47394. #ifndef SQLITE_OMIT_WAL
  47395. u32 iFrame = 0; /* Frame of WAL containing pgno */
  47396. assert( pPager->eState>=PAGER_READER && !MEMDB );
  47397. assert( isOpen(pPager->fd) );
  47398. if( pagerUseWal(pPager) ){
  47399. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  47400. if( rc ) return rc;
  47401. }
  47402. if( iFrame ){
  47403. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  47404. }else
  47405. #endif
  47406. {
  47407. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  47408. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  47409. if( rc==SQLITE_IOERR_SHORT_READ ){
  47410. rc = SQLITE_OK;
  47411. }
  47412. }
  47413. if( pPg->pgno==1 ){
  47414. if( rc ){
  47415. /* If the read is unsuccessful, set the dbFileVers[] to something
  47416. ** that will never be a valid file version. dbFileVers[] is a copy
  47417. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  47418. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  47419. ** should be page numbers which are never 0xffffffff. So filling
  47420. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  47421. **
  47422. ** For an encrypted database, the situation is more complex: bytes
  47423. ** 24..39 of the database are white noise. But the probability of
  47424. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  47425. ** we should still be ok.
  47426. */
  47427. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  47428. }else{
  47429. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  47430. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  47431. }
  47432. }
  47433. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  47434. PAGER_INCR(sqlite3_pager_readdb_count);
  47435. PAGER_INCR(pPager->nRead);
  47436. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  47437. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  47438. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  47439. return rc;
  47440. }
  47441. /*
  47442. ** Update the value of the change-counter at offsets 24 and 92 in
  47443. ** the header and the sqlite version number at offset 96.
  47444. **
  47445. ** This is an unconditional update. See also the pager_incr_changecounter()
  47446. ** routine which only updates the change-counter if the update is actually
  47447. ** needed, as determined by the pPager->changeCountDone state variable.
  47448. */
  47449. static void pager_write_changecounter(PgHdr *pPg){
  47450. u32 change_counter;
  47451. /* Increment the value just read and write it back to byte 24. */
  47452. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  47453. put32bits(((char*)pPg->pData)+24, change_counter);
  47454. /* Also store the SQLite version number in bytes 96..99 and in
  47455. ** bytes 92..95 store the change counter for which the version number
  47456. ** is valid. */
  47457. put32bits(((char*)pPg->pData)+92, change_counter);
  47458. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  47459. }
  47460. #ifndef SQLITE_OMIT_WAL
  47461. /*
  47462. ** This function is invoked once for each page that has already been
  47463. ** written into the log file when a WAL transaction is rolled back.
  47464. ** Parameter iPg is the page number of said page. The pCtx argument
  47465. ** is actually a pointer to the Pager structure.
  47466. **
  47467. ** If page iPg is present in the cache, and has no outstanding references,
  47468. ** it is discarded. Otherwise, if there are one or more outstanding
  47469. ** references, the page content is reloaded from the database. If the
  47470. ** attempt to reload content from the database is required and fails,
  47471. ** return an SQLite error code. Otherwise, SQLITE_OK.
  47472. */
  47473. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  47474. int rc = SQLITE_OK;
  47475. Pager *pPager = (Pager *)pCtx;
  47476. PgHdr *pPg;
  47477. assert( pagerUseWal(pPager) );
  47478. pPg = sqlite3PagerLookup(pPager, iPg);
  47479. if( pPg ){
  47480. if( sqlite3PcachePageRefcount(pPg)==1 ){
  47481. sqlite3PcacheDrop(pPg);
  47482. }else{
  47483. rc = readDbPage(pPg);
  47484. if( rc==SQLITE_OK ){
  47485. pPager->xReiniter(pPg);
  47486. }
  47487. sqlite3PagerUnrefNotNull(pPg);
  47488. }
  47489. }
  47490. /* Normally, if a transaction is rolled back, any backup processes are
  47491. ** updated as data is copied out of the rollback journal and into the
  47492. ** database. This is not generally possible with a WAL database, as
  47493. ** rollback involves simply truncating the log file. Therefore, if one
  47494. ** or more frames have already been written to the log (and therefore
  47495. ** also copied into the backup databases) as part of this transaction,
  47496. ** the backups must be restarted.
  47497. */
  47498. sqlite3BackupRestart(pPager->pBackup);
  47499. return rc;
  47500. }
  47501. /*
  47502. ** This function is called to rollback a transaction on a WAL database.
  47503. */
  47504. static int pagerRollbackWal(Pager *pPager){
  47505. int rc; /* Return Code */
  47506. PgHdr *pList; /* List of dirty pages to revert */
  47507. /* For all pages in the cache that are currently dirty or have already
  47508. ** been written (but not committed) to the log file, do one of the
  47509. ** following:
  47510. **
  47511. ** + Discard the cached page (if refcount==0), or
  47512. ** + Reload page content from the database (if refcount>0).
  47513. */
  47514. pPager->dbSize = pPager->dbOrigSize;
  47515. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  47516. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  47517. while( pList && rc==SQLITE_OK ){
  47518. PgHdr *pNext = pList->pDirty;
  47519. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  47520. pList = pNext;
  47521. }
  47522. return rc;
  47523. }
  47524. /*
  47525. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  47526. ** the contents of the list of pages headed by pList (connected by pDirty),
  47527. ** this function notifies any active backup processes that the pages have
  47528. ** changed.
  47529. **
  47530. ** The list of pages passed into this routine is always sorted by page number.
  47531. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  47532. */
  47533. static int pagerWalFrames(
  47534. Pager *pPager, /* Pager object */
  47535. PgHdr *pList, /* List of frames to log */
  47536. Pgno nTruncate, /* Database size after this commit */
  47537. int isCommit /* True if this is a commit */
  47538. ){
  47539. int rc; /* Return code */
  47540. int nList; /* Number of pages in pList */
  47541. PgHdr *p; /* For looping over pages */
  47542. assert( pPager->pWal );
  47543. assert( pList );
  47544. #ifdef SQLITE_DEBUG
  47545. /* Verify that the page list is in accending order */
  47546. for(p=pList; p && p->pDirty; p=p->pDirty){
  47547. assert( p->pgno < p->pDirty->pgno );
  47548. }
  47549. #endif
  47550. assert( pList->pDirty==0 || isCommit );
  47551. if( isCommit ){
  47552. /* If a WAL transaction is being committed, there is no point in writing
  47553. ** any pages with page numbers greater than nTruncate into the WAL file.
  47554. ** They will never be read by any client. So remove them from the pDirty
  47555. ** list here. */
  47556. PgHdr **ppNext = &pList;
  47557. nList = 0;
  47558. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  47559. if( p->pgno<=nTruncate ){
  47560. ppNext = &p->pDirty;
  47561. nList++;
  47562. }
  47563. }
  47564. assert( pList );
  47565. }else{
  47566. nList = 1;
  47567. }
  47568. pPager->aStat[PAGER_STAT_WRITE] += nList;
  47569. if( pList->pgno==1 ) pager_write_changecounter(pList);
  47570. rc = sqlite3WalFrames(pPager->pWal,
  47571. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  47572. );
  47573. if( rc==SQLITE_OK && pPager->pBackup ){
  47574. for(p=pList; p; p=p->pDirty){
  47575. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  47576. }
  47577. }
  47578. #ifdef SQLITE_CHECK_PAGES
  47579. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  47580. for(p=pList; p; p=p->pDirty){
  47581. pager_set_pagehash(p);
  47582. }
  47583. #endif
  47584. return rc;
  47585. }
  47586. /*
  47587. ** Begin a read transaction on the WAL.
  47588. **
  47589. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  47590. ** makes a snapshot of the database at the current point in time and preserves
  47591. ** that snapshot for use by the reader in spite of concurrently changes by
  47592. ** other writers or checkpointers.
  47593. */
  47594. static int pagerBeginReadTransaction(Pager *pPager){
  47595. int rc; /* Return code */
  47596. int changed = 0; /* True if cache must be reset */
  47597. assert( pagerUseWal(pPager) );
  47598. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  47599. /* sqlite3WalEndReadTransaction() was not called for the previous
  47600. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  47601. ** are in locking_mode=NORMAL and EndRead() was previously called,
  47602. ** the duplicate call is harmless.
  47603. */
  47604. sqlite3WalEndReadTransaction(pPager->pWal);
  47605. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  47606. if( rc!=SQLITE_OK || changed ){
  47607. pager_reset(pPager);
  47608. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  47609. }
  47610. return rc;
  47611. }
  47612. #endif
  47613. /*
  47614. ** This function is called as part of the transition from PAGER_OPEN
  47615. ** to PAGER_READER state to determine the size of the database file
  47616. ** in pages (assuming the page size currently stored in Pager.pageSize).
  47617. **
  47618. ** If no error occurs, SQLITE_OK is returned and the size of the database
  47619. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  47620. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  47621. */
  47622. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  47623. Pgno nPage; /* Value to return via *pnPage */
  47624. /* Query the WAL sub-system for the database size. The WalDbsize()
  47625. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  47626. ** if the database size is not available. The database size is not
  47627. ** available from the WAL sub-system if the log file is empty or
  47628. ** contains no valid committed transactions.
  47629. */
  47630. assert( pPager->eState==PAGER_OPEN );
  47631. assert( pPager->eLock>=SHARED_LOCK );
  47632. assert( isOpen(pPager->fd) );
  47633. assert( pPager->tempFile==0 );
  47634. nPage = sqlite3WalDbsize(pPager->pWal);
  47635. /* If the number of pages in the database is not available from the
  47636. ** WAL sub-system, determine the page count based on the size of
  47637. ** the database file. If the size of the database file is not an
  47638. ** integer multiple of the page-size, round up the result.
  47639. */
  47640. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  47641. i64 n = 0; /* Size of db file in bytes */
  47642. int rc = sqlite3OsFileSize(pPager->fd, &n);
  47643. if( rc!=SQLITE_OK ){
  47644. return rc;
  47645. }
  47646. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  47647. }
  47648. /* If the current number of pages in the file is greater than the
  47649. ** configured maximum pager number, increase the allowed limit so
  47650. ** that the file can be read.
  47651. */
  47652. if( nPage>pPager->mxPgno ){
  47653. pPager->mxPgno = (Pgno)nPage;
  47654. }
  47655. *pnPage = nPage;
  47656. return SQLITE_OK;
  47657. }
  47658. #ifndef SQLITE_OMIT_WAL
  47659. /*
  47660. ** Check if the *-wal file that corresponds to the database opened by pPager
  47661. ** exists if the database is not empy, or verify that the *-wal file does
  47662. ** not exist (by deleting it) if the database file is empty.
  47663. **
  47664. ** If the database is not empty and the *-wal file exists, open the pager
  47665. ** in WAL mode. If the database is empty or if no *-wal file exists and
  47666. ** if no error occurs, make sure Pager.journalMode is not set to
  47667. ** PAGER_JOURNALMODE_WAL.
  47668. **
  47669. ** Return SQLITE_OK or an error code.
  47670. **
  47671. ** The caller must hold a SHARED lock on the database file to call this
  47672. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  47673. ** a WAL on a none-empty database, this ensures there is no race condition
  47674. ** between the xAccess() below and an xDelete() being executed by some
  47675. ** other connection.
  47676. */
  47677. static int pagerOpenWalIfPresent(Pager *pPager){
  47678. int rc = SQLITE_OK;
  47679. assert( pPager->eState==PAGER_OPEN );
  47680. assert( pPager->eLock>=SHARED_LOCK );
  47681. if( !pPager->tempFile ){
  47682. int isWal; /* True if WAL file exists */
  47683. rc = sqlite3OsAccess(
  47684. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  47685. );
  47686. if( rc==SQLITE_OK ){
  47687. if( isWal ){
  47688. Pgno nPage; /* Size of the database file */
  47689. rc = pagerPagecount(pPager, &nPage);
  47690. if( rc ) return rc;
  47691. if( nPage==0 ){
  47692. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  47693. }else{
  47694. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  47695. rc = sqlite3PagerOpenWal(pPager, 0);
  47696. }
  47697. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  47698. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  47699. }
  47700. }
  47701. }
  47702. return rc;
  47703. }
  47704. #endif
  47705. /*
  47706. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  47707. ** the entire master journal file. The case pSavepoint==NULL occurs when
  47708. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  47709. ** savepoint.
  47710. **
  47711. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  47712. ** being rolled back), then the rollback consists of up to three stages,
  47713. ** performed in the order specified:
  47714. **
  47715. ** * Pages are played back from the main journal starting at byte
  47716. ** offset PagerSavepoint.iOffset and continuing to
  47717. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  47718. ** file if PagerSavepoint.iHdrOffset is zero.
  47719. **
  47720. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  47721. ** back starting from the journal header immediately following
  47722. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  47723. **
  47724. ** * Pages are then played back from the sub-journal file, starting
  47725. ** with the PagerSavepoint.iSubRec and continuing to the end of
  47726. ** the journal file.
  47727. **
  47728. ** Throughout the rollback process, each time a page is rolled back, the
  47729. ** corresponding bit is set in a bitvec structure (variable pDone in the
  47730. ** implementation below). This is used to ensure that a page is only
  47731. ** rolled back the first time it is encountered in either journal.
  47732. **
  47733. ** If pSavepoint is NULL, then pages are only played back from the main
  47734. ** journal file. There is no need for a bitvec in this case.
  47735. **
  47736. ** In either case, before playback commences the Pager.dbSize variable
  47737. ** is reset to the value that it held at the start of the savepoint
  47738. ** (or transaction). No page with a page-number greater than this value
  47739. ** is played back. If one is encountered it is simply skipped.
  47740. */
  47741. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  47742. i64 szJ; /* Effective size of the main journal */
  47743. i64 iHdrOff; /* End of first segment of main-journal records */
  47744. int rc = SQLITE_OK; /* Return code */
  47745. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  47746. assert( pPager->eState!=PAGER_ERROR );
  47747. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  47748. /* Allocate a bitvec to use to store the set of pages rolled back */
  47749. if( pSavepoint ){
  47750. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  47751. if( !pDone ){
  47752. return SQLITE_NOMEM_BKPT;
  47753. }
  47754. }
  47755. /* Set the database size back to the value it was before the savepoint
  47756. ** being reverted was opened.
  47757. */
  47758. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  47759. pPager->changeCountDone = pPager->tempFile;
  47760. if( !pSavepoint && pagerUseWal(pPager) ){
  47761. return pagerRollbackWal(pPager);
  47762. }
  47763. /* Use pPager->journalOff as the effective size of the main rollback
  47764. ** journal. The actual file might be larger than this in
  47765. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  47766. ** past pPager->journalOff is off-limits to us.
  47767. */
  47768. szJ = pPager->journalOff;
  47769. assert( pagerUseWal(pPager)==0 || szJ==0 );
  47770. /* Begin by rolling back records from the main journal starting at
  47771. ** PagerSavepoint.iOffset and continuing to the next journal header.
  47772. ** There might be records in the main journal that have a page number
  47773. ** greater than the current database size (pPager->dbSize) but those
  47774. ** will be skipped automatically. Pages are added to pDone as they
  47775. ** are played back.
  47776. */
  47777. if( pSavepoint && !pagerUseWal(pPager) ){
  47778. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  47779. pPager->journalOff = pSavepoint->iOffset;
  47780. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  47781. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47782. }
  47783. assert( rc!=SQLITE_DONE );
  47784. }else{
  47785. pPager->journalOff = 0;
  47786. }
  47787. /* Continue rolling back records out of the main journal starting at
  47788. ** the first journal header seen and continuing until the effective end
  47789. ** of the main journal file. Continue to skip out-of-range pages and
  47790. ** continue adding pages rolled back to pDone.
  47791. */
  47792. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  47793. u32 ii; /* Loop counter */
  47794. u32 nJRec = 0; /* Number of Journal Records */
  47795. u32 dummy;
  47796. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  47797. assert( rc!=SQLITE_DONE );
  47798. /*
  47799. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  47800. ** test is related to ticket #2565. See the discussion in the
  47801. ** pager_playback() function for additional information.
  47802. */
  47803. if( nJRec==0
  47804. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  47805. ){
  47806. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  47807. }
  47808. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  47809. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47810. }
  47811. assert( rc!=SQLITE_DONE );
  47812. }
  47813. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  47814. /* Finally, rollback pages from the sub-journal. Page that were
  47815. ** previously rolled back out of the main journal (and are hence in pDone)
  47816. ** will be skipped. Out-of-range pages are also skipped.
  47817. */
  47818. if( pSavepoint ){
  47819. u32 ii; /* Loop counter */
  47820. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  47821. if( pagerUseWal(pPager) ){
  47822. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  47823. }
  47824. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  47825. assert( offset==(i64)ii*(4+pPager->pageSize) );
  47826. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  47827. }
  47828. assert( rc!=SQLITE_DONE );
  47829. }
  47830. sqlite3BitvecDestroy(pDone);
  47831. if( rc==SQLITE_OK ){
  47832. pPager->journalOff = szJ;
  47833. }
  47834. return rc;
  47835. }
  47836. /*
  47837. ** Change the maximum number of in-memory pages that are allowed
  47838. ** before attempting to recycle clean and unused pages.
  47839. */
  47840. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  47841. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  47842. }
  47843. /*
  47844. ** Change the maximum number of in-memory pages that are allowed
  47845. ** before attempting to spill pages to journal.
  47846. */
  47847. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  47848. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  47849. }
  47850. /*
  47851. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  47852. */
  47853. static void pagerFixMaplimit(Pager *pPager){
  47854. #if SQLITE_MAX_MMAP_SIZE>0
  47855. sqlite3_file *fd = pPager->fd;
  47856. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  47857. sqlite3_int64 sz;
  47858. sz = pPager->szMmap;
  47859. pPager->bUseFetch = (sz>0);
  47860. setGetterMethod(pPager);
  47861. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  47862. }
  47863. #endif
  47864. }
  47865. /*
  47866. ** Change the maximum size of any memory mapping made of the database file.
  47867. */
  47868. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  47869. pPager->szMmap = szMmap;
  47870. pagerFixMaplimit(pPager);
  47871. }
  47872. /*
  47873. ** Free as much memory as possible from the pager.
  47874. */
  47875. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  47876. sqlite3PcacheShrink(pPager->pPCache);
  47877. }
  47878. /*
  47879. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  47880. **
  47881. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  47882. ** of the database to damage due to OS crashes or power failures by
  47883. ** changing the number of syncs()s when writing the journals.
  47884. ** There are four levels:
  47885. **
  47886. ** OFF sqlite3OsSync() is never called. This is the default
  47887. ** for temporary and transient files.
  47888. **
  47889. ** NORMAL The journal is synced once before writes begin on the
  47890. ** database. This is normally adequate protection, but
  47891. ** it is theoretically possible, though very unlikely,
  47892. ** that an inopertune power failure could leave the journal
  47893. ** in a state which would cause damage to the database
  47894. ** when it is rolled back.
  47895. **
  47896. ** FULL The journal is synced twice before writes begin on the
  47897. ** database (with some additional information - the nRec field
  47898. ** of the journal header - being written in between the two
  47899. ** syncs). If we assume that writing a
  47900. ** single disk sector is atomic, then this mode provides
  47901. ** assurance that the journal will not be corrupted to the
  47902. ** point of causing damage to the database during rollback.
  47903. **
  47904. ** EXTRA This is like FULL except that is also syncs the directory
  47905. ** that contains the rollback journal after the rollback
  47906. ** journal is unlinked.
  47907. **
  47908. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  47909. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  47910. ** prior to the start of checkpoint and that the database file is synced
  47911. ** at the conclusion of the checkpoint if the entire content of the WAL
  47912. ** was written back into the database. But no sync operations occur for
  47913. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  47914. ** file is synced following each commit operation, in addition to the
  47915. ** syncs associated with NORMAL. There is no difference between FULL
  47916. ** and EXTRA for WAL mode.
  47917. **
  47918. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  47919. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  47920. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  47921. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  47922. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  47923. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  47924. ** the xSync primitive is called and is relevant to all platforms.
  47925. **
  47926. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  47927. ** and FULL=3.
  47928. */
  47929. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  47930. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  47931. Pager *pPager, /* The pager to set safety level for */
  47932. unsigned pgFlags /* Various flags */
  47933. ){
  47934. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  47935. if( pPager->tempFile ){
  47936. pPager->noSync = 1;
  47937. pPager->fullSync = 0;
  47938. pPager->extraSync = 0;
  47939. }else{
  47940. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  47941. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  47942. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  47943. }
  47944. if( pPager->noSync ){
  47945. pPager->syncFlags = 0;
  47946. }else if( pgFlags & PAGER_FULLFSYNC ){
  47947. pPager->syncFlags = SQLITE_SYNC_FULL;
  47948. }else{
  47949. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  47950. }
  47951. pPager->walSyncFlags = (pPager->syncFlags<<2);
  47952. if( pPager->fullSync ){
  47953. pPager->walSyncFlags |= pPager->syncFlags;
  47954. }
  47955. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  47956. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  47957. }
  47958. if( pgFlags & PAGER_CACHESPILL ){
  47959. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  47960. }else{
  47961. pPager->doNotSpill |= SPILLFLAG_OFF;
  47962. }
  47963. }
  47964. #endif
  47965. /*
  47966. ** The following global variable is incremented whenever the library
  47967. ** attempts to open a temporary file. This information is used for
  47968. ** testing and analysis only.
  47969. */
  47970. #ifdef SQLITE_TEST
  47971. SQLITE_API int sqlite3_opentemp_count = 0;
  47972. #endif
  47973. /*
  47974. ** Open a temporary file.
  47975. **
  47976. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  47977. ** or some other error code if we fail. The OS will automatically
  47978. ** delete the temporary file when it is closed.
  47979. **
  47980. ** The flags passed to the VFS layer xOpen() call are those specified
  47981. ** by parameter vfsFlags ORed with the following:
  47982. **
  47983. ** SQLITE_OPEN_READWRITE
  47984. ** SQLITE_OPEN_CREATE
  47985. ** SQLITE_OPEN_EXCLUSIVE
  47986. ** SQLITE_OPEN_DELETEONCLOSE
  47987. */
  47988. static int pagerOpentemp(
  47989. Pager *pPager, /* The pager object */
  47990. sqlite3_file *pFile, /* Write the file descriptor here */
  47991. int vfsFlags /* Flags passed through to the VFS */
  47992. ){
  47993. int rc; /* Return code */
  47994. #ifdef SQLITE_TEST
  47995. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  47996. #endif
  47997. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  47998. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  47999. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  48000. assert( rc!=SQLITE_OK || isOpen(pFile) );
  48001. return rc;
  48002. }
  48003. /*
  48004. ** Set the busy handler function.
  48005. **
  48006. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  48007. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  48008. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  48009. ** lock. It does *not* invoke the busy handler when upgrading from
  48010. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  48011. ** (which occurs during hot-journal rollback). Summary:
  48012. **
  48013. ** Transition | Invokes xBusyHandler
  48014. ** --------------------------------------------------------
  48015. ** NO_LOCK -> SHARED_LOCK | Yes
  48016. ** SHARED_LOCK -> RESERVED_LOCK | No
  48017. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  48018. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  48019. **
  48020. ** If the busy-handler callback returns non-zero, the lock is
  48021. ** retried. If it returns zero, then the SQLITE_BUSY error is
  48022. ** returned to the caller of the pager API function.
  48023. */
  48024. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  48025. Pager *pPager, /* Pager object */
  48026. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  48027. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  48028. ){
  48029. pPager->xBusyHandler = xBusyHandler;
  48030. pPager->pBusyHandlerArg = pBusyHandlerArg;
  48031. if( isOpen(pPager->fd) ){
  48032. void **ap = (void **)&pPager->xBusyHandler;
  48033. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  48034. assert( ap[1]==pBusyHandlerArg );
  48035. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  48036. }
  48037. }
  48038. /*
  48039. ** Change the page size used by the Pager object. The new page size
  48040. ** is passed in *pPageSize.
  48041. **
  48042. ** If the pager is in the error state when this function is called, it
  48043. ** is a no-op. The value returned is the error state error code (i.e.
  48044. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  48045. **
  48046. ** Otherwise, if all of the following are true:
  48047. **
  48048. ** * the new page size (value of *pPageSize) is valid (a power
  48049. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  48050. **
  48051. ** * there are no outstanding page references, and
  48052. **
  48053. ** * the database is either not an in-memory database or it is
  48054. ** an in-memory database that currently consists of zero pages.
  48055. **
  48056. ** then the pager object page size is set to *pPageSize.
  48057. **
  48058. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  48059. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  48060. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  48061. ** In all other cases, SQLITE_OK is returned.
  48062. **
  48063. ** If the page size is not changed, either because one of the enumerated
  48064. ** conditions above is not true, the pager was in error state when this
  48065. ** function was called, or because the memory allocation attempt failed,
  48066. ** then *pPageSize is set to the old, retained page size before returning.
  48067. */
  48068. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  48069. int rc = SQLITE_OK;
  48070. /* It is not possible to do a full assert_pager_state() here, as this
  48071. ** function may be called from within PagerOpen(), before the state
  48072. ** of the Pager object is internally consistent.
  48073. **
  48074. ** At one point this function returned an error if the pager was in
  48075. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  48076. ** there is at least one outstanding page reference, this function
  48077. ** is a no-op for that case anyhow.
  48078. */
  48079. u32 pageSize = *pPageSize;
  48080. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  48081. if( (pPager->memDb==0 || pPager->dbSize==0)
  48082. && sqlite3PcacheRefCount(pPager->pPCache)==0
  48083. && pageSize && pageSize!=(u32)pPager->pageSize
  48084. ){
  48085. char *pNew = NULL; /* New temp space */
  48086. i64 nByte = 0;
  48087. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  48088. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  48089. }
  48090. if( rc==SQLITE_OK ){
  48091. pNew = (char *)sqlite3PageMalloc(pageSize);
  48092. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  48093. }
  48094. if( rc==SQLITE_OK ){
  48095. pager_reset(pPager);
  48096. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  48097. }
  48098. if( rc==SQLITE_OK ){
  48099. sqlite3PageFree(pPager->pTmpSpace);
  48100. pPager->pTmpSpace = pNew;
  48101. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  48102. pPager->pageSize = pageSize;
  48103. }else{
  48104. sqlite3PageFree(pNew);
  48105. }
  48106. }
  48107. *pPageSize = pPager->pageSize;
  48108. if( rc==SQLITE_OK ){
  48109. if( nReserve<0 ) nReserve = pPager->nReserve;
  48110. assert( nReserve>=0 && nReserve<1000 );
  48111. pPager->nReserve = (i16)nReserve;
  48112. pagerReportSize(pPager);
  48113. pagerFixMaplimit(pPager);
  48114. }
  48115. return rc;
  48116. }
  48117. /*
  48118. ** Return a pointer to the "temporary page" buffer held internally
  48119. ** by the pager. This is a buffer that is big enough to hold the
  48120. ** entire content of a database page. This buffer is used internally
  48121. ** during rollback and will be overwritten whenever a rollback
  48122. ** occurs. But other modules are free to use it too, as long as
  48123. ** no rollbacks are happening.
  48124. */
  48125. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  48126. return pPager->pTmpSpace;
  48127. }
  48128. /*
  48129. ** Attempt to set the maximum database page count if mxPage is positive.
  48130. ** Make no changes if mxPage is zero or negative. And never reduce the
  48131. ** maximum page count below the current size of the database.
  48132. **
  48133. ** Regardless of mxPage, return the current maximum page count.
  48134. */
  48135. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  48136. if( mxPage>0 ){
  48137. pPager->mxPgno = mxPage;
  48138. }
  48139. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  48140. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  48141. return pPager->mxPgno;
  48142. }
  48143. /*
  48144. ** The following set of routines are used to disable the simulated
  48145. ** I/O error mechanism. These routines are used to avoid simulated
  48146. ** errors in places where we do not care about errors.
  48147. **
  48148. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  48149. ** and generate no code.
  48150. */
  48151. #ifdef SQLITE_TEST
  48152. SQLITE_API extern int sqlite3_io_error_pending;
  48153. SQLITE_API extern int sqlite3_io_error_hit;
  48154. static int saved_cnt;
  48155. void disable_simulated_io_errors(void){
  48156. saved_cnt = sqlite3_io_error_pending;
  48157. sqlite3_io_error_pending = -1;
  48158. }
  48159. void enable_simulated_io_errors(void){
  48160. sqlite3_io_error_pending = saved_cnt;
  48161. }
  48162. #else
  48163. # define disable_simulated_io_errors()
  48164. # define enable_simulated_io_errors()
  48165. #endif
  48166. /*
  48167. ** Read the first N bytes from the beginning of the file into memory
  48168. ** that pDest points to.
  48169. **
  48170. ** If the pager was opened on a transient file (zFilename==""), or
  48171. ** opened on a file less than N bytes in size, the output buffer is
  48172. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  48173. ** function is used to read database headers, and a new transient or
  48174. ** zero sized database has a header than consists entirely of zeroes.
  48175. **
  48176. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  48177. ** the error code is returned to the caller and the contents of the
  48178. ** output buffer undefined.
  48179. */
  48180. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  48181. int rc = SQLITE_OK;
  48182. memset(pDest, 0, N);
  48183. assert( isOpen(pPager->fd) || pPager->tempFile );
  48184. /* This routine is only called by btree immediately after creating
  48185. ** the Pager object. There has not been an opportunity to transition
  48186. ** to WAL mode yet.
  48187. */
  48188. assert( !pagerUseWal(pPager) );
  48189. if( isOpen(pPager->fd) ){
  48190. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  48191. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  48192. if( rc==SQLITE_IOERR_SHORT_READ ){
  48193. rc = SQLITE_OK;
  48194. }
  48195. }
  48196. return rc;
  48197. }
  48198. /*
  48199. ** This function may only be called when a read-transaction is open on
  48200. ** the pager. It returns the total number of pages in the database.
  48201. **
  48202. ** However, if the file is between 1 and <page-size> bytes in size, then
  48203. ** this is considered a 1 page file.
  48204. */
  48205. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  48206. assert( pPager->eState>=PAGER_READER );
  48207. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  48208. *pnPage = (int)pPager->dbSize;
  48209. }
  48210. /*
  48211. ** Try to obtain a lock of type locktype on the database file. If
  48212. ** a similar or greater lock is already held, this function is a no-op
  48213. ** (returning SQLITE_OK immediately).
  48214. **
  48215. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  48216. ** the busy callback if the lock is currently not available. Repeat
  48217. ** until the busy callback returns false or until the attempt to
  48218. ** obtain the lock succeeds.
  48219. **
  48220. ** Return SQLITE_OK on success and an error code if we cannot obtain
  48221. ** the lock. If the lock is obtained successfully, set the Pager.state
  48222. ** variable to locktype before returning.
  48223. */
  48224. static int pager_wait_on_lock(Pager *pPager, int locktype){
  48225. int rc; /* Return code */
  48226. /* Check that this is either a no-op (because the requested lock is
  48227. ** already held), or one of the transitions that the busy-handler
  48228. ** may be invoked during, according to the comment above
  48229. ** sqlite3PagerSetBusyhandler().
  48230. */
  48231. assert( (pPager->eLock>=locktype)
  48232. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  48233. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  48234. );
  48235. do {
  48236. rc = pagerLockDb(pPager, locktype);
  48237. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  48238. return rc;
  48239. }
  48240. /*
  48241. ** Function assertTruncateConstraint(pPager) checks that one of the
  48242. ** following is true for all dirty pages currently in the page-cache:
  48243. **
  48244. ** a) The page number is less than or equal to the size of the
  48245. ** current database image, in pages, OR
  48246. **
  48247. ** b) if the page content were written at this time, it would not
  48248. ** be necessary to write the current content out to the sub-journal
  48249. ** (as determined by function subjRequiresPage()).
  48250. **
  48251. ** If the condition asserted by this function were not true, and the
  48252. ** dirty page were to be discarded from the cache via the pagerStress()
  48253. ** routine, pagerStress() would not write the current page content to
  48254. ** the database file. If a savepoint transaction were rolled back after
  48255. ** this happened, the correct behavior would be to restore the current
  48256. ** content of the page. However, since this content is not present in either
  48257. ** the database file or the portion of the rollback journal and
  48258. ** sub-journal rolled back the content could not be restored and the
  48259. ** database image would become corrupt. It is therefore fortunate that
  48260. ** this circumstance cannot arise.
  48261. */
  48262. #if defined(SQLITE_DEBUG)
  48263. static void assertTruncateConstraintCb(PgHdr *pPg){
  48264. assert( pPg->flags&PGHDR_DIRTY );
  48265. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  48266. }
  48267. static void assertTruncateConstraint(Pager *pPager){
  48268. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  48269. }
  48270. #else
  48271. # define assertTruncateConstraint(pPager)
  48272. #endif
  48273. /*
  48274. ** Truncate the in-memory database file image to nPage pages. This
  48275. ** function does not actually modify the database file on disk. It
  48276. ** just sets the internal state of the pager object so that the
  48277. ** truncation will be done when the current transaction is committed.
  48278. **
  48279. ** This function is only called right before committing a transaction.
  48280. ** Once this function has been called, the transaction must either be
  48281. ** rolled back or committed. It is not safe to call this function and
  48282. ** then continue writing to the database.
  48283. */
  48284. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  48285. assert( pPager->dbSize>=nPage );
  48286. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  48287. pPager->dbSize = nPage;
  48288. /* At one point the code here called assertTruncateConstraint() to
  48289. ** ensure that all pages being truncated away by this operation are,
  48290. ** if one or more savepoints are open, present in the savepoint
  48291. ** journal so that they can be restored if the savepoint is rolled
  48292. ** back. This is no longer necessary as this function is now only
  48293. ** called right before committing a transaction. So although the
  48294. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  48295. ** they cannot be rolled back. So the assertTruncateConstraint() call
  48296. ** is no longer correct. */
  48297. }
  48298. /*
  48299. ** This function is called before attempting a hot-journal rollback. It
  48300. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  48301. ** size of the journal file so that the pager_playback() routine knows
  48302. ** that the entire journal file has been synced.
  48303. **
  48304. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  48305. ** that if a power-failure occurs during the rollback, the process that
  48306. ** attempts rollback following system recovery sees the same journal
  48307. ** content as this process.
  48308. **
  48309. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  48310. ** an SQLite error code.
  48311. */
  48312. static int pagerSyncHotJournal(Pager *pPager){
  48313. int rc = SQLITE_OK;
  48314. if( !pPager->noSync ){
  48315. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  48316. }
  48317. if( rc==SQLITE_OK ){
  48318. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  48319. }
  48320. return rc;
  48321. }
  48322. #if SQLITE_MAX_MMAP_SIZE>0
  48323. /*
  48324. ** Obtain a reference to a memory mapped page object for page number pgno.
  48325. ** The new object will use the pointer pData, obtained from xFetch().
  48326. ** If successful, set *ppPage to point to the new page reference
  48327. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  48328. ** *ppPage to zero.
  48329. **
  48330. ** Page references obtained by calling this function should be released
  48331. ** by calling pagerReleaseMapPage().
  48332. */
  48333. static int pagerAcquireMapPage(
  48334. Pager *pPager, /* Pager object */
  48335. Pgno pgno, /* Page number */
  48336. void *pData, /* xFetch()'d data for this page */
  48337. PgHdr **ppPage /* OUT: Acquired page object */
  48338. ){
  48339. PgHdr *p; /* Memory mapped page to return */
  48340. if( pPager->pMmapFreelist ){
  48341. *ppPage = p = pPager->pMmapFreelist;
  48342. pPager->pMmapFreelist = p->pDirty;
  48343. p->pDirty = 0;
  48344. assert( pPager->nExtra>=8 );
  48345. memset(p->pExtra, 0, 8);
  48346. }else{
  48347. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  48348. if( p==0 ){
  48349. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  48350. return SQLITE_NOMEM_BKPT;
  48351. }
  48352. p->pExtra = (void *)&p[1];
  48353. p->flags = PGHDR_MMAP;
  48354. p->nRef = 1;
  48355. p->pPager = pPager;
  48356. }
  48357. assert( p->pExtra==(void *)&p[1] );
  48358. assert( p->pPage==0 );
  48359. assert( p->flags==PGHDR_MMAP );
  48360. assert( p->pPager==pPager );
  48361. assert( p->nRef==1 );
  48362. p->pgno = pgno;
  48363. p->pData = pData;
  48364. pPager->nMmapOut++;
  48365. return SQLITE_OK;
  48366. }
  48367. #endif
  48368. /*
  48369. ** Release a reference to page pPg. pPg must have been returned by an
  48370. ** earlier call to pagerAcquireMapPage().
  48371. */
  48372. static void pagerReleaseMapPage(PgHdr *pPg){
  48373. Pager *pPager = pPg->pPager;
  48374. pPager->nMmapOut--;
  48375. pPg->pDirty = pPager->pMmapFreelist;
  48376. pPager->pMmapFreelist = pPg;
  48377. assert( pPager->fd->pMethods->iVersion>=3 );
  48378. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  48379. }
  48380. /*
  48381. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  48382. */
  48383. static void pagerFreeMapHdrs(Pager *pPager){
  48384. PgHdr *p;
  48385. PgHdr *pNext;
  48386. for(p=pPager->pMmapFreelist; p; p=pNext){
  48387. pNext = p->pDirty;
  48388. sqlite3_free(p);
  48389. }
  48390. }
  48391. /*
  48392. ** Shutdown the page cache. Free all memory and close all files.
  48393. **
  48394. ** If a transaction was in progress when this routine is called, that
  48395. ** transaction is rolled back. All outstanding pages are invalidated
  48396. ** and their memory is freed. Any attempt to use a page associated
  48397. ** with this page cache after this function returns will likely
  48398. ** result in a coredump.
  48399. **
  48400. ** This function always succeeds. If a transaction is active an attempt
  48401. ** is made to roll it back. If an error occurs during the rollback
  48402. ** a hot journal may be left in the filesystem but no error is returned
  48403. ** to the caller.
  48404. */
  48405. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  48406. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  48407. assert( db || pagerUseWal(pPager)==0 );
  48408. assert( assert_pager_state(pPager) );
  48409. disable_simulated_io_errors();
  48410. sqlite3BeginBenignMalloc();
  48411. pagerFreeMapHdrs(pPager);
  48412. /* pPager->errCode = 0; */
  48413. pPager->exclusiveMode = 0;
  48414. #ifndef SQLITE_OMIT_WAL
  48415. assert( db || pPager->pWal==0 );
  48416. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,
  48417. (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
  48418. );
  48419. pPager->pWal = 0;
  48420. #endif
  48421. pager_reset(pPager);
  48422. if( MEMDB ){
  48423. pager_unlock(pPager);
  48424. }else{
  48425. /* If it is open, sync the journal file before calling UnlockAndRollback.
  48426. ** If this is not done, then an unsynced portion of the open journal
  48427. ** file may be played back into the database. If a power failure occurs
  48428. ** while this is happening, the database could become corrupt.
  48429. **
  48430. ** If an error occurs while trying to sync the journal, shift the pager
  48431. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  48432. ** database and close the journal file without attempting to roll it
  48433. ** back or finalize it. The next database user will have to do hot-journal
  48434. ** rollback before accessing the database file.
  48435. */
  48436. if( isOpen(pPager->jfd) ){
  48437. pager_error(pPager, pagerSyncHotJournal(pPager));
  48438. }
  48439. pagerUnlockAndRollback(pPager);
  48440. }
  48441. sqlite3EndBenignMalloc();
  48442. enable_simulated_io_errors();
  48443. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  48444. IOTRACE(("CLOSE %p\n", pPager))
  48445. sqlite3OsClose(pPager->jfd);
  48446. sqlite3OsClose(pPager->fd);
  48447. sqlite3PageFree(pTmp);
  48448. sqlite3PcacheClose(pPager->pPCache);
  48449. #ifdef SQLITE_HAS_CODEC
  48450. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  48451. #endif
  48452. assert( !pPager->aSavepoint && !pPager->pInJournal );
  48453. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  48454. sqlite3_free(pPager);
  48455. return SQLITE_OK;
  48456. }
  48457. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  48458. /*
  48459. ** Return the page number for page pPg.
  48460. */
  48461. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  48462. return pPg->pgno;
  48463. }
  48464. #endif
  48465. /*
  48466. ** Increment the reference count for page pPg.
  48467. */
  48468. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  48469. sqlite3PcacheRef(pPg);
  48470. }
  48471. /*
  48472. ** Sync the journal. In other words, make sure all the pages that have
  48473. ** been written to the journal have actually reached the surface of the
  48474. ** disk and can be restored in the event of a hot-journal rollback.
  48475. **
  48476. ** If the Pager.noSync flag is set, then this function is a no-op.
  48477. ** Otherwise, the actions required depend on the journal-mode and the
  48478. ** device characteristics of the file-system, as follows:
  48479. **
  48480. ** * If the journal file is an in-memory journal file, no action need
  48481. ** be taken.
  48482. **
  48483. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  48484. ** then the nRec field of the most recently written journal header
  48485. ** is updated to contain the number of journal records that have
  48486. ** been written following it. If the pager is operating in full-sync
  48487. ** mode, then the journal file is synced before this field is updated.
  48488. **
  48489. ** * If the device does not support the SEQUENTIAL property, then
  48490. ** journal file is synced.
  48491. **
  48492. ** Or, in pseudo-code:
  48493. **
  48494. ** if( NOT <in-memory journal> ){
  48495. ** if( NOT SAFE_APPEND ){
  48496. ** if( <full-sync mode> ) xSync(<journal file>);
  48497. ** <update nRec field>
  48498. ** }
  48499. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  48500. ** }
  48501. **
  48502. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  48503. ** page currently held in memory before returning SQLITE_OK. If an IO
  48504. ** error is encountered, then the IO error code is returned to the caller.
  48505. */
  48506. static int syncJournal(Pager *pPager, int newHdr){
  48507. int rc; /* Return code */
  48508. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  48509. || pPager->eState==PAGER_WRITER_DBMOD
  48510. );
  48511. assert( assert_pager_state(pPager) );
  48512. assert( !pagerUseWal(pPager) );
  48513. rc = sqlite3PagerExclusiveLock(pPager);
  48514. if( rc!=SQLITE_OK ) return rc;
  48515. if( !pPager->noSync ){
  48516. assert( !pPager->tempFile );
  48517. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  48518. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48519. assert( isOpen(pPager->jfd) );
  48520. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  48521. /* This block deals with an obscure problem. If the last connection
  48522. ** that wrote to this database was operating in persistent-journal
  48523. ** mode, then the journal file may at this point actually be larger
  48524. ** than Pager.journalOff bytes. If the next thing in the journal
  48525. ** file happens to be a journal-header (written as part of the
  48526. ** previous connection's transaction), and a crash or power-failure
  48527. ** occurs after nRec is updated but before this connection writes
  48528. ** anything else to the journal file (or commits/rolls back its
  48529. ** transaction), then SQLite may become confused when doing the
  48530. ** hot-journal rollback following recovery. It may roll back all
  48531. ** of this connections data, then proceed to rolling back the old,
  48532. ** out-of-date data that follows it. Database corruption.
  48533. **
  48534. ** To work around this, if the journal file does appear to contain
  48535. ** a valid header following Pager.journalOff, then write a 0x00
  48536. ** byte to the start of it to prevent it from being recognized.
  48537. **
  48538. ** Variable iNextHdrOffset is set to the offset at which this
  48539. ** problematic header will occur, if it exists. aMagic is used
  48540. ** as a temporary buffer to inspect the first couple of bytes of
  48541. ** the potential journal header.
  48542. */
  48543. i64 iNextHdrOffset;
  48544. u8 aMagic[8];
  48545. u8 zHeader[sizeof(aJournalMagic)+4];
  48546. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  48547. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  48548. iNextHdrOffset = journalHdrOffset(pPager);
  48549. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  48550. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  48551. static const u8 zerobyte = 0;
  48552. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  48553. }
  48554. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  48555. return rc;
  48556. }
  48557. /* Write the nRec value into the journal file header. If in
  48558. ** full-synchronous mode, sync the journal first. This ensures that
  48559. ** all data has really hit the disk before nRec is updated to mark
  48560. ** it as a candidate for rollback.
  48561. **
  48562. ** This is not required if the persistent media supports the
  48563. ** SAFE_APPEND property. Because in this case it is not possible
  48564. ** for garbage data to be appended to the file, the nRec field
  48565. ** is populated with 0xFFFFFFFF when the journal header is written
  48566. ** and never needs to be updated.
  48567. */
  48568. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  48569. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  48570. IOTRACE(("JSYNC %p\n", pPager))
  48571. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  48572. if( rc!=SQLITE_OK ) return rc;
  48573. }
  48574. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  48575. rc = sqlite3OsWrite(
  48576. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  48577. );
  48578. if( rc!=SQLITE_OK ) return rc;
  48579. }
  48580. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  48581. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  48582. IOTRACE(("JSYNC %p\n", pPager))
  48583. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  48584. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  48585. );
  48586. if( rc!=SQLITE_OK ) return rc;
  48587. }
  48588. pPager->journalHdr = pPager->journalOff;
  48589. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  48590. pPager->nRec = 0;
  48591. rc = writeJournalHdr(pPager);
  48592. if( rc!=SQLITE_OK ) return rc;
  48593. }
  48594. }else{
  48595. pPager->journalHdr = pPager->journalOff;
  48596. }
  48597. }
  48598. /* Unless the pager is in noSync mode, the journal file was just
  48599. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  48600. ** all pages.
  48601. */
  48602. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  48603. pPager->eState = PAGER_WRITER_DBMOD;
  48604. assert( assert_pager_state(pPager) );
  48605. return SQLITE_OK;
  48606. }
  48607. /*
  48608. ** The argument is the first in a linked list of dirty pages connected
  48609. ** by the PgHdr.pDirty pointer. This function writes each one of the
  48610. ** in-memory pages in the list to the database file. The argument may
  48611. ** be NULL, representing an empty list. In this case this function is
  48612. ** a no-op.
  48613. **
  48614. ** The pager must hold at least a RESERVED lock when this function
  48615. ** is called. Before writing anything to the database file, this lock
  48616. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  48617. ** SQLITE_BUSY is returned and no data is written to the database file.
  48618. **
  48619. ** If the pager is a temp-file pager and the actual file-system file
  48620. ** is not yet open, it is created and opened before any data is
  48621. ** written out.
  48622. **
  48623. ** Once the lock has been upgraded and, if necessary, the file opened,
  48624. ** the pages are written out to the database file in list order. Writing
  48625. ** a page is skipped if it meets either of the following criteria:
  48626. **
  48627. ** * The page number is greater than Pager.dbSize, or
  48628. ** * The PGHDR_DONT_WRITE flag is set on the page.
  48629. **
  48630. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  48631. ** is updated accordingly. If page 1 is written out, then the value cached
  48632. ** in Pager.dbFileVers[] is updated to match the new value stored in
  48633. ** the database file.
  48634. **
  48635. ** If everything is successful, SQLITE_OK is returned. If an IO error
  48636. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  48637. ** be obtained, SQLITE_BUSY is returned.
  48638. */
  48639. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  48640. int rc = SQLITE_OK; /* Return code */
  48641. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  48642. assert( !pagerUseWal(pPager) );
  48643. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  48644. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48645. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  48646. /* If the file is a temp-file has not yet been opened, open it now. It
  48647. ** is not possible for rc to be other than SQLITE_OK if this branch
  48648. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  48649. */
  48650. if( !isOpen(pPager->fd) ){
  48651. assert( pPager->tempFile && rc==SQLITE_OK );
  48652. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  48653. }
  48654. /* Before the first write, give the VFS a hint of what the final
  48655. ** file size will be.
  48656. */
  48657. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  48658. if( rc==SQLITE_OK
  48659. && pPager->dbHintSize<pPager->dbSize
  48660. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  48661. ){
  48662. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  48663. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  48664. pPager->dbHintSize = pPager->dbSize;
  48665. }
  48666. while( rc==SQLITE_OK && pList ){
  48667. Pgno pgno = pList->pgno;
  48668. /* If there are dirty pages in the page cache with page numbers greater
  48669. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  48670. ** make the file smaller (presumably by auto-vacuum code). Do not write
  48671. ** any such pages to the file.
  48672. **
  48673. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  48674. ** set (set by sqlite3PagerDontWrite()).
  48675. */
  48676. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  48677. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  48678. char *pData; /* Data to write */
  48679. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  48680. if( pList->pgno==1 ) pager_write_changecounter(pList);
  48681. /* Encode the database */
  48682. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  48683. /* Write out the page data. */
  48684. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  48685. /* If page 1 was just written, update Pager.dbFileVers to match
  48686. ** the value now stored in the database file. If writing this
  48687. ** page caused the database file to grow, update dbFileSize.
  48688. */
  48689. if( pgno==1 ){
  48690. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  48691. }
  48692. if( pgno>pPager->dbFileSize ){
  48693. pPager->dbFileSize = pgno;
  48694. }
  48695. pPager->aStat[PAGER_STAT_WRITE]++;
  48696. /* Update any backup objects copying the contents of this pager. */
  48697. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  48698. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  48699. PAGERID(pPager), pgno, pager_pagehash(pList)));
  48700. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  48701. PAGER_INCR(sqlite3_pager_writedb_count);
  48702. }else{
  48703. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  48704. }
  48705. pager_set_pagehash(pList);
  48706. pList = pList->pDirty;
  48707. }
  48708. return rc;
  48709. }
  48710. /*
  48711. ** Ensure that the sub-journal file is open. If it is already open, this
  48712. ** function is a no-op.
  48713. **
  48714. ** SQLITE_OK is returned if everything goes according to plan. An
  48715. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  48716. ** fails.
  48717. */
  48718. static int openSubJournal(Pager *pPager){
  48719. int rc = SQLITE_OK;
  48720. if( !isOpen(pPager->sjfd) ){
  48721. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  48722. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  48723. | SQLITE_OPEN_DELETEONCLOSE;
  48724. int nStmtSpill = sqlite3Config.nStmtSpill;
  48725. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  48726. nStmtSpill = -1;
  48727. }
  48728. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  48729. }
  48730. return rc;
  48731. }
  48732. /*
  48733. ** Append a record of the current state of page pPg to the sub-journal.
  48734. **
  48735. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  48736. ** for all open savepoints before returning.
  48737. **
  48738. ** This function returns SQLITE_OK if everything is successful, an IO
  48739. ** error code if the attempt to write to the sub-journal fails, or
  48740. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  48741. ** bitvec.
  48742. */
  48743. static int subjournalPage(PgHdr *pPg){
  48744. int rc = SQLITE_OK;
  48745. Pager *pPager = pPg->pPager;
  48746. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  48747. /* Open the sub-journal, if it has not already been opened */
  48748. assert( pPager->useJournal );
  48749. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  48750. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  48751. assert( pagerUseWal(pPager)
  48752. || pageInJournal(pPager, pPg)
  48753. || pPg->pgno>pPager->dbOrigSize
  48754. );
  48755. rc = openSubJournal(pPager);
  48756. /* If the sub-journal was opened successfully (or was already open),
  48757. ** write the journal record into the file. */
  48758. if( rc==SQLITE_OK ){
  48759. void *pData = pPg->pData;
  48760. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  48761. char *pData2;
  48762. #if SQLITE_HAS_CODEC
  48763. if( !pPager->subjInMemory ){
  48764. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  48765. }else
  48766. #endif
  48767. pData2 = pData;
  48768. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  48769. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  48770. if( rc==SQLITE_OK ){
  48771. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  48772. }
  48773. }
  48774. }
  48775. if( rc==SQLITE_OK ){
  48776. pPager->nSubRec++;
  48777. assert( pPager->nSavepoint>0 );
  48778. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  48779. }
  48780. return rc;
  48781. }
  48782. static int subjournalPageIfRequired(PgHdr *pPg){
  48783. if( subjRequiresPage(pPg) ){
  48784. return subjournalPage(pPg);
  48785. }else{
  48786. return SQLITE_OK;
  48787. }
  48788. }
  48789. /*
  48790. ** This function is called by the pcache layer when it has reached some
  48791. ** soft memory limit. The first argument is a pointer to a Pager object
  48792. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  48793. ** database). The second argument is a reference to a page that is
  48794. ** currently dirty but has no outstanding references. The page
  48795. ** is always associated with the Pager object passed as the first
  48796. ** argument.
  48797. **
  48798. ** The job of this function is to make pPg clean by writing its contents
  48799. ** out to the database file, if possible. This may involve syncing the
  48800. ** journal file.
  48801. **
  48802. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  48803. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  48804. ** page clean, the IO error code is returned. If the page cannot be
  48805. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  48806. ** is returned by sqlite3PcacheMakeClean() is not called.
  48807. */
  48808. static int pagerStress(void *p, PgHdr *pPg){
  48809. Pager *pPager = (Pager *)p;
  48810. int rc = SQLITE_OK;
  48811. assert( pPg->pPager==pPager );
  48812. assert( pPg->flags&PGHDR_DIRTY );
  48813. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  48814. ** journal (and adding a new header) is not allowed. This occurs
  48815. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  48816. ** pages belonging to the same sector.
  48817. **
  48818. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  48819. ** regardless of whether or not a sync is required. This is set during
  48820. ** a rollback or by user request, respectively.
  48821. **
  48822. ** Spilling is also prohibited when in an error state since that could
  48823. ** lead to database corruption. In the current implementation it
  48824. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  48825. ** while in the error state, hence it is impossible for this routine to
  48826. ** be called in the error state. Nevertheless, we include a NEVER()
  48827. ** test for the error state as a safeguard against future changes.
  48828. */
  48829. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  48830. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  48831. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  48832. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  48833. if( pPager->doNotSpill
  48834. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  48835. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  48836. ){
  48837. return SQLITE_OK;
  48838. }
  48839. pPg->pDirty = 0;
  48840. if( pagerUseWal(pPager) ){
  48841. /* Write a single frame for this page to the log. */
  48842. rc = subjournalPageIfRequired(pPg);
  48843. if( rc==SQLITE_OK ){
  48844. rc = pagerWalFrames(pPager, pPg, 0, 0);
  48845. }
  48846. }else{
  48847. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  48848. if( pPager->tempFile==0 ){
  48849. rc = sqlite3JournalCreate(pPager->jfd);
  48850. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  48851. }
  48852. #endif
  48853. /* Sync the journal file if required. */
  48854. if( pPg->flags&PGHDR_NEED_SYNC
  48855. || pPager->eState==PAGER_WRITER_CACHEMOD
  48856. ){
  48857. rc = syncJournal(pPager, 1);
  48858. }
  48859. /* Write the contents of the page out to the database file. */
  48860. if( rc==SQLITE_OK ){
  48861. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  48862. rc = pager_write_pagelist(pPager, pPg);
  48863. }
  48864. }
  48865. /* Mark the page as clean. */
  48866. if( rc==SQLITE_OK ){
  48867. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  48868. sqlite3PcacheMakeClean(pPg);
  48869. }
  48870. return pager_error(pPager, rc);
  48871. }
  48872. /*
  48873. ** Flush all unreferenced dirty pages to disk.
  48874. */
  48875. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  48876. int rc = pPager->errCode;
  48877. if( !MEMDB ){
  48878. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  48879. assert( assert_pager_state(pPager) );
  48880. while( rc==SQLITE_OK && pList ){
  48881. PgHdr *pNext = pList->pDirty;
  48882. if( pList->nRef==0 ){
  48883. rc = pagerStress((void*)pPager, pList);
  48884. }
  48885. pList = pNext;
  48886. }
  48887. }
  48888. return rc;
  48889. }
  48890. /*
  48891. ** Allocate and initialize a new Pager object and put a pointer to it
  48892. ** in *ppPager. The pager should eventually be freed by passing it
  48893. ** to sqlite3PagerClose().
  48894. **
  48895. ** The zFilename argument is the path to the database file to open.
  48896. ** If zFilename is NULL then a randomly-named temporary file is created
  48897. ** and used as the file to be cached. Temporary files are be deleted
  48898. ** automatically when they are closed. If zFilename is ":memory:" then
  48899. ** all information is held in cache. It is never written to disk.
  48900. ** This can be used to implement an in-memory database.
  48901. **
  48902. ** The nExtra parameter specifies the number of bytes of space allocated
  48903. ** along with each page reference. This space is available to the user
  48904. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  48905. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  48906. ** (The extra space is used by btree as the MemPage object.)
  48907. **
  48908. ** The flags argument is used to specify properties that affect the
  48909. ** operation of the pager. It should be passed some bitwise combination
  48910. ** of the PAGER_* flags.
  48911. **
  48912. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  48913. ** of the xOpen() method of the supplied VFS when opening files.
  48914. **
  48915. ** If the pager object is allocated and the specified file opened
  48916. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  48917. ** the new pager object. If an error occurs, *ppPager is set to NULL
  48918. ** and error code returned. This function may return SQLITE_NOMEM
  48919. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  48920. ** various SQLITE_IO_XXX errors.
  48921. */
  48922. SQLITE_PRIVATE int sqlite3PagerOpen(
  48923. sqlite3_vfs *pVfs, /* The virtual file system to use */
  48924. Pager **ppPager, /* OUT: Return the Pager structure here */
  48925. const char *zFilename, /* Name of the database file to open */
  48926. int nExtra, /* Extra bytes append to each in-memory page */
  48927. int flags, /* flags controlling this file */
  48928. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  48929. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  48930. ){
  48931. u8 *pPtr;
  48932. Pager *pPager = 0; /* Pager object to allocate and return */
  48933. int rc = SQLITE_OK; /* Return code */
  48934. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  48935. int memDb = 0; /* True if this is an in-memory file */
  48936. int readOnly = 0; /* True if this is a read-only file */
  48937. int journalFileSize; /* Bytes to allocate for each journal fd */
  48938. char *zPathname = 0; /* Full path to database file */
  48939. int nPathname = 0; /* Number of bytes in zPathname */
  48940. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  48941. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  48942. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  48943. const char *zUri = 0; /* URI args to copy */
  48944. int nUri = 0; /* Number of bytes of URI args at *zUri */
  48945. /* Figure out how much space is required for each journal file-handle
  48946. ** (there are two of them, the main journal and the sub-journal). */
  48947. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  48948. /* Set the output variable to NULL in case an error occurs. */
  48949. *ppPager = 0;
  48950. #ifndef SQLITE_OMIT_MEMORYDB
  48951. if( flags & PAGER_MEMORY ){
  48952. memDb = 1;
  48953. if( zFilename && zFilename[0] ){
  48954. zPathname = sqlite3DbStrDup(0, zFilename);
  48955. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  48956. nPathname = sqlite3Strlen30(zPathname);
  48957. zFilename = 0;
  48958. }
  48959. }
  48960. #endif
  48961. /* Compute and store the full pathname in an allocated buffer pointed
  48962. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  48963. ** leave both nPathname and zPathname set to 0.
  48964. */
  48965. if( zFilename && zFilename[0] ){
  48966. const char *z;
  48967. nPathname = pVfs->mxPathname+1;
  48968. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  48969. if( zPathname==0 ){
  48970. return SQLITE_NOMEM_BKPT;
  48971. }
  48972. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  48973. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  48974. nPathname = sqlite3Strlen30(zPathname);
  48975. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  48976. while( *z ){
  48977. z += sqlite3Strlen30(z)+1;
  48978. z += sqlite3Strlen30(z)+1;
  48979. }
  48980. nUri = (int)(&z[1] - zUri);
  48981. assert( nUri>=0 );
  48982. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  48983. /* This branch is taken when the journal path required by
  48984. ** the database being opened will be more than pVfs->mxPathname
  48985. ** bytes in length. This means the database cannot be opened,
  48986. ** as it will not be possible to open the journal file or even
  48987. ** check for a hot-journal before reading.
  48988. */
  48989. rc = SQLITE_CANTOPEN_BKPT;
  48990. }
  48991. if( rc!=SQLITE_OK ){
  48992. sqlite3DbFree(0, zPathname);
  48993. return rc;
  48994. }
  48995. }
  48996. /* Allocate memory for the Pager structure, PCache object, the
  48997. ** three file descriptors, the database file name and the journal
  48998. ** file name. The layout in memory is as follows:
  48999. **
  49000. ** Pager object (sizeof(Pager) bytes)
  49001. ** PCache object (sqlite3PcacheSize() bytes)
  49002. ** Database file handle (pVfs->szOsFile bytes)
  49003. ** Sub-journal file handle (journalFileSize bytes)
  49004. ** Main journal file handle (journalFileSize bytes)
  49005. ** Database file name (nPathname+1 bytes)
  49006. ** Journal file name (nPathname+8+1 bytes)
  49007. */
  49008. pPtr = (u8 *)sqlite3MallocZero(
  49009. ROUND8(sizeof(*pPager)) + /* Pager structure */
  49010. ROUND8(pcacheSize) + /* PCache object */
  49011. ROUND8(pVfs->szOsFile) + /* The main db file */
  49012. journalFileSize * 2 + /* The two journal files */
  49013. nPathname + 1 + nUri + /* zFilename */
  49014. nPathname + 8 + 2 /* zJournal */
  49015. #ifndef SQLITE_OMIT_WAL
  49016. + nPathname + 4 + 2 /* zWal */
  49017. #endif
  49018. );
  49019. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  49020. if( !pPtr ){
  49021. sqlite3DbFree(0, zPathname);
  49022. return SQLITE_NOMEM_BKPT;
  49023. }
  49024. pPager = (Pager*)(pPtr);
  49025. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  49026. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  49027. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  49028. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  49029. pPager->zFilename = (char*)(pPtr += journalFileSize);
  49030. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  49031. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  49032. if( zPathname ){
  49033. assert( nPathname>0 );
  49034. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  49035. memcpy(pPager->zFilename, zPathname, nPathname);
  49036. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  49037. memcpy(pPager->zJournal, zPathname, nPathname);
  49038. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  49039. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  49040. #ifndef SQLITE_OMIT_WAL
  49041. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  49042. memcpy(pPager->zWal, zPathname, nPathname);
  49043. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  49044. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  49045. #endif
  49046. sqlite3DbFree(0, zPathname);
  49047. }
  49048. pPager->pVfs = pVfs;
  49049. pPager->vfsFlags = vfsFlags;
  49050. /* Open the pager file.
  49051. */
  49052. if( zFilename && zFilename[0] ){
  49053. int fout = 0; /* VFS flags returned by xOpen() */
  49054. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  49055. assert( !memDb );
  49056. readOnly = (fout&SQLITE_OPEN_READONLY);
  49057. /* If the file was successfully opened for read/write access,
  49058. ** choose a default page size in case we have to create the
  49059. ** database file. The default page size is the maximum of:
  49060. **
  49061. ** + SQLITE_DEFAULT_PAGE_SIZE,
  49062. ** + The value returned by sqlite3OsSectorSize()
  49063. ** + The largest page size that can be written atomically.
  49064. */
  49065. if( rc==SQLITE_OK ){
  49066. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  49067. if( !readOnly ){
  49068. setSectorSize(pPager);
  49069. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  49070. if( szPageDflt<pPager->sectorSize ){
  49071. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  49072. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  49073. }else{
  49074. szPageDflt = (u32)pPager->sectorSize;
  49075. }
  49076. }
  49077. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  49078. {
  49079. int ii;
  49080. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  49081. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  49082. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  49083. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  49084. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  49085. szPageDflt = ii;
  49086. }
  49087. }
  49088. }
  49089. #endif
  49090. }
  49091. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  49092. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  49093. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  49094. vfsFlags |= SQLITE_OPEN_READONLY;
  49095. goto act_like_temp_file;
  49096. }
  49097. }
  49098. }else{
  49099. /* If a temporary file is requested, it is not opened immediately.
  49100. ** In this case we accept the default page size and delay actually
  49101. ** opening the file until the first call to OsWrite().
  49102. **
  49103. ** This branch is also run for an in-memory database. An in-memory
  49104. ** database is the same as a temp-file that is never written out to
  49105. ** disk and uses an in-memory rollback journal.
  49106. **
  49107. ** This branch also runs for files marked as immutable.
  49108. */
  49109. act_like_temp_file:
  49110. tempFile = 1;
  49111. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  49112. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  49113. pPager->noLock = 1; /* Do no locking */
  49114. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  49115. }
  49116. /* The following call to PagerSetPagesize() serves to set the value of
  49117. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  49118. */
  49119. if( rc==SQLITE_OK ){
  49120. assert( pPager->memDb==0 );
  49121. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  49122. testcase( rc!=SQLITE_OK );
  49123. }
  49124. /* Initialize the PCache object. */
  49125. if( rc==SQLITE_OK ){
  49126. nExtra = ROUND8(nExtra);
  49127. assert( nExtra>=8 && nExtra<1000 );
  49128. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  49129. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  49130. }
  49131. /* If an error occurred above, free the Pager structure and close the file.
  49132. */
  49133. if( rc!=SQLITE_OK ){
  49134. sqlite3OsClose(pPager->fd);
  49135. sqlite3PageFree(pPager->pTmpSpace);
  49136. sqlite3_free(pPager);
  49137. return rc;
  49138. }
  49139. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  49140. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  49141. pPager->useJournal = (u8)useJournal;
  49142. /* pPager->stmtOpen = 0; */
  49143. /* pPager->stmtInUse = 0; */
  49144. /* pPager->nRef = 0; */
  49145. /* pPager->stmtSize = 0; */
  49146. /* pPager->stmtJSize = 0; */
  49147. /* pPager->nPage = 0; */
  49148. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  49149. /* pPager->state = PAGER_UNLOCK; */
  49150. /* pPager->errMask = 0; */
  49151. pPager->tempFile = (u8)tempFile;
  49152. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  49153. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  49154. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  49155. pPager->exclusiveMode = (u8)tempFile;
  49156. pPager->changeCountDone = pPager->tempFile;
  49157. pPager->memDb = (u8)memDb;
  49158. pPager->readOnly = (u8)readOnly;
  49159. assert( useJournal || pPager->tempFile );
  49160. pPager->noSync = pPager->tempFile;
  49161. if( pPager->noSync ){
  49162. assert( pPager->fullSync==0 );
  49163. assert( pPager->extraSync==0 );
  49164. assert( pPager->syncFlags==0 );
  49165. assert( pPager->walSyncFlags==0 );
  49166. }else{
  49167. pPager->fullSync = 1;
  49168. pPager->extraSync = 0;
  49169. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  49170. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  49171. }
  49172. /* pPager->pFirst = 0; */
  49173. /* pPager->pFirstSynced = 0; */
  49174. /* pPager->pLast = 0; */
  49175. pPager->nExtra = (u16)nExtra;
  49176. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  49177. assert( isOpen(pPager->fd) || tempFile );
  49178. setSectorSize(pPager);
  49179. if( !useJournal ){
  49180. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  49181. }else if( memDb ){
  49182. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  49183. }
  49184. /* pPager->xBusyHandler = 0; */
  49185. /* pPager->pBusyHandlerArg = 0; */
  49186. pPager->xReiniter = xReinit;
  49187. setGetterMethod(pPager);
  49188. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  49189. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  49190. *ppPager = pPager;
  49191. return SQLITE_OK;
  49192. }
  49193. /* Verify that the database file has not be deleted or renamed out from
  49194. ** under the pager. Return SQLITE_OK if the database is still were it ought
  49195. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  49196. ** code from sqlite3OsAccess()) if the database has gone missing.
  49197. */
  49198. static int databaseIsUnmoved(Pager *pPager){
  49199. int bHasMoved = 0;
  49200. int rc;
  49201. if( pPager->tempFile ) return SQLITE_OK;
  49202. if( pPager->dbSize==0 ) return SQLITE_OK;
  49203. assert( pPager->zFilename && pPager->zFilename[0] );
  49204. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  49205. if( rc==SQLITE_NOTFOUND ){
  49206. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  49207. ** has not been moved. That is the historical behavior of SQLite: prior to
  49208. ** version 3.8.3, it never checked */
  49209. rc = SQLITE_OK;
  49210. }else if( rc==SQLITE_OK && bHasMoved ){
  49211. rc = SQLITE_READONLY_DBMOVED;
  49212. }
  49213. return rc;
  49214. }
  49215. /*
  49216. ** This function is called after transitioning from PAGER_UNLOCK to
  49217. ** PAGER_SHARED state. It tests if there is a hot journal present in
  49218. ** the file-system for the given pager. A hot journal is one that
  49219. ** needs to be played back. According to this function, a hot-journal
  49220. ** file exists if the following criteria are met:
  49221. **
  49222. ** * The journal file exists in the file system, and
  49223. ** * No process holds a RESERVED or greater lock on the database file, and
  49224. ** * The database file itself is greater than 0 bytes in size, and
  49225. ** * The first byte of the journal file exists and is not 0x00.
  49226. **
  49227. ** If the current size of the database file is 0 but a journal file
  49228. ** exists, that is probably an old journal left over from a prior
  49229. ** database with the same name. In this case the journal file is
  49230. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  49231. ** is returned.
  49232. **
  49233. ** This routine does not check if there is a master journal filename
  49234. ** at the end of the file. If there is, and that master journal file
  49235. ** does not exist, then the journal file is not really hot. In this
  49236. ** case this routine will return a false-positive. The pager_playback()
  49237. ** routine will discover that the journal file is not really hot and
  49238. ** will not roll it back.
  49239. **
  49240. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  49241. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  49242. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  49243. ** to determine whether or not a hot-journal file exists, the IO error
  49244. ** code is returned and the value of *pExists is undefined.
  49245. */
  49246. static int hasHotJournal(Pager *pPager, int *pExists){
  49247. sqlite3_vfs * const pVfs = pPager->pVfs;
  49248. int rc = SQLITE_OK; /* Return code */
  49249. int exists = 1; /* True if a journal file is present */
  49250. int jrnlOpen = !!isOpen(pPager->jfd);
  49251. assert( pPager->useJournal );
  49252. assert( isOpen(pPager->fd) );
  49253. assert( pPager->eState==PAGER_OPEN );
  49254. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  49255. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  49256. ));
  49257. *pExists = 0;
  49258. if( !jrnlOpen ){
  49259. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  49260. }
  49261. if( rc==SQLITE_OK && exists ){
  49262. int locked = 0; /* True if some process holds a RESERVED lock */
  49263. /* Race condition here: Another process might have been holding the
  49264. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  49265. ** call above, but then delete the journal and drop the lock before
  49266. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  49267. ** is the case, this routine might think there is a hot journal when
  49268. ** in fact there is none. This results in a false-positive which will
  49269. ** be dealt with by the playback routine. Ticket #3883.
  49270. */
  49271. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  49272. if( rc==SQLITE_OK && !locked ){
  49273. Pgno nPage; /* Number of pages in database file */
  49274. assert( pPager->tempFile==0 );
  49275. rc = pagerPagecount(pPager, &nPage);
  49276. if( rc==SQLITE_OK ){
  49277. /* If the database is zero pages in size, that means that either (1) the
  49278. ** journal is a remnant from a prior database with the same name where
  49279. ** the database file but not the journal was deleted, or (2) the initial
  49280. ** transaction that populates a new database is being rolled back.
  49281. ** In either case, the journal file can be deleted. However, take care
  49282. ** not to delete the journal file if it is already open due to
  49283. ** journal_mode=PERSIST.
  49284. */
  49285. if( nPage==0 && !jrnlOpen ){
  49286. sqlite3BeginBenignMalloc();
  49287. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  49288. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  49289. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  49290. }
  49291. sqlite3EndBenignMalloc();
  49292. }else{
  49293. /* The journal file exists and no other connection has a reserved
  49294. ** or greater lock on the database file. Now check that there is
  49295. ** at least one non-zero bytes at the start of the journal file.
  49296. ** If there is, then we consider this journal to be hot. If not,
  49297. ** it can be ignored.
  49298. */
  49299. if( !jrnlOpen ){
  49300. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  49301. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  49302. }
  49303. if( rc==SQLITE_OK ){
  49304. u8 first = 0;
  49305. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  49306. if( rc==SQLITE_IOERR_SHORT_READ ){
  49307. rc = SQLITE_OK;
  49308. }
  49309. if( !jrnlOpen ){
  49310. sqlite3OsClose(pPager->jfd);
  49311. }
  49312. *pExists = (first!=0);
  49313. }else if( rc==SQLITE_CANTOPEN ){
  49314. /* If we cannot open the rollback journal file in order to see if
  49315. ** it has a zero header, that might be due to an I/O error, or
  49316. ** it might be due to the race condition described above and in
  49317. ** ticket #3883. Either way, assume that the journal is hot.
  49318. ** This might be a false positive. But if it is, then the
  49319. ** automatic journal playback and recovery mechanism will deal
  49320. ** with it under an EXCLUSIVE lock where we do not need to
  49321. ** worry so much with race conditions.
  49322. */
  49323. *pExists = 1;
  49324. rc = SQLITE_OK;
  49325. }
  49326. }
  49327. }
  49328. }
  49329. }
  49330. return rc;
  49331. }
  49332. /*
  49333. ** This function is called to obtain a shared lock on the database file.
  49334. ** It is illegal to call sqlite3PagerGet() until after this function
  49335. ** has been successfully called. If a shared-lock is already held when
  49336. ** this function is called, it is a no-op.
  49337. **
  49338. ** The following operations are also performed by this function.
  49339. **
  49340. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  49341. ** on the database file), then an attempt is made to obtain a
  49342. ** SHARED lock on the database file. Immediately after obtaining
  49343. ** the SHARED lock, the file-system is checked for a hot-journal,
  49344. ** which is played back if present. Following any hot-journal
  49345. ** rollback, the contents of the cache are validated by checking
  49346. ** the 'change-counter' field of the database file header and
  49347. ** discarded if they are found to be invalid.
  49348. **
  49349. ** 2) If the pager is running in exclusive-mode, and there are currently
  49350. ** no outstanding references to any pages, and is in the error state,
  49351. ** then an attempt is made to clear the error state by discarding
  49352. ** the contents of the page cache and rolling back any open journal
  49353. ** file.
  49354. **
  49355. ** If everything is successful, SQLITE_OK is returned. If an IO error
  49356. ** occurs while locking the database, checking for a hot-journal file or
  49357. ** rolling back a journal file, the IO error code is returned.
  49358. */
  49359. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  49360. int rc = SQLITE_OK; /* Return code */
  49361. /* This routine is only called from b-tree and only when there are no
  49362. ** outstanding pages. This implies that the pager state should either
  49363. ** be OPEN or READER. READER is only possible if the pager is or was in
  49364. ** exclusive access mode. */
  49365. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  49366. assert( assert_pager_state(pPager) );
  49367. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  49368. assert( pPager->errCode==SQLITE_OK );
  49369. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  49370. int bHotJournal = 1; /* True if there exists a hot journal-file */
  49371. assert( !MEMDB );
  49372. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  49373. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  49374. if( rc!=SQLITE_OK ){
  49375. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  49376. goto failed;
  49377. }
  49378. /* If a journal file exists, and there is no RESERVED lock on the
  49379. ** database file, then it either needs to be played back or deleted.
  49380. */
  49381. if( pPager->eLock<=SHARED_LOCK ){
  49382. rc = hasHotJournal(pPager, &bHotJournal);
  49383. }
  49384. if( rc!=SQLITE_OK ){
  49385. goto failed;
  49386. }
  49387. if( bHotJournal ){
  49388. if( pPager->readOnly ){
  49389. rc = SQLITE_READONLY_ROLLBACK;
  49390. goto failed;
  49391. }
  49392. /* Get an EXCLUSIVE lock on the database file. At this point it is
  49393. ** important that a RESERVED lock is not obtained on the way to the
  49394. ** EXCLUSIVE lock. If it were, another process might open the
  49395. ** database file, detect the RESERVED lock, and conclude that the
  49396. ** database is safe to read while this process is still rolling the
  49397. ** hot-journal back.
  49398. **
  49399. ** Because the intermediate RESERVED lock is not requested, any
  49400. ** other process attempting to access the database file will get to
  49401. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  49402. ** on the database file.
  49403. **
  49404. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  49405. ** downgraded to SHARED_LOCK before this function returns.
  49406. */
  49407. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  49408. if( rc!=SQLITE_OK ){
  49409. goto failed;
  49410. }
  49411. /* If it is not already open and the file exists on disk, open the
  49412. ** journal for read/write access. Write access is required because
  49413. ** in exclusive-access mode the file descriptor will be kept open
  49414. ** and possibly used for a transaction later on. Also, write-access
  49415. ** is usually required to finalize the journal in journal_mode=persist
  49416. ** mode (and also for journal_mode=truncate on some systems).
  49417. **
  49418. ** If the journal does not exist, it usually means that some
  49419. ** other connection managed to get in and roll it back before
  49420. ** this connection obtained the exclusive lock above. Or, it
  49421. ** may mean that the pager was in the error-state when this
  49422. ** function was called and the journal file does not exist.
  49423. */
  49424. if( !isOpen(pPager->jfd) ){
  49425. sqlite3_vfs * const pVfs = pPager->pVfs;
  49426. int bExists; /* True if journal file exists */
  49427. rc = sqlite3OsAccess(
  49428. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  49429. if( rc==SQLITE_OK && bExists ){
  49430. int fout = 0;
  49431. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  49432. assert( !pPager->tempFile );
  49433. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  49434. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  49435. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  49436. rc = SQLITE_CANTOPEN_BKPT;
  49437. sqlite3OsClose(pPager->jfd);
  49438. }
  49439. }
  49440. }
  49441. /* Playback and delete the journal. Drop the database write
  49442. ** lock and reacquire the read lock. Purge the cache before
  49443. ** playing back the hot-journal so that we don't end up with
  49444. ** an inconsistent cache. Sync the hot journal before playing
  49445. ** it back since the process that crashed and left the hot journal
  49446. ** probably did not sync it and we are required to always sync
  49447. ** the journal before playing it back.
  49448. */
  49449. if( isOpen(pPager->jfd) ){
  49450. assert( rc==SQLITE_OK );
  49451. rc = pagerSyncHotJournal(pPager);
  49452. if( rc==SQLITE_OK ){
  49453. rc = pager_playback(pPager, !pPager->tempFile);
  49454. pPager->eState = PAGER_OPEN;
  49455. }
  49456. }else if( !pPager->exclusiveMode ){
  49457. pagerUnlockDb(pPager, SHARED_LOCK);
  49458. }
  49459. if( rc!=SQLITE_OK ){
  49460. /* This branch is taken if an error occurs while trying to open
  49461. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  49462. ** pager_unlock() routine will be called before returning to unlock
  49463. ** the file. If the unlock attempt fails, then Pager.eLock must be
  49464. ** set to UNKNOWN_LOCK (see the comment above the #define for
  49465. ** UNKNOWN_LOCK above for an explanation).
  49466. **
  49467. ** In order to get pager_unlock() to do this, set Pager.eState to
  49468. ** PAGER_ERROR now. This is not actually counted as a transition
  49469. ** to ERROR state in the state diagram at the top of this file,
  49470. ** since we know that the same call to pager_unlock() will very
  49471. ** shortly transition the pager object to the OPEN state. Calling
  49472. ** assert_pager_state() would fail now, as it should not be possible
  49473. ** to be in ERROR state when there are zero outstanding page
  49474. ** references.
  49475. */
  49476. pager_error(pPager, rc);
  49477. goto failed;
  49478. }
  49479. assert( pPager->eState==PAGER_OPEN );
  49480. assert( (pPager->eLock==SHARED_LOCK)
  49481. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  49482. );
  49483. }
  49484. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  49485. /* The shared-lock has just been acquired then check to
  49486. ** see if the database has been modified. If the database has changed,
  49487. ** flush the cache. The hasHeldSharedLock flag prevents this from
  49488. ** occurring on the very first access to a file, in order to save a
  49489. ** single unnecessary sqlite3OsRead() call at the start-up.
  49490. **
  49491. ** Database changes are detected by looking at 15 bytes beginning
  49492. ** at offset 24 into the file. The first 4 of these 16 bytes are
  49493. ** a 32-bit counter that is incremented with each change. The
  49494. ** other bytes change randomly with each file change when
  49495. ** a codec is in use.
  49496. **
  49497. ** There is a vanishingly small chance that a change will not be
  49498. ** detected. The chance of an undetected change is so small that
  49499. ** it can be neglected.
  49500. */
  49501. char dbFileVers[sizeof(pPager->dbFileVers)];
  49502. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  49503. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  49504. if( rc!=SQLITE_OK ){
  49505. if( rc!=SQLITE_IOERR_SHORT_READ ){
  49506. goto failed;
  49507. }
  49508. memset(dbFileVers, 0, sizeof(dbFileVers));
  49509. }
  49510. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  49511. pager_reset(pPager);
  49512. /* Unmap the database file. It is possible that external processes
  49513. ** may have truncated the database file and then extended it back
  49514. ** to its original size while this process was not holding a lock.
  49515. ** In this case there may exist a Pager.pMap mapping that appears
  49516. ** to be the right size but is not actually valid. Avoid this
  49517. ** possibility by unmapping the db here. */
  49518. if( USEFETCH(pPager) ){
  49519. sqlite3OsUnfetch(pPager->fd, 0, 0);
  49520. }
  49521. }
  49522. }
  49523. /* If there is a WAL file in the file-system, open this database in WAL
  49524. ** mode. Otherwise, the following function call is a no-op.
  49525. */
  49526. rc = pagerOpenWalIfPresent(pPager);
  49527. #ifndef SQLITE_OMIT_WAL
  49528. assert( pPager->pWal==0 || rc==SQLITE_OK );
  49529. #endif
  49530. }
  49531. if( pagerUseWal(pPager) ){
  49532. assert( rc==SQLITE_OK );
  49533. rc = pagerBeginReadTransaction(pPager);
  49534. }
  49535. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  49536. rc = pagerPagecount(pPager, &pPager->dbSize);
  49537. }
  49538. failed:
  49539. if( rc!=SQLITE_OK ){
  49540. assert( !MEMDB );
  49541. pager_unlock(pPager);
  49542. assert( pPager->eState==PAGER_OPEN );
  49543. }else{
  49544. pPager->eState = PAGER_READER;
  49545. pPager->hasHeldSharedLock = 1;
  49546. }
  49547. return rc;
  49548. }
  49549. /*
  49550. ** If the reference count has reached zero, rollback any active
  49551. ** transaction and unlock the pager.
  49552. **
  49553. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  49554. ** the rollback journal, the unlock is not performed and there is
  49555. ** nothing to rollback, so this routine is a no-op.
  49556. */
  49557. static void pagerUnlockIfUnused(Pager *pPager){
  49558. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  49559. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  49560. pagerUnlockAndRollback(pPager);
  49561. }
  49562. }
  49563. /*
  49564. ** The page getter methods each try to acquire a reference to a
  49565. ** page with page number pgno. If the requested reference is
  49566. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  49567. **
  49568. ** There are different implementations of the getter method depending
  49569. ** on the current state of the pager.
  49570. **
  49571. ** getPageNormal() -- The normal getter
  49572. ** getPageError() -- Used if the pager is in an error state
  49573. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  49574. **
  49575. ** If the requested page is already in the cache, it is returned.
  49576. ** Otherwise, a new page object is allocated and populated with data
  49577. ** read from the database file. In some cases, the pcache module may
  49578. ** choose not to allocate a new page object and may reuse an existing
  49579. ** object with no outstanding references.
  49580. **
  49581. ** The extra data appended to a page is always initialized to zeros the
  49582. ** first time a page is loaded into memory. If the page requested is
  49583. ** already in the cache when this function is called, then the extra
  49584. ** data is left as it was when the page object was last used.
  49585. **
  49586. ** If the database image is smaller than the requested page or if
  49587. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  49588. ** requested page is not already stored in the cache, then no
  49589. ** actual disk read occurs. In this case the memory image of the
  49590. ** page is initialized to all zeros.
  49591. **
  49592. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  49593. ** the contents of the page. This occurs in two scenarios:
  49594. **
  49595. ** a) When reading a free-list leaf page from the database, and
  49596. **
  49597. ** b) When a savepoint is being rolled back and we need to load
  49598. ** a new page into the cache to be filled with the data read
  49599. ** from the savepoint journal.
  49600. **
  49601. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  49602. ** of being read from the database. Additionally, the bits corresponding
  49603. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  49604. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  49605. ** savepoints are set. This means if the page is made writable at any
  49606. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  49607. ** will not be journaled. This saves IO.
  49608. **
  49609. ** The acquisition might fail for several reasons. In all cases,
  49610. ** an appropriate error code is returned and *ppPage is set to NULL.
  49611. **
  49612. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  49613. ** to find a page in the in-memory cache first. If the page is not already
  49614. ** in memory, this routine goes to disk to read it in whereas Lookup()
  49615. ** just returns 0. This routine acquires a read-lock the first time it
  49616. ** has to go to disk, and could also playback an old journal if necessary.
  49617. ** Since Lookup() never goes to disk, it never has to deal with locks
  49618. ** or journal files.
  49619. */
  49620. static int getPageNormal(
  49621. Pager *pPager, /* The pager open on the database file */
  49622. Pgno pgno, /* Page number to fetch */
  49623. DbPage **ppPage, /* Write a pointer to the page here */
  49624. int flags /* PAGER_GET_XXX flags */
  49625. ){
  49626. int rc = SQLITE_OK;
  49627. PgHdr *pPg;
  49628. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  49629. sqlite3_pcache_page *pBase;
  49630. assert( pPager->errCode==SQLITE_OK );
  49631. assert( pPager->eState>=PAGER_READER );
  49632. assert( assert_pager_state(pPager) );
  49633. assert( pPager->hasHeldSharedLock==1 );
  49634. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  49635. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  49636. if( pBase==0 ){
  49637. pPg = 0;
  49638. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  49639. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  49640. if( pBase==0 ){
  49641. rc = SQLITE_NOMEM_BKPT;
  49642. goto pager_acquire_err;
  49643. }
  49644. }
  49645. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  49646. assert( pPg==(*ppPage) );
  49647. assert( pPg->pgno==pgno );
  49648. assert( pPg->pPager==pPager || pPg->pPager==0 );
  49649. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  49650. if( pPg->pPager && !noContent ){
  49651. /* In this case the pcache already contains an initialized copy of
  49652. ** the page. Return without further ado. */
  49653. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  49654. pPager->aStat[PAGER_STAT_HIT]++;
  49655. return SQLITE_OK;
  49656. }else{
  49657. /* The pager cache has created a new page. Its content needs to
  49658. ** be initialized. But first some error checks:
  49659. **
  49660. ** (1) The maximum page number is 2^31
  49661. ** (2) Never try to fetch the locking page
  49662. */
  49663. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  49664. rc = SQLITE_CORRUPT_BKPT;
  49665. goto pager_acquire_err;
  49666. }
  49667. pPg->pPager = pPager;
  49668. assert( !isOpen(pPager->fd) || !MEMDB );
  49669. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  49670. if( pgno>pPager->mxPgno ){
  49671. rc = SQLITE_FULL;
  49672. goto pager_acquire_err;
  49673. }
  49674. if( noContent ){
  49675. /* Failure to set the bits in the InJournal bit-vectors is benign.
  49676. ** It merely means that we might do some extra work to journal a
  49677. ** page that does not need to be journaled. Nevertheless, be sure
  49678. ** to test the case where a malloc error occurs while trying to set
  49679. ** a bit in a bit vector.
  49680. */
  49681. sqlite3BeginBenignMalloc();
  49682. if( pgno<=pPager->dbOrigSize ){
  49683. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  49684. testcase( rc==SQLITE_NOMEM );
  49685. }
  49686. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  49687. testcase( rc==SQLITE_NOMEM );
  49688. sqlite3EndBenignMalloc();
  49689. }
  49690. memset(pPg->pData, 0, pPager->pageSize);
  49691. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  49692. }else{
  49693. assert( pPg->pPager==pPager );
  49694. pPager->aStat[PAGER_STAT_MISS]++;
  49695. rc = readDbPage(pPg);
  49696. if( rc!=SQLITE_OK ){
  49697. goto pager_acquire_err;
  49698. }
  49699. }
  49700. pager_set_pagehash(pPg);
  49701. }
  49702. return SQLITE_OK;
  49703. pager_acquire_err:
  49704. assert( rc!=SQLITE_OK );
  49705. if( pPg ){
  49706. sqlite3PcacheDrop(pPg);
  49707. }
  49708. pagerUnlockIfUnused(pPager);
  49709. *ppPage = 0;
  49710. return rc;
  49711. }
  49712. #if SQLITE_MAX_MMAP_SIZE>0
  49713. /* The page getter for when memory-mapped I/O is enabled */
  49714. static int getPageMMap(
  49715. Pager *pPager, /* The pager open on the database file */
  49716. Pgno pgno, /* Page number to fetch */
  49717. DbPage **ppPage, /* Write a pointer to the page here */
  49718. int flags /* PAGER_GET_XXX flags */
  49719. ){
  49720. int rc = SQLITE_OK;
  49721. PgHdr *pPg = 0;
  49722. u32 iFrame = 0; /* Frame to read from WAL file */
  49723. /* It is acceptable to use a read-only (mmap) page for any page except
  49724. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  49725. ** flag was specified by the caller. And so long as the db is not a
  49726. ** temporary or in-memory database. */
  49727. const int bMmapOk = (pgno>1
  49728. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  49729. );
  49730. assert( USEFETCH(pPager) );
  49731. #ifdef SQLITE_HAS_CODEC
  49732. assert( pPager->xCodec==0 );
  49733. #endif
  49734. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  49735. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  49736. ** test in the previous statement, and avoid testing pgno==0 in the
  49737. ** common case where pgno is large. */
  49738. if( pgno<=1 && pgno==0 ){
  49739. return SQLITE_CORRUPT_BKPT;
  49740. }
  49741. assert( pPager->eState>=PAGER_READER );
  49742. assert( assert_pager_state(pPager) );
  49743. assert( pPager->hasHeldSharedLock==1 );
  49744. assert( pPager->errCode==SQLITE_OK );
  49745. if( bMmapOk && pagerUseWal(pPager) ){
  49746. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  49747. if( rc!=SQLITE_OK ){
  49748. *ppPage = 0;
  49749. return rc;
  49750. }
  49751. }
  49752. if( bMmapOk && iFrame==0 ){
  49753. void *pData = 0;
  49754. rc = sqlite3OsFetch(pPager->fd,
  49755. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  49756. );
  49757. if( rc==SQLITE_OK && pData ){
  49758. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  49759. pPg = sqlite3PagerLookup(pPager, pgno);
  49760. }
  49761. if( pPg==0 ){
  49762. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  49763. }else{
  49764. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  49765. }
  49766. if( pPg ){
  49767. assert( rc==SQLITE_OK );
  49768. *ppPage = pPg;
  49769. return SQLITE_OK;
  49770. }
  49771. }
  49772. if( rc!=SQLITE_OK ){
  49773. *ppPage = 0;
  49774. return rc;
  49775. }
  49776. }
  49777. return getPageNormal(pPager, pgno, ppPage, flags);
  49778. }
  49779. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  49780. /* The page getter method for when the pager is an error state */
  49781. static int getPageError(
  49782. Pager *pPager, /* The pager open on the database file */
  49783. Pgno pgno, /* Page number to fetch */
  49784. DbPage **ppPage, /* Write a pointer to the page here */
  49785. int flags /* PAGER_GET_XXX flags */
  49786. ){
  49787. UNUSED_PARAMETER(pgno);
  49788. UNUSED_PARAMETER(flags);
  49789. assert( pPager->errCode!=SQLITE_OK );
  49790. *ppPage = 0;
  49791. return pPager->errCode;
  49792. }
  49793. /* Dispatch all page fetch requests to the appropriate getter method.
  49794. */
  49795. SQLITE_PRIVATE int sqlite3PagerGet(
  49796. Pager *pPager, /* The pager open on the database file */
  49797. Pgno pgno, /* Page number to fetch */
  49798. DbPage **ppPage, /* Write a pointer to the page here */
  49799. int flags /* PAGER_GET_XXX flags */
  49800. ){
  49801. return pPager->xGet(pPager, pgno, ppPage, flags);
  49802. }
  49803. /*
  49804. ** Acquire a page if it is already in the in-memory cache. Do
  49805. ** not read the page from disk. Return a pointer to the page,
  49806. ** or 0 if the page is not in cache.
  49807. **
  49808. ** See also sqlite3PagerGet(). The difference between this routine
  49809. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  49810. ** in the page if the page is not already in cache. This routine
  49811. ** returns NULL if the page is not in cache or if a disk I/O error
  49812. ** has ever happened.
  49813. */
  49814. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  49815. sqlite3_pcache_page *pPage;
  49816. assert( pPager!=0 );
  49817. assert( pgno!=0 );
  49818. assert( pPager->pPCache!=0 );
  49819. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  49820. assert( pPage==0 || pPager->hasHeldSharedLock );
  49821. if( pPage==0 ) return 0;
  49822. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  49823. }
  49824. /*
  49825. ** Release a page reference.
  49826. **
  49827. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  49828. ** used if we know that the page being released is not the last page.
  49829. ** The btree layer always holds page1 open until the end, so these first
  49830. ** to routines can be used to release any page other than BtShared.pPage1.
  49831. **
  49832. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  49833. ** checks the total number of outstanding pages and if the number of
  49834. ** pages reaches zero it drops the database lock.
  49835. */
  49836. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  49837. TESTONLY( Pager *pPager = pPg->pPager; )
  49838. assert( pPg!=0 );
  49839. if( pPg->flags & PGHDR_MMAP ){
  49840. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  49841. pagerReleaseMapPage(pPg);
  49842. }else{
  49843. sqlite3PcacheRelease(pPg);
  49844. }
  49845. /* Do not use this routine to release the last reference to page1 */
  49846. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  49847. }
  49848. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  49849. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  49850. }
  49851. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  49852. Pager *pPager;
  49853. assert( pPg!=0 );
  49854. assert( pPg->pgno==1 );
  49855. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  49856. pPager = pPg->pPager;
  49857. sqlite3PcacheRelease(pPg);
  49858. pagerUnlockIfUnused(pPager);
  49859. }
  49860. /*
  49861. ** This function is called at the start of every write transaction.
  49862. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  49863. ** file when this routine is called.
  49864. **
  49865. ** Open the journal file for pager pPager and write a journal header
  49866. ** to the start of it. If there are active savepoints, open the sub-journal
  49867. ** as well. This function is only used when the journal file is being
  49868. ** opened to write a rollback log for a transaction. It is not used
  49869. ** when opening a hot journal file to roll it back.
  49870. **
  49871. ** If the journal file is already open (as it may be in exclusive mode),
  49872. ** then this function just writes a journal header to the start of the
  49873. ** already open file.
  49874. **
  49875. ** Whether or not the journal file is opened by this function, the
  49876. ** Pager.pInJournal bitvec structure is allocated.
  49877. **
  49878. ** Return SQLITE_OK if everything is successful. Otherwise, return
  49879. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  49880. ** an IO error code if opening or writing the journal file fails.
  49881. */
  49882. static int pager_open_journal(Pager *pPager){
  49883. int rc = SQLITE_OK; /* Return code */
  49884. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  49885. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49886. assert( assert_pager_state(pPager) );
  49887. assert( pPager->pInJournal==0 );
  49888. /* If already in the error state, this function is a no-op. But on
  49889. ** the other hand, this routine is never called if we are already in
  49890. ** an error state. */
  49891. if( NEVER(pPager->errCode) ) return pPager->errCode;
  49892. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  49893. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  49894. if( pPager->pInJournal==0 ){
  49895. return SQLITE_NOMEM_BKPT;
  49896. }
  49897. /* Open the journal file if it is not already open. */
  49898. if( !isOpen(pPager->jfd) ){
  49899. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  49900. sqlite3MemJournalOpen(pPager->jfd);
  49901. }else{
  49902. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  49903. int nSpill;
  49904. if( pPager->tempFile ){
  49905. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  49906. nSpill = sqlite3Config.nStmtSpill;
  49907. }else{
  49908. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  49909. nSpill = jrnlBufferSize(pPager);
  49910. }
  49911. /* Verify that the database still has the same name as it did when
  49912. ** it was originally opened. */
  49913. rc = databaseIsUnmoved(pPager);
  49914. if( rc==SQLITE_OK ){
  49915. rc = sqlite3JournalOpen (
  49916. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  49917. );
  49918. }
  49919. }
  49920. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  49921. }
  49922. /* Write the first journal header to the journal file and open
  49923. ** the sub-journal if necessary.
  49924. */
  49925. if( rc==SQLITE_OK ){
  49926. /* TODO: Check if all of these are really required. */
  49927. pPager->nRec = 0;
  49928. pPager->journalOff = 0;
  49929. pPager->setMaster = 0;
  49930. pPager->journalHdr = 0;
  49931. rc = writeJournalHdr(pPager);
  49932. }
  49933. }
  49934. if( rc!=SQLITE_OK ){
  49935. sqlite3BitvecDestroy(pPager->pInJournal);
  49936. pPager->pInJournal = 0;
  49937. }else{
  49938. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49939. pPager->eState = PAGER_WRITER_CACHEMOD;
  49940. }
  49941. return rc;
  49942. }
  49943. /*
  49944. ** Begin a write-transaction on the specified pager object. If a
  49945. ** write-transaction has already been opened, this function is a no-op.
  49946. **
  49947. ** If the exFlag argument is false, then acquire at least a RESERVED
  49948. ** lock on the database file. If exFlag is true, then acquire at least
  49949. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  49950. ** functions need be called.
  49951. **
  49952. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  49953. ** within this transaction will be opened as an in-memory file. This
  49954. ** has no effect if the sub-journal is already opened (as it may be when
  49955. ** running in exclusive mode) or if the transaction does not require a
  49956. ** sub-journal. If the subjInMemory argument is zero, then any required
  49957. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  49958. ** or using a temporary file otherwise.
  49959. */
  49960. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  49961. int rc = SQLITE_OK;
  49962. if( pPager->errCode ) return pPager->errCode;
  49963. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  49964. pPager->subjInMemory = (u8)subjInMemory;
  49965. if( ALWAYS(pPager->eState==PAGER_READER) ){
  49966. assert( pPager->pInJournal==0 );
  49967. if( pagerUseWal(pPager) ){
  49968. /* If the pager is configured to use locking_mode=exclusive, and an
  49969. ** exclusive lock on the database is not already held, obtain it now.
  49970. */
  49971. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  49972. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  49973. if( rc!=SQLITE_OK ){
  49974. return rc;
  49975. }
  49976. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  49977. }
  49978. /* Grab the write lock on the log file. If successful, upgrade to
  49979. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  49980. ** The busy-handler is not invoked if another connection already
  49981. ** holds the write-lock. If possible, the upper layer will call it.
  49982. */
  49983. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  49984. }else{
  49985. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  49986. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  49987. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  49988. ** lock, but not when obtaining the RESERVED lock.
  49989. */
  49990. rc = pagerLockDb(pPager, RESERVED_LOCK);
  49991. if( rc==SQLITE_OK && exFlag ){
  49992. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  49993. }
  49994. }
  49995. if( rc==SQLITE_OK ){
  49996. /* Change to WRITER_LOCKED state.
  49997. **
  49998. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  49999. ** when it has an open transaction, but never to DBMOD or FINISHED.
  50000. ** This is because in those states the code to roll back savepoint
  50001. ** transactions may copy data from the sub-journal into the database
  50002. ** file as well as into the page cache. Which would be incorrect in
  50003. ** WAL mode.
  50004. */
  50005. pPager->eState = PAGER_WRITER_LOCKED;
  50006. pPager->dbHintSize = pPager->dbSize;
  50007. pPager->dbFileSize = pPager->dbSize;
  50008. pPager->dbOrigSize = pPager->dbSize;
  50009. pPager->journalOff = 0;
  50010. }
  50011. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  50012. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  50013. assert( assert_pager_state(pPager) );
  50014. }
  50015. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  50016. return rc;
  50017. }
  50018. /*
  50019. ** Write page pPg onto the end of the rollback journal.
  50020. */
  50021. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  50022. Pager *pPager = pPg->pPager;
  50023. int rc;
  50024. u32 cksum;
  50025. char *pData2;
  50026. i64 iOff = pPager->journalOff;
  50027. /* We should never write to the journal file the page that
  50028. ** contains the database locks. The following assert verifies
  50029. ** that we do not. */
  50030. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  50031. assert( pPager->journalHdr<=pPager->journalOff );
  50032. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  50033. cksum = pager_cksum(pPager, (u8*)pData2);
  50034. /* Even if an IO or diskfull error occurs while journalling the
  50035. ** page in the block above, set the need-sync flag for the page.
  50036. ** Otherwise, when the transaction is rolled back, the logic in
  50037. ** playback_one_page() will think that the page needs to be restored
  50038. ** in the database file. And if an IO error occurs while doing so,
  50039. ** then corruption may follow.
  50040. */
  50041. pPg->flags |= PGHDR_NEED_SYNC;
  50042. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  50043. if( rc!=SQLITE_OK ) return rc;
  50044. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  50045. if( rc!=SQLITE_OK ) return rc;
  50046. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  50047. if( rc!=SQLITE_OK ) return rc;
  50048. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  50049. pPager->journalOff, pPager->pageSize));
  50050. PAGER_INCR(sqlite3_pager_writej_count);
  50051. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  50052. PAGERID(pPager), pPg->pgno,
  50053. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  50054. pPager->journalOff += 8 + pPager->pageSize;
  50055. pPager->nRec++;
  50056. assert( pPager->pInJournal!=0 );
  50057. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  50058. testcase( rc==SQLITE_NOMEM );
  50059. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  50060. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  50061. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  50062. return rc;
  50063. }
  50064. /*
  50065. ** Mark a single data page as writeable. The page is written into the
  50066. ** main journal or sub-journal as required. If the page is written into
  50067. ** one of the journals, the corresponding bit is set in the
  50068. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  50069. ** of any open savepoints as appropriate.
  50070. */
  50071. static int pager_write(PgHdr *pPg){
  50072. Pager *pPager = pPg->pPager;
  50073. int rc = SQLITE_OK;
  50074. /* This routine is not called unless a write-transaction has already
  50075. ** been started. The journal file may or may not be open at this point.
  50076. ** It is never called in the ERROR state.
  50077. */
  50078. assert( pPager->eState==PAGER_WRITER_LOCKED
  50079. || pPager->eState==PAGER_WRITER_CACHEMOD
  50080. || pPager->eState==PAGER_WRITER_DBMOD
  50081. );
  50082. assert( assert_pager_state(pPager) );
  50083. assert( pPager->errCode==0 );
  50084. assert( pPager->readOnly==0 );
  50085. CHECK_PAGE(pPg);
  50086. /* The journal file needs to be opened. Higher level routines have already
  50087. ** obtained the necessary locks to begin the write-transaction, but the
  50088. ** rollback journal might not yet be open. Open it now if this is the case.
  50089. **
  50090. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  50091. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  50092. ** an error might occur and the pager would end up in WRITER_LOCKED state
  50093. ** with pages marked as dirty in the cache.
  50094. */
  50095. if( pPager->eState==PAGER_WRITER_LOCKED ){
  50096. rc = pager_open_journal(pPager);
  50097. if( rc!=SQLITE_OK ) return rc;
  50098. }
  50099. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  50100. assert( assert_pager_state(pPager) );
  50101. /* Mark the page that is about to be modified as dirty. */
  50102. sqlite3PcacheMakeDirty(pPg);
  50103. /* If a rollback journal is in use, them make sure the page that is about
  50104. ** to change is in the rollback journal, or if the page is a new page off
  50105. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  50106. */
  50107. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  50108. if( pPager->pInJournal!=0
  50109. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  50110. ){
  50111. assert( pagerUseWal(pPager)==0 );
  50112. if( pPg->pgno<=pPager->dbOrigSize ){
  50113. rc = pagerAddPageToRollbackJournal(pPg);
  50114. if( rc!=SQLITE_OK ){
  50115. return rc;
  50116. }
  50117. }else{
  50118. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  50119. pPg->flags |= PGHDR_NEED_SYNC;
  50120. }
  50121. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  50122. PAGERID(pPager), pPg->pgno,
  50123. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  50124. }
  50125. }
  50126. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  50127. ** and before writing the page into the rollback journal. Wait until now,
  50128. ** after the page has been successfully journalled, before setting the
  50129. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  50130. */
  50131. pPg->flags |= PGHDR_WRITEABLE;
  50132. /* If the statement journal is open and the page is not in it,
  50133. ** then write the page into the statement journal.
  50134. */
  50135. if( pPager->nSavepoint>0 ){
  50136. rc = subjournalPageIfRequired(pPg);
  50137. }
  50138. /* Update the database size and return. */
  50139. if( pPager->dbSize<pPg->pgno ){
  50140. pPager->dbSize = pPg->pgno;
  50141. }
  50142. return rc;
  50143. }
  50144. /*
  50145. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  50146. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  50147. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  50148. ** a sector need to be journalled in case of a power loss in the middle of
  50149. ** a write.
  50150. **
  50151. ** Usually, the sector size is less than or equal to the page size, in which
  50152. ** case pages can be individually written. This routine only runs in the
  50153. ** exceptional case where the page size is smaller than the sector size.
  50154. */
  50155. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  50156. int rc = SQLITE_OK; /* Return code */
  50157. Pgno nPageCount; /* Total number of pages in database file */
  50158. Pgno pg1; /* First page of the sector pPg is located on. */
  50159. int nPage = 0; /* Number of pages starting at pg1 to journal */
  50160. int ii; /* Loop counter */
  50161. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  50162. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  50163. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  50164. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  50165. ** a journal header to be written between the pages journaled by
  50166. ** this function.
  50167. */
  50168. assert( !MEMDB );
  50169. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  50170. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  50171. /* This trick assumes that both the page-size and sector-size are
  50172. ** an integer power of 2. It sets variable pg1 to the identifier
  50173. ** of the first page of the sector pPg is located on.
  50174. */
  50175. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  50176. nPageCount = pPager->dbSize;
  50177. if( pPg->pgno>nPageCount ){
  50178. nPage = (pPg->pgno - pg1)+1;
  50179. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  50180. nPage = nPageCount+1-pg1;
  50181. }else{
  50182. nPage = nPagePerSector;
  50183. }
  50184. assert(nPage>0);
  50185. assert(pg1<=pPg->pgno);
  50186. assert((pg1+nPage)>pPg->pgno);
  50187. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  50188. Pgno pg = pg1+ii;
  50189. PgHdr *pPage;
  50190. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  50191. if( pg!=PAGER_MJ_PGNO(pPager) ){
  50192. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  50193. if( rc==SQLITE_OK ){
  50194. rc = pager_write(pPage);
  50195. if( pPage->flags&PGHDR_NEED_SYNC ){
  50196. needSync = 1;
  50197. }
  50198. sqlite3PagerUnrefNotNull(pPage);
  50199. }
  50200. }
  50201. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  50202. if( pPage->flags&PGHDR_NEED_SYNC ){
  50203. needSync = 1;
  50204. }
  50205. sqlite3PagerUnrefNotNull(pPage);
  50206. }
  50207. }
  50208. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  50209. ** starting at pg1, then it needs to be set for all of them. Because
  50210. ** writing to any of these nPage pages may damage the others, the
  50211. ** journal file must contain sync()ed copies of all of them
  50212. ** before any of them can be written out to the database file.
  50213. */
  50214. if( rc==SQLITE_OK && needSync ){
  50215. assert( !MEMDB );
  50216. for(ii=0; ii<nPage; ii++){
  50217. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  50218. if( pPage ){
  50219. pPage->flags |= PGHDR_NEED_SYNC;
  50220. sqlite3PagerUnrefNotNull(pPage);
  50221. }
  50222. }
  50223. }
  50224. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  50225. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  50226. return rc;
  50227. }
  50228. /*
  50229. ** Mark a data page as writeable. This routine must be called before
  50230. ** making changes to a page. The caller must check the return value
  50231. ** of this function and be careful not to change any page data unless
  50232. ** this routine returns SQLITE_OK.
  50233. **
  50234. ** The difference between this function and pager_write() is that this
  50235. ** function also deals with the special case where 2 or more pages
  50236. ** fit on a single disk sector. In this case all co-resident pages
  50237. ** must have been written to the journal file before returning.
  50238. **
  50239. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  50240. ** as appropriate. Otherwise, SQLITE_OK.
  50241. */
  50242. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  50243. Pager *pPager = pPg->pPager;
  50244. assert( (pPg->flags & PGHDR_MMAP)==0 );
  50245. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50246. assert( assert_pager_state(pPager) );
  50247. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  50248. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  50249. return SQLITE_OK;
  50250. }else if( pPager->errCode ){
  50251. return pPager->errCode;
  50252. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  50253. assert( pPager->tempFile==0 );
  50254. return pagerWriteLargeSector(pPg);
  50255. }else{
  50256. return pager_write(pPg);
  50257. }
  50258. }
  50259. /*
  50260. ** Return TRUE if the page given in the argument was previously passed
  50261. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  50262. ** to change the content of the page.
  50263. */
  50264. #ifndef NDEBUG
  50265. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  50266. return pPg->flags & PGHDR_WRITEABLE;
  50267. }
  50268. #endif
  50269. /*
  50270. ** A call to this routine tells the pager that it is not necessary to
  50271. ** write the information on page pPg back to the disk, even though
  50272. ** that page might be marked as dirty. This happens, for example, when
  50273. ** the page has been added as a leaf of the freelist and so its
  50274. ** content no longer matters.
  50275. **
  50276. ** The overlying software layer calls this routine when all of the data
  50277. ** on the given page is unused. The pager marks the page as clean so
  50278. ** that it does not get written to disk.
  50279. **
  50280. ** Tests show that this optimization can quadruple the speed of large
  50281. ** DELETE operations.
  50282. **
  50283. ** This optimization cannot be used with a temp-file, as the page may
  50284. ** have been dirty at the start of the transaction. In that case, if
  50285. ** memory pressure forces page pPg out of the cache, the data does need
  50286. ** to be written out to disk so that it may be read back in if the
  50287. ** current transaction is rolled back.
  50288. */
  50289. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  50290. Pager *pPager = pPg->pPager;
  50291. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  50292. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  50293. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  50294. pPg->flags |= PGHDR_DONT_WRITE;
  50295. pPg->flags &= ~PGHDR_WRITEABLE;
  50296. testcase( pPg->flags & PGHDR_NEED_SYNC );
  50297. pager_set_pagehash(pPg);
  50298. }
  50299. }
  50300. /*
  50301. ** This routine is called to increment the value of the database file
  50302. ** change-counter, stored as a 4-byte big-endian integer starting at
  50303. ** byte offset 24 of the pager file. The secondary change counter at
  50304. ** 92 is also updated, as is the SQLite version number at offset 96.
  50305. **
  50306. ** But this only happens if the pPager->changeCountDone flag is false.
  50307. ** To avoid excess churning of page 1, the update only happens once.
  50308. ** See also the pager_write_changecounter() routine that does an
  50309. ** unconditional update of the change counters.
  50310. **
  50311. ** If the isDirectMode flag is zero, then this is done by calling
  50312. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  50313. ** page data. In this case the file will be updated when the current
  50314. ** transaction is committed.
  50315. **
  50316. ** The isDirectMode flag may only be non-zero if the library was compiled
  50317. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  50318. ** if isDirect is non-zero, then the database file is updated directly
  50319. ** by writing an updated version of page 1 using a call to the
  50320. ** sqlite3OsWrite() function.
  50321. */
  50322. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  50323. int rc = SQLITE_OK;
  50324. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50325. || pPager->eState==PAGER_WRITER_DBMOD
  50326. );
  50327. assert( assert_pager_state(pPager) );
  50328. /* Declare and initialize constant integer 'isDirect'. If the
  50329. ** atomic-write optimization is enabled in this build, then isDirect
  50330. ** is initialized to the value passed as the isDirectMode parameter
  50331. ** to this function. Otherwise, it is always set to zero.
  50332. **
  50333. ** The idea is that if the atomic-write optimization is not
  50334. ** enabled at compile time, the compiler can omit the tests of
  50335. ** 'isDirect' below, as well as the block enclosed in the
  50336. ** "if( isDirect )" condition.
  50337. */
  50338. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  50339. # define DIRECT_MODE 0
  50340. assert( isDirectMode==0 );
  50341. UNUSED_PARAMETER(isDirectMode);
  50342. #else
  50343. # define DIRECT_MODE isDirectMode
  50344. #endif
  50345. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  50346. PgHdr *pPgHdr; /* Reference to page 1 */
  50347. assert( !pPager->tempFile && isOpen(pPager->fd) );
  50348. /* Open page 1 of the file for writing. */
  50349. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  50350. assert( pPgHdr==0 || rc==SQLITE_OK );
  50351. /* If page one was fetched successfully, and this function is not
  50352. ** operating in direct-mode, make page 1 writable. When not in
  50353. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  50354. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  50355. */
  50356. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  50357. rc = sqlite3PagerWrite(pPgHdr);
  50358. }
  50359. if( rc==SQLITE_OK ){
  50360. /* Actually do the update of the change counter */
  50361. pager_write_changecounter(pPgHdr);
  50362. /* If running in direct mode, write the contents of page 1 to the file. */
  50363. if( DIRECT_MODE ){
  50364. const void *zBuf;
  50365. assert( pPager->dbFileSize>0 );
  50366. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  50367. if( rc==SQLITE_OK ){
  50368. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  50369. pPager->aStat[PAGER_STAT_WRITE]++;
  50370. }
  50371. if( rc==SQLITE_OK ){
  50372. /* Update the pager's copy of the change-counter. Otherwise, the
  50373. ** next time a read transaction is opened the cache will be
  50374. ** flushed (as the change-counter values will not match). */
  50375. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  50376. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  50377. pPager->changeCountDone = 1;
  50378. }
  50379. }else{
  50380. pPager->changeCountDone = 1;
  50381. }
  50382. }
  50383. /* Release the page reference. */
  50384. sqlite3PagerUnref(pPgHdr);
  50385. }
  50386. return rc;
  50387. }
  50388. /*
  50389. ** Sync the database file to disk. This is a no-op for in-memory databases
  50390. ** or pages with the Pager.noSync flag set.
  50391. **
  50392. ** If successful, or if called on a pager for which it is a no-op, this
  50393. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  50394. */
  50395. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  50396. int rc = SQLITE_OK;
  50397. if( isOpen(pPager->fd) ){
  50398. void *pArg = (void*)zMaster;
  50399. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  50400. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  50401. }
  50402. if( rc==SQLITE_OK && !pPager->noSync ){
  50403. assert( !MEMDB );
  50404. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  50405. }
  50406. return rc;
  50407. }
  50408. /*
  50409. ** This function may only be called while a write-transaction is active in
  50410. ** rollback. If the connection is in WAL mode, this call is a no-op.
  50411. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  50412. ** the database file, an attempt is made to obtain one.
  50413. **
  50414. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  50415. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  50416. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  50417. ** returned.
  50418. */
  50419. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  50420. int rc = pPager->errCode;
  50421. assert( assert_pager_state(pPager) );
  50422. if( rc==SQLITE_OK ){
  50423. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50424. || pPager->eState==PAGER_WRITER_DBMOD
  50425. || pPager->eState==PAGER_WRITER_LOCKED
  50426. );
  50427. assert( assert_pager_state(pPager) );
  50428. if( 0==pagerUseWal(pPager) ){
  50429. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  50430. }
  50431. }
  50432. return rc;
  50433. }
  50434. /*
  50435. ** Sync the database file for the pager pPager. zMaster points to the name
  50436. ** of a master journal file that should be written into the individual
  50437. ** journal file. zMaster may be NULL, which is interpreted as no master
  50438. ** journal (a single database transaction).
  50439. **
  50440. ** This routine ensures that:
  50441. **
  50442. ** * The database file change-counter is updated,
  50443. ** * the journal is synced (unless the atomic-write optimization is used),
  50444. ** * all dirty pages are written to the database file,
  50445. ** * the database file is truncated (if required), and
  50446. ** * the database file synced.
  50447. **
  50448. ** The only thing that remains to commit the transaction is to finalize
  50449. ** (delete, truncate or zero the first part of) the journal file (or
  50450. ** delete the master journal file if specified).
  50451. **
  50452. ** Note that if zMaster==NULL, this does not overwrite a previous value
  50453. ** passed to an sqlite3PagerCommitPhaseOne() call.
  50454. **
  50455. ** If the final parameter - noSync - is true, then the database file itself
  50456. ** is not synced. The caller must call sqlite3PagerSync() directly to
  50457. ** sync the database file before calling CommitPhaseTwo() to delete the
  50458. ** journal file in this case.
  50459. */
  50460. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  50461. Pager *pPager, /* Pager object */
  50462. const char *zMaster, /* If not NULL, the master journal name */
  50463. int noSync /* True to omit the xSync on the db file */
  50464. ){
  50465. int rc = SQLITE_OK; /* Return code */
  50466. assert( pPager->eState==PAGER_WRITER_LOCKED
  50467. || pPager->eState==PAGER_WRITER_CACHEMOD
  50468. || pPager->eState==PAGER_WRITER_DBMOD
  50469. || pPager->eState==PAGER_ERROR
  50470. );
  50471. assert( assert_pager_state(pPager) );
  50472. /* If a prior error occurred, report that error again. */
  50473. if( NEVER(pPager->errCode) ) return pPager->errCode;
  50474. /* Provide the ability to easily simulate an I/O error during testing */
  50475. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  50476. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  50477. pPager->zFilename, zMaster, pPager->dbSize));
  50478. /* If no database changes have been made, return early. */
  50479. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  50480. assert( MEMDB==0 || pPager->tempFile );
  50481. assert( isOpen(pPager->fd) || pPager->tempFile );
  50482. if( 0==pagerFlushOnCommit(pPager, 1) ){
  50483. /* If this is an in-memory db, or no pages have been written to, or this
  50484. ** function has already been called, it is mostly a no-op. However, any
  50485. ** backup in progress needs to be restarted. */
  50486. sqlite3BackupRestart(pPager->pBackup);
  50487. }else{
  50488. if( pagerUseWal(pPager) ){
  50489. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50490. PgHdr *pPageOne = 0;
  50491. if( pList==0 ){
  50492. /* Must have at least one page for the WAL commit flag.
  50493. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  50494. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  50495. pList = pPageOne;
  50496. pList->pDirty = 0;
  50497. }
  50498. assert( rc==SQLITE_OK );
  50499. if( ALWAYS(pList) ){
  50500. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  50501. }
  50502. sqlite3PagerUnref(pPageOne);
  50503. if( rc==SQLITE_OK ){
  50504. sqlite3PcacheCleanAll(pPager->pPCache);
  50505. }
  50506. }else{
  50507. /* The bBatch boolean is true if the batch-atomic-write commit method
  50508. ** should be used. No rollback journal is created if batch-atomic-write
  50509. ** is enabled.
  50510. */
  50511. sqlite3_file *fd = pPager->fd;
  50512. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  50513. const int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  50514. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  50515. && !pPager->noSync
  50516. && sqlite3JournalIsInMemory(pPager->jfd);
  50517. #else
  50518. # define bBatch 0
  50519. #endif
  50520. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  50521. /* The following block updates the change-counter. Exactly how it
  50522. ** does this depends on whether or not the atomic-update optimization
  50523. ** was enabled at compile time, and if this transaction meets the
  50524. ** runtime criteria to use the operation:
  50525. **
  50526. ** * The file-system supports the atomic-write property for
  50527. ** blocks of size page-size, and
  50528. ** * This commit is not part of a multi-file transaction, and
  50529. ** * Exactly one page has been modified and store in the journal file.
  50530. **
  50531. ** If the optimization was not enabled at compile time, then the
  50532. ** pager_incr_changecounter() function is called to update the change
  50533. ** counter in 'indirect-mode'. If the optimization is compiled in but
  50534. ** is not applicable to this transaction, call sqlite3JournalCreate()
  50535. ** to make sure the journal file has actually been created, then call
  50536. ** pager_incr_changecounter() to update the change-counter in indirect
  50537. ** mode.
  50538. **
  50539. ** Otherwise, if the optimization is both enabled and applicable,
  50540. ** then call pager_incr_changecounter() to update the change-counter
  50541. ** in 'direct' mode. In this case the journal file will never be
  50542. ** created for this transaction.
  50543. */
  50544. if( bBatch==0 ){
  50545. PgHdr *pPg;
  50546. assert( isOpen(pPager->jfd)
  50547. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  50548. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  50549. );
  50550. if( !zMaster && isOpen(pPager->jfd)
  50551. && pPager->journalOff==jrnlBufferSize(pPager)
  50552. && pPager->dbSize>=pPager->dbOrigSize
  50553. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  50554. ){
  50555. /* Update the db file change counter via the direct-write method. The
  50556. ** following call will modify the in-memory representation of page 1
  50557. ** to include the updated change counter and then write page 1
  50558. ** directly to the database file. Because of the atomic-write
  50559. ** property of the host file-system, this is safe.
  50560. */
  50561. rc = pager_incr_changecounter(pPager, 1);
  50562. }else{
  50563. rc = sqlite3JournalCreate(pPager->jfd);
  50564. if( rc==SQLITE_OK ){
  50565. rc = pager_incr_changecounter(pPager, 0);
  50566. }
  50567. }
  50568. }
  50569. #else
  50570. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  50571. if( zMaster ){
  50572. rc = sqlite3JournalCreate(pPager->jfd);
  50573. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50574. }
  50575. #endif
  50576. rc = pager_incr_changecounter(pPager, 0);
  50577. #endif
  50578. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50579. /* Write the master journal name into the journal file. If a master
  50580. ** journal file name has already been written to the journal file,
  50581. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  50582. */
  50583. rc = writeMasterJournal(pPager, zMaster);
  50584. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50585. /* Sync the journal file and write all dirty pages to the database.
  50586. ** If the atomic-update optimization is being used, this sync will not
  50587. ** create the journal file or perform any real IO.
  50588. **
  50589. ** Because the change-counter page was just modified, unless the
  50590. ** atomic-update optimization is used it is almost certain that the
  50591. ** journal requires a sync here. However, in locking_mode=exclusive
  50592. ** on a system under memory pressure it is just possible that this is
  50593. ** not the case. In this case it is likely enough that the redundant
  50594. ** xSync() call will be changed to a no-op by the OS anyhow.
  50595. */
  50596. rc = syncJournal(pPager, 0);
  50597. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50598. if( bBatch ){
  50599. /* The pager is now in DBMOD state. But regardless of what happens
  50600. ** next, attempting to play the journal back into the database would
  50601. ** be unsafe. Close it now to make sure that does not happen. */
  50602. sqlite3OsClose(pPager->jfd);
  50603. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  50604. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50605. }
  50606. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  50607. if( bBatch ){
  50608. if( rc==SQLITE_OK ){
  50609. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  50610. }else{
  50611. sqlite3OsFileControl(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  50612. }
  50613. }
  50614. if( rc!=SQLITE_OK ){
  50615. assert( rc!=SQLITE_IOERR_BLOCKED );
  50616. goto commit_phase_one_exit;
  50617. }
  50618. sqlite3PcacheCleanAll(pPager->pPCache);
  50619. /* If the file on disk is smaller than the database image, use
  50620. ** pager_truncate to grow the file here. This can happen if the database
  50621. ** image was extended as part of the current transaction and then the
  50622. ** last page in the db image moved to the free-list. In this case the
  50623. ** last page is never written out to disk, leaving the database file
  50624. ** undersized. Fix this now if it is the case. */
  50625. if( pPager->dbSize>pPager->dbFileSize ){
  50626. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  50627. assert( pPager->eState==PAGER_WRITER_DBMOD );
  50628. rc = pager_truncate(pPager, nNew);
  50629. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50630. }
  50631. /* Finally, sync the database file. */
  50632. if( !noSync ){
  50633. rc = sqlite3PagerSync(pPager, zMaster);
  50634. }
  50635. IOTRACE(("DBSYNC %p\n", pPager))
  50636. }
  50637. }
  50638. commit_phase_one_exit:
  50639. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  50640. pPager->eState = PAGER_WRITER_FINISHED;
  50641. }
  50642. return rc;
  50643. }
  50644. /*
  50645. ** When this function is called, the database file has been completely
  50646. ** updated to reflect the changes made by the current transaction and
  50647. ** synced to disk. The journal file still exists in the file-system
  50648. ** though, and if a failure occurs at this point it will eventually
  50649. ** be used as a hot-journal and the current transaction rolled back.
  50650. **
  50651. ** This function finalizes the journal file, either by deleting,
  50652. ** truncating or partially zeroing it, so that it cannot be used
  50653. ** for hot-journal rollback. Once this is done the transaction is
  50654. ** irrevocably committed.
  50655. **
  50656. ** If an error occurs, an IO error code is returned and the pager
  50657. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  50658. */
  50659. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  50660. int rc = SQLITE_OK; /* Return code */
  50661. /* This routine should not be called if a prior error has occurred.
  50662. ** But if (due to a coding error elsewhere in the system) it does get
  50663. ** called, just return the same error code without doing anything. */
  50664. if( NEVER(pPager->errCode) ) return pPager->errCode;
  50665. assert( pPager->eState==PAGER_WRITER_LOCKED
  50666. || pPager->eState==PAGER_WRITER_FINISHED
  50667. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  50668. );
  50669. assert( assert_pager_state(pPager) );
  50670. /* An optimization. If the database was not actually modified during
  50671. ** this transaction, the pager is running in exclusive-mode and is
  50672. ** using persistent journals, then this function is a no-op.
  50673. **
  50674. ** The start of the journal file currently contains a single journal
  50675. ** header with the nRec field set to 0. If such a journal is used as
  50676. ** a hot-journal during hot-journal rollback, 0 changes will be made
  50677. ** to the database file. So there is no need to zero the journal
  50678. ** header. Since the pager is in exclusive mode, there is no need
  50679. ** to drop any locks either.
  50680. */
  50681. if( pPager->eState==PAGER_WRITER_LOCKED
  50682. && pPager->exclusiveMode
  50683. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  50684. ){
  50685. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  50686. pPager->eState = PAGER_READER;
  50687. return SQLITE_OK;
  50688. }
  50689. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  50690. pPager->iDataVersion++;
  50691. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  50692. return pager_error(pPager, rc);
  50693. }
  50694. /*
  50695. ** If a write transaction is open, then all changes made within the
  50696. ** transaction are reverted and the current write-transaction is closed.
  50697. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  50698. ** state if an error occurs.
  50699. **
  50700. ** If the pager is already in PAGER_ERROR state when this function is called,
  50701. ** it returns Pager.errCode immediately. No work is performed in this case.
  50702. **
  50703. ** Otherwise, in rollback mode, this function performs two functions:
  50704. **
  50705. ** 1) It rolls back the journal file, restoring all database file and
  50706. ** in-memory cache pages to the state they were in when the transaction
  50707. ** was opened, and
  50708. **
  50709. ** 2) It finalizes the journal file, so that it is not used for hot
  50710. ** rollback at any point in the future.
  50711. **
  50712. ** Finalization of the journal file (task 2) is only performed if the
  50713. ** rollback is successful.
  50714. **
  50715. ** In WAL mode, all cache-entries containing data modified within the
  50716. ** current transaction are either expelled from the cache or reverted to
  50717. ** their pre-transaction state by re-reading data from the database or
  50718. ** WAL files. The WAL transaction is then closed.
  50719. */
  50720. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  50721. int rc = SQLITE_OK; /* Return code */
  50722. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  50723. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  50724. ** the pager is already in the ERROR state, the rollback is not
  50725. ** attempted here. Instead, the error code is returned to the caller.
  50726. */
  50727. assert( assert_pager_state(pPager) );
  50728. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  50729. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  50730. if( pagerUseWal(pPager) ){
  50731. int rc2;
  50732. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  50733. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  50734. if( rc==SQLITE_OK ) rc = rc2;
  50735. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  50736. int eState = pPager->eState;
  50737. rc = pager_end_transaction(pPager, 0, 0);
  50738. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  50739. /* This can happen using journal_mode=off. Move the pager to the error
  50740. ** state to indicate that the contents of the cache may not be trusted.
  50741. ** Any active readers will get SQLITE_ABORT.
  50742. */
  50743. pPager->errCode = SQLITE_ABORT;
  50744. pPager->eState = PAGER_ERROR;
  50745. setGetterMethod(pPager);
  50746. return rc;
  50747. }
  50748. }else{
  50749. rc = pager_playback(pPager, 0);
  50750. }
  50751. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  50752. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  50753. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  50754. || rc==SQLITE_CANTOPEN
  50755. );
  50756. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  50757. ** cache. So call pager_error() on the way out to make any error persistent.
  50758. */
  50759. return pager_error(pPager, rc);
  50760. }
  50761. /*
  50762. ** Return TRUE if the database file is opened read-only. Return FALSE
  50763. ** if the database is (in theory) writable.
  50764. */
  50765. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  50766. return pPager->readOnly;
  50767. }
  50768. #ifdef SQLITE_DEBUG
  50769. /*
  50770. ** Return the sum of the reference counts for all pages held by pPager.
  50771. */
  50772. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  50773. return sqlite3PcacheRefCount(pPager->pPCache);
  50774. }
  50775. #endif
  50776. /*
  50777. ** Return the approximate number of bytes of memory currently
  50778. ** used by the pager and its associated cache.
  50779. */
  50780. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  50781. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  50782. + 5*sizeof(void*);
  50783. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  50784. + sqlite3MallocSize(pPager)
  50785. + pPager->pageSize;
  50786. }
  50787. /*
  50788. ** Return the number of references to the specified page.
  50789. */
  50790. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  50791. return sqlite3PcachePageRefcount(pPage);
  50792. }
  50793. #ifdef SQLITE_TEST
  50794. /*
  50795. ** This routine is used for testing and analysis only.
  50796. */
  50797. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  50798. static int a[11];
  50799. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  50800. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  50801. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  50802. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  50803. a[4] = pPager->eState;
  50804. a[5] = pPager->errCode;
  50805. a[6] = pPager->aStat[PAGER_STAT_HIT];
  50806. a[7] = pPager->aStat[PAGER_STAT_MISS];
  50807. a[8] = 0; /* Used to be pPager->nOvfl */
  50808. a[9] = pPager->nRead;
  50809. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  50810. return a;
  50811. }
  50812. #endif
  50813. /*
  50814. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  50815. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  50816. ** current cache hit or miss count, according to the value of eStat. If the
  50817. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  50818. ** returning.
  50819. */
  50820. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  50821. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  50822. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  50823. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  50824. );
  50825. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  50826. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  50827. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  50828. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  50829. if( reset ){
  50830. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  50831. }
  50832. }
  50833. /*
  50834. ** Return true if this is an in-memory or temp-file backed pager.
  50835. */
  50836. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  50837. return pPager->tempFile;
  50838. }
  50839. /*
  50840. ** Check that there are at least nSavepoint savepoints open. If there are
  50841. ** currently less than nSavepoints open, then open one or more savepoints
  50842. ** to make up the difference. If the number of savepoints is already
  50843. ** equal to nSavepoint, then this function is a no-op.
  50844. **
  50845. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  50846. ** occurs while opening the sub-journal file, then an IO error code is
  50847. ** returned. Otherwise, SQLITE_OK.
  50848. */
  50849. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50850. int rc = SQLITE_OK; /* Return code */
  50851. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  50852. int ii; /* Iterator variable */
  50853. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  50854. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50855. assert( assert_pager_state(pPager) );
  50856. assert( nSavepoint>nCurrent && pPager->useJournal );
  50857. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  50858. ** if the allocation fails. Otherwise, zero the new portion in case a
  50859. ** malloc failure occurs while populating it in the for(...) loop below.
  50860. */
  50861. aNew = (PagerSavepoint *)sqlite3Realloc(
  50862. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  50863. );
  50864. if( !aNew ){
  50865. return SQLITE_NOMEM_BKPT;
  50866. }
  50867. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  50868. pPager->aSavepoint = aNew;
  50869. /* Populate the PagerSavepoint structures just allocated. */
  50870. for(ii=nCurrent; ii<nSavepoint; ii++){
  50871. aNew[ii].nOrig = pPager->dbSize;
  50872. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  50873. aNew[ii].iOffset = pPager->journalOff;
  50874. }else{
  50875. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  50876. }
  50877. aNew[ii].iSubRec = pPager->nSubRec;
  50878. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  50879. if( !aNew[ii].pInSavepoint ){
  50880. return SQLITE_NOMEM_BKPT;
  50881. }
  50882. if( pagerUseWal(pPager) ){
  50883. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  50884. }
  50885. pPager->nSavepoint = ii+1;
  50886. }
  50887. assert( pPager->nSavepoint==nSavepoint );
  50888. assertTruncateConstraint(pPager);
  50889. return rc;
  50890. }
  50891. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50892. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50893. assert( assert_pager_state(pPager) );
  50894. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  50895. return pagerOpenSavepoint(pPager, nSavepoint);
  50896. }else{
  50897. return SQLITE_OK;
  50898. }
  50899. }
  50900. /*
  50901. ** This function is called to rollback or release (commit) a savepoint.
  50902. ** The savepoint to release or rollback need not be the most recently
  50903. ** created savepoint.
  50904. **
  50905. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  50906. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  50907. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  50908. ** that have occurred since the specified savepoint was created.
  50909. **
  50910. ** The savepoint to rollback or release is identified by parameter
  50911. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  50912. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  50913. ** on the most recently created savepoint. If iSavepoint is greater than
  50914. ** (Pager.nSavepoint-1), then this function is a no-op.
  50915. **
  50916. ** If a negative value is passed to this function, then the current
  50917. ** transaction is rolled back. This is different to calling
  50918. ** sqlite3PagerRollback() because this function does not terminate
  50919. ** the transaction or unlock the database, it just restores the
  50920. ** contents of the database to its original state.
  50921. **
  50922. ** In any case, all savepoints with an index greater than iSavepoint
  50923. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  50924. ** then savepoint iSavepoint is also destroyed.
  50925. **
  50926. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  50927. ** or an IO error code if an IO error occurs while rolling back a
  50928. ** savepoint. If no errors occur, SQLITE_OK is returned.
  50929. */
  50930. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  50931. int rc = pPager->errCode;
  50932. #ifdef SQLITE_ENABLE_ZIPVFS
  50933. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  50934. #endif
  50935. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  50936. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  50937. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  50938. int ii; /* Iterator variable */
  50939. int nNew; /* Number of remaining savepoints after this op. */
  50940. /* Figure out how many savepoints will still be active after this
  50941. ** operation. Store this value in nNew. Then free resources associated
  50942. ** with any savepoints that are destroyed by this operation.
  50943. */
  50944. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  50945. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  50946. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  50947. }
  50948. pPager->nSavepoint = nNew;
  50949. /* If this is a release of the outermost savepoint, truncate
  50950. ** the sub-journal to zero bytes in size. */
  50951. if( op==SAVEPOINT_RELEASE ){
  50952. if( nNew==0 && isOpen(pPager->sjfd) ){
  50953. /* Only truncate if it is an in-memory sub-journal. */
  50954. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  50955. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  50956. assert( rc==SQLITE_OK );
  50957. }
  50958. pPager->nSubRec = 0;
  50959. }
  50960. }
  50961. /* Else this is a rollback operation, playback the specified savepoint.
  50962. ** If this is a temp-file, it is possible that the journal file has
  50963. ** not yet been opened. In this case there have been no changes to
  50964. ** the database file, so the playback operation can be skipped.
  50965. */
  50966. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  50967. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  50968. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  50969. assert(rc!=SQLITE_DONE);
  50970. }
  50971. #ifdef SQLITE_ENABLE_ZIPVFS
  50972. /* If the cache has been modified but the savepoint cannot be rolled
  50973. ** back journal_mode=off, put the pager in the error state. This way,
  50974. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  50975. ** can be rolled back at the ZipVFS level. */
  50976. else if(
  50977. pPager->journalMode==PAGER_JOURNALMODE_OFF
  50978. && pPager->eState>=PAGER_WRITER_CACHEMOD
  50979. ){
  50980. pPager->errCode = SQLITE_ABORT;
  50981. pPager->eState = PAGER_ERROR;
  50982. setGetterMethod(pPager);
  50983. }
  50984. #endif
  50985. }
  50986. return rc;
  50987. }
  50988. /*
  50989. ** Return the full pathname of the database file.
  50990. **
  50991. ** Except, if the pager is in-memory only, then return an empty string if
  50992. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  50993. ** used to report the filename to the user, for compatibility with legacy
  50994. ** behavior. But when the Btree needs to know the filename for matching to
  50995. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  50996. ** participate in shared-cache.
  50997. */
  50998. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  50999. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  51000. }
  51001. /*
  51002. ** Return the VFS structure for the pager.
  51003. */
  51004. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  51005. return pPager->pVfs;
  51006. }
  51007. /*
  51008. ** Return the file handle for the database file associated
  51009. ** with the pager. This might return NULL if the file has
  51010. ** not yet been opened.
  51011. */
  51012. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  51013. return pPager->fd;
  51014. }
  51015. /*
  51016. ** Return the file handle for the journal file (if it exists).
  51017. ** This will be either the rollback journal or the WAL file.
  51018. */
  51019. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  51020. #if SQLITE_OMIT_WAL
  51021. return pPager->jfd;
  51022. #else
  51023. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  51024. #endif
  51025. }
  51026. /*
  51027. ** Return the full pathname of the journal file.
  51028. */
  51029. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  51030. return pPager->zJournal;
  51031. }
  51032. #ifdef SQLITE_HAS_CODEC
  51033. /*
  51034. ** Set or retrieve the codec for this pager
  51035. */
  51036. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  51037. Pager *pPager,
  51038. void *(*xCodec)(void*,void*,Pgno,int),
  51039. void (*xCodecSizeChng)(void*,int,int),
  51040. void (*xCodecFree)(void*),
  51041. void *pCodec
  51042. ){
  51043. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  51044. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  51045. pPager->xCodecSizeChng = xCodecSizeChng;
  51046. pPager->xCodecFree = xCodecFree;
  51047. pPager->pCodec = pCodec;
  51048. setGetterMethod(pPager);
  51049. pagerReportSize(pPager);
  51050. }
  51051. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  51052. return pPager->pCodec;
  51053. }
  51054. /*
  51055. ** This function is called by the wal module when writing page content
  51056. ** into the log file.
  51057. **
  51058. ** This function returns a pointer to a buffer containing the encrypted
  51059. ** page content. If a malloc fails, this function may return NULL.
  51060. */
  51061. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  51062. void *aData = 0;
  51063. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  51064. return aData;
  51065. }
  51066. /*
  51067. ** Return the current pager state
  51068. */
  51069. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  51070. return pPager->eState;
  51071. }
  51072. #endif /* SQLITE_HAS_CODEC */
  51073. #ifndef SQLITE_OMIT_AUTOVACUUM
  51074. /*
  51075. ** Move the page pPg to location pgno in the file.
  51076. **
  51077. ** There must be no references to the page previously located at
  51078. ** pgno (which we call pPgOld) though that page is allowed to be
  51079. ** in cache. If the page previously located at pgno is not already
  51080. ** in the rollback journal, it is not put there by by this routine.
  51081. **
  51082. ** References to the page pPg remain valid. Updating any
  51083. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  51084. ** allocated along with the page) is the responsibility of the caller.
  51085. **
  51086. ** A transaction must be active when this routine is called. It used to be
  51087. ** required that a statement transaction was not active, but this restriction
  51088. ** has been removed (CREATE INDEX needs to move a page when a statement
  51089. ** transaction is active).
  51090. **
  51091. ** If the fourth argument, isCommit, is non-zero, then this page is being
  51092. ** moved as part of a database reorganization just before the transaction
  51093. ** is being committed. In this case, it is guaranteed that the database page
  51094. ** pPg refers to will not be written to again within this transaction.
  51095. **
  51096. ** This function may return SQLITE_NOMEM or an IO error code if an error
  51097. ** occurs. Otherwise, it returns SQLITE_OK.
  51098. */
  51099. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  51100. PgHdr *pPgOld; /* The page being overwritten. */
  51101. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  51102. int rc; /* Return code */
  51103. Pgno origPgno; /* The original page number */
  51104. assert( pPg->nRef>0 );
  51105. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51106. || pPager->eState==PAGER_WRITER_DBMOD
  51107. );
  51108. assert( assert_pager_state(pPager) );
  51109. /* In order to be able to rollback, an in-memory database must journal
  51110. ** the page we are moving from.
  51111. */
  51112. assert( pPager->tempFile || !MEMDB );
  51113. if( pPager->tempFile ){
  51114. rc = sqlite3PagerWrite(pPg);
  51115. if( rc ) return rc;
  51116. }
  51117. /* If the page being moved is dirty and has not been saved by the latest
  51118. ** savepoint, then save the current contents of the page into the
  51119. ** sub-journal now. This is required to handle the following scenario:
  51120. **
  51121. ** BEGIN;
  51122. ** <journal page X, then modify it in memory>
  51123. ** SAVEPOINT one;
  51124. ** <Move page X to location Y>
  51125. ** ROLLBACK TO one;
  51126. **
  51127. ** If page X were not written to the sub-journal here, it would not
  51128. ** be possible to restore its contents when the "ROLLBACK TO one"
  51129. ** statement were is processed.
  51130. **
  51131. ** subjournalPage() may need to allocate space to store pPg->pgno into
  51132. ** one or more savepoint bitvecs. This is the reason this function
  51133. ** may return SQLITE_NOMEM.
  51134. */
  51135. if( (pPg->flags & PGHDR_DIRTY)!=0
  51136. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  51137. ){
  51138. return rc;
  51139. }
  51140. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  51141. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  51142. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  51143. /* If the journal needs to be sync()ed before page pPg->pgno can
  51144. ** be written to, store pPg->pgno in local variable needSyncPgno.
  51145. **
  51146. ** If the isCommit flag is set, there is no need to remember that
  51147. ** the journal needs to be sync()ed before database page pPg->pgno
  51148. ** can be written to. The caller has already promised not to write to it.
  51149. */
  51150. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  51151. needSyncPgno = pPg->pgno;
  51152. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  51153. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  51154. assert( pPg->flags&PGHDR_DIRTY );
  51155. }
  51156. /* If the cache contains a page with page-number pgno, remove it
  51157. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  51158. ** page pgno before the 'move' operation, it needs to be retained
  51159. ** for the page moved there.
  51160. */
  51161. pPg->flags &= ~PGHDR_NEED_SYNC;
  51162. pPgOld = sqlite3PagerLookup(pPager, pgno);
  51163. assert( !pPgOld || pPgOld->nRef==1 );
  51164. if( pPgOld ){
  51165. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  51166. if( pPager->tempFile ){
  51167. /* Do not discard pages from an in-memory database since we might
  51168. ** need to rollback later. Just move the page out of the way. */
  51169. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  51170. }else{
  51171. sqlite3PcacheDrop(pPgOld);
  51172. }
  51173. }
  51174. origPgno = pPg->pgno;
  51175. sqlite3PcacheMove(pPg, pgno);
  51176. sqlite3PcacheMakeDirty(pPg);
  51177. /* For an in-memory database, make sure the original page continues
  51178. ** to exist, in case the transaction needs to roll back. Use pPgOld
  51179. ** as the original page since it has already been allocated.
  51180. */
  51181. if( pPager->tempFile && pPgOld ){
  51182. sqlite3PcacheMove(pPgOld, origPgno);
  51183. sqlite3PagerUnrefNotNull(pPgOld);
  51184. }
  51185. if( needSyncPgno ){
  51186. /* If needSyncPgno is non-zero, then the journal file needs to be
  51187. ** sync()ed before any data is written to database file page needSyncPgno.
  51188. ** Currently, no such page exists in the page-cache and the
  51189. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  51190. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  51191. ** flag.
  51192. **
  51193. ** If the attempt to load the page into the page-cache fails, (due
  51194. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  51195. ** array. Otherwise, if the page is loaded and written again in
  51196. ** this transaction, it may be written to the database file before
  51197. ** it is synced into the journal file. This way, it may end up in
  51198. ** the journal file twice, but that is not a problem.
  51199. */
  51200. PgHdr *pPgHdr;
  51201. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  51202. if( rc!=SQLITE_OK ){
  51203. if( needSyncPgno<=pPager->dbOrigSize ){
  51204. assert( pPager->pTmpSpace!=0 );
  51205. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  51206. }
  51207. return rc;
  51208. }
  51209. pPgHdr->flags |= PGHDR_NEED_SYNC;
  51210. sqlite3PcacheMakeDirty(pPgHdr);
  51211. sqlite3PagerUnrefNotNull(pPgHdr);
  51212. }
  51213. return SQLITE_OK;
  51214. }
  51215. #endif
  51216. /*
  51217. ** The page handle passed as the first argument refers to a dirty page
  51218. ** with a page number other than iNew. This function changes the page's
  51219. ** page number to iNew and sets the value of the PgHdr.flags field to
  51220. ** the value passed as the third parameter.
  51221. */
  51222. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  51223. assert( pPg->pgno!=iNew );
  51224. pPg->flags = flags;
  51225. sqlite3PcacheMove(pPg, iNew);
  51226. }
  51227. /*
  51228. ** Return a pointer to the data for the specified page.
  51229. */
  51230. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  51231. assert( pPg->nRef>0 || pPg->pPager->memDb );
  51232. return pPg->pData;
  51233. }
  51234. /*
  51235. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  51236. ** allocated along with the specified page.
  51237. */
  51238. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  51239. return pPg->pExtra;
  51240. }
  51241. /*
  51242. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  51243. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  51244. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  51245. ** the locking-mode is set to the value specified.
  51246. **
  51247. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  51248. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  51249. ** locking-mode.
  51250. */
  51251. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  51252. assert( eMode==PAGER_LOCKINGMODE_QUERY
  51253. || eMode==PAGER_LOCKINGMODE_NORMAL
  51254. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  51255. assert( PAGER_LOCKINGMODE_QUERY<0 );
  51256. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  51257. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  51258. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  51259. pPager->exclusiveMode = (u8)eMode;
  51260. }
  51261. return (int)pPager->exclusiveMode;
  51262. }
  51263. /*
  51264. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  51265. **
  51266. ** PAGER_JOURNALMODE_DELETE
  51267. ** PAGER_JOURNALMODE_TRUNCATE
  51268. ** PAGER_JOURNALMODE_PERSIST
  51269. ** PAGER_JOURNALMODE_OFF
  51270. ** PAGER_JOURNALMODE_MEMORY
  51271. ** PAGER_JOURNALMODE_WAL
  51272. **
  51273. ** The journalmode is set to the value specified if the change is allowed.
  51274. ** The change may be disallowed for the following reasons:
  51275. **
  51276. ** * An in-memory database can only have its journal_mode set to _OFF
  51277. ** or _MEMORY.
  51278. **
  51279. ** * Temporary databases cannot have _WAL journalmode.
  51280. **
  51281. ** The returned indicate the current (possibly updated) journal-mode.
  51282. */
  51283. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  51284. u8 eOld = pPager->journalMode; /* Prior journalmode */
  51285. #ifdef SQLITE_DEBUG
  51286. /* The print_pager_state() routine is intended to be used by the debugger
  51287. ** only. We invoke it once here to suppress a compiler warning. */
  51288. print_pager_state(pPager);
  51289. #endif
  51290. /* The eMode parameter is always valid */
  51291. assert( eMode==PAGER_JOURNALMODE_DELETE
  51292. || eMode==PAGER_JOURNALMODE_TRUNCATE
  51293. || eMode==PAGER_JOURNALMODE_PERSIST
  51294. || eMode==PAGER_JOURNALMODE_OFF
  51295. || eMode==PAGER_JOURNALMODE_WAL
  51296. || eMode==PAGER_JOURNALMODE_MEMORY );
  51297. /* This routine is only called from the OP_JournalMode opcode, and
  51298. ** the logic there will never allow a temporary file to be changed
  51299. ** to WAL mode.
  51300. */
  51301. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  51302. /* Do allow the journalmode of an in-memory database to be set to
  51303. ** anything other than MEMORY or OFF
  51304. */
  51305. if( MEMDB ){
  51306. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  51307. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  51308. eMode = eOld;
  51309. }
  51310. }
  51311. if( eMode!=eOld ){
  51312. /* Change the journal mode. */
  51313. assert( pPager->eState!=PAGER_ERROR );
  51314. pPager->journalMode = (u8)eMode;
  51315. /* When transistioning from TRUNCATE or PERSIST to any other journal
  51316. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  51317. ** delete the journal file.
  51318. */
  51319. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  51320. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  51321. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  51322. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  51323. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  51324. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  51325. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  51326. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  51327. /* In this case we would like to delete the journal file. If it is
  51328. ** not possible, then that is not a problem. Deleting the journal file
  51329. ** here is an optimization only.
  51330. **
  51331. ** Before deleting the journal file, obtain a RESERVED lock on the
  51332. ** database file. This ensures that the journal file is not deleted
  51333. ** while it is in use by some other client.
  51334. */
  51335. sqlite3OsClose(pPager->jfd);
  51336. if( pPager->eLock>=RESERVED_LOCK ){
  51337. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  51338. }else{
  51339. int rc = SQLITE_OK;
  51340. int state = pPager->eState;
  51341. assert( state==PAGER_OPEN || state==PAGER_READER );
  51342. if( state==PAGER_OPEN ){
  51343. rc = sqlite3PagerSharedLock(pPager);
  51344. }
  51345. if( pPager->eState==PAGER_READER ){
  51346. assert( rc==SQLITE_OK );
  51347. rc = pagerLockDb(pPager, RESERVED_LOCK);
  51348. }
  51349. if( rc==SQLITE_OK ){
  51350. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  51351. }
  51352. if( rc==SQLITE_OK && state==PAGER_READER ){
  51353. pagerUnlockDb(pPager, SHARED_LOCK);
  51354. }else if( state==PAGER_OPEN ){
  51355. pager_unlock(pPager);
  51356. }
  51357. assert( state==pPager->eState );
  51358. }
  51359. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  51360. sqlite3OsClose(pPager->jfd);
  51361. }
  51362. }
  51363. /* Return the new journal mode */
  51364. return (int)pPager->journalMode;
  51365. }
  51366. /*
  51367. ** Return the current journal mode.
  51368. */
  51369. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  51370. return (int)pPager->journalMode;
  51371. }
  51372. /*
  51373. ** Return TRUE if the pager is in a state where it is OK to change the
  51374. ** journalmode. Journalmode changes can only happen when the database
  51375. ** is unmodified.
  51376. */
  51377. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  51378. assert( assert_pager_state(pPager) );
  51379. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  51380. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  51381. return 1;
  51382. }
  51383. /*
  51384. ** Get/set the size-limit used for persistent journal files.
  51385. **
  51386. ** Setting the size limit to -1 means no limit is enforced.
  51387. ** An attempt to set a limit smaller than -1 is a no-op.
  51388. */
  51389. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  51390. if( iLimit>=-1 ){
  51391. pPager->journalSizeLimit = iLimit;
  51392. sqlite3WalLimit(pPager->pWal, iLimit);
  51393. }
  51394. return pPager->journalSizeLimit;
  51395. }
  51396. /*
  51397. ** Return a pointer to the pPager->pBackup variable. The backup module
  51398. ** in backup.c maintains the content of this variable. This module
  51399. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  51400. ** sqlite3BackupUpdate() only.
  51401. */
  51402. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  51403. return &pPager->pBackup;
  51404. }
  51405. #ifndef SQLITE_OMIT_VACUUM
  51406. /*
  51407. ** Unless this is an in-memory or temporary database, clear the pager cache.
  51408. */
  51409. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  51410. assert( MEMDB==0 || pPager->tempFile );
  51411. if( pPager->tempFile==0 ) pager_reset(pPager);
  51412. }
  51413. #endif
  51414. #ifndef SQLITE_OMIT_WAL
  51415. /*
  51416. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  51417. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  51418. ** or wal_blocking_checkpoint() API functions.
  51419. **
  51420. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  51421. */
  51422. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  51423. Pager *pPager, /* Checkpoint on this pager */
  51424. sqlite3 *db, /* Db handle used to check for interrupts */
  51425. int eMode, /* Type of checkpoint */
  51426. int *pnLog, /* OUT: Final number of frames in log */
  51427. int *pnCkpt /* OUT: Final number of checkpointed frames */
  51428. ){
  51429. int rc = SQLITE_OK;
  51430. if( pPager->pWal ){
  51431. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  51432. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  51433. pPager->pBusyHandlerArg,
  51434. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  51435. pnLog, pnCkpt
  51436. );
  51437. }
  51438. return rc;
  51439. }
  51440. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  51441. return sqlite3WalCallback(pPager->pWal);
  51442. }
  51443. /*
  51444. ** Return true if the underlying VFS for the given pager supports the
  51445. ** primitives necessary for write-ahead logging.
  51446. */
  51447. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  51448. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  51449. if( pPager->noLock ) return 0;
  51450. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  51451. }
  51452. /*
  51453. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  51454. ** is obtained instead, immediately release it.
  51455. */
  51456. static int pagerExclusiveLock(Pager *pPager){
  51457. int rc; /* Return code */
  51458. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  51459. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  51460. if( rc!=SQLITE_OK ){
  51461. /* If the attempt to grab the exclusive lock failed, release the
  51462. ** pending lock that may have been obtained instead. */
  51463. pagerUnlockDb(pPager, SHARED_LOCK);
  51464. }
  51465. return rc;
  51466. }
  51467. /*
  51468. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  51469. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  51470. ** lock on the database file and use heap-memory to store the wal-index
  51471. ** in. Otherwise, use the normal shared-memory.
  51472. */
  51473. static int pagerOpenWal(Pager *pPager){
  51474. int rc = SQLITE_OK;
  51475. assert( pPager->pWal==0 && pPager->tempFile==0 );
  51476. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  51477. /* If the pager is already in exclusive-mode, the WAL module will use
  51478. ** heap-memory for the wal-index instead of the VFS shared-memory
  51479. ** implementation. Take the exclusive lock now, before opening the WAL
  51480. ** file, to make sure this is safe.
  51481. */
  51482. if( pPager->exclusiveMode ){
  51483. rc = pagerExclusiveLock(pPager);
  51484. }
  51485. /* Open the connection to the log file. If this operation fails,
  51486. ** (e.g. due to malloc() failure), return an error code.
  51487. */
  51488. if( rc==SQLITE_OK ){
  51489. rc = sqlite3WalOpen(pPager->pVfs,
  51490. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  51491. pPager->journalSizeLimit, &pPager->pWal
  51492. );
  51493. }
  51494. pagerFixMaplimit(pPager);
  51495. return rc;
  51496. }
  51497. /*
  51498. ** The caller must be holding a SHARED lock on the database file to call
  51499. ** this function.
  51500. **
  51501. ** If the pager passed as the first argument is open on a real database
  51502. ** file (not a temp file or an in-memory database), and the WAL file
  51503. ** is not already open, make an attempt to open it now. If successful,
  51504. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  51505. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  51506. ** not modified in either case.
  51507. **
  51508. ** If the pager is open on a temp-file (or in-memory database), or if
  51509. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  51510. ** without doing anything.
  51511. */
  51512. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  51513. Pager *pPager, /* Pager object */
  51514. int *pbOpen /* OUT: Set to true if call is a no-op */
  51515. ){
  51516. int rc = SQLITE_OK; /* Return code */
  51517. assert( assert_pager_state(pPager) );
  51518. assert( pPager->eState==PAGER_OPEN || pbOpen );
  51519. assert( pPager->eState==PAGER_READER || !pbOpen );
  51520. assert( pbOpen==0 || *pbOpen==0 );
  51521. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  51522. if( !pPager->tempFile && !pPager->pWal ){
  51523. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  51524. /* Close any rollback journal previously open */
  51525. sqlite3OsClose(pPager->jfd);
  51526. rc = pagerOpenWal(pPager);
  51527. if( rc==SQLITE_OK ){
  51528. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  51529. pPager->eState = PAGER_OPEN;
  51530. }
  51531. }else{
  51532. *pbOpen = 1;
  51533. }
  51534. return rc;
  51535. }
  51536. /*
  51537. ** This function is called to close the connection to the log file prior
  51538. ** to switching from WAL to rollback mode.
  51539. **
  51540. ** Before closing the log file, this function attempts to take an
  51541. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  51542. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  51543. ** If successful, the EXCLUSIVE lock is not released before returning.
  51544. */
  51545. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  51546. int rc = SQLITE_OK;
  51547. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  51548. /* If the log file is not already open, but does exist in the file-system,
  51549. ** it may need to be checkpointed before the connection can switch to
  51550. ** rollback mode. Open it now so this can happen.
  51551. */
  51552. if( !pPager->pWal ){
  51553. int logexists = 0;
  51554. rc = pagerLockDb(pPager, SHARED_LOCK);
  51555. if( rc==SQLITE_OK ){
  51556. rc = sqlite3OsAccess(
  51557. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  51558. );
  51559. }
  51560. if( rc==SQLITE_OK && logexists ){
  51561. rc = pagerOpenWal(pPager);
  51562. }
  51563. }
  51564. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  51565. ** the database file, the log and log-summary files will be deleted.
  51566. */
  51567. if( rc==SQLITE_OK && pPager->pWal ){
  51568. rc = pagerExclusiveLock(pPager);
  51569. if( rc==SQLITE_OK ){
  51570. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  51571. pPager->pageSize, (u8*)pPager->pTmpSpace);
  51572. pPager->pWal = 0;
  51573. pagerFixMaplimit(pPager);
  51574. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  51575. }
  51576. }
  51577. return rc;
  51578. }
  51579. #ifdef SQLITE_ENABLE_SNAPSHOT
  51580. /*
  51581. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  51582. ** currently open. Otherwise, return an error.
  51583. */
  51584. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  51585. int rc = SQLITE_ERROR;
  51586. if( pPager->pWal ){
  51587. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  51588. }
  51589. return rc;
  51590. }
  51591. /*
  51592. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  51593. ** read transaction is opened, attempt to read from the snapshot it
  51594. ** identifies. If this is not a WAL database, return an error.
  51595. */
  51596. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  51597. int rc = SQLITE_OK;
  51598. if( pPager->pWal ){
  51599. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  51600. }else{
  51601. rc = SQLITE_ERROR;
  51602. }
  51603. return rc;
  51604. }
  51605. /*
  51606. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  51607. ** is not a WAL database, return an error.
  51608. */
  51609. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  51610. int rc;
  51611. if( pPager->pWal ){
  51612. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  51613. }else{
  51614. rc = SQLITE_ERROR;
  51615. }
  51616. return rc;
  51617. }
  51618. #endif /* SQLITE_ENABLE_SNAPSHOT */
  51619. #endif /* !SQLITE_OMIT_WAL */
  51620. #ifdef SQLITE_ENABLE_ZIPVFS
  51621. /*
  51622. ** A read-lock must be held on the pager when this function is called. If
  51623. ** the pager is in WAL mode and the WAL file currently contains one or more
  51624. ** frames, return the size in bytes of the page images stored within the
  51625. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  51626. ** is empty, return 0.
  51627. */
  51628. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  51629. assert( pPager->eState>=PAGER_READER );
  51630. return sqlite3WalFramesize(pPager->pWal);
  51631. }
  51632. #endif
  51633. #endif /* SQLITE_OMIT_DISKIO */
  51634. /************** End of pager.c ***********************************************/
  51635. /************** Begin file wal.c *********************************************/
  51636. /*
  51637. ** 2010 February 1
  51638. **
  51639. ** The author disclaims copyright to this source code. In place of
  51640. ** a legal notice, here is a blessing:
  51641. **
  51642. ** May you do good and not evil.
  51643. ** May you find forgiveness for yourself and forgive others.
  51644. ** May you share freely, never taking more than you give.
  51645. **
  51646. *************************************************************************
  51647. **
  51648. ** This file contains the implementation of a write-ahead log (WAL) used in
  51649. ** "journal_mode=WAL" mode.
  51650. **
  51651. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  51652. **
  51653. ** A WAL file consists of a header followed by zero or more "frames".
  51654. ** Each frame records the revised content of a single page from the
  51655. ** database file. All changes to the database are recorded by writing
  51656. ** frames into the WAL. Transactions commit when a frame is written that
  51657. ** contains a commit marker. A single WAL can and usually does record
  51658. ** multiple transactions. Periodically, the content of the WAL is
  51659. ** transferred back into the database file in an operation called a
  51660. ** "checkpoint".
  51661. **
  51662. ** A single WAL file can be used multiple times. In other words, the
  51663. ** WAL can fill up with frames and then be checkpointed and then new
  51664. ** frames can overwrite the old ones. A WAL always grows from beginning
  51665. ** toward the end. Checksums and counters attached to each frame are
  51666. ** used to determine which frames within the WAL are valid and which
  51667. ** are leftovers from prior checkpoints.
  51668. **
  51669. ** The WAL header is 32 bytes in size and consists of the following eight
  51670. ** big-endian 32-bit unsigned integer values:
  51671. **
  51672. ** 0: Magic number. 0x377f0682 or 0x377f0683
  51673. ** 4: File format version. Currently 3007000
  51674. ** 8: Database page size. Example: 1024
  51675. ** 12: Checkpoint sequence number
  51676. ** 16: Salt-1, random integer incremented with each checkpoint
  51677. ** 20: Salt-2, a different random integer changing with each ckpt
  51678. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  51679. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  51680. **
  51681. ** Immediately following the wal-header are zero or more frames. Each
  51682. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  51683. ** of page data. The frame-header is six big-endian 32-bit unsigned
  51684. ** integer values, as follows:
  51685. **
  51686. ** 0: Page number.
  51687. ** 4: For commit records, the size of the database image in pages
  51688. ** after the commit. For all other records, zero.
  51689. ** 8: Salt-1 (copied from the header)
  51690. ** 12: Salt-2 (copied from the header)
  51691. ** 16: Checksum-1.
  51692. ** 20: Checksum-2.
  51693. **
  51694. ** A frame is considered valid if and only if the following conditions are
  51695. ** true:
  51696. **
  51697. ** (1) The salt-1 and salt-2 values in the frame-header match
  51698. ** salt values in the wal-header
  51699. **
  51700. ** (2) The checksum values in the final 8 bytes of the frame-header
  51701. ** exactly match the checksum computed consecutively on the
  51702. ** WAL header and the first 8 bytes and the content of all frames
  51703. ** up to and including the current frame.
  51704. **
  51705. ** The checksum is computed using 32-bit big-endian integers if the
  51706. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  51707. ** is computed using little-endian if the magic number is 0x377f0682.
  51708. ** The checksum values are always stored in the frame header in a
  51709. ** big-endian format regardless of which byte order is used to compute
  51710. ** the checksum. The checksum is computed by interpreting the input as
  51711. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  51712. ** algorithm used for the checksum is as follows:
  51713. **
  51714. ** for i from 0 to n-1 step 2:
  51715. ** s0 += x[i] + s1;
  51716. ** s1 += x[i+1] + s0;
  51717. ** endfor
  51718. **
  51719. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  51720. ** in reverse order (the largest fibonacci weight occurs on the first element
  51721. ** of the sequence being summed.) The s1 value spans all 32-bit
  51722. ** terms of the sequence whereas s0 omits the final term.
  51723. **
  51724. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  51725. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  51726. ** The VFS.xSync operations serve as write barriers - all writes launched
  51727. ** before the xSync must complete before any write that launches after the
  51728. ** xSync begins.
  51729. **
  51730. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  51731. ** value is randomized. This prevents old and new frames in the WAL from
  51732. ** being considered valid at the same time and being checkpointing together
  51733. ** following a crash.
  51734. **
  51735. ** READER ALGORITHM
  51736. **
  51737. ** To read a page from the database (call it page number P), a reader
  51738. ** first checks the WAL to see if it contains page P. If so, then the
  51739. ** last valid instance of page P that is a followed by a commit frame
  51740. ** or is a commit frame itself becomes the value read. If the WAL
  51741. ** contains no copies of page P that are valid and which are a commit
  51742. ** frame or are followed by a commit frame, then page P is read from
  51743. ** the database file.
  51744. **
  51745. ** To start a read transaction, the reader records the index of the last
  51746. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  51747. ** for all subsequent read operations. New transactions can be appended
  51748. ** to the WAL, but as long as the reader uses its original mxFrame value
  51749. ** and ignores the newly appended content, it will see a consistent snapshot
  51750. ** of the database from a single point in time. This technique allows
  51751. ** multiple concurrent readers to view different versions of the database
  51752. ** content simultaneously.
  51753. **
  51754. ** The reader algorithm in the previous paragraphs works correctly, but
  51755. ** because frames for page P can appear anywhere within the WAL, the
  51756. ** reader has to scan the entire WAL looking for page P frames. If the
  51757. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  51758. ** and read performance suffers. To overcome this problem, a separate
  51759. ** data structure called the wal-index is maintained to expedite the
  51760. ** search for frames of a particular page.
  51761. **
  51762. ** WAL-INDEX FORMAT
  51763. **
  51764. ** Conceptually, the wal-index is shared memory, though VFS implementations
  51765. ** might choose to implement the wal-index using a mmapped file. Because
  51766. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  51767. ** on a network filesystem. All users of the database must be able to
  51768. ** share memory.
  51769. **
  51770. ** The wal-index is transient. After a crash, the wal-index can (and should
  51771. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  51772. ** to either truncate or zero the header of the wal-index when the last
  51773. ** connection to it closes. Because the wal-index is transient, it can
  51774. ** use an architecture-specific format; it does not have to be cross-platform.
  51775. ** Hence, unlike the database and WAL file formats which store all values
  51776. ** as big endian, the wal-index can store multi-byte values in the native
  51777. ** byte order of the host computer.
  51778. **
  51779. ** The purpose of the wal-index is to answer this question quickly: Given
  51780. ** a page number P and a maximum frame index M, return the index of the
  51781. ** last frame in the wal before frame M for page P in the WAL, or return
  51782. ** NULL if there are no frames for page P in the WAL prior to M.
  51783. **
  51784. ** The wal-index consists of a header region, followed by an one or
  51785. ** more index blocks.
  51786. **
  51787. ** The wal-index header contains the total number of frames within the WAL
  51788. ** in the mxFrame field.
  51789. **
  51790. ** Each index block except for the first contains information on
  51791. ** HASHTABLE_NPAGE frames. The first index block contains information on
  51792. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  51793. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  51794. ** first index block are the same size as all other index blocks in the
  51795. ** wal-index.
  51796. **
  51797. ** Each index block contains two sections, a page-mapping that contains the
  51798. ** database page number associated with each wal frame, and a hash-table
  51799. ** that allows readers to query an index block for a specific page number.
  51800. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  51801. ** for the first index block) 32-bit page numbers. The first entry in the
  51802. ** first index-block contains the database page number corresponding to the
  51803. ** first frame in the WAL file. The first entry in the second index block
  51804. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  51805. ** the log, and so on.
  51806. **
  51807. ** The last index block in a wal-index usually contains less than the full
  51808. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  51809. ** depending on the contents of the WAL file. This does not change the
  51810. ** allocated size of the page-mapping array - the page-mapping array merely
  51811. ** contains unused entries.
  51812. **
  51813. ** Even without using the hash table, the last frame for page P
  51814. ** can be found by scanning the page-mapping sections of each index block
  51815. ** starting with the last index block and moving toward the first, and
  51816. ** within each index block, starting at the end and moving toward the
  51817. ** beginning. The first entry that equals P corresponds to the frame
  51818. ** holding the content for that page.
  51819. **
  51820. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  51821. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  51822. ** hash table for each page number in the mapping section, so the hash
  51823. ** table is never more than half full. The expected number of collisions
  51824. ** prior to finding a match is 1. Each entry of the hash table is an
  51825. ** 1-based index of an entry in the mapping section of the same
  51826. ** index block. Let K be the 1-based index of the largest entry in
  51827. ** the mapping section. (For index blocks other than the last, K will
  51828. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  51829. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  51830. ** contain a value of 0.
  51831. **
  51832. ** To look for page P in the hash table, first compute a hash iKey on
  51833. ** P as follows:
  51834. **
  51835. ** iKey = (P * 383) % HASHTABLE_NSLOT
  51836. **
  51837. ** Then start scanning entries of the hash table, starting with iKey
  51838. ** (wrapping around to the beginning when the end of the hash table is
  51839. ** reached) until an unused hash slot is found. Let the first unused slot
  51840. ** be at index iUnused. (iUnused might be less than iKey if there was
  51841. ** wrap-around.) Because the hash table is never more than half full,
  51842. ** the search is guaranteed to eventually hit an unused entry. Let
  51843. ** iMax be the value between iKey and iUnused, closest to iUnused,
  51844. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  51845. ** no hash slot such that aHash[i]==p) then page P is not in the
  51846. ** current index block. Otherwise the iMax-th mapping entry of the
  51847. ** current index block corresponds to the last entry that references
  51848. ** page P.
  51849. **
  51850. ** A hash search begins with the last index block and moves toward the
  51851. ** first index block, looking for entries corresponding to page P. On
  51852. ** average, only two or three slots in each index block need to be
  51853. ** examined in order to either find the last entry for page P, or to
  51854. ** establish that no such entry exists in the block. Each index block
  51855. ** holds over 4000 entries. So two or three index blocks are sufficient
  51856. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  51857. ** comparisons (on average) suffice to either locate a frame in the
  51858. ** WAL or to establish that the frame does not exist in the WAL. This
  51859. ** is much faster than scanning the entire 10MB WAL.
  51860. **
  51861. ** Note that entries are added in order of increasing K. Hence, one
  51862. ** reader might be using some value K0 and a second reader that started
  51863. ** at a later time (after additional transactions were added to the WAL
  51864. ** and to the wal-index) might be using a different value K1, where K1>K0.
  51865. ** Both readers can use the same hash table and mapping section to get
  51866. ** the correct result. There may be entries in the hash table with
  51867. ** K>K0 but to the first reader, those entries will appear to be unused
  51868. ** slots in the hash table and so the first reader will get an answer as
  51869. ** if no values greater than K0 had ever been inserted into the hash table
  51870. ** in the first place - which is what reader one wants. Meanwhile, the
  51871. ** second reader using K1 will see additional values that were inserted
  51872. ** later, which is exactly what reader two wants.
  51873. **
  51874. ** When a rollback occurs, the value of K is decreased. Hash table entries
  51875. ** that correspond to frames greater than the new K value are removed
  51876. ** from the hash table at this point.
  51877. */
  51878. #ifndef SQLITE_OMIT_WAL
  51879. /* #include "wal.h" */
  51880. /*
  51881. ** Trace output macros
  51882. */
  51883. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  51884. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  51885. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  51886. #else
  51887. # define WALTRACE(X)
  51888. #endif
  51889. /*
  51890. ** The maximum (and only) versions of the wal and wal-index formats
  51891. ** that may be interpreted by this version of SQLite.
  51892. **
  51893. ** If a client begins recovering a WAL file and finds that (a) the checksum
  51894. ** values in the wal-header are correct and (b) the version field is not
  51895. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  51896. **
  51897. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  51898. ** checksum test is successful) and finds that the version field is not
  51899. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  51900. ** returns SQLITE_CANTOPEN.
  51901. */
  51902. #define WAL_MAX_VERSION 3007000
  51903. #define WALINDEX_MAX_VERSION 3007000
  51904. /*
  51905. ** Indices of various locking bytes. WAL_NREADER is the number
  51906. ** of available reader locks and should be at least 3. The default
  51907. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  51908. */
  51909. #define WAL_WRITE_LOCK 0
  51910. #define WAL_ALL_BUT_WRITE 1
  51911. #define WAL_CKPT_LOCK 1
  51912. #define WAL_RECOVER_LOCK 2
  51913. #define WAL_READ_LOCK(I) (3+(I))
  51914. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  51915. /* Object declarations */
  51916. typedef struct WalIndexHdr WalIndexHdr;
  51917. typedef struct WalIterator WalIterator;
  51918. typedef struct WalCkptInfo WalCkptInfo;
  51919. /*
  51920. ** The following object holds a copy of the wal-index header content.
  51921. **
  51922. ** The actual header in the wal-index consists of two copies of this
  51923. ** object followed by one instance of the WalCkptInfo object.
  51924. ** For all versions of SQLite through 3.10.0 and probably beyond,
  51925. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  51926. ** the total header size is 136 bytes.
  51927. **
  51928. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  51929. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  51930. ** added in 3.7.1 when support for 64K pages was added.
  51931. */
  51932. struct WalIndexHdr {
  51933. u32 iVersion; /* Wal-index version */
  51934. u32 unused; /* Unused (padding) field */
  51935. u32 iChange; /* Counter incremented each transaction */
  51936. u8 isInit; /* 1 when initialized */
  51937. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  51938. u16 szPage; /* Database page size in bytes. 1==64K */
  51939. u32 mxFrame; /* Index of last valid frame in the WAL */
  51940. u32 nPage; /* Size of database in pages */
  51941. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  51942. u32 aSalt[2]; /* Two salt values copied from WAL header */
  51943. u32 aCksum[2]; /* Checksum over all prior fields */
  51944. };
  51945. /*
  51946. ** A copy of the following object occurs in the wal-index immediately
  51947. ** following the second copy of the WalIndexHdr. This object stores
  51948. ** information used by checkpoint.
  51949. **
  51950. ** nBackfill is the number of frames in the WAL that have been written
  51951. ** back into the database. (We call the act of moving content from WAL to
  51952. ** database "backfilling".) The nBackfill number is never greater than
  51953. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  51954. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  51955. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  51956. ** mxFrame back to zero when the WAL is reset.
  51957. **
  51958. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  51959. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  51960. ** the nBackfillAttempted is set before any backfilling is done and the
  51961. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  51962. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  51963. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  51964. **
  51965. ** The aLock[] field is a set of bytes used for locking. These bytes should
  51966. ** never be read or written.
  51967. **
  51968. ** There is one entry in aReadMark[] for each reader lock. If a reader
  51969. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  51970. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  51971. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  51972. ** a special case; its value is never used and it exists as a place-holder
  51973. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  51974. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  51975. ** directly from the database.
  51976. **
  51977. ** The value of aReadMark[K] may only be changed by a thread that
  51978. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  51979. ** aReadMark[K] cannot changed while there is a reader is using that mark
  51980. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  51981. **
  51982. ** The checkpointer may only transfer frames from WAL to database where
  51983. ** the frame numbers are less than or equal to every aReadMark[] that is
  51984. ** in use (that is, every aReadMark[j] for which there is a corresponding
  51985. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  51986. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  51987. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  51988. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  51989. ** in the WAL has been backfilled into the database) then new readers
  51990. ** will choose aReadMark[0] which has value 0 and hence such reader will
  51991. ** get all their all content directly from the database file and ignore
  51992. ** the WAL.
  51993. **
  51994. ** Writers normally append new frames to the end of the WAL. However,
  51995. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  51996. ** written back into the database) and if no readers are using the WAL
  51997. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  51998. ** the writer will first "reset" the WAL back to the beginning and start
  51999. ** writing new content beginning at frame 1.
  52000. **
  52001. ** We assume that 32-bit loads are atomic and so no locks are needed in
  52002. ** order to read from any aReadMark[] entries.
  52003. */
  52004. struct WalCkptInfo {
  52005. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  52006. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  52007. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  52008. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  52009. u32 notUsed0; /* Available for future enhancements */
  52010. };
  52011. #define READMARK_NOT_USED 0xffffffff
  52012. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  52013. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  52014. ** only support mandatory file-locks, we do not read or write data
  52015. ** from the region of the file on which locks are applied.
  52016. */
  52017. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  52018. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  52019. /* Size of header before each frame in wal */
  52020. #define WAL_FRAME_HDRSIZE 24
  52021. /* Size of write ahead log header, including checksum. */
  52022. /* #define WAL_HDRSIZE 24 */
  52023. #define WAL_HDRSIZE 32
  52024. /* WAL magic value. Either this value, or the same value with the least
  52025. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  52026. ** big-endian format in the first 4 bytes of a WAL file.
  52027. **
  52028. ** If the LSB is set, then the checksums for each frame within the WAL
  52029. ** file are calculated by treating all data as an array of 32-bit
  52030. ** big-endian words. Otherwise, they are calculated by interpreting
  52031. ** all data as 32-bit little-endian words.
  52032. */
  52033. #define WAL_MAGIC 0x377f0682
  52034. /*
  52035. ** Return the offset of frame iFrame in the write-ahead log file,
  52036. ** assuming a database page size of szPage bytes. The offset returned
  52037. ** is to the start of the write-ahead log frame-header.
  52038. */
  52039. #define walFrameOffset(iFrame, szPage) ( \
  52040. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  52041. )
  52042. /*
  52043. ** An open write-ahead log file is represented by an instance of the
  52044. ** following object.
  52045. */
  52046. struct Wal {
  52047. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  52048. sqlite3_file *pDbFd; /* File handle for the database file */
  52049. sqlite3_file *pWalFd; /* File handle for WAL file */
  52050. u32 iCallback; /* Value to pass to log callback (or 0) */
  52051. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  52052. int nWiData; /* Size of array apWiData */
  52053. int szFirstBlock; /* Size of first block written to WAL file */
  52054. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  52055. u32 szPage; /* Database page size */
  52056. i16 readLock; /* Which read lock is being held. -1 for none */
  52057. u8 syncFlags; /* Flags to use to sync header writes */
  52058. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  52059. u8 writeLock; /* True if in a write transaction */
  52060. u8 ckptLock; /* True if holding a checkpoint lock */
  52061. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  52062. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  52063. u8 syncHeader; /* Fsync the WAL header if true */
  52064. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  52065. WalIndexHdr hdr; /* Wal-index header for current transaction */
  52066. u32 minFrame; /* Ignore wal frames before this one */
  52067. u32 iReCksum; /* On commit, recalculate checksums from here */
  52068. const char *zWalName; /* Name of WAL file */
  52069. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  52070. #ifdef SQLITE_DEBUG
  52071. u8 lockError; /* True if a locking error has occurred */
  52072. #endif
  52073. #ifdef SQLITE_ENABLE_SNAPSHOT
  52074. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  52075. #endif
  52076. };
  52077. /*
  52078. ** Candidate values for Wal.exclusiveMode.
  52079. */
  52080. #define WAL_NORMAL_MODE 0
  52081. #define WAL_EXCLUSIVE_MODE 1
  52082. #define WAL_HEAPMEMORY_MODE 2
  52083. /*
  52084. ** Possible values for WAL.readOnly
  52085. */
  52086. #define WAL_RDWR 0 /* Normal read/write connection */
  52087. #define WAL_RDONLY 1 /* The WAL file is readonly */
  52088. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  52089. /*
  52090. ** Each page of the wal-index mapping contains a hash-table made up of
  52091. ** an array of HASHTABLE_NSLOT elements of the following type.
  52092. */
  52093. typedef u16 ht_slot;
  52094. /*
  52095. ** This structure is used to implement an iterator that loops through
  52096. ** all frames in the WAL in database page order. Where two or more frames
  52097. ** correspond to the same database page, the iterator visits only the
  52098. ** frame most recently written to the WAL (in other words, the frame with
  52099. ** the largest index).
  52100. **
  52101. ** The internals of this structure are only accessed by:
  52102. **
  52103. ** walIteratorInit() - Create a new iterator,
  52104. ** walIteratorNext() - Step an iterator,
  52105. ** walIteratorFree() - Free an iterator.
  52106. **
  52107. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  52108. */
  52109. struct WalIterator {
  52110. int iPrior; /* Last result returned from the iterator */
  52111. int nSegment; /* Number of entries in aSegment[] */
  52112. struct WalSegment {
  52113. int iNext; /* Next slot in aIndex[] not yet returned */
  52114. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  52115. u32 *aPgno; /* Array of page numbers. */
  52116. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  52117. int iZero; /* Frame number associated with aPgno[0] */
  52118. } aSegment[1]; /* One for every 32KB page in the wal-index */
  52119. };
  52120. /*
  52121. ** Define the parameters of the hash tables in the wal-index file. There
  52122. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  52123. ** wal-index.
  52124. **
  52125. ** Changing any of these constants will alter the wal-index format and
  52126. ** create incompatibilities.
  52127. */
  52128. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  52129. #define HASHTABLE_HASH_1 383 /* Should be prime */
  52130. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  52131. /*
  52132. ** The block of page numbers associated with the first hash-table in a
  52133. ** wal-index is smaller than usual. This is so that there is a complete
  52134. ** hash-table on each aligned 32KB page of the wal-index.
  52135. */
  52136. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  52137. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  52138. #define WALINDEX_PGSZ ( \
  52139. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  52140. )
  52141. /*
  52142. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  52143. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  52144. ** numbered from zero.
  52145. **
  52146. ** If this call is successful, *ppPage is set to point to the wal-index
  52147. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  52148. ** then an SQLite error code is returned and *ppPage is set to 0.
  52149. */
  52150. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  52151. int rc = SQLITE_OK;
  52152. /* Enlarge the pWal->apWiData[] array if required */
  52153. if( pWal->nWiData<=iPage ){
  52154. int nByte = sizeof(u32*)*(iPage+1);
  52155. volatile u32 **apNew;
  52156. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  52157. if( !apNew ){
  52158. *ppPage = 0;
  52159. return SQLITE_NOMEM_BKPT;
  52160. }
  52161. memset((void*)&apNew[pWal->nWiData], 0,
  52162. sizeof(u32*)*(iPage+1-pWal->nWiData));
  52163. pWal->apWiData = apNew;
  52164. pWal->nWiData = iPage+1;
  52165. }
  52166. /* Request a pointer to the required page from the VFS */
  52167. if( pWal->apWiData[iPage]==0 ){
  52168. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  52169. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  52170. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  52171. }else{
  52172. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  52173. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  52174. );
  52175. if( rc==SQLITE_READONLY ){
  52176. pWal->readOnly |= WAL_SHM_RDONLY;
  52177. rc = SQLITE_OK;
  52178. }
  52179. }
  52180. }
  52181. *ppPage = pWal->apWiData[iPage];
  52182. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  52183. return rc;
  52184. }
  52185. /*
  52186. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  52187. */
  52188. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  52189. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  52190. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  52191. }
  52192. /*
  52193. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  52194. */
  52195. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  52196. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  52197. return (volatile WalIndexHdr*)pWal->apWiData[0];
  52198. }
  52199. /*
  52200. ** The argument to this macro must be of type u32. On a little-endian
  52201. ** architecture, it returns the u32 value that results from interpreting
  52202. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  52203. ** returns the value that would be produced by interpreting the 4 bytes
  52204. ** of the input value as a little-endian integer.
  52205. */
  52206. #define BYTESWAP32(x) ( \
  52207. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  52208. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  52209. )
  52210. /*
  52211. ** Generate or extend an 8 byte checksum based on the data in
  52212. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  52213. ** initial values of 0 and 0 if aIn==NULL).
  52214. **
  52215. ** The checksum is written back into aOut[] before returning.
  52216. **
  52217. ** nByte must be a positive multiple of 8.
  52218. */
  52219. static void walChecksumBytes(
  52220. int nativeCksum, /* True for native byte-order, false for non-native */
  52221. u8 *a, /* Content to be checksummed */
  52222. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  52223. const u32 *aIn, /* Initial checksum value input */
  52224. u32 *aOut /* OUT: Final checksum value output */
  52225. ){
  52226. u32 s1, s2;
  52227. u32 *aData = (u32 *)a;
  52228. u32 *aEnd = (u32 *)&a[nByte];
  52229. if( aIn ){
  52230. s1 = aIn[0];
  52231. s2 = aIn[1];
  52232. }else{
  52233. s1 = s2 = 0;
  52234. }
  52235. assert( nByte>=8 );
  52236. assert( (nByte&0x00000007)==0 );
  52237. if( nativeCksum ){
  52238. do {
  52239. s1 += *aData++ + s2;
  52240. s2 += *aData++ + s1;
  52241. }while( aData<aEnd );
  52242. }else{
  52243. do {
  52244. s1 += BYTESWAP32(aData[0]) + s2;
  52245. s2 += BYTESWAP32(aData[1]) + s1;
  52246. aData += 2;
  52247. }while( aData<aEnd );
  52248. }
  52249. aOut[0] = s1;
  52250. aOut[1] = s2;
  52251. }
  52252. static void walShmBarrier(Wal *pWal){
  52253. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  52254. sqlite3OsShmBarrier(pWal->pDbFd);
  52255. }
  52256. }
  52257. /*
  52258. ** Write the header information in pWal->hdr into the wal-index.
  52259. **
  52260. ** The checksum on pWal->hdr is updated before it is written.
  52261. */
  52262. static void walIndexWriteHdr(Wal *pWal){
  52263. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  52264. const int nCksum = offsetof(WalIndexHdr, aCksum);
  52265. assert( pWal->writeLock );
  52266. pWal->hdr.isInit = 1;
  52267. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  52268. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  52269. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  52270. walShmBarrier(pWal);
  52271. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  52272. }
  52273. /*
  52274. ** This function encodes a single frame header and writes it to a buffer
  52275. ** supplied by the caller. A frame-header is made up of a series of
  52276. ** 4-byte big-endian integers, as follows:
  52277. **
  52278. ** 0: Page number.
  52279. ** 4: For commit records, the size of the database image in pages
  52280. ** after the commit. For all other records, zero.
  52281. ** 8: Salt-1 (copied from the wal-header)
  52282. ** 12: Salt-2 (copied from the wal-header)
  52283. ** 16: Checksum-1.
  52284. ** 20: Checksum-2.
  52285. */
  52286. static void walEncodeFrame(
  52287. Wal *pWal, /* The write-ahead log */
  52288. u32 iPage, /* Database page number for frame */
  52289. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  52290. u8 *aData, /* Pointer to page data */
  52291. u8 *aFrame /* OUT: Write encoded frame here */
  52292. ){
  52293. int nativeCksum; /* True for native byte-order checksums */
  52294. u32 *aCksum = pWal->hdr.aFrameCksum;
  52295. assert( WAL_FRAME_HDRSIZE==24 );
  52296. sqlite3Put4byte(&aFrame[0], iPage);
  52297. sqlite3Put4byte(&aFrame[4], nTruncate);
  52298. if( pWal->iReCksum==0 ){
  52299. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  52300. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  52301. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  52302. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  52303. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  52304. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  52305. }else{
  52306. memset(&aFrame[8], 0, 16);
  52307. }
  52308. }
  52309. /*
  52310. ** Check to see if the frame with header in aFrame[] and content
  52311. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  52312. ** *pnTruncate and return true. Return if the frame is not valid.
  52313. */
  52314. static int walDecodeFrame(
  52315. Wal *pWal, /* The write-ahead log */
  52316. u32 *piPage, /* OUT: Database page number for frame */
  52317. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  52318. u8 *aData, /* Pointer to page data (for checksum) */
  52319. u8 *aFrame /* Frame data */
  52320. ){
  52321. int nativeCksum; /* True for native byte-order checksums */
  52322. u32 *aCksum = pWal->hdr.aFrameCksum;
  52323. u32 pgno; /* Page number of the frame */
  52324. assert( WAL_FRAME_HDRSIZE==24 );
  52325. /* A frame is only valid if the salt values in the frame-header
  52326. ** match the salt values in the wal-header.
  52327. */
  52328. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  52329. return 0;
  52330. }
  52331. /* A frame is only valid if the page number is creater than zero.
  52332. */
  52333. pgno = sqlite3Get4byte(&aFrame[0]);
  52334. if( pgno==0 ){
  52335. return 0;
  52336. }
  52337. /* A frame is only valid if a checksum of the WAL header,
  52338. ** all prior frams, the first 16 bytes of this frame-header,
  52339. ** and the frame-data matches the checksum in the last 8
  52340. ** bytes of this frame-header.
  52341. */
  52342. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  52343. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  52344. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  52345. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  52346. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  52347. ){
  52348. /* Checksum failed. */
  52349. return 0;
  52350. }
  52351. /* If we reach this point, the frame is valid. Return the page number
  52352. ** and the new database size.
  52353. */
  52354. *piPage = pgno;
  52355. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  52356. return 1;
  52357. }
  52358. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  52359. /*
  52360. ** Names of locks. This routine is used to provide debugging output and is not
  52361. ** a part of an ordinary build.
  52362. */
  52363. static const char *walLockName(int lockIdx){
  52364. if( lockIdx==WAL_WRITE_LOCK ){
  52365. return "WRITE-LOCK";
  52366. }else if( lockIdx==WAL_CKPT_LOCK ){
  52367. return "CKPT-LOCK";
  52368. }else if( lockIdx==WAL_RECOVER_LOCK ){
  52369. return "RECOVER-LOCK";
  52370. }else{
  52371. static char zName[15];
  52372. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  52373. lockIdx-WAL_READ_LOCK(0));
  52374. return zName;
  52375. }
  52376. }
  52377. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  52378. /*
  52379. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  52380. ** A lock cannot be moved directly between shared and exclusive - it must go
  52381. ** through the unlocked state first.
  52382. **
  52383. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  52384. */
  52385. static int walLockShared(Wal *pWal, int lockIdx){
  52386. int rc;
  52387. if( pWal->exclusiveMode ) return SQLITE_OK;
  52388. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  52389. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  52390. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  52391. walLockName(lockIdx), rc ? "failed" : "ok"));
  52392. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  52393. return rc;
  52394. }
  52395. static void walUnlockShared(Wal *pWal, int lockIdx){
  52396. if( pWal->exclusiveMode ) return;
  52397. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  52398. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  52399. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  52400. }
  52401. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  52402. int rc;
  52403. if( pWal->exclusiveMode ) return SQLITE_OK;
  52404. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  52405. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  52406. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  52407. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  52408. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  52409. return rc;
  52410. }
  52411. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  52412. if( pWal->exclusiveMode ) return;
  52413. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  52414. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  52415. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  52416. walLockName(lockIdx), n));
  52417. }
  52418. /*
  52419. ** Compute a hash on a page number. The resulting hash value must land
  52420. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  52421. ** the hash to the next value in the event of a collision.
  52422. */
  52423. static int walHash(u32 iPage){
  52424. assert( iPage>0 );
  52425. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  52426. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  52427. }
  52428. static int walNextHash(int iPriorHash){
  52429. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  52430. }
  52431. /*
  52432. ** Return pointers to the hash table and page number array stored on
  52433. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  52434. ** numbered starting from 0.
  52435. **
  52436. ** Set output variable *paHash to point to the start of the hash table
  52437. ** in the wal-index file. Set *piZero to one less than the frame
  52438. ** number of the first frame indexed by this hash table. If a
  52439. ** slot in the hash table is set to N, it refers to frame number
  52440. ** (*piZero+N) in the log.
  52441. **
  52442. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  52443. ** first frame indexed by the hash table, frame (*piZero+1).
  52444. */
  52445. static int walHashGet(
  52446. Wal *pWal, /* WAL handle */
  52447. int iHash, /* Find the iHash'th table */
  52448. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  52449. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  52450. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  52451. ){
  52452. int rc; /* Return code */
  52453. volatile u32 *aPgno;
  52454. rc = walIndexPage(pWal, iHash, &aPgno);
  52455. assert( rc==SQLITE_OK || iHash>0 );
  52456. if( rc==SQLITE_OK ){
  52457. u32 iZero;
  52458. volatile ht_slot *aHash;
  52459. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  52460. if( iHash==0 ){
  52461. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  52462. iZero = 0;
  52463. }else{
  52464. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  52465. }
  52466. *paPgno = &aPgno[-1];
  52467. *paHash = aHash;
  52468. *piZero = iZero;
  52469. }
  52470. return rc;
  52471. }
  52472. /*
  52473. ** Return the number of the wal-index page that contains the hash-table
  52474. ** and page-number array that contain entries corresponding to WAL frame
  52475. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  52476. ** are numbered starting from 0.
  52477. */
  52478. static int walFramePage(u32 iFrame){
  52479. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  52480. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  52481. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  52482. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  52483. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  52484. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  52485. );
  52486. return iHash;
  52487. }
  52488. /*
  52489. ** Return the page number associated with frame iFrame in this WAL.
  52490. */
  52491. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  52492. int iHash = walFramePage(iFrame);
  52493. if( iHash==0 ){
  52494. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  52495. }
  52496. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  52497. }
  52498. /*
  52499. ** Remove entries from the hash table that point to WAL slots greater
  52500. ** than pWal->hdr.mxFrame.
  52501. **
  52502. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  52503. ** to a rollback or savepoint.
  52504. **
  52505. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  52506. ** updated. Any later hash tables will be automatically cleared when
  52507. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  52508. ** actually needed.
  52509. */
  52510. static void walCleanupHash(Wal *pWal){
  52511. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  52512. volatile u32 *aPgno = 0; /* Page number array for hash table */
  52513. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  52514. int iLimit = 0; /* Zero values greater than this */
  52515. int nByte; /* Number of bytes to zero in aPgno[] */
  52516. int i; /* Used to iterate through aHash[] */
  52517. assert( pWal->writeLock );
  52518. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  52519. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  52520. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  52521. if( pWal->hdr.mxFrame==0 ) return;
  52522. /* Obtain pointers to the hash-table and page-number array containing
  52523. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  52524. ** that the page said hash-table and array reside on is already mapped.
  52525. */
  52526. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  52527. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  52528. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  52529. /* Zero all hash-table entries that correspond to frame numbers greater
  52530. ** than pWal->hdr.mxFrame.
  52531. */
  52532. iLimit = pWal->hdr.mxFrame - iZero;
  52533. assert( iLimit>0 );
  52534. for(i=0; i<HASHTABLE_NSLOT; i++){
  52535. if( aHash[i]>iLimit ){
  52536. aHash[i] = 0;
  52537. }
  52538. }
  52539. /* Zero the entries in the aPgno array that correspond to frames with
  52540. ** frame numbers greater than pWal->hdr.mxFrame.
  52541. */
  52542. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  52543. memset((void *)&aPgno[iLimit+1], 0, nByte);
  52544. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  52545. /* Verify that the every entry in the mapping region is still reachable
  52546. ** via the hash table even after the cleanup.
  52547. */
  52548. if( iLimit ){
  52549. int j; /* Loop counter */
  52550. int iKey; /* Hash key */
  52551. for(j=1; j<=iLimit; j++){
  52552. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  52553. if( aHash[iKey]==j ) break;
  52554. }
  52555. assert( aHash[iKey]==j );
  52556. }
  52557. }
  52558. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  52559. }
  52560. /*
  52561. ** Set an entry in the wal-index that will map database page number
  52562. ** pPage into WAL frame iFrame.
  52563. */
  52564. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  52565. int rc; /* Return code */
  52566. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  52567. volatile u32 *aPgno = 0; /* Page number array */
  52568. volatile ht_slot *aHash = 0; /* Hash table */
  52569. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  52570. /* Assuming the wal-index file was successfully mapped, populate the
  52571. ** page number array and hash table entry.
  52572. */
  52573. if( rc==SQLITE_OK ){
  52574. int iKey; /* Hash table key */
  52575. int idx; /* Value to write to hash-table slot */
  52576. int nCollide; /* Number of hash collisions */
  52577. idx = iFrame - iZero;
  52578. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  52579. /* If this is the first entry to be added to this hash-table, zero the
  52580. ** entire hash table and aPgno[] array before proceeding.
  52581. */
  52582. if( idx==1 ){
  52583. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  52584. memset((void*)&aPgno[1], 0, nByte);
  52585. }
  52586. /* If the entry in aPgno[] is already set, then the previous writer
  52587. ** must have exited unexpectedly in the middle of a transaction (after
  52588. ** writing one or more dirty pages to the WAL to free up memory).
  52589. ** Remove the remnants of that writers uncommitted transaction from
  52590. ** the hash-table before writing any new entries.
  52591. */
  52592. if( aPgno[idx] ){
  52593. walCleanupHash(pWal);
  52594. assert( !aPgno[idx] );
  52595. }
  52596. /* Write the aPgno[] array entry and the hash-table slot. */
  52597. nCollide = idx;
  52598. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  52599. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  52600. }
  52601. aPgno[idx] = iPage;
  52602. aHash[iKey] = (ht_slot)idx;
  52603. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  52604. /* Verify that the number of entries in the hash table exactly equals
  52605. ** the number of entries in the mapping region.
  52606. */
  52607. {
  52608. int i; /* Loop counter */
  52609. int nEntry = 0; /* Number of entries in the hash table */
  52610. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  52611. assert( nEntry==idx );
  52612. }
  52613. /* Verify that the every entry in the mapping region is reachable
  52614. ** via the hash table. This turns out to be a really, really expensive
  52615. ** thing to check, so only do this occasionally - not on every
  52616. ** iteration.
  52617. */
  52618. if( (idx&0x3ff)==0 ){
  52619. int i; /* Loop counter */
  52620. for(i=1; i<=idx; i++){
  52621. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  52622. if( aHash[iKey]==i ) break;
  52623. }
  52624. assert( aHash[iKey]==i );
  52625. }
  52626. }
  52627. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  52628. }
  52629. return rc;
  52630. }
  52631. /*
  52632. ** Recover the wal-index by reading the write-ahead log file.
  52633. **
  52634. ** This routine first tries to establish an exclusive lock on the
  52635. ** wal-index to prevent other threads/processes from doing anything
  52636. ** with the WAL or wal-index while recovery is running. The
  52637. ** WAL_RECOVER_LOCK is also held so that other threads will know
  52638. ** that this thread is running recovery. If unable to establish
  52639. ** the necessary locks, this routine returns SQLITE_BUSY.
  52640. */
  52641. static int walIndexRecover(Wal *pWal){
  52642. int rc; /* Return Code */
  52643. i64 nSize; /* Size of log file */
  52644. u32 aFrameCksum[2] = {0, 0};
  52645. int iLock; /* Lock offset to lock for checkpoint */
  52646. int nLock; /* Number of locks to hold */
  52647. /* Obtain an exclusive lock on all byte in the locking range not already
  52648. ** locked by the caller. The caller is guaranteed to have locked the
  52649. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  52650. ** If successful, the same bytes that are locked here are unlocked before
  52651. ** this function returns.
  52652. */
  52653. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  52654. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  52655. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  52656. assert( pWal->writeLock );
  52657. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  52658. nLock = SQLITE_SHM_NLOCK - iLock;
  52659. rc = walLockExclusive(pWal, iLock, nLock);
  52660. if( rc ){
  52661. return rc;
  52662. }
  52663. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  52664. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  52665. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  52666. if( rc!=SQLITE_OK ){
  52667. goto recovery_error;
  52668. }
  52669. if( nSize>WAL_HDRSIZE ){
  52670. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  52671. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  52672. int szFrame; /* Number of bytes in buffer aFrame[] */
  52673. u8 *aData; /* Pointer to data part of aFrame buffer */
  52674. int iFrame; /* Index of last frame read */
  52675. i64 iOffset; /* Next offset to read from log file */
  52676. int szPage; /* Page size according to the log */
  52677. u32 magic; /* Magic value read from WAL header */
  52678. u32 version; /* Magic value read from WAL header */
  52679. int isValid; /* True if this frame is valid */
  52680. /* Read in the WAL header. */
  52681. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  52682. if( rc!=SQLITE_OK ){
  52683. goto recovery_error;
  52684. }
  52685. /* If the database page size is not a power of two, or is greater than
  52686. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  52687. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  52688. ** WAL file.
  52689. */
  52690. magic = sqlite3Get4byte(&aBuf[0]);
  52691. szPage = sqlite3Get4byte(&aBuf[8]);
  52692. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  52693. || szPage&(szPage-1)
  52694. || szPage>SQLITE_MAX_PAGE_SIZE
  52695. || szPage<512
  52696. ){
  52697. goto finished;
  52698. }
  52699. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  52700. pWal->szPage = szPage;
  52701. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  52702. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  52703. /* Verify that the WAL header checksum is correct */
  52704. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  52705. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  52706. );
  52707. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  52708. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  52709. ){
  52710. goto finished;
  52711. }
  52712. /* Verify that the version number on the WAL format is one that
  52713. ** are able to understand */
  52714. version = sqlite3Get4byte(&aBuf[4]);
  52715. if( version!=WAL_MAX_VERSION ){
  52716. rc = SQLITE_CANTOPEN_BKPT;
  52717. goto finished;
  52718. }
  52719. /* Malloc a buffer to read frames into. */
  52720. szFrame = szPage + WAL_FRAME_HDRSIZE;
  52721. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  52722. if( !aFrame ){
  52723. rc = SQLITE_NOMEM_BKPT;
  52724. goto recovery_error;
  52725. }
  52726. aData = &aFrame[WAL_FRAME_HDRSIZE];
  52727. /* Read all frames from the log file. */
  52728. iFrame = 0;
  52729. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  52730. u32 pgno; /* Database page number for frame */
  52731. u32 nTruncate; /* dbsize field from frame header */
  52732. /* Read and decode the next log frame. */
  52733. iFrame++;
  52734. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  52735. if( rc!=SQLITE_OK ) break;
  52736. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  52737. if( !isValid ) break;
  52738. rc = walIndexAppend(pWal, iFrame, pgno);
  52739. if( rc!=SQLITE_OK ) break;
  52740. /* If nTruncate is non-zero, this is a commit record. */
  52741. if( nTruncate ){
  52742. pWal->hdr.mxFrame = iFrame;
  52743. pWal->hdr.nPage = nTruncate;
  52744. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  52745. testcase( szPage<=32768 );
  52746. testcase( szPage>=65536 );
  52747. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  52748. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  52749. }
  52750. }
  52751. sqlite3_free(aFrame);
  52752. }
  52753. finished:
  52754. if( rc==SQLITE_OK ){
  52755. volatile WalCkptInfo *pInfo;
  52756. int i;
  52757. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  52758. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  52759. walIndexWriteHdr(pWal);
  52760. /* Reset the checkpoint-header. This is safe because this thread is
  52761. ** currently holding locks that exclude all other readers, writers and
  52762. ** checkpointers.
  52763. */
  52764. pInfo = walCkptInfo(pWal);
  52765. pInfo->nBackfill = 0;
  52766. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  52767. pInfo->aReadMark[0] = 0;
  52768. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  52769. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  52770. /* If more than one frame was recovered from the log file, report an
  52771. ** event via sqlite3_log(). This is to help with identifying performance
  52772. ** problems caused by applications routinely shutting down without
  52773. ** checkpointing the log file.
  52774. */
  52775. if( pWal->hdr.nPage ){
  52776. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  52777. "recovered %d frames from WAL file %s",
  52778. pWal->hdr.mxFrame, pWal->zWalName
  52779. );
  52780. }
  52781. }
  52782. recovery_error:
  52783. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  52784. walUnlockExclusive(pWal, iLock, nLock);
  52785. return rc;
  52786. }
  52787. /*
  52788. ** Close an open wal-index.
  52789. */
  52790. static void walIndexClose(Wal *pWal, int isDelete){
  52791. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  52792. int i;
  52793. for(i=0; i<pWal->nWiData; i++){
  52794. sqlite3_free((void *)pWal->apWiData[i]);
  52795. pWal->apWiData[i] = 0;
  52796. }
  52797. }else{
  52798. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  52799. }
  52800. }
  52801. /*
  52802. ** Open a connection to the WAL file zWalName. The database file must
  52803. ** already be opened on connection pDbFd. The buffer that zWalName points
  52804. ** to must remain valid for the lifetime of the returned Wal* handle.
  52805. **
  52806. ** A SHARED lock should be held on the database file when this function
  52807. ** is called. The purpose of this SHARED lock is to prevent any other
  52808. ** client from unlinking the WAL or wal-index file. If another process
  52809. ** were to do this just after this client opened one of these files, the
  52810. ** system would be badly broken.
  52811. **
  52812. ** If the log file is successfully opened, SQLITE_OK is returned and
  52813. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  52814. ** an SQLite error code is returned and *ppWal is left unmodified.
  52815. */
  52816. SQLITE_PRIVATE int sqlite3WalOpen(
  52817. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  52818. sqlite3_file *pDbFd, /* The open database file */
  52819. const char *zWalName, /* Name of the WAL file */
  52820. int bNoShm, /* True to run in heap-memory mode */
  52821. i64 mxWalSize, /* Truncate WAL to this size on reset */
  52822. Wal **ppWal /* OUT: Allocated Wal handle */
  52823. ){
  52824. int rc; /* Return Code */
  52825. Wal *pRet; /* Object to allocate and return */
  52826. int flags; /* Flags passed to OsOpen() */
  52827. assert( zWalName && zWalName[0] );
  52828. assert( pDbFd );
  52829. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  52830. ** this source file. Verify that the #defines of the locking byte offsets
  52831. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  52832. ** For that matter, if the lock offset ever changes from its initial design
  52833. ** value of 120, we need to know that so there is an assert() to check it.
  52834. */
  52835. assert( 120==WALINDEX_LOCK_OFFSET );
  52836. assert( 136==WALINDEX_HDR_SIZE );
  52837. #ifdef WIN_SHM_BASE
  52838. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52839. #endif
  52840. #ifdef UNIX_SHM_BASE
  52841. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52842. #endif
  52843. /* Allocate an instance of struct Wal to return. */
  52844. *ppWal = 0;
  52845. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  52846. if( !pRet ){
  52847. return SQLITE_NOMEM_BKPT;
  52848. }
  52849. pRet->pVfs = pVfs;
  52850. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  52851. pRet->pDbFd = pDbFd;
  52852. pRet->readLock = -1;
  52853. pRet->mxWalSize = mxWalSize;
  52854. pRet->zWalName = zWalName;
  52855. pRet->syncHeader = 1;
  52856. pRet->padToSectorBoundary = 1;
  52857. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  52858. /* Open file handle on the write-ahead log file. */
  52859. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  52860. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  52861. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  52862. pRet->readOnly = WAL_RDONLY;
  52863. }
  52864. if( rc!=SQLITE_OK ){
  52865. walIndexClose(pRet, 0);
  52866. sqlite3OsClose(pRet->pWalFd);
  52867. sqlite3_free(pRet);
  52868. }else{
  52869. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  52870. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  52871. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  52872. pRet->padToSectorBoundary = 0;
  52873. }
  52874. *ppWal = pRet;
  52875. WALTRACE(("WAL%d: opened\n", pRet));
  52876. }
  52877. return rc;
  52878. }
  52879. /*
  52880. ** Change the size to which the WAL file is trucated on each reset.
  52881. */
  52882. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  52883. if( pWal ) pWal->mxWalSize = iLimit;
  52884. }
  52885. /*
  52886. ** Find the smallest page number out of all pages held in the WAL that
  52887. ** has not been returned by any prior invocation of this method on the
  52888. ** same WalIterator object. Write into *piFrame the frame index where
  52889. ** that page was last written into the WAL. Write into *piPage the page
  52890. ** number.
  52891. **
  52892. ** Return 0 on success. If there are no pages in the WAL with a page
  52893. ** number larger than *piPage, then return 1.
  52894. */
  52895. static int walIteratorNext(
  52896. WalIterator *p, /* Iterator */
  52897. u32 *piPage, /* OUT: The page number of the next page */
  52898. u32 *piFrame /* OUT: Wal frame index of next page */
  52899. ){
  52900. u32 iMin; /* Result pgno must be greater than iMin */
  52901. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  52902. int i; /* For looping through segments */
  52903. iMin = p->iPrior;
  52904. assert( iMin<0xffffffff );
  52905. for(i=p->nSegment-1; i>=0; i--){
  52906. struct WalSegment *pSegment = &p->aSegment[i];
  52907. while( pSegment->iNext<pSegment->nEntry ){
  52908. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  52909. if( iPg>iMin ){
  52910. if( iPg<iRet ){
  52911. iRet = iPg;
  52912. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  52913. }
  52914. break;
  52915. }
  52916. pSegment->iNext++;
  52917. }
  52918. }
  52919. *piPage = p->iPrior = iRet;
  52920. return (iRet==0xFFFFFFFF);
  52921. }
  52922. /*
  52923. ** This function merges two sorted lists into a single sorted list.
  52924. **
  52925. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  52926. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  52927. ** is guaranteed for all J<K:
  52928. **
  52929. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  52930. ** aContent[aRight[J]] < aContent[aRight[K]]
  52931. **
  52932. ** This routine overwrites aRight[] with a new (probably longer) sequence
  52933. ** of indices such that the aRight[] contains every index that appears in
  52934. ** either aLeft[] or the old aRight[] and such that the second condition
  52935. ** above is still met.
  52936. **
  52937. ** The aContent[aLeft[X]] values will be unique for all X. And the
  52938. ** aContent[aRight[X]] values will be unique too. But there might be
  52939. ** one or more combinations of X and Y such that
  52940. **
  52941. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  52942. **
  52943. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  52944. */
  52945. static void walMerge(
  52946. const u32 *aContent, /* Pages in wal - keys for the sort */
  52947. ht_slot *aLeft, /* IN: Left hand input list */
  52948. int nLeft, /* IN: Elements in array *paLeft */
  52949. ht_slot **paRight, /* IN/OUT: Right hand input list */
  52950. int *pnRight, /* IN/OUT: Elements in *paRight */
  52951. ht_slot *aTmp /* Temporary buffer */
  52952. ){
  52953. int iLeft = 0; /* Current index in aLeft */
  52954. int iRight = 0; /* Current index in aRight */
  52955. int iOut = 0; /* Current index in output buffer */
  52956. int nRight = *pnRight;
  52957. ht_slot *aRight = *paRight;
  52958. assert( nLeft>0 && nRight>0 );
  52959. while( iRight<nRight || iLeft<nLeft ){
  52960. ht_slot logpage;
  52961. Pgno dbpage;
  52962. if( (iLeft<nLeft)
  52963. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  52964. ){
  52965. logpage = aLeft[iLeft++];
  52966. }else{
  52967. logpage = aRight[iRight++];
  52968. }
  52969. dbpage = aContent[logpage];
  52970. aTmp[iOut++] = logpage;
  52971. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  52972. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  52973. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  52974. }
  52975. *paRight = aLeft;
  52976. *pnRight = iOut;
  52977. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  52978. }
  52979. /*
  52980. ** Sort the elements in list aList using aContent[] as the sort key.
  52981. ** Remove elements with duplicate keys, preferring to keep the
  52982. ** larger aList[] values.
  52983. **
  52984. ** The aList[] entries are indices into aContent[]. The values in
  52985. ** aList[] are to be sorted so that for all J<K:
  52986. **
  52987. ** aContent[aList[J]] < aContent[aList[K]]
  52988. **
  52989. ** For any X and Y such that
  52990. **
  52991. ** aContent[aList[X]] == aContent[aList[Y]]
  52992. **
  52993. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  52994. ** the smaller.
  52995. */
  52996. static void walMergesort(
  52997. const u32 *aContent, /* Pages in wal */
  52998. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  52999. ht_slot *aList, /* IN/OUT: List to sort */
  53000. int *pnList /* IN/OUT: Number of elements in aList[] */
  53001. ){
  53002. struct Sublist {
  53003. int nList; /* Number of elements in aList */
  53004. ht_slot *aList; /* Pointer to sub-list content */
  53005. };
  53006. const int nList = *pnList; /* Size of input list */
  53007. int nMerge = 0; /* Number of elements in list aMerge */
  53008. ht_slot *aMerge = 0; /* List to be merged */
  53009. int iList; /* Index into input list */
  53010. u32 iSub = 0; /* Index into aSub array */
  53011. struct Sublist aSub[13]; /* Array of sub-lists */
  53012. memset(aSub, 0, sizeof(aSub));
  53013. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  53014. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  53015. for(iList=0; iList<nList; iList++){
  53016. nMerge = 1;
  53017. aMerge = &aList[iList];
  53018. for(iSub=0; iList & (1<<iSub); iSub++){
  53019. struct Sublist *p;
  53020. assert( iSub<ArraySize(aSub) );
  53021. p = &aSub[iSub];
  53022. assert( p->aList && p->nList<=(1<<iSub) );
  53023. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  53024. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  53025. }
  53026. aSub[iSub].aList = aMerge;
  53027. aSub[iSub].nList = nMerge;
  53028. }
  53029. for(iSub++; iSub<ArraySize(aSub); iSub++){
  53030. if( nList & (1<<iSub) ){
  53031. struct Sublist *p;
  53032. assert( iSub<ArraySize(aSub) );
  53033. p = &aSub[iSub];
  53034. assert( p->nList<=(1<<iSub) );
  53035. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  53036. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  53037. }
  53038. }
  53039. assert( aMerge==aList );
  53040. *pnList = nMerge;
  53041. #ifdef SQLITE_DEBUG
  53042. {
  53043. int i;
  53044. for(i=1; i<*pnList; i++){
  53045. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  53046. }
  53047. }
  53048. #endif
  53049. }
  53050. /*
  53051. ** Free an iterator allocated by walIteratorInit().
  53052. */
  53053. static void walIteratorFree(WalIterator *p){
  53054. sqlite3_free(p);
  53055. }
  53056. /*
  53057. ** Construct a WalInterator object that can be used to loop over all
  53058. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  53059. ** lock.
  53060. **
  53061. ** On success, make *pp point to the newly allocated WalInterator object
  53062. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  53063. ** returns an error, the value of *pp is undefined.
  53064. **
  53065. ** The calling routine should invoke walIteratorFree() to destroy the
  53066. ** WalIterator object when it has finished with it.
  53067. */
  53068. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  53069. WalIterator *p; /* Return value */
  53070. int nSegment; /* Number of segments to merge */
  53071. u32 iLast; /* Last frame in log */
  53072. int nByte; /* Number of bytes to allocate */
  53073. int i; /* Iterator variable */
  53074. ht_slot *aTmp; /* Temp space used by merge-sort */
  53075. int rc = SQLITE_OK; /* Return Code */
  53076. /* This routine only runs while holding the checkpoint lock. And
  53077. ** it only runs if there is actually content in the log (mxFrame>0).
  53078. */
  53079. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  53080. iLast = pWal->hdr.mxFrame;
  53081. /* Allocate space for the WalIterator object. */
  53082. nSegment = walFramePage(iLast) + 1;
  53083. nByte = sizeof(WalIterator)
  53084. + (nSegment-1)*sizeof(struct WalSegment)
  53085. + iLast*sizeof(ht_slot);
  53086. p = (WalIterator *)sqlite3_malloc64(nByte);
  53087. if( !p ){
  53088. return SQLITE_NOMEM_BKPT;
  53089. }
  53090. memset(p, 0, nByte);
  53091. p->nSegment = nSegment;
  53092. /* Allocate temporary space used by the merge-sort routine. This block
  53093. ** of memory will be freed before this function returns.
  53094. */
  53095. aTmp = (ht_slot *)sqlite3_malloc64(
  53096. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  53097. );
  53098. if( !aTmp ){
  53099. rc = SQLITE_NOMEM_BKPT;
  53100. }
  53101. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  53102. volatile ht_slot *aHash;
  53103. u32 iZero;
  53104. volatile u32 *aPgno;
  53105. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  53106. if( rc==SQLITE_OK ){
  53107. int j; /* Counter variable */
  53108. int nEntry; /* Number of entries in this segment */
  53109. ht_slot *aIndex; /* Sorted index for this segment */
  53110. aPgno++;
  53111. if( (i+1)==nSegment ){
  53112. nEntry = (int)(iLast - iZero);
  53113. }else{
  53114. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  53115. }
  53116. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  53117. iZero++;
  53118. for(j=0; j<nEntry; j++){
  53119. aIndex[j] = (ht_slot)j;
  53120. }
  53121. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  53122. p->aSegment[i].iZero = iZero;
  53123. p->aSegment[i].nEntry = nEntry;
  53124. p->aSegment[i].aIndex = aIndex;
  53125. p->aSegment[i].aPgno = (u32 *)aPgno;
  53126. }
  53127. }
  53128. sqlite3_free(aTmp);
  53129. if( rc!=SQLITE_OK ){
  53130. walIteratorFree(p);
  53131. }
  53132. *pp = p;
  53133. return rc;
  53134. }
  53135. /*
  53136. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  53137. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  53138. ** busy-handler function. Invoke it and retry the lock until either the
  53139. ** lock is successfully obtained or the busy-handler returns 0.
  53140. */
  53141. static int walBusyLock(
  53142. Wal *pWal, /* WAL connection */
  53143. int (*xBusy)(void*), /* Function to call when busy */
  53144. void *pBusyArg, /* Context argument for xBusyHandler */
  53145. int lockIdx, /* Offset of first byte to lock */
  53146. int n /* Number of bytes to lock */
  53147. ){
  53148. int rc;
  53149. do {
  53150. rc = walLockExclusive(pWal, lockIdx, n);
  53151. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  53152. return rc;
  53153. }
  53154. /*
  53155. ** The cache of the wal-index header must be valid to call this function.
  53156. ** Return the page-size in bytes used by the database.
  53157. */
  53158. static int walPagesize(Wal *pWal){
  53159. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  53160. }
  53161. /*
  53162. ** The following is guaranteed when this function is called:
  53163. **
  53164. ** a) the WRITER lock is held,
  53165. ** b) the entire log file has been checkpointed, and
  53166. ** c) any existing readers are reading exclusively from the database
  53167. ** file - there are no readers that may attempt to read a frame from
  53168. ** the log file.
  53169. **
  53170. ** This function updates the shared-memory structures so that the next
  53171. ** client to write to the database (which may be this one) does so by
  53172. ** writing frames into the start of the log file.
  53173. **
  53174. ** The value of parameter salt1 is used as the aSalt[1] value in the
  53175. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  53176. ** one obtained from sqlite3_randomness()).
  53177. */
  53178. static void walRestartHdr(Wal *pWal, u32 salt1){
  53179. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53180. int i; /* Loop counter */
  53181. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  53182. pWal->nCkpt++;
  53183. pWal->hdr.mxFrame = 0;
  53184. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  53185. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  53186. walIndexWriteHdr(pWal);
  53187. pInfo->nBackfill = 0;
  53188. pInfo->nBackfillAttempted = 0;
  53189. pInfo->aReadMark[1] = 0;
  53190. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  53191. assert( pInfo->aReadMark[0]==0 );
  53192. }
  53193. /*
  53194. ** Copy as much content as we can from the WAL back into the database file
  53195. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  53196. **
  53197. ** The amount of information copies from WAL to database might be limited
  53198. ** by active readers. This routine will never overwrite a database page
  53199. ** that a concurrent reader might be using.
  53200. **
  53201. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  53202. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  53203. ** checkpoints are always run by a background thread or background
  53204. ** process, foreground threads will never block on a lengthy fsync call.
  53205. **
  53206. ** Fsync is called on the WAL before writing content out of the WAL and
  53207. ** into the database. This ensures that if the new content is persistent
  53208. ** in the WAL and can be recovered following a power-loss or hard reset.
  53209. **
  53210. ** Fsync is also called on the database file if (and only if) the entire
  53211. ** WAL content is copied into the database file. This second fsync makes
  53212. ** it safe to delete the WAL since the new content will persist in the
  53213. ** database file.
  53214. **
  53215. ** This routine uses and updates the nBackfill field of the wal-index header.
  53216. ** This is the only routine that will increase the value of nBackfill.
  53217. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  53218. ** its value.)
  53219. **
  53220. ** The caller must be holding sufficient locks to ensure that no other
  53221. ** checkpoint is running (in any other thread or process) at the same
  53222. ** time.
  53223. */
  53224. static int walCheckpoint(
  53225. Wal *pWal, /* Wal connection */
  53226. sqlite3 *db, /* Check for interrupts on this handle */
  53227. int eMode, /* One of PASSIVE, FULL or RESTART */
  53228. int (*xBusy)(void*), /* Function to call when busy */
  53229. void *pBusyArg, /* Context argument for xBusyHandler */
  53230. int sync_flags, /* Flags for OsSync() (or 0) */
  53231. u8 *zBuf /* Temporary buffer to use */
  53232. ){
  53233. int rc = SQLITE_OK; /* Return code */
  53234. int szPage; /* Database page-size */
  53235. WalIterator *pIter = 0; /* Wal iterator context */
  53236. u32 iDbpage = 0; /* Next database page to write */
  53237. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  53238. u32 mxSafeFrame; /* Max frame that can be backfilled */
  53239. u32 mxPage; /* Max database page to write */
  53240. int i; /* Loop counter */
  53241. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  53242. szPage = walPagesize(pWal);
  53243. testcase( szPage<=32768 );
  53244. testcase( szPage>=65536 );
  53245. pInfo = walCkptInfo(pWal);
  53246. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  53247. /* Allocate the iterator */
  53248. rc = walIteratorInit(pWal, &pIter);
  53249. if( rc!=SQLITE_OK ){
  53250. return rc;
  53251. }
  53252. assert( pIter );
  53253. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  53254. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  53255. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  53256. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  53257. ** safe to write into the database. Frames beyond mxSafeFrame might
  53258. ** overwrite database pages that are in use by active readers and thus
  53259. ** cannot be backfilled from the WAL.
  53260. */
  53261. mxSafeFrame = pWal->hdr.mxFrame;
  53262. mxPage = pWal->hdr.nPage;
  53263. for(i=1; i<WAL_NREADER; i++){
  53264. /* Thread-sanitizer reports that the following is an unsafe read,
  53265. ** as some other thread may be in the process of updating the value
  53266. ** of the aReadMark[] slot. The assumption here is that if that is
  53267. ** happening, the other client may only be increasing the value,
  53268. ** not decreasing it. So assuming either that either the "old" or
  53269. ** "new" version of the value is read, and not some arbitrary value
  53270. ** that would never be written by a real client, things are still
  53271. ** safe. */
  53272. u32 y = pInfo->aReadMark[i];
  53273. if( mxSafeFrame>y ){
  53274. assert( y<=pWal->hdr.mxFrame );
  53275. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  53276. if( rc==SQLITE_OK ){
  53277. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  53278. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53279. }else if( rc==SQLITE_BUSY ){
  53280. mxSafeFrame = y;
  53281. xBusy = 0;
  53282. }else{
  53283. goto walcheckpoint_out;
  53284. }
  53285. }
  53286. }
  53287. if( pInfo->nBackfill<mxSafeFrame
  53288. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  53289. ){
  53290. i64 nSize; /* Current size of database file */
  53291. u32 nBackfill = pInfo->nBackfill;
  53292. pInfo->nBackfillAttempted = mxSafeFrame;
  53293. /* Sync the WAL to disk */
  53294. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  53295. /* If the database may grow as a result of this checkpoint, hint
  53296. ** about the eventual size of the db file to the VFS layer.
  53297. */
  53298. if( rc==SQLITE_OK ){
  53299. i64 nReq = ((i64)mxPage * szPage);
  53300. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  53301. if( rc==SQLITE_OK && nSize<nReq ){
  53302. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  53303. }
  53304. }
  53305. /* Iterate through the contents of the WAL, copying data to the db file */
  53306. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  53307. i64 iOffset;
  53308. assert( walFramePgno(pWal, iFrame)==iDbpage );
  53309. if( db->u1.isInterrupted ){
  53310. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  53311. break;
  53312. }
  53313. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  53314. continue;
  53315. }
  53316. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  53317. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  53318. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  53319. if( rc!=SQLITE_OK ) break;
  53320. iOffset = (iDbpage-1)*(i64)szPage;
  53321. testcase( IS_BIG_INT(iOffset) );
  53322. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  53323. if( rc!=SQLITE_OK ) break;
  53324. }
  53325. /* If work was actually accomplished... */
  53326. if( rc==SQLITE_OK ){
  53327. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  53328. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  53329. testcase( IS_BIG_INT(szDb) );
  53330. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  53331. if( rc==SQLITE_OK ){
  53332. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  53333. }
  53334. }
  53335. if( rc==SQLITE_OK ){
  53336. pInfo->nBackfill = mxSafeFrame;
  53337. }
  53338. }
  53339. /* Release the reader lock held while backfilling */
  53340. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  53341. }
  53342. if( rc==SQLITE_BUSY ){
  53343. /* Reset the return code so as not to report a checkpoint failure
  53344. ** just because there are active readers. */
  53345. rc = SQLITE_OK;
  53346. }
  53347. }
  53348. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  53349. ** entire wal file has been copied into the database file, then block
  53350. ** until all readers have finished using the wal file. This ensures that
  53351. ** the next process to write to the database restarts the wal file.
  53352. */
  53353. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  53354. assert( pWal->writeLock );
  53355. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  53356. rc = SQLITE_BUSY;
  53357. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  53358. u32 salt1;
  53359. sqlite3_randomness(4, &salt1);
  53360. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  53361. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  53362. if( rc==SQLITE_OK ){
  53363. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  53364. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  53365. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  53366. ** truncates the log file to zero bytes just prior to a
  53367. ** successful return.
  53368. **
  53369. ** In theory, it might be safe to do this without updating the
  53370. ** wal-index header in shared memory, as all subsequent reader or
  53371. ** writer clients should see that the entire log file has been
  53372. ** checkpointed and behave accordingly. This seems unsafe though,
  53373. ** as it would leave the system in a state where the contents of
  53374. ** the wal-index header do not match the contents of the
  53375. ** file-system. To avoid this, update the wal-index header to
  53376. ** indicate that the log file contains zero valid frames. */
  53377. walRestartHdr(pWal, salt1);
  53378. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  53379. }
  53380. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  53381. }
  53382. }
  53383. }
  53384. walcheckpoint_out:
  53385. walIteratorFree(pIter);
  53386. return rc;
  53387. }
  53388. /*
  53389. ** If the WAL file is currently larger than nMax bytes in size, truncate
  53390. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  53391. */
  53392. static void walLimitSize(Wal *pWal, i64 nMax){
  53393. i64 sz;
  53394. int rx;
  53395. sqlite3BeginBenignMalloc();
  53396. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  53397. if( rx==SQLITE_OK && (sz > nMax ) ){
  53398. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  53399. }
  53400. sqlite3EndBenignMalloc();
  53401. if( rx ){
  53402. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  53403. }
  53404. }
  53405. /*
  53406. ** Close a connection to a log file.
  53407. */
  53408. SQLITE_PRIVATE int sqlite3WalClose(
  53409. Wal *pWal, /* Wal to close */
  53410. sqlite3 *db, /* For interrupt flag */
  53411. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  53412. int nBuf,
  53413. u8 *zBuf /* Buffer of at least nBuf bytes */
  53414. ){
  53415. int rc = SQLITE_OK;
  53416. if( pWal ){
  53417. int isDelete = 0; /* True to unlink wal and wal-index files */
  53418. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  53419. ** ordinary, rollback-mode locking methods, this guarantees that the
  53420. ** connection associated with this log file is the only connection to
  53421. ** the database. In this case checkpoint the database and unlink both
  53422. ** the wal and wal-index files.
  53423. **
  53424. ** The EXCLUSIVE lock is not released before returning.
  53425. */
  53426. if( zBuf!=0
  53427. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  53428. ){
  53429. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  53430. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  53431. }
  53432. rc = sqlite3WalCheckpoint(pWal, db,
  53433. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  53434. );
  53435. if( rc==SQLITE_OK ){
  53436. int bPersist = -1;
  53437. sqlite3OsFileControlHint(
  53438. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  53439. );
  53440. if( bPersist!=1 ){
  53441. /* Try to delete the WAL file if the checkpoint completed and
  53442. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  53443. ** mode (!bPersist) */
  53444. isDelete = 1;
  53445. }else if( pWal->mxWalSize>=0 ){
  53446. /* Try to truncate the WAL file to zero bytes if the checkpoint
  53447. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  53448. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  53449. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  53450. ** to zero bytes as truncating to the journal_size_limit might
  53451. ** leave a corrupt WAL file on disk. */
  53452. walLimitSize(pWal, 0);
  53453. }
  53454. }
  53455. }
  53456. walIndexClose(pWal, isDelete);
  53457. sqlite3OsClose(pWal->pWalFd);
  53458. if( isDelete ){
  53459. sqlite3BeginBenignMalloc();
  53460. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  53461. sqlite3EndBenignMalloc();
  53462. }
  53463. WALTRACE(("WAL%p: closed\n", pWal));
  53464. sqlite3_free((void *)pWal->apWiData);
  53465. sqlite3_free(pWal);
  53466. }
  53467. return rc;
  53468. }
  53469. /*
  53470. ** Try to read the wal-index header. Return 0 on success and 1 if
  53471. ** there is a problem.
  53472. **
  53473. ** The wal-index is in shared memory. Another thread or process might
  53474. ** be writing the header at the same time this procedure is trying to
  53475. ** read it, which might result in inconsistency. A dirty read is detected
  53476. ** by verifying that both copies of the header are the same and also by
  53477. ** a checksum on the header.
  53478. **
  53479. ** If and only if the read is consistent and the header is different from
  53480. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  53481. ** and *pChanged is set to 1.
  53482. **
  53483. ** If the checksum cannot be verified return non-zero. If the header
  53484. ** is read successfully and the checksum verified, return zero.
  53485. */
  53486. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  53487. u32 aCksum[2]; /* Checksum on the header content */
  53488. WalIndexHdr h1, h2; /* Two copies of the header content */
  53489. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  53490. /* The first page of the wal-index must be mapped at this point. */
  53491. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  53492. /* Read the header. This might happen concurrently with a write to the
  53493. ** same area of shared memory on a different CPU in a SMP,
  53494. ** meaning it is possible that an inconsistent snapshot is read
  53495. ** from the file. If this happens, return non-zero.
  53496. **
  53497. ** There are two copies of the header at the beginning of the wal-index.
  53498. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  53499. ** Memory barriers are used to prevent the compiler or the hardware from
  53500. ** reordering the reads and writes.
  53501. */
  53502. aHdr = walIndexHdr(pWal);
  53503. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  53504. walShmBarrier(pWal);
  53505. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  53506. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  53507. return 1; /* Dirty read */
  53508. }
  53509. if( h1.isInit==0 ){
  53510. return 1; /* Malformed header - probably all zeros */
  53511. }
  53512. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  53513. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  53514. return 1; /* Checksum does not match */
  53515. }
  53516. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  53517. *pChanged = 1;
  53518. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  53519. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  53520. testcase( pWal->szPage<=32768 );
  53521. testcase( pWal->szPage>=65536 );
  53522. }
  53523. /* The header was successfully read. Return zero. */
  53524. return 0;
  53525. }
  53526. /*
  53527. ** Read the wal-index header from the wal-index and into pWal->hdr.
  53528. ** If the wal-header appears to be corrupt, try to reconstruct the
  53529. ** wal-index from the WAL before returning.
  53530. **
  53531. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  53532. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  53533. ** to 0.
  53534. **
  53535. ** If the wal-index header is successfully read, return SQLITE_OK.
  53536. ** Otherwise an SQLite error code.
  53537. */
  53538. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  53539. int rc; /* Return code */
  53540. int badHdr; /* True if a header read failed */
  53541. volatile u32 *page0; /* Chunk of wal-index containing header */
  53542. /* Ensure that page 0 of the wal-index (the page that contains the
  53543. ** wal-index header) is mapped. Return early if an error occurs here.
  53544. */
  53545. assert( pChanged );
  53546. rc = walIndexPage(pWal, 0, &page0);
  53547. if( rc!=SQLITE_OK ){
  53548. return rc;
  53549. };
  53550. assert( page0 || pWal->writeLock==0 );
  53551. /* If the first page of the wal-index has been mapped, try to read the
  53552. ** wal-index header immediately, without holding any lock. This usually
  53553. ** works, but may fail if the wal-index header is corrupt or currently
  53554. ** being modified by another thread or process.
  53555. */
  53556. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  53557. /* If the first attempt failed, it might have been due to a race
  53558. ** with a writer. So get a WRITE lock and try again.
  53559. */
  53560. assert( badHdr==0 || pWal->writeLock==0 );
  53561. if( badHdr ){
  53562. if( pWal->readOnly & WAL_SHM_RDONLY ){
  53563. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  53564. walUnlockShared(pWal, WAL_WRITE_LOCK);
  53565. rc = SQLITE_READONLY_RECOVERY;
  53566. }
  53567. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  53568. pWal->writeLock = 1;
  53569. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  53570. badHdr = walIndexTryHdr(pWal, pChanged);
  53571. if( badHdr ){
  53572. /* If the wal-index header is still malformed even while holding
  53573. ** a WRITE lock, it can only mean that the header is corrupted and
  53574. ** needs to be reconstructed. So run recovery to do exactly that.
  53575. */
  53576. rc = walIndexRecover(pWal);
  53577. *pChanged = 1;
  53578. }
  53579. }
  53580. pWal->writeLock = 0;
  53581. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53582. }
  53583. }
  53584. /* If the header is read successfully, check the version number to make
  53585. ** sure the wal-index was not constructed with some future format that
  53586. ** this version of SQLite cannot understand.
  53587. */
  53588. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  53589. rc = SQLITE_CANTOPEN_BKPT;
  53590. }
  53591. return rc;
  53592. }
  53593. /*
  53594. ** This is the value that walTryBeginRead returns when it needs to
  53595. ** be retried.
  53596. */
  53597. #define WAL_RETRY (-1)
  53598. /*
  53599. ** Attempt to start a read transaction. This might fail due to a race or
  53600. ** other transient condition. When that happens, it returns WAL_RETRY to
  53601. ** indicate to the caller that it is safe to retry immediately.
  53602. **
  53603. ** On success return SQLITE_OK. On a permanent failure (such an
  53604. ** I/O error or an SQLITE_BUSY because another process is running
  53605. ** recovery) return a positive error code.
  53606. **
  53607. ** The useWal parameter is true to force the use of the WAL and disable
  53608. ** the case where the WAL is bypassed because it has been completely
  53609. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  53610. ** to make a copy of the wal-index header into pWal->hdr. If the
  53611. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  53612. ** to the caller that the local paget cache is obsolete and needs to be
  53613. ** flushed.) When useWal==1, the wal-index header is assumed to already
  53614. ** be loaded and the pChanged parameter is unused.
  53615. **
  53616. ** The caller must set the cnt parameter to the number of prior calls to
  53617. ** this routine during the current read attempt that returned WAL_RETRY.
  53618. ** This routine will start taking more aggressive measures to clear the
  53619. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  53620. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  53621. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  53622. ** and is not honoring the locking protocol. There is a vanishingly small
  53623. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  53624. ** bad luck when there is lots of contention for the wal-index, but that
  53625. ** possibility is so small that it can be safely neglected, we believe.
  53626. **
  53627. ** On success, this routine obtains a read lock on
  53628. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  53629. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  53630. ** that means the Wal does not hold any read lock. The reader must not
  53631. ** access any database page that is modified by a WAL frame up to and
  53632. ** including frame number aReadMark[pWal->readLock]. The reader will
  53633. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  53634. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  53635. ** completely and get all content directly from the database file.
  53636. ** If the useWal parameter is 1 then the WAL will never be ignored and
  53637. ** this routine will always set pWal->readLock>0 on success.
  53638. ** When the read transaction is completed, the caller must release the
  53639. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  53640. **
  53641. ** This routine uses the nBackfill and aReadMark[] fields of the header
  53642. ** to select a particular WAL_READ_LOCK() that strives to let the
  53643. ** checkpoint process do as much work as possible. This routine might
  53644. ** update values of the aReadMark[] array in the header, but if it does
  53645. ** so it takes care to hold an exclusive lock on the corresponding
  53646. ** WAL_READ_LOCK() while changing values.
  53647. */
  53648. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  53649. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  53650. u32 mxReadMark; /* Largest aReadMark[] value */
  53651. int mxI; /* Index of largest aReadMark[] value */
  53652. int i; /* Loop counter */
  53653. int rc = SQLITE_OK; /* Return code */
  53654. u32 mxFrame; /* Wal frame to lock to */
  53655. assert( pWal->readLock<0 ); /* Not currently locked */
  53656. /* Take steps to avoid spinning forever if there is a protocol error.
  53657. **
  53658. ** Circumstances that cause a RETRY should only last for the briefest
  53659. ** instances of time. No I/O or other system calls are done while the
  53660. ** locks are held, so the locks should not be held for very long. But
  53661. ** if we are unlucky, another process that is holding a lock might get
  53662. ** paged out or take a page-fault that is time-consuming to resolve,
  53663. ** during the few nanoseconds that it is holding the lock. In that case,
  53664. ** it might take longer than normal for the lock to free.
  53665. **
  53666. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  53667. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  53668. ** is more of a scheduler yield than an actual delay. But on the 10th
  53669. ** an subsequent retries, the delays start becoming longer and longer,
  53670. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  53671. ** The total delay time before giving up is less than 10 seconds.
  53672. */
  53673. if( cnt>5 ){
  53674. int nDelay = 1; /* Pause time in microseconds */
  53675. if( cnt>100 ){
  53676. VVA_ONLY( pWal->lockError = 1; )
  53677. return SQLITE_PROTOCOL;
  53678. }
  53679. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  53680. sqlite3OsSleep(pWal->pVfs, nDelay);
  53681. }
  53682. if( !useWal ){
  53683. rc = walIndexReadHdr(pWal, pChanged);
  53684. if( rc==SQLITE_BUSY ){
  53685. /* If there is not a recovery running in another thread or process
  53686. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  53687. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  53688. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  53689. ** would be technically correct. But the race is benign since with
  53690. ** WAL_RETRY this routine will be called again and will probably be
  53691. ** right on the second iteration.
  53692. */
  53693. if( pWal->apWiData[0]==0 ){
  53694. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  53695. ** We assume this is a transient condition, so return WAL_RETRY. The
  53696. ** xShmMap() implementation used by the default unix and win32 VFS
  53697. ** modules may return SQLITE_BUSY due to a race condition in the
  53698. ** code that determines whether or not the shared-memory region
  53699. ** must be zeroed before the requested page is returned.
  53700. */
  53701. rc = WAL_RETRY;
  53702. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  53703. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  53704. rc = WAL_RETRY;
  53705. }else if( rc==SQLITE_BUSY ){
  53706. rc = SQLITE_BUSY_RECOVERY;
  53707. }
  53708. }
  53709. if( rc!=SQLITE_OK ){
  53710. return rc;
  53711. }
  53712. }
  53713. pInfo = walCkptInfo(pWal);
  53714. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  53715. #ifdef SQLITE_ENABLE_SNAPSHOT
  53716. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
  53717. || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
  53718. #endif
  53719. ){
  53720. /* The WAL has been completely backfilled (or it is empty).
  53721. ** and can be safely ignored.
  53722. */
  53723. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  53724. walShmBarrier(pWal);
  53725. if( rc==SQLITE_OK ){
  53726. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  53727. /* It is not safe to allow the reader to continue here if frames
  53728. ** may have been appended to the log before READ_LOCK(0) was obtained.
  53729. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  53730. ** which implies that the database file contains a trustworthy
  53731. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  53732. ** happening, this is usually correct.
  53733. **
  53734. ** However, if frames have been appended to the log (or if the log
  53735. ** is wrapped and written for that matter) before the READ_LOCK(0)
  53736. ** is obtained, that is not necessarily true. A checkpointer may
  53737. ** have started to backfill the appended frames but crashed before
  53738. ** it finished. Leaving a corrupt image in the database file.
  53739. */
  53740. walUnlockShared(pWal, WAL_READ_LOCK(0));
  53741. return WAL_RETRY;
  53742. }
  53743. pWal->readLock = 0;
  53744. return SQLITE_OK;
  53745. }else if( rc!=SQLITE_BUSY ){
  53746. return rc;
  53747. }
  53748. }
  53749. /* If we get this far, it means that the reader will want to use
  53750. ** the WAL to get at content from recent commits. The job now is
  53751. ** to select one of the aReadMark[] entries that is closest to
  53752. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  53753. */
  53754. mxReadMark = 0;
  53755. mxI = 0;
  53756. mxFrame = pWal->hdr.mxFrame;
  53757. #ifdef SQLITE_ENABLE_SNAPSHOT
  53758. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  53759. mxFrame = pWal->pSnapshot->mxFrame;
  53760. }
  53761. #endif
  53762. for(i=1; i<WAL_NREADER; i++){
  53763. u32 thisMark = pInfo->aReadMark[i];
  53764. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  53765. assert( thisMark!=READMARK_NOT_USED );
  53766. mxReadMark = thisMark;
  53767. mxI = i;
  53768. }
  53769. }
  53770. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  53771. && (mxReadMark<mxFrame || mxI==0)
  53772. ){
  53773. for(i=1; i<WAL_NREADER; i++){
  53774. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53775. if( rc==SQLITE_OK ){
  53776. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  53777. mxI = i;
  53778. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53779. break;
  53780. }else if( rc!=SQLITE_BUSY ){
  53781. return rc;
  53782. }
  53783. }
  53784. }
  53785. if( mxI==0 ){
  53786. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  53787. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  53788. }
  53789. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  53790. if( rc ){
  53791. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  53792. }
  53793. /* Now that the read-lock has been obtained, check that neither the
  53794. ** value in the aReadMark[] array or the contents of the wal-index
  53795. ** header have changed.
  53796. **
  53797. ** It is necessary to check that the wal-index header did not change
  53798. ** between the time it was read and when the shared-lock was obtained
  53799. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  53800. ** that the log file may have been wrapped by a writer, or that frames
  53801. ** that occur later in the log than pWal->hdr.mxFrame may have been
  53802. ** copied into the database by a checkpointer. If either of these things
  53803. ** happened, then reading the database with the current value of
  53804. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  53805. ** instead.
  53806. **
  53807. ** Before checking that the live wal-index header has not changed
  53808. ** since it was read, set Wal.minFrame to the first frame in the wal
  53809. ** file that has not yet been checkpointed. This client will not need
  53810. ** to read any frames earlier than minFrame from the wal file - they
  53811. ** can be safely read directly from the database file.
  53812. **
  53813. ** Because a ShmBarrier() call is made between taking the copy of
  53814. ** nBackfill and checking that the wal-header in shared-memory still
  53815. ** matches the one cached in pWal->hdr, it is guaranteed that the
  53816. ** checkpointer that set nBackfill was not working with a wal-index
  53817. ** header newer than that cached in pWal->hdr. If it were, that could
  53818. ** cause a problem. The checkpointer could omit to checkpoint
  53819. ** a version of page X that lies before pWal->minFrame (call that version
  53820. ** A) on the basis that there is a newer version (version B) of the same
  53821. ** page later in the wal file. But if version B happens to like past
  53822. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  53823. ** that it can read version A from the database file. However, since
  53824. ** we can guarantee that the checkpointer that set nBackfill could not
  53825. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  53826. */
  53827. pWal->minFrame = pInfo->nBackfill+1;
  53828. walShmBarrier(pWal);
  53829. if( pInfo->aReadMark[mxI]!=mxReadMark
  53830. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  53831. ){
  53832. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  53833. return WAL_RETRY;
  53834. }else{
  53835. assert( mxReadMark<=pWal->hdr.mxFrame );
  53836. pWal->readLock = (i16)mxI;
  53837. }
  53838. return rc;
  53839. }
  53840. #ifdef SQLITE_ENABLE_SNAPSHOT
  53841. /*
  53842. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  53843. ** variable so that older snapshots can be accessed. To do this, loop
  53844. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  53845. ** comparing their content to the corresponding page with the database
  53846. ** file, if any. Set nBackfillAttempted to the frame number of the
  53847. ** first frame for which the wal file content matches the db file.
  53848. **
  53849. ** This is only really safe if the file-system is such that any page
  53850. ** writes made by earlier checkpointers were atomic operations, which
  53851. ** is not always true. It is also possible that nBackfillAttempted
  53852. ** may be left set to a value larger than expected, if a wal frame
  53853. ** contains content that duplicate of an earlier version of the same
  53854. ** page.
  53855. **
  53856. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  53857. ** error occurs. It is not an error if nBackfillAttempted cannot be
  53858. ** decreased at all.
  53859. */
  53860. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  53861. int rc;
  53862. assert( pWal->readLock>=0 );
  53863. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53864. if( rc==SQLITE_OK ){
  53865. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53866. int szPage = (int)pWal->szPage;
  53867. i64 szDb; /* Size of db file in bytes */
  53868. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  53869. if( rc==SQLITE_OK ){
  53870. void *pBuf1 = sqlite3_malloc(szPage);
  53871. void *pBuf2 = sqlite3_malloc(szPage);
  53872. if( pBuf1==0 || pBuf2==0 ){
  53873. rc = SQLITE_NOMEM;
  53874. }else{
  53875. u32 i = pInfo->nBackfillAttempted;
  53876. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  53877. volatile ht_slot *dummy;
  53878. volatile u32 *aPgno; /* Array of page numbers */
  53879. u32 iZero; /* Frame corresponding to aPgno[0] */
  53880. u32 pgno; /* Page number in db file */
  53881. i64 iDbOff; /* Offset of db file entry */
  53882. i64 iWalOff; /* Offset of wal file entry */
  53883. rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
  53884. if( rc!=SQLITE_OK ) break;
  53885. pgno = aPgno[i-iZero];
  53886. iDbOff = (i64)(pgno-1) * szPage;
  53887. if( iDbOff+szPage<=szDb ){
  53888. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  53889. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  53890. if( rc==SQLITE_OK ){
  53891. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  53892. }
  53893. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  53894. break;
  53895. }
  53896. }
  53897. pInfo->nBackfillAttempted = i-1;
  53898. }
  53899. }
  53900. sqlite3_free(pBuf1);
  53901. sqlite3_free(pBuf2);
  53902. }
  53903. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53904. }
  53905. return rc;
  53906. }
  53907. #endif /* SQLITE_ENABLE_SNAPSHOT */
  53908. /*
  53909. ** Begin a read transaction on the database.
  53910. **
  53911. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  53912. ** it takes a snapshot of the state of the WAL and wal-index for the current
  53913. ** instant in time. The current thread will continue to use this snapshot.
  53914. ** Other threads might append new content to the WAL and wal-index but
  53915. ** that extra content is ignored by the current thread.
  53916. **
  53917. ** If the database contents have changes since the previous read
  53918. ** transaction, then *pChanged is set to 1 before returning. The
  53919. ** Pager layer will use this to know that is cache is stale and
  53920. ** needs to be flushed.
  53921. */
  53922. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  53923. int rc; /* Return code */
  53924. int cnt = 0; /* Number of TryBeginRead attempts */
  53925. #ifdef SQLITE_ENABLE_SNAPSHOT
  53926. int bChanged = 0;
  53927. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  53928. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53929. bChanged = 1;
  53930. }
  53931. #endif
  53932. do{
  53933. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  53934. }while( rc==WAL_RETRY );
  53935. testcase( (rc&0xff)==SQLITE_BUSY );
  53936. testcase( (rc&0xff)==SQLITE_IOERR );
  53937. testcase( rc==SQLITE_PROTOCOL );
  53938. testcase( rc==SQLITE_OK );
  53939. #ifdef SQLITE_ENABLE_SNAPSHOT
  53940. if( rc==SQLITE_OK ){
  53941. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53942. /* At this point the client has a lock on an aReadMark[] slot holding
  53943. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  53944. ** is populated with the wal-index header corresponding to the head
  53945. ** of the wal file. Verify that pSnapshot is still valid before
  53946. ** continuing. Reasons why pSnapshot might no longer be valid:
  53947. **
  53948. ** (1) The WAL file has been reset since the snapshot was taken.
  53949. ** In this case, the salt will have changed.
  53950. **
  53951. ** (2) A checkpoint as been attempted that wrote frames past
  53952. ** pSnapshot->mxFrame into the database file. Note that the
  53953. ** checkpoint need not have completed for this to cause problems.
  53954. */
  53955. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53956. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  53957. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  53958. /* It is possible that there is a checkpointer thread running
  53959. ** concurrent with this code. If this is the case, it may be that the
  53960. ** checkpointer has already determined that it will checkpoint
  53961. ** snapshot X, where X is later in the wal file than pSnapshot, but
  53962. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  53963. ** its intent. To avoid the race condition this leads to, ensure that
  53964. ** there is no checkpointer process by taking a shared CKPT lock
  53965. ** before checking pInfo->nBackfillAttempted.
  53966. **
  53967. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  53968. ** this already?
  53969. */
  53970. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  53971. if( rc==SQLITE_OK ){
  53972. /* Check that the wal file has not been wrapped. Assuming that it has
  53973. ** not, also check that no checkpointer has attempted to checkpoint any
  53974. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  53975. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  53976. ** with *pSnapshot and set *pChanged as appropriate for opening the
  53977. ** snapshot. */
  53978. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  53979. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  53980. ){
  53981. assert( pWal->readLock>0 );
  53982. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  53983. *pChanged = bChanged;
  53984. }else{
  53985. rc = SQLITE_BUSY_SNAPSHOT;
  53986. }
  53987. /* Release the shared CKPT lock obtained above. */
  53988. walUnlockShared(pWal, WAL_CKPT_LOCK);
  53989. }
  53990. if( rc!=SQLITE_OK ){
  53991. sqlite3WalEndReadTransaction(pWal);
  53992. }
  53993. }
  53994. }
  53995. #endif
  53996. return rc;
  53997. }
  53998. /*
  53999. ** Finish with a read transaction. All this does is release the
  54000. ** read-lock.
  54001. */
  54002. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  54003. sqlite3WalEndWriteTransaction(pWal);
  54004. if( pWal->readLock>=0 ){
  54005. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  54006. pWal->readLock = -1;
  54007. }
  54008. }
  54009. /*
  54010. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  54011. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  54012. ** to zero.
  54013. **
  54014. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  54015. ** error does occur, the final value of *piRead is undefined.
  54016. */
  54017. SQLITE_PRIVATE int sqlite3WalFindFrame(
  54018. Wal *pWal, /* WAL handle */
  54019. Pgno pgno, /* Database page number to read data for */
  54020. u32 *piRead /* OUT: Frame number (or zero) */
  54021. ){
  54022. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  54023. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  54024. int iHash; /* Used to loop through N hash tables */
  54025. int iMinHash;
  54026. /* This routine is only be called from within a read transaction. */
  54027. assert( pWal->readLock>=0 || pWal->lockError );
  54028. /* If the "last page" field of the wal-index header snapshot is 0, then
  54029. ** no data will be read from the wal under any circumstances. Return early
  54030. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  54031. ** then the WAL is ignored by the reader so return early, as if the
  54032. ** WAL were empty.
  54033. */
  54034. if( iLast==0 || pWal->readLock==0 ){
  54035. *piRead = 0;
  54036. return SQLITE_OK;
  54037. }
  54038. /* Search the hash table or tables for an entry matching page number
  54039. ** pgno. Each iteration of the following for() loop searches one
  54040. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  54041. **
  54042. ** This code might run concurrently to the code in walIndexAppend()
  54043. ** that adds entries to the wal-index (and possibly to this hash
  54044. ** table). This means the value just read from the hash
  54045. ** slot (aHash[iKey]) may have been added before or after the
  54046. ** current read transaction was opened. Values added after the
  54047. ** read transaction was opened may have been written incorrectly -
  54048. ** i.e. these slots may contain garbage data. However, we assume
  54049. ** that any slots written before the current read transaction was
  54050. ** opened remain unmodified.
  54051. **
  54052. ** For the reasons above, the if(...) condition featured in the inner
  54053. ** loop of the following block is more stringent that would be required
  54054. ** if we had exclusive access to the hash-table:
  54055. **
  54056. ** (aPgno[iFrame]==pgno):
  54057. ** This condition filters out normal hash-table collisions.
  54058. **
  54059. ** (iFrame<=iLast):
  54060. ** This condition filters out entries that were added to the hash
  54061. ** table after the current read-transaction had started.
  54062. */
  54063. iMinHash = walFramePage(pWal->minFrame);
  54064. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  54065. volatile ht_slot *aHash; /* Pointer to hash table */
  54066. volatile u32 *aPgno; /* Pointer to array of page numbers */
  54067. u32 iZero; /* Frame number corresponding to aPgno[0] */
  54068. int iKey; /* Hash slot index */
  54069. int nCollide; /* Number of hash collisions remaining */
  54070. int rc; /* Error code */
  54071. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  54072. if( rc!=SQLITE_OK ){
  54073. return rc;
  54074. }
  54075. nCollide = HASHTABLE_NSLOT;
  54076. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  54077. u32 iFrame = aHash[iKey] + iZero;
  54078. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  54079. assert( iFrame>iRead || CORRUPT_DB );
  54080. iRead = iFrame;
  54081. }
  54082. if( (nCollide--)==0 ){
  54083. return SQLITE_CORRUPT_BKPT;
  54084. }
  54085. }
  54086. }
  54087. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  54088. /* If expensive assert() statements are available, do a linear search
  54089. ** of the wal-index file content. Make sure the results agree with the
  54090. ** result obtained using the hash indexes above. */
  54091. {
  54092. u32 iRead2 = 0;
  54093. u32 iTest;
  54094. assert( pWal->minFrame>0 );
  54095. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  54096. if( walFramePgno(pWal, iTest)==pgno ){
  54097. iRead2 = iTest;
  54098. break;
  54099. }
  54100. }
  54101. assert( iRead==iRead2 );
  54102. }
  54103. #endif
  54104. *piRead = iRead;
  54105. return SQLITE_OK;
  54106. }
  54107. /*
  54108. ** Read the contents of frame iRead from the wal file into buffer pOut
  54109. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  54110. ** error code otherwise.
  54111. */
  54112. SQLITE_PRIVATE int sqlite3WalReadFrame(
  54113. Wal *pWal, /* WAL handle */
  54114. u32 iRead, /* Frame to read */
  54115. int nOut, /* Size of buffer pOut in bytes */
  54116. u8 *pOut /* Buffer to write page data to */
  54117. ){
  54118. int sz;
  54119. i64 iOffset;
  54120. sz = pWal->hdr.szPage;
  54121. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  54122. testcase( sz<=32768 );
  54123. testcase( sz>=65536 );
  54124. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  54125. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  54126. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  54127. }
  54128. /*
  54129. ** Return the size of the database in pages (or zero, if unknown).
  54130. */
  54131. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  54132. if( pWal && ALWAYS(pWal->readLock>=0) ){
  54133. return pWal->hdr.nPage;
  54134. }
  54135. return 0;
  54136. }
  54137. /*
  54138. ** This function starts a write transaction on the WAL.
  54139. **
  54140. ** A read transaction must have already been started by a prior call
  54141. ** to sqlite3WalBeginReadTransaction().
  54142. **
  54143. ** If another thread or process has written into the database since
  54144. ** the read transaction was started, then it is not possible for this
  54145. ** thread to write as doing so would cause a fork. So this routine
  54146. ** returns SQLITE_BUSY in that case and no write transaction is started.
  54147. **
  54148. ** There can only be a single writer active at a time.
  54149. */
  54150. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  54151. int rc;
  54152. /* Cannot start a write transaction without first holding a read
  54153. ** transaction. */
  54154. assert( pWal->readLock>=0 );
  54155. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  54156. if( pWal->readOnly ){
  54157. return SQLITE_READONLY;
  54158. }
  54159. /* Only one writer allowed at a time. Get the write lock. Return
  54160. ** SQLITE_BUSY if unable.
  54161. */
  54162. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  54163. if( rc ){
  54164. return rc;
  54165. }
  54166. pWal->writeLock = 1;
  54167. /* If another connection has written to the database file since the
  54168. ** time the read transaction on this connection was started, then
  54169. ** the write is disallowed.
  54170. */
  54171. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  54172. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  54173. pWal->writeLock = 0;
  54174. rc = SQLITE_BUSY_SNAPSHOT;
  54175. }
  54176. return rc;
  54177. }
  54178. /*
  54179. ** End a write transaction. The commit has already been done. This
  54180. ** routine merely releases the lock.
  54181. */
  54182. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  54183. if( pWal->writeLock ){
  54184. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  54185. pWal->writeLock = 0;
  54186. pWal->iReCksum = 0;
  54187. pWal->truncateOnCommit = 0;
  54188. }
  54189. return SQLITE_OK;
  54190. }
  54191. /*
  54192. ** If any data has been written (but not committed) to the log file, this
  54193. ** function moves the write-pointer back to the start of the transaction.
  54194. **
  54195. ** Additionally, the callback function is invoked for each frame written
  54196. ** to the WAL since the start of the transaction. If the callback returns
  54197. ** other than SQLITE_OK, it is not invoked again and the error code is
  54198. ** returned to the caller.
  54199. **
  54200. ** Otherwise, if the callback function does not return an error, this
  54201. ** function returns SQLITE_OK.
  54202. */
  54203. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  54204. int rc = SQLITE_OK;
  54205. if( ALWAYS(pWal->writeLock) ){
  54206. Pgno iMax = pWal->hdr.mxFrame;
  54207. Pgno iFrame;
  54208. /* Restore the clients cache of the wal-index header to the state it
  54209. ** was in before the client began writing to the database.
  54210. */
  54211. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  54212. for(iFrame=pWal->hdr.mxFrame+1;
  54213. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  54214. iFrame++
  54215. ){
  54216. /* This call cannot fail. Unless the page for which the page number
  54217. ** is passed as the second argument is (a) in the cache and
  54218. ** (b) has an outstanding reference, then xUndo is either a no-op
  54219. ** (if (a) is false) or simply expels the page from the cache (if (b)
  54220. ** is false).
  54221. **
  54222. ** If the upper layer is doing a rollback, it is guaranteed that there
  54223. ** are no outstanding references to any page other than page 1. And
  54224. ** page 1 is never written to the log until the transaction is
  54225. ** committed. As a result, the call to xUndo may not fail.
  54226. */
  54227. assert( walFramePgno(pWal, iFrame)!=1 );
  54228. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  54229. }
  54230. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  54231. }
  54232. return rc;
  54233. }
  54234. /*
  54235. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  54236. ** values. This function populates the array with values required to
  54237. ** "rollback" the write position of the WAL handle back to the current
  54238. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  54239. */
  54240. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  54241. assert( pWal->writeLock );
  54242. aWalData[0] = pWal->hdr.mxFrame;
  54243. aWalData[1] = pWal->hdr.aFrameCksum[0];
  54244. aWalData[2] = pWal->hdr.aFrameCksum[1];
  54245. aWalData[3] = pWal->nCkpt;
  54246. }
  54247. /*
  54248. ** Move the write position of the WAL back to the point identified by
  54249. ** the values in the aWalData[] array. aWalData must point to an array
  54250. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  54251. ** by a call to WalSavepoint().
  54252. */
  54253. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  54254. int rc = SQLITE_OK;
  54255. assert( pWal->writeLock );
  54256. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  54257. if( aWalData[3]!=pWal->nCkpt ){
  54258. /* This savepoint was opened immediately after the write-transaction
  54259. ** was started. Right after that, the writer decided to wrap around
  54260. ** to the start of the log. Update the savepoint values to match.
  54261. */
  54262. aWalData[0] = 0;
  54263. aWalData[3] = pWal->nCkpt;
  54264. }
  54265. if( aWalData[0]<pWal->hdr.mxFrame ){
  54266. pWal->hdr.mxFrame = aWalData[0];
  54267. pWal->hdr.aFrameCksum[0] = aWalData[1];
  54268. pWal->hdr.aFrameCksum[1] = aWalData[2];
  54269. walCleanupHash(pWal);
  54270. }
  54271. return rc;
  54272. }
  54273. /*
  54274. ** This function is called just before writing a set of frames to the log
  54275. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  54276. ** to the current log file, it is possible to overwrite the start of the
  54277. ** existing log file with the new frames (i.e. "reset" the log). If so,
  54278. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  54279. ** unchanged.
  54280. **
  54281. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  54282. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  54283. ** if an error occurs.
  54284. */
  54285. static int walRestartLog(Wal *pWal){
  54286. int rc = SQLITE_OK;
  54287. int cnt;
  54288. if( pWal->readLock==0 ){
  54289. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  54290. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  54291. if( pInfo->nBackfill>0 ){
  54292. u32 salt1;
  54293. sqlite3_randomness(4, &salt1);
  54294. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54295. if( rc==SQLITE_OK ){
  54296. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  54297. ** readers are currently using the WAL), then the transactions
  54298. ** frames will overwrite the start of the existing log. Update the
  54299. ** wal-index header to reflect this.
  54300. **
  54301. ** In theory it would be Ok to update the cache of the header only
  54302. ** at this point. But updating the actual wal-index header is also
  54303. ** safe and means there is no special case for sqlite3WalUndo()
  54304. ** to handle if this transaction is rolled back. */
  54305. walRestartHdr(pWal, salt1);
  54306. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54307. }else if( rc!=SQLITE_BUSY ){
  54308. return rc;
  54309. }
  54310. }
  54311. walUnlockShared(pWal, WAL_READ_LOCK(0));
  54312. pWal->readLock = -1;
  54313. cnt = 0;
  54314. do{
  54315. int notUsed;
  54316. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  54317. }while( rc==WAL_RETRY );
  54318. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  54319. testcase( (rc&0xff)==SQLITE_IOERR );
  54320. testcase( rc==SQLITE_PROTOCOL );
  54321. testcase( rc==SQLITE_OK );
  54322. }
  54323. return rc;
  54324. }
  54325. /*
  54326. ** Information about the current state of the WAL file and where
  54327. ** the next fsync should occur - passed from sqlite3WalFrames() into
  54328. ** walWriteToLog().
  54329. */
  54330. typedef struct WalWriter {
  54331. Wal *pWal; /* The complete WAL information */
  54332. sqlite3_file *pFd; /* The WAL file to which we write */
  54333. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  54334. int syncFlags; /* Flags for the fsync */
  54335. int szPage; /* Size of one page */
  54336. } WalWriter;
  54337. /*
  54338. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  54339. ** Do a sync when crossing the p->iSyncPoint boundary.
  54340. **
  54341. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  54342. ** first write the part before iSyncPoint, then sync, then write the
  54343. ** rest.
  54344. */
  54345. static int walWriteToLog(
  54346. WalWriter *p, /* WAL to write to */
  54347. void *pContent, /* Content to be written */
  54348. int iAmt, /* Number of bytes to write */
  54349. sqlite3_int64 iOffset /* Start writing at this offset */
  54350. ){
  54351. int rc;
  54352. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  54353. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  54354. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  54355. if( rc ) return rc;
  54356. iOffset += iFirstAmt;
  54357. iAmt -= iFirstAmt;
  54358. pContent = (void*)(iFirstAmt + (char*)pContent);
  54359. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  54360. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  54361. if( iAmt==0 || rc ) return rc;
  54362. }
  54363. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  54364. return rc;
  54365. }
  54366. /*
  54367. ** Write out a single frame of the WAL
  54368. */
  54369. static int walWriteOneFrame(
  54370. WalWriter *p, /* Where to write the frame */
  54371. PgHdr *pPage, /* The page of the frame to be written */
  54372. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  54373. sqlite3_int64 iOffset /* Byte offset at which to write */
  54374. ){
  54375. int rc; /* Result code from subfunctions */
  54376. void *pData; /* Data actually written */
  54377. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  54378. #if defined(SQLITE_HAS_CODEC)
  54379. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  54380. #else
  54381. pData = pPage->pData;
  54382. #endif
  54383. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  54384. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  54385. if( rc ) return rc;
  54386. /* Write the page data */
  54387. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  54388. return rc;
  54389. }
  54390. /*
  54391. ** This function is called as part of committing a transaction within which
  54392. ** one or more frames have been overwritten. It updates the checksums for
  54393. ** all frames written to the wal file by the current transaction starting
  54394. ** with the earliest to have been overwritten.
  54395. **
  54396. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  54397. */
  54398. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  54399. const int szPage = pWal->szPage;/* Database page size */
  54400. int rc = SQLITE_OK; /* Return code */
  54401. u8 *aBuf; /* Buffer to load data from wal file into */
  54402. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  54403. u32 iRead; /* Next frame to read from wal file */
  54404. i64 iCksumOff;
  54405. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  54406. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  54407. /* Find the checksum values to use as input for the recalculating the
  54408. ** first checksum. If the first frame is frame 1 (implying that the current
  54409. ** transaction restarted the wal file), these values must be read from the
  54410. ** wal-file header. Otherwise, read them from the frame header of the
  54411. ** previous frame. */
  54412. assert( pWal->iReCksum>0 );
  54413. if( pWal->iReCksum==1 ){
  54414. iCksumOff = 24;
  54415. }else{
  54416. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  54417. }
  54418. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  54419. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  54420. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  54421. iRead = pWal->iReCksum;
  54422. pWal->iReCksum = 0;
  54423. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  54424. i64 iOff = walFrameOffset(iRead, szPage);
  54425. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  54426. if( rc==SQLITE_OK ){
  54427. u32 iPgno, nDbSize;
  54428. iPgno = sqlite3Get4byte(aBuf);
  54429. nDbSize = sqlite3Get4byte(&aBuf[4]);
  54430. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  54431. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  54432. }
  54433. }
  54434. sqlite3_free(aBuf);
  54435. return rc;
  54436. }
  54437. /*
  54438. ** Write a set of frames to the log. The caller must hold the write-lock
  54439. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  54440. */
  54441. SQLITE_PRIVATE int sqlite3WalFrames(
  54442. Wal *pWal, /* Wal handle to write to */
  54443. int szPage, /* Database page-size in bytes */
  54444. PgHdr *pList, /* List of dirty pages to write */
  54445. Pgno nTruncate, /* Database size after this commit */
  54446. int isCommit, /* True if this is a commit */
  54447. int sync_flags /* Flags to pass to OsSync() (or 0) */
  54448. ){
  54449. int rc; /* Used to catch return codes */
  54450. u32 iFrame; /* Next frame address */
  54451. PgHdr *p; /* Iterator to run through pList with. */
  54452. PgHdr *pLast = 0; /* Last frame in list */
  54453. int nExtra = 0; /* Number of extra copies of last page */
  54454. int szFrame; /* The size of a single frame */
  54455. i64 iOffset; /* Next byte to write in WAL file */
  54456. WalWriter w; /* The writer */
  54457. u32 iFirst = 0; /* First frame that may be overwritten */
  54458. WalIndexHdr *pLive; /* Pointer to shared header */
  54459. assert( pList );
  54460. assert( pWal->writeLock );
  54461. /* If this frame set completes a transaction, then nTruncate>0. If
  54462. ** nTruncate==0 then this frame set does not complete the transaction. */
  54463. assert( (isCommit!=0)==(nTruncate!=0) );
  54464. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  54465. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  54466. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  54467. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  54468. }
  54469. #endif
  54470. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  54471. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  54472. iFirst = pLive->mxFrame+1;
  54473. }
  54474. /* See if it is possible to write these frames into the start of the
  54475. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  54476. */
  54477. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  54478. return rc;
  54479. }
  54480. /* If this is the first frame written into the log, write the WAL
  54481. ** header to the start of the WAL file. See comments at the top of
  54482. ** this source file for a description of the WAL header format.
  54483. */
  54484. iFrame = pWal->hdr.mxFrame;
  54485. if( iFrame==0 ){
  54486. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  54487. u32 aCksum[2]; /* Checksum for wal-header */
  54488. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  54489. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  54490. sqlite3Put4byte(&aWalHdr[8], szPage);
  54491. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  54492. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  54493. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  54494. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  54495. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  54496. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  54497. pWal->szPage = szPage;
  54498. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  54499. pWal->hdr.aFrameCksum[0] = aCksum[0];
  54500. pWal->hdr.aFrameCksum[1] = aCksum[1];
  54501. pWal->truncateOnCommit = 1;
  54502. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  54503. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  54504. if( rc!=SQLITE_OK ){
  54505. return rc;
  54506. }
  54507. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  54508. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  54509. ** an out-of-order write following a WAL restart could result in
  54510. ** database corruption. See the ticket:
  54511. **
  54512. ** https://sqlite.org/src/info/ff5be73dee
  54513. */
  54514. if( pWal->syncHeader ){
  54515. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  54516. if( rc ) return rc;
  54517. }
  54518. }
  54519. assert( (int)pWal->szPage==szPage );
  54520. /* Setup information needed to write frames into the WAL */
  54521. w.pWal = pWal;
  54522. w.pFd = pWal->pWalFd;
  54523. w.iSyncPoint = 0;
  54524. w.syncFlags = sync_flags;
  54525. w.szPage = szPage;
  54526. iOffset = walFrameOffset(iFrame+1, szPage);
  54527. szFrame = szPage + WAL_FRAME_HDRSIZE;
  54528. /* Write all frames into the log file exactly once */
  54529. for(p=pList; p; p=p->pDirty){
  54530. int nDbSize; /* 0 normally. Positive == commit flag */
  54531. /* Check if this page has already been written into the wal file by
  54532. ** the current transaction. If so, overwrite the existing frame and
  54533. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  54534. ** checksums must be recomputed when the transaction is committed. */
  54535. if( iFirst && (p->pDirty || isCommit==0) ){
  54536. u32 iWrite = 0;
  54537. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  54538. assert( rc==SQLITE_OK || iWrite==0 );
  54539. if( iWrite>=iFirst ){
  54540. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  54541. void *pData;
  54542. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  54543. pWal->iReCksum = iWrite;
  54544. }
  54545. #if defined(SQLITE_HAS_CODEC)
  54546. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  54547. #else
  54548. pData = p->pData;
  54549. #endif
  54550. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  54551. if( rc ) return rc;
  54552. p->flags &= ~PGHDR_WAL_APPEND;
  54553. continue;
  54554. }
  54555. }
  54556. iFrame++;
  54557. assert( iOffset==walFrameOffset(iFrame, szPage) );
  54558. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  54559. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  54560. if( rc ) return rc;
  54561. pLast = p;
  54562. iOffset += szFrame;
  54563. p->flags |= PGHDR_WAL_APPEND;
  54564. }
  54565. /* Recalculate checksums within the wal file if required. */
  54566. if( isCommit && pWal->iReCksum ){
  54567. rc = walRewriteChecksums(pWal, iFrame);
  54568. if( rc ) return rc;
  54569. }
  54570. /* If this is the end of a transaction, then we might need to pad
  54571. ** the transaction and/or sync the WAL file.
  54572. **
  54573. ** Padding and syncing only occur if this set of frames complete a
  54574. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  54575. ** or synchronous==OFF, then no padding or syncing are needed.
  54576. **
  54577. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  54578. ** needed and only the sync is done. If padding is needed, then the
  54579. ** final frame is repeated (with its commit mark) until the next sector
  54580. ** boundary is crossed. Only the part of the WAL prior to the last
  54581. ** sector boundary is synced; the part of the last frame that extends
  54582. ** past the sector boundary is written after the sync.
  54583. */
  54584. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  54585. int bSync = 1;
  54586. if( pWal->padToSectorBoundary ){
  54587. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  54588. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  54589. bSync = (w.iSyncPoint==iOffset);
  54590. testcase( bSync );
  54591. while( iOffset<w.iSyncPoint ){
  54592. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  54593. if( rc ) return rc;
  54594. iOffset += szFrame;
  54595. nExtra++;
  54596. }
  54597. }
  54598. if( bSync ){
  54599. assert( rc==SQLITE_OK );
  54600. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  54601. }
  54602. }
  54603. /* If this frame set completes the first transaction in the WAL and
  54604. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  54605. ** journal size limit, if possible.
  54606. */
  54607. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  54608. i64 sz = pWal->mxWalSize;
  54609. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  54610. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  54611. }
  54612. walLimitSize(pWal, sz);
  54613. pWal->truncateOnCommit = 0;
  54614. }
  54615. /* Append data to the wal-index. It is not necessary to lock the
  54616. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  54617. ** guarantees that there are no other writers, and no data that may
  54618. ** be in use by existing readers is being overwritten.
  54619. */
  54620. iFrame = pWal->hdr.mxFrame;
  54621. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  54622. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  54623. iFrame++;
  54624. rc = walIndexAppend(pWal, iFrame, p->pgno);
  54625. }
  54626. while( rc==SQLITE_OK && nExtra>0 ){
  54627. iFrame++;
  54628. nExtra--;
  54629. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  54630. }
  54631. if( rc==SQLITE_OK ){
  54632. /* Update the private copy of the header. */
  54633. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  54634. testcase( szPage<=32768 );
  54635. testcase( szPage>=65536 );
  54636. pWal->hdr.mxFrame = iFrame;
  54637. if( isCommit ){
  54638. pWal->hdr.iChange++;
  54639. pWal->hdr.nPage = nTruncate;
  54640. }
  54641. /* If this is a commit, update the wal-index header too. */
  54642. if( isCommit ){
  54643. walIndexWriteHdr(pWal);
  54644. pWal->iCallback = iFrame;
  54645. }
  54646. }
  54647. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  54648. return rc;
  54649. }
  54650. /*
  54651. ** This routine is called to implement sqlite3_wal_checkpoint() and
  54652. ** related interfaces.
  54653. **
  54654. ** Obtain a CHECKPOINT lock and then backfill as much information as
  54655. ** we can from WAL into the database.
  54656. **
  54657. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  54658. ** callback. In this case this function runs a blocking checkpoint.
  54659. */
  54660. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  54661. Wal *pWal, /* Wal connection */
  54662. sqlite3 *db, /* Check this handle's interrupt flag */
  54663. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  54664. int (*xBusy)(void*), /* Function to call when busy */
  54665. void *pBusyArg, /* Context argument for xBusyHandler */
  54666. int sync_flags, /* Flags to sync db file with (or 0) */
  54667. int nBuf, /* Size of temporary buffer */
  54668. u8 *zBuf, /* Temporary buffer to use */
  54669. int *pnLog, /* OUT: Number of frames in WAL */
  54670. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  54671. ){
  54672. int rc; /* Return code */
  54673. int isChanged = 0; /* True if a new wal-index header is loaded */
  54674. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  54675. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  54676. assert( pWal->ckptLock==0 );
  54677. assert( pWal->writeLock==0 );
  54678. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  54679. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  54680. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  54681. if( pWal->readOnly ) return SQLITE_READONLY;
  54682. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  54683. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  54684. ** "checkpoint" lock on the database file. */
  54685. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54686. if( rc ){
  54687. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  54688. ** checkpoint operation at the same time, the lock cannot be obtained and
  54689. ** SQLITE_BUSY is returned.
  54690. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  54691. ** it will not be invoked in this case.
  54692. */
  54693. testcase( rc==SQLITE_BUSY );
  54694. testcase( xBusy!=0 );
  54695. return rc;
  54696. }
  54697. pWal->ckptLock = 1;
  54698. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  54699. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  54700. ** file.
  54701. **
  54702. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  54703. ** immediately, and a busy-handler is configured, it is invoked and the
  54704. ** writer lock retried until either the busy-handler returns 0 or the
  54705. ** lock is successfully obtained.
  54706. */
  54707. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  54708. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  54709. if( rc==SQLITE_OK ){
  54710. pWal->writeLock = 1;
  54711. }else if( rc==SQLITE_BUSY ){
  54712. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  54713. xBusy2 = 0;
  54714. rc = SQLITE_OK;
  54715. }
  54716. }
  54717. /* Read the wal-index header. */
  54718. if( rc==SQLITE_OK ){
  54719. rc = walIndexReadHdr(pWal, &isChanged);
  54720. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  54721. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  54722. }
  54723. }
  54724. /* Copy data from the log to the database file. */
  54725. if( rc==SQLITE_OK ){
  54726. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  54727. rc = SQLITE_CORRUPT_BKPT;
  54728. }else{
  54729. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  54730. }
  54731. /* If no error occurred, set the output variables. */
  54732. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  54733. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  54734. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  54735. }
  54736. }
  54737. if( isChanged ){
  54738. /* If a new wal-index header was loaded before the checkpoint was
  54739. ** performed, then the pager-cache associated with pWal is now
  54740. ** out of date. So zero the cached wal-index header to ensure that
  54741. ** next time the pager opens a snapshot on this database it knows that
  54742. ** the cache needs to be reset.
  54743. */
  54744. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  54745. }
  54746. /* Release the locks. */
  54747. sqlite3WalEndWriteTransaction(pWal);
  54748. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54749. pWal->ckptLock = 0;
  54750. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  54751. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  54752. }
  54753. /* Return the value to pass to a sqlite3_wal_hook callback, the
  54754. ** number of frames in the WAL at the point of the last commit since
  54755. ** sqlite3WalCallback() was called. If no commits have occurred since
  54756. ** the last call, then return 0.
  54757. */
  54758. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  54759. u32 ret = 0;
  54760. if( pWal ){
  54761. ret = pWal->iCallback;
  54762. pWal->iCallback = 0;
  54763. }
  54764. return (int)ret;
  54765. }
  54766. /*
  54767. ** This function is called to change the WAL subsystem into or out
  54768. ** of locking_mode=EXCLUSIVE.
  54769. **
  54770. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  54771. ** into locking_mode=NORMAL. This means that we must acquire a lock
  54772. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  54773. ** or if the acquisition of the lock fails, then return 0. If the
  54774. ** transition out of exclusive-mode is successful, return 1. This
  54775. ** operation must occur while the pager is still holding the exclusive
  54776. ** lock on the main database file.
  54777. **
  54778. ** If op is one, then change from locking_mode=NORMAL into
  54779. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  54780. ** be released. Return 1 if the transition is made and 0 if the
  54781. ** WAL is already in exclusive-locking mode - meaning that this
  54782. ** routine is a no-op. The pager must already hold the exclusive lock
  54783. ** on the main database file before invoking this operation.
  54784. **
  54785. ** If op is negative, then do a dry-run of the op==1 case but do
  54786. ** not actually change anything. The pager uses this to see if it
  54787. ** should acquire the database exclusive lock prior to invoking
  54788. ** the op==1 case.
  54789. */
  54790. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  54791. int rc;
  54792. assert( pWal->writeLock==0 );
  54793. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  54794. /* pWal->readLock is usually set, but might be -1 if there was a
  54795. ** prior error while attempting to acquire are read-lock. This cannot
  54796. ** happen if the connection is actually in exclusive mode (as no xShmLock
  54797. ** locks are taken in this case). Nor should the pager attempt to
  54798. ** upgrade to exclusive-mode following such an error.
  54799. */
  54800. assert( pWal->readLock>=0 || pWal->lockError );
  54801. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  54802. if( op==0 ){
  54803. if( pWal->exclusiveMode ){
  54804. pWal->exclusiveMode = 0;
  54805. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  54806. pWal->exclusiveMode = 1;
  54807. }
  54808. rc = pWal->exclusiveMode==0;
  54809. }else{
  54810. /* Already in locking_mode=NORMAL */
  54811. rc = 0;
  54812. }
  54813. }else if( op>0 ){
  54814. assert( pWal->exclusiveMode==0 );
  54815. assert( pWal->readLock>=0 );
  54816. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  54817. pWal->exclusiveMode = 1;
  54818. rc = 1;
  54819. }else{
  54820. rc = pWal->exclusiveMode==0;
  54821. }
  54822. return rc;
  54823. }
  54824. /*
  54825. ** Return true if the argument is non-NULL and the WAL module is using
  54826. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  54827. ** WAL module is using shared-memory, return false.
  54828. */
  54829. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  54830. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  54831. }
  54832. #ifdef SQLITE_ENABLE_SNAPSHOT
  54833. /* Create a snapshot object. The content of a snapshot is opaque to
  54834. ** every other subsystem, so the WAL module can put whatever it needs
  54835. ** in the object.
  54836. */
  54837. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  54838. int rc = SQLITE_OK;
  54839. WalIndexHdr *pRet;
  54840. static const u32 aZero[4] = { 0, 0, 0, 0 };
  54841. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  54842. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  54843. *ppSnapshot = 0;
  54844. return SQLITE_ERROR;
  54845. }
  54846. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  54847. if( pRet==0 ){
  54848. rc = SQLITE_NOMEM_BKPT;
  54849. }else{
  54850. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  54851. *ppSnapshot = (sqlite3_snapshot*)pRet;
  54852. }
  54853. return rc;
  54854. }
  54855. /* Try to open on pSnapshot when the next read-transaction starts
  54856. */
  54857. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  54858. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  54859. }
  54860. /*
  54861. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  54862. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  54863. */
  54864. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  54865. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  54866. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  54867. /* aSalt[0] is a copy of the value stored in the wal file header. It
  54868. ** is incremented each time the wal file is restarted. */
  54869. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  54870. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  54871. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  54872. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  54873. return 0;
  54874. }
  54875. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54876. #ifdef SQLITE_ENABLE_ZIPVFS
  54877. /*
  54878. ** If the argument is not NULL, it points to a Wal object that holds a
  54879. ** read-lock. This function returns the database page-size if it is known,
  54880. ** or zero if it is not (or if pWal is NULL).
  54881. */
  54882. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  54883. assert( pWal==0 || pWal->readLock>=0 );
  54884. return (pWal ? pWal->szPage : 0);
  54885. }
  54886. #endif
  54887. /* Return the sqlite3_file object for the WAL file
  54888. */
  54889. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  54890. return pWal->pWalFd;
  54891. }
  54892. #endif /* #ifndef SQLITE_OMIT_WAL */
  54893. /************** End of wal.c *************************************************/
  54894. /************** Begin file btmutex.c *****************************************/
  54895. /*
  54896. ** 2007 August 27
  54897. **
  54898. ** The author disclaims copyright to this source code. In place of
  54899. ** a legal notice, here is a blessing:
  54900. **
  54901. ** May you do good and not evil.
  54902. ** May you find forgiveness for yourself and forgive others.
  54903. ** May you share freely, never taking more than you give.
  54904. **
  54905. *************************************************************************
  54906. **
  54907. ** This file contains code used to implement mutexes on Btree objects.
  54908. ** This code really belongs in btree.c. But btree.c is getting too
  54909. ** big and we want to break it down some. This packaged seemed like
  54910. ** a good breakout.
  54911. */
  54912. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  54913. /************** Begin file btreeInt.h ****************************************/
  54914. /*
  54915. ** 2004 April 6
  54916. **
  54917. ** The author disclaims copyright to this source code. In place of
  54918. ** a legal notice, here is a blessing:
  54919. **
  54920. ** May you do good and not evil.
  54921. ** May you find forgiveness for yourself and forgive others.
  54922. ** May you share freely, never taking more than you give.
  54923. **
  54924. *************************************************************************
  54925. ** This file implements an external (disk-based) database using BTrees.
  54926. ** For a detailed discussion of BTrees, refer to
  54927. **
  54928. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  54929. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  54930. ** Publishing Company, Reading, Massachusetts.
  54931. **
  54932. ** The basic idea is that each page of the file contains N database
  54933. ** entries and N+1 pointers to subpages.
  54934. **
  54935. ** ----------------------------------------------------------------
  54936. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  54937. ** ----------------------------------------------------------------
  54938. **
  54939. ** All of the keys on the page that Ptr(0) points to have values less
  54940. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  54941. ** values greater than Key(0) and less than Key(1). All of the keys
  54942. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  54943. ** so forth.
  54944. **
  54945. ** Finding a particular key requires reading O(log(M)) pages from the
  54946. ** disk where M is the number of entries in the tree.
  54947. **
  54948. ** In this implementation, a single file can hold one or more separate
  54949. ** BTrees. Each BTree is identified by the index of its root page. The
  54950. ** key and data for any entry are combined to form the "payload". A
  54951. ** fixed amount of payload can be carried directly on the database
  54952. ** page. If the payload is larger than the preset amount then surplus
  54953. ** bytes are stored on overflow pages. The payload for an entry
  54954. ** and the preceding pointer are combined to form a "Cell". Each
  54955. ** page has a small header which contains the Ptr(N) pointer and other
  54956. ** information such as the size of key and data.
  54957. **
  54958. ** FORMAT DETAILS
  54959. **
  54960. ** The file is divided into pages. The first page is called page 1,
  54961. ** the second is page 2, and so forth. A page number of zero indicates
  54962. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  54963. ** Each page can be either a btree page, a freelist page, an overflow
  54964. ** page, or a pointer-map page.
  54965. **
  54966. ** The first page is always a btree page. The first 100 bytes of the first
  54967. ** page contain a special header (the "file header") that describes the file.
  54968. ** The format of the file header is as follows:
  54969. **
  54970. ** OFFSET SIZE DESCRIPTION
  54971. ** 0 16 Header string: "SQLite format 3\000"
  54972. ** 16 2 Page size in bytes. (1 means 65536)
  54973. ** 18 1 File format write version
  54974. ** 19 1 File format read version
  54975. ** 20 1 Bytes of unused space at the end of each page
  54976. ** 21 1 Max embedded payload fraction (must be 64)
  54977. ** 22 1 Min embedded payload fraction (must be 32)
  54978. ** 23 1 Min leaf payload fraction (must be 32)
  54979. ** 24 4 File change counter
  54980. ** 28 4 Reserved for future use
  54981. ** 32 4 First freelist page
  54982. ** 36 4 Number of freelist pages in the file
  54983. ** 40 60 15 4-byte meta values passed to higher layers
  54984. **
  54985. ** 40 4 Schema cookie
  54986. ** 44 4 File format of schema layer
  54987. ** 48 4 Size of page cache
  54988. ** 52 4 Largest root-page (auto/incr_vacuum)
  54989. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  54990. ** 60 4 User version
  54991. ** 64 4 Incremental vacuum mode
  54992. ** 68 4 Application-ID
  54993. ** 72 20 unused
  54994. ** 92 4 The version-valid-for number
  54995. ** 96 4 SQLITE_VERSION_NUMBER
  54996. **
  54997. ** All of the integer values are big-endian (most significant byte first).
  54998. **
  54999. ** The file change counter is incremented when the database is changed
  55000. ** This counter allows other processes to know when the file has changed
  55001. ** and thus when they need to flush their cache.
  55002. **
  55003. ** The max embedded payload fraction is the amount of the total usable
  55004. ** space in a page that can be consumed by a single cell for standard
  55005. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  55006. ** is to limit the maximum cell size so that at least 4 cells will fit
  55007. ** on one page. Thus the default max embedded payload fraction is 64.
  55008. **
  55009. ** If the payload for a cell is larger than the max payload, then extra
  55010. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  55011. ** as many bytes as possible are moved into the overflow pages without letting
  55012. ** the cell size drop below the min embedded payload fraction.
  55013. **
  55014. ** The min leaf payload fraction is like the min embedded payload fraction
  55015. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  55016. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  55017. ** not specified in the header.
  55018. **
  55019. ** Each btree pages is divided into three sections: The header, the
  55020. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  55021. ** file header that occurs before the page header.
  55022. **
  55023. ** |----------------|
  55024. ** | file header | 100 bytes. Page 1 only.
  55025. ** |----------------|
  55026. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  55027. ** |----------------|
  55028. ** | cell pointer | | 2 bytes per cell. Sorted order.
  55029. ** | array | | Grows downward
  55030. ** | | v
  55031. ** |----------------|
  55032. ** | unallocated |
  55033. ** | space |
  55034. ** |----------------| ^ Grows upwards
  55035. ** | cell content | | Arbitrary order interspersed with freeblocks.
  55036. ** | area | | and free space fragments.
  55037. ** |----------------|
  55038. **
  55039. ** The page headers looks like this:
  55040. **
  55041. ** OFFSET SIZE DESCRIPTION
  55042. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  55043. ** 1 2 byte offset to the first freeblock
  55044. ** 3 2 number of cells on this page
  55045. ** 5 2 first byte of the cell content area
  55046. ** 7 1 number of fragmented free bytes
  55047. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  55048. **
  55049. ** The flags define the format of this btree page. The leaf flag means that
  55050. ** this page has no children. The zerodata flag means that this page carries
  55051. ** only keys and no data. The intkey flag means that the key is an integer
  55052. ** which is stored in the key size entry of the cell header rather than in
  55053. ** the payload area.
  55054. **
  55055. ** The cell pointer array begins on the first byte after the page header.
  55056. ** The cell pointer array contains zero or more 2-byte numbers which are
  55057. ** offsets from the beginning of the page to the cell content in the cell
  55058. ** content area. The cell pointers occur in sorted order. The system strives
  55059. ** to keep free space after the last cell pointer so that new cells can
  55060. ** be easily added without having to defragment the page.
  55061. **
  55062. ** Cell content is stored at the very end of the page and grows toward the
  55063. ** beginning of the page.
  55064. **
  55065. ** Unused space within the cell content area is collected into a linked list of
  55066. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  55067. ** to the first freeblock is given in the header. Freeblocks occur in
  55068. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  55069. ** any group of 3 or fewer unused bytes in the cell content area cannot
  55070. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  55071. ** a fragment. The total number of bytes in all fragments is recorded.
  55072. ** in the page header at offset 7.
  55073. **
  55074. ** SIZE DESCRIPTION
  55075. ** 2 Byte offset of the next freeblock
  55076. ** 2 Bytes in this freeblock
  55077. **
  55078. ** Cells are of variable length. Cells are stored in the cell content area at
  55079. ** the end of the page. Pointers to the cells are in the cell pointer array
  55080. ** that immediately follows the page header. Cells is not necessarily
  55081. ** contiguous or in order, but cell pointers are contiguous and in order.
  55082. **
  55083. ** Cell content makes use of variable length integers. A variable
  55084. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  55085. ** byte are used. The integer consists of all bytes that have bit 8 set and
  55086. ** the first byte with bit 8 clear. The most significant byte of the integer
  55087. ** appears first. A variable-length integer may not be more than 9 bytes long.
  55088. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  55089. ** allows a 64-bit integer to be encoded in 9 bytes.
  55090. **
  55091. ** 0x00 becomes 0x00000000
  55092. ** 0x7f becomes 0x0000007f
  55093. ** 0x81 0x00 becomes 0x00000080
  55094. ** 0x82 0x00 becomes 0x00000100
  55095. ** 0x80 0x7f becomes 0x0000007f
  55096. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  55097. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  55098. **
  55099. ** Variable length integers are used for rowids and to hold the number of
  55100. ** bytes of key and data in a btree cell.
  55101. **
  55102. ** The content of a cell looks like this:
  55103. **
  55104. ** SIZE DESCRIPTION
  55105. ** 4 Page number of the left child. Omitted if leaf flag is set.
  55106. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  55107. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  55108. ** * Payload
  55109. ** 4 First page of the overflow chain. Omitted if no overflow
  55110. **
  55111. ** Overflow pages form a linked list. Each page except the last is completely
  55112. ** filled with data (pagesize - 4 bytes). The last page can have as little
  55113. ** as 1 byte of data.
  55114. **
  55115. ** SIZE DESCRIPTION
  55116. ** 4 Page number of next overflow page
  55117. ** * Data
  55118. **
  55119. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  55120. ** file header points to the first in a linked list of trunk page. Each trunk
  55121. ** page points to multiple leaf pages. The content of a leaf page is
  55122. ** unspecified. A trunk page looks like this:
  55123. **
  55124. ** SIZE DESCRIPTION
  55125. ** 4 Page number of next trunk page
  55126. ** 4 Number of leaf pointers on this page
  55127. ** * zero or more pages numbers of leaves
  55128. */
  55129. /* #include "sqliteInt.h" */
  55130. /* The following value is the maximum cell size assuming a maximum page
  55131. ** size give above.
  55132. */
  55133. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  55134. /* The maximum number of cells on a single page of the database. This
  55135. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  55136. ** plus 2 bytes for the index to the cell in the page header). Such
  55137. ** small cells will be rare, but they are possible.
  55138. */
  55139. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  55140. /* Forward declarations */
  55141. typedef struct MemPage MemPage;
  55142. typedef struct BtLock BtLock;
  55143. typedef struct CellInfo CellInfo;
  55144. /*
  55145. ** This is a magic string that appears at the beginning of every
  55146. ** SQLite database in order to identify the file as a real database.
  55147. **
  55148. ** You can change this value at compile-time by specifying a
  55149. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  55150. ** header must be exactly 16 bytes including the zero-terminator so
  55151. ** the string itself should be 15 characters long. If you change
  55152. ** the header, then your custom library will not be able to read
  55153. ** databases generated by the standard tools and the standard tools
  55154. ** will not be able to read databases created by your custom library.
  55155. */
  55156. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  55157. # define SQLITE_FILE_HEADER "SQLite format 3"
  55158. #endif
  55159. /*
  55160. ** Page type flags. An ORed combination of these flags appear as the
  55161. ** first byte of on-disk image of every BTree page.
  55162. */
  55163. #define PTF_INTKEY 0x01
  55164. #define PTF_ZERODATA 0x02
  55165. #define PTF_LEAFDATA 0x04
  55166. #define PTF_LEAF 0x08
  55167. /*
  55168. ** An instance of this object stores information about each a single database
  55169. ** page that has been loaded into memory. The information in this object
  55170. ** is derived from the raw on-disk page content.
  55171. **
  55172. ** As each database page is loaded into memory, the pager allocats an
  55173. ** instance of this object and zeros the first 8 bytes. (This is the
  55174. ** "extra" information associated with each page of the pager.)
  55175. **
  55176. ** Access to all fields of this structure is controlled by the mutex
  55177. ** stored in MemPage.pBt->mutex.
  55178. */
  55179. struct MemPage {
  55180. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  55181. u8 bBusy; /* Prevent endless loops on corrupt database files */
  55182. u8 intKey; /* True if table b-trees. False for index b-trees */
  55183. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  55184. Pgno pgno; /* Page number for this page */
  55185. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  55186. ** is allocated. All fields that follow must be initialized before use */
  55187. u8 leaf; /* True if a leaf page */
  55188. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  55189. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  55190. u8 max1bytePayload; /* min(maxLocal,127) */
  55191. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  55192. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  55193. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  55194. u16 cellOffset; /* Index in aData of first cell pointer */
  55195. u16 nFree; /* Number of free bytes on the page */
  55196. u16 nCell; /* Number of cells on this page, local and ovfl */
  55197. u16 maskPage; /* Mask for page offset */
  55198. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  55199. ** non-overflow cell */
  55200. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  55201. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  55202. u8 *aData; /* Pointer to disk image of the page data */
  55203. u8 *aDataEnd; /* One byte past the end of usable data */
  55204. u8 *aCellIdx; /* The cell index area */
  55205. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  55206. DbPage *pDbPage; /* Pager page handle */
  55207. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  55208. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  55209. };
  55210. /*
  55211. ** A linked list of the following structures is stored at BtShared.pLock.
  55212. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  55213. ** is opened on the table with root page BtShared.iTable. Locks are removed
  55214. ** from this list when a transaction is committed or rolled back, or when
  55215. ** a btree handle is closed.
  55216. */
  55217. struct BtLock {
  55218. Btree *pBtree; /* Btree handle holding this lock */
  55219. Pgno iTable; /* Root page of table */
  55220. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  55221. BtLock *pNext; /* Next in BtShared.pLock list */
  55222. };
  55223. /* Candidate values for BtLock.eLock */
  55224. #define READ_LOCK 1
  55225. #define WRITE_LOCK 2
  55226. /* A Btree handle
  55227. **
  55228. ** A database connection contains a pointer to an instance of
  55229. ** this object for every database file that it has open. This structure
  55230. ** is opaque to the database connection. The database connection cannot
  55231. ** see the internals of this structure and only deals with pointers to
  55232. ** this structure.
  55233. **
  55234. ** For some database files, the same underlying database cache might be
  55235. ** shared between multiple connections. In that case, each connection
  55236. ** has it own instance of this object. But each instance of this object
  55237. ** points to the same BtShared object. The database cache and the
  55238. ** schema associated with the database file are all contained within
  55239. ** the BtShared object.
  55240. **
  55241. ** All fields in this structure are accessed under sqlite3.mutex.
  55242. ** The pBt pointer itself may not be changed while there exists cursors
  55243. ** in the referenced BtShared that point back to this Btree since those
  55244. ** cursors have to go through this Btree to find their BtShared and
  55245. ** they often do so without holding sqlite3.mutex.
  55246. */
  55247. struct Btree {
  55248. sqlite3 *db; /* The database connection holding this btree */
  55249. BtShared *pBt; /* Sharable content of this btree */
  55250. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  55251. u8 sharable; /* True if we can share pBt with another db */
  55252. u8 locked; /* True if db currently has pBt locked */
  55253. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  55254. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  55255. int nBackup; /* Number of backup operations reading this btree */
  55256. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  55257. Btree *pNext; /* List of other sharable Btrees from the same db */
  55258. Btree *pPrev; /* Back pointer of the same list */
  55259. #ifndef SQLITE_OMIT_SHARED_CACHE
  55260. BtLock lock; /* Object used to lock page 1 */
  55261. #endif
  55262. };
  55263. /*
  55264. ** Btree.inTrans may take one of the following values.
  55265. **
  55266. ** If the shared-data extension is enabled, there may be multiple users
  55267. ** of the Btree structure. At most one of these may open a write transaction,
  55268. ** but any number may have active read transactions.
  55269. */
  55270. #define TRANS_NONE 0
  55271. #define TRANS_READ 1
  55272. #define TRANS_WRITE 2
  55273. /*
  55274. ** An instance of this object represents a single database file.
  55275. **
  55276. ** A single database file can be in use at the same time by two
  55277. ** or more database connections. When two or more connections are
  55278. ** sharing the same database file, each connection has it own
  55279. ** private Btree object for the file and each of those Btrees points
  55280. ** to this one BtShared object. BtShared.nRef is the number of
  55281. ** connections currently sharing this database file.
  55282. **
  55283. ** Fields in this structure are accessed under the BtShared.mutex
  55284. ** mutex, except for nRef and pNext which are accessed under the
  55285. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  55286. ** may not be modified once it is initially set as long as nRef>0.
  55287. ** The pSchema field may be set once under BtShared.mutex and
  55288. ** thereafter is unchanged as long as nRef>0.
  55289. **
  55290. ** isPending:
  55291. **
  55292. ** If a BtShared client fails to obtain a write-lock on a database
  55293. ** table (because there exists one or more read-locks on the table),
  55294. ** the shared-cache enters 'pending-lock' state and isPending is
  55295. ** set to true.
  55296. **
  55297. ** The shared-cache leaves the 'pending lock' state when either of
  55298. ** the following occur:
  55299. **
  55300. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  55301. ** 2) The number of locks held by other connections drops to zero.
  55302. **
  55303. ** while in the 'pending-lock' state, no connection may start a new
  55304. ** transaction.
  55305. **
  55306. ** This feature is included to help prevent writer-starvation.
  55307. */
  55308. struct BtShared {
  55309. Pager *pPager; /* The page cache */
  55310. sqlite3 *db; /* Database connection currently using this Btree */
  55311. BtCursor *pCursor; /* A list of all open cursors */
  55312. MemPage *pPage1; /* First page of the database */
  55313. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  55314. #ifndef SQLITE_OMIT_AUTOVACUUM
  55315. u8 autoVacuum; /* True if auto-vacuum is enabled */
  55316. u8 incrVacuum; /* True if incr-vacuum is enabled */
  55317. u8 bDoTruncate; /* True to truncate db on commit */
  55318. #endif
  55319. u8 inTransaction; /* Transaction state */
  55320. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  55321. #ifdef SQLITE_HAS_CODEC
  55322. u8 optimalReserve; /* Desired amount of reserved space per page */
  55323. #endif
  55324. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  55325. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  55326. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  55327. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  55328. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  55329. u32 pageSize; /* Total number of bytes on a page */
  55330. u32 usableSize; /* Number of usable bytes on each page */
  55331. int nTransaction; /* Number of open transactions (read + write) */
  55332. u32 nPage; /* Number of pages in the database */
  55333. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  55334. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  55335. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  55336. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  55337. #ifndef SQLITE_OMIT_SHARED_CACHE
  55338. int nRef; /* Number of references to this structure */
  55339. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  55340. BtLock *pLock; /* List of locks held on this shared-btree struct */
  55341. Btree *pWriter; /* Btree with currently open write transaction */
  55342. #endif
  55343. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  55344. };
  55345. /*
  55346. ** Allowed values for BtShared.btsFlags
  55347. */
  55348. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  55349. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  55350. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  55351. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  55352. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  55353. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  55354. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  55355. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  55356. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  55357. /*
  55358. ** An instance of the following structure is used to hold information
  55359. ** about a cell. The parseCellPtr() function fills in this structure
  55360. ** based on information extract from the raw disk page.
  55361. */
  55362. struct CellInfo {
  55363. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  55364. u8 *pPayload; /* Pointer to the start of payload */
  55365. u32 nPayload; /* Bytes of payload */
  55366. u16 nLocal; /* Amount of payload held locally, not on overflow */
  55367. u16 nSize; /* Size of the cell content on the main b-tree page */
  55368. };
  55369. /*
  55370. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  55371. ** this will be declared corrupt. This value is calculated based on a
  55372. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  55373. ** root-node and 3 for all other internal nodes.
  55374. **
  55375. ** If a tree that appears to be taller than this is encountered, it is
  55376. ** assumed that the database is corrupt.
  55377. */
  55378. #define BTCURSOR_MAX_DEPTH 20
  55379. /*
  55380. ** A cursor is a pointer to a particular entry within a particular
  55381. ** b-tree within a database file.
  55382. **
  55383. ** The entry is identified by its MemPage and the index in
  55384. ** MemPage.aCell[] of the entry.
  55385. **
  55386. ** A single database file can be shared by two more database connections,
  55387. ** but cursors cannot be shared. Each cursor is associated with a
  55388. ** particular database connection identified BtCursor.pBtree.db.
  55389. **
  55390. ** Fields in this structure are accessed under the BtShared.mutex
  55391. ** found at self->pBt->mutex.
  55392. **
  55393. ** skipNext meaning:
  55394. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  55395. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  55396. ** eState==FAULT: Cursor fault with skipNext as error code.
  55397. */
  55398. struct BtCursor {
  55399. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  55400. u8 curFlags; /* zero or more BTCF_* flags defined below */
  55401. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  55402. u8 hints; /* As configured by CursorSetHints() */
  55403. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  55404. Btree *pBtree; /* The Btree to which this cursor belongs */
  55405. BtShared *pBt; /* The BtShared this cursor points to */
  55406. BtCursor *pNext; /* Forms a linked list of all cursors */
  55407. Pgno *aOverflow; /* Cache of overflow page locations */
  55408. CellInfo info; /* A parse of the cell we are pointing at */
  55409. i64 nKey; /* Size of pKey, or last integer key */
  55410. void *pKey; /* Saved key that was cursor last known position */
  55411. Pgno pgnoRoot; /* The root page of this tree */
  55412. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  55413. ** Error code if eState==CURSOR_FAULT */
  55414. /* All fields above are zeroed when the cursor is allocated. See
  55415. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  55416. ** initialized. */
  55417. i8 iPage; /* Index of current page in apPage */
  55418. u8 curIntKey; /* Value of apPage[0]->intKey */
  55419. u16 ix; /* Current index for apPage[iPage] */
  55420. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  55421. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  55422. MemPage *pPage; /* Current page */
  55423. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  55424. };
  55425. /*
  55426. ** Legal values for BtCursor.curFlags
  55427. */
  55428. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  55429. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  55430. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  55431. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  55432. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  55433. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  55434. /*
  55435. ** Potential values for BtCursor.eState.
  55436. **
  55437. ** CURSOR_INVALID:
  55438. ** Cursor does not point to a valid entry. This can happen (for example)
  55439. ** because the table is empty or because BtreeCursorFirst() has not been
  55440. ** called.
  55441. **
  55442. ** CURSOR_VALID:
  55443. ** Cursor points to a valid entry. getPayload() etc. may be called.
  55444. **
  55445. ** CURSOR_SKIPNEXT:
  55446. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  55447. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  55448. ** operation should be a no-op.
  55449. **
  55450. ** CURSOR_REQUIRESEEK:
  55451. ** The table that this cursor was opened on still exists, but has been
  55452. ** modified since the cursor was last used. The cursor position is saved
  55453. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  55454. ** this state, restoreCursorPosition() can be called to attempt to
  55455. ** seek the cursor to the saved position.
  55456. **
  55457. ** CURSOR_FAULT:
  55458. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  55459. ** on a different connection that shares the BtShared cache with this
  55460. ** cursor. The error has left the cache in an inconsistent state.
  55461. ** Do nothing else with this cursor. Any attempt to use the cursor
  55462. ** should return the error code stored in BtCursor.skipNext
  55463. */
  55464. #define CURSOR_INVALID 0
  55465. #define CURSOR_VALID 1
  55466. #define CURSOR_SKIPNEXT 2
  55467. #define CURSOR_REQUIRESEEK 3
  55468. #define CURSOR_FAULT 4
  55469. /*
  55470. ** The database page the PENDING_BYTE occupies. This page is never used.
  55471. */
  55472. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  55473. /*
  55474. ** These macros define the location of the pointer-map entry for a
  55475. ** database page. The first argument to each is the number of usable
  55476. ** bytes on each page of the database (often 1024). The second is the
  55477. ** page number to look up in the pointer map.
  55478. **
  55479. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  55480. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  55481. ** the offset of the requested map entry.
  55482. **
  55483. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  55484. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  55485. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  55486. ** this test.
  55487. */
  55488. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  55489. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  55490. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  55491. /*
  55492. ** The pointer map is a lookup table that identifies the parent page for
  55493. ** each child page in the database file. The parent page is the page that
  55494. ** contains a pointer to the child. Every page in the database contains
  55495. ** 0 or 1 parent pages. (In this context 'database page' refers
  55496. ** to any page that is not part of the pointer map itself.) Each pointer map
  55497. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  55498. ** The PTRMAP_XXX identifiers below are the valid types.
  55499. **
  55500. ** The purpose of the pointer map is to facility moving pages from one
  55501. ** position in the file to another as part of autovacuum. When a page
  55502. ** is moved, the pointer in its parent must be updated to point to the
  55503. ** new location. The pointer map is used to locate the parent page quickly.
  55504. **
  55505. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  55506. ** used in this case.
  55507. **
  55508. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  55509. ** is not used in this case.
  55510. **
  55511. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  55512. ** overflow pages. The page number identifies the page that
  55513. ** contains the cell with a pointer to this overflow page.
  55514. **
  55515. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  55516. ** overflow pages. The page-number identifies the previous
  55517. ** page in the overflow page list.
  55518. **
  55519. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  55520. ** identifies the parent page in the btree.
  55521. */
  55522. #define PTRMAP_ROOTPAGE 1
  55523. #define PTRMAP_FREEPAGE 2
  55524. #define PTRMAP_OVERFLOW1 3
  55525. #define PTRMAP_OVERFLOW2 4
  55526. #define PTRMAP_BTREE 5
  55527. /* A bunch of assert() statements to check the transaction state variables
  55528. ** of handle p (type Btree*) are internally consistent.
  55529. */
  55530. #define btreeIntegrity(p) \
  55531. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  55532. assert( p->pBt->inTransaction>=p->inTrans );
  55533. /*
  55534. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  55535. ** if the database supports auto-vacuum or not. Because it is used
  55536. ** within an expression that is an argument to another macro
  55537. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  55538. ** So, this macro is defined instead.
  55539. */
  55540. #ifndef SQLITE_OMIT_AUTOVACUUM
  55541. #define ISAUTOVACUUM (pBt->autoVacuum)
  55542. #else
  55543. #define ISAUTOVACUUM 0
  55544. #endif
  55545. /*
  55546. ** This structure is passed around through all the sanity checking routines
  55547. ** in order to keep track of some global state information.
  55548. **
  55549. ** The aRef[] array is allocated so that there is 1 bit for each page in
  55550. ** the database. As the integrity-check proceeds, for each page used in
  55551. ** the database the corresponding bit is set. This allows integrity-check to
  55552. ** detect pages that are used twice and orphaned pages (both of which
  55553. ** indicate corruption).
  55554. */
  55555. typedef struct IntegrityCk IntegrityCk;
  55556. struct IntegrityCk {
  55557. BtShared *pBt; /* The tree being checked out */
  55558. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  55559. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  55560. Pgno nPage; /* Number of pages in the database */
  55561. int mxErr; /* Stop accumulating errors when this reaches zero */
  55562. int nErr; /* Number of messages written to zErrMsg so far */
  55563. int mallocFailed; /* A memory allocation error has occurred */
  55564. const char *zPfx; /* Error message prefix */
  55565. int v1, v2; /* Values for up to two %d fields in zPfx */
  55566. StrAccum errMsg; /* Accumulate the error message text here */
  55567. u32 *heap; /* Min-heap used for analyzing cell coverage */
  55568. };
  55569. /*
  55570. ** Routines to read or write a two- and four-byte big-endian integer values.
  55571. */
  55572. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  55573. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  55574. #define get4byte sqlite3Get4byte
  55575. #define put4byte sqlite3Put4byte
  55576. /*
  55577. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  55578. ** two-byte aligned address. get2bytea() is only used for accessing the
  55579. ** cell addresses in a btree header.
  55580. */
  55581. #if SQLITE_BYTEORDER==4321
  55582. # define get2byteAligned(x) (*(u16*)(x))
  55583. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  55584. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  55585. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  55586. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  55587. #else
  55588. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  55589. #endif
  55590. /************** End of btreeInt.h ********************************************/
  55591. /************** Continuing where we left off in btmutex.c ********************/
  55592. #ifndef SQLITE_OMIT_SHARED_CACHE
  55593. #if SQLITE_THREADSAFE
  55594. /*
  55595. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  55596. ** set BtShared.db to the database handle associated with p and the
  55597. ** p->locked boolean to true.
  55598. */
  55599. static void lockBtreeMutex(Btree *p){
  55600. assert( p->locked==0 );
  55601. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  55602. assert( sqlite3_mutex_held(p->db->mutex) );
  55603. sqlite3_mutex_enter(p->pBt->mutex);
  55604. p->pBt->db = p->db;
  55605. p->locked = 1;
  55606. }
  55607. /*
  55608. ** Release the BtShared mutex associated with B-Tree handle p and
  55609. ** clear the p->locked boolean.
  55610. */
  55611. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  55612. BtShared *pBt = p->pBt;
  55613. assert( p->locked==1 );
  55614. assert( sqlite3_mutex_held(pBt->mutex) );
  55615. assert( sqlite3_mutex_held(p->db->mutex) );
  55616. assert( p->db==pBt->db );
  55617. sqlite3_mutex_leave(pBt->mutex);
  55618. p->locked = 0;
  55619. }
  55620. /* Forward reference */
  55621. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  55622. /*
  55623. ** Enter a mutex on the given BTree object.
  55624. **
  55625. ** If the object is not sharable, then no mutex is ever required
  55626. ** and this routine is a no-op. The underlying mutex is non-recursive.
  55627. ** But we keep a reference count in Btree.wantToLock so the behavior
  55628. ** of this interface is recursive.
  55629. **
  55630. ** To avoid deadlocks, multiple Btrees are locked in the same order
  55631. ** by all database connections. The p->pNext is a list of other
  55632. ** Btrees belonging to the same database connection as the p Btree
  55633. ** which need to be locked after p. If we cannot get a lock on
  55634. ** p, then first unlock all of the others on p->pNext, then wait
  55635. ** for the lock to become available on p, then relock all of the
  55636. ** subsequent Btrees that desire a lock.
  55637. */
  55638. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55639. /* Some basic sanity checking on the Btree. The list of Btrees
  55640. ** connected by pNext and pPrev should be in sorted order by
  55641. ** Btree.pBt value. All elements of the list should belong to
  55642. ** the same connection. Only shared Btrees are on the list. */
  55643. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  55644. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  55645. assert( p->pNext==0 || p->pNext->db==p->db );
  55646. assert( p->pPrev==0 || p->pPrev->db==p->db );
  55647. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  55648. /* Check for locking consistency */
  55649. assert( !p->locked || p->wantToLock>0 );
  55650. assert( p->sharable || p->wantToLock==0 );
  55651. /* We should already hold a lock on the database connection */
  55652. assert( sqlite3_mutex_held(p->db->mutex) );
  55653. /* Unless the database is sharable and unlocked, then BtShared.db
  55654. ** should already be set correctly. */
  55655. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  55656. if( !p->sharable ) return;
  55657. p->wantToLock++;
  55658. if( p->locked ) return;
  55659. btreeLockCarefully(p);
  55660. }
  55661. /* This is a helper function for sqlite3BtreeLock(). By moving
  55662. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  55663. ** into this routine, we avoid unnecessary stack pointer changes
  55664. ** and thus help the sqlite3BtreeLock() routine to run much faster
  55665. ** in the common case.
  55666. */
  55667. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  55668. Btree *pLater;
  55669. /* In most cases, we should be able to acquire the lock we
  55670. ** want without having to go through the ascending lock
  55671. ** procedure that follows. Just be sure not to block.
  55672. */
  55673. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  55674. p->pBt->db = p->db;
  55675. p->locked = 1;
  55676. return;
  55677. }
  55678. /* To avoid deadlock, first release all locks with a larger
  55679. ** BtShared address. Then acquire our lock. Then reacquire
  55680. ** the other BtShared locks that we used to hold in ascending
  55681. ** order.
  55682. */
  55683. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55684. assert( pLater->sharable );
  55685. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  55686. assert( !pLater->locked || pLater->wantToLock>0 );
  55687. if( pLater->locked ){
  55688. unlockBtreeMutex(pLater);
  55689. }
  55690. }
  55691. lockBtreeMutex(p);
  55692. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55693. if( pLater->wantToLock ){
  55694. lockBtreeMutex(pLater);
  55695. }
  55696. }
  55697. }
  55698. /*
  55699. ** Exit the recursive mutex on a Btree.
  55700. */
  55701. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  55702. assert( sqlite3_mutex_held(p->db->mutex) );
  55703. if( p->sharable ){
  55704. assert( p->wantToLock>0 );
  55705. p->wantToLock--;
  55706. if( p->wantToLock==0 ){
  55707. unlockBtreeMutex(p);
  55708. }
  55709. }
  55710. }
  55711. #ifndef NDEBUG
  55712. /*
  55713. ** Return true if the BtShared mutex is held on the btree, or if the
  55714. ** B-Tree is not marked as sharable.
  55715. **
  55716. ** This routine is used only from within assert() statements.
  55717. */
  55718. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  55719. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  55720. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  55721. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  55722. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  55723. return (p->sharable==0 || p->locked);
  55724. }
  55725. #endif
  55726. /*
  55727. ** Enter the mutex on every Btree associated with a database
  55728. ** connection. This is needed (for example) prior to parsing
  55729. ** a statement since we will be comparing table and column names
  55730. ** against all schemas and we do not want those schemas being
  55731. ** reset out from under us.
  55732. **
  55733. ** There is a corresponding leave-all procedures.
  55734. **
  55735. ** Enter the mutexes in accending order by BtShared pointer address
  55736. ** to avoid the possibility of deadlock when two threads with
  55737. ** two or more btrees in common both try to lock all their btrees
  55738. ** at the same instant.
  55739. */
  55740. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  55741. int i;
  55742. int skipOk = 1;
  55743. Btree *p;
  55744. assert( sqlite3_mutex_held(db->mutex) );
  55745. for(i=0; i<db->nDb; i++){
  55746. p = db->aDb[i].pBt;
  55747. if( p && p->sharable ){
  55748. sqlite3BtreeEnter(p);
  55749. skipOk = 0;
  55750. }
  55751. }
  55752. db->skipBtreeMutex = skipOk;
  55753. }
  55754. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55755. if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
  55756. }
  55757. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  55758. int i;
  55759. Btree *p;
  55760. assert( sqlite3_mutex_held(db->mutex) );
  55761. for(i=0; i<db->nDb; i++){
  55762. p = db->aDb[i].pBt;
  55763. if( p ) sqlite3BtreeLeave(p);
  55764. }
  55765. }
  55766. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  55767. if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
  55768. }
  55769. #ifndef NDEBUG
  55770. /*
  55771. ** Return true if the current thread holds the database connection
  55772. ** mutex and all required BtShared mutexes.
  55773. **
  55774. ** This routine is used inside assert() statements only.
  55775. */
  55776. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  55777. int i;
  55778. if( !sqlite3_mutex_held(db->mutex) ){
  55779. return 0;
  55780. }
  55781. for(i=0; i<db->nDb; i++){
  55782. Btree *p;
  55783. p = db->aDb[i].pBt;
  55784. if( p && p->sharable &&
  55785. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  55786. return 0;
  55787. }
  55788. }
  55789. return 1;
  55790. }
  55791. #endif /* NDEBUG */
  55792. #ifndef NDEBUG
  55793. /*
  55794. ** Return true if the correct mutexes are held for accessing the
  55795. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  55796. ** access are:
  55797. **
  55798. ** (1) The mutex on db
  55799. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  55800. **
  55801. ** If pSchema is not NULL, then iDb is computed from pSchema and
  55802. ** db using sqlite3SchemaToIndex().
  55803. */
  55804. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  55805. Btree *p;
  55806. assert( db!=0 );
  55807. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  55808. assert( iDb>=0 && iDb<db->nDb );
  55809. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  55810. if( iDb==1 ) return 1;
  55811. p = db->aDb[iDb].pBt;
  55812. assert( p!=0 );
  55813. return p->sharable==0 || p->locked==1;
  55814. }
  55815. #endif /* NDEBUG */
  55816. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  55817. /*
  55818. ** The following are special cases for mutex enter routines for use
  55819. ** in single threaded applications that use shared cache. Except for
  55820. ** these two routines, all mutex operations are no-ops in that case and
  55821. ** are null #defines in btree.h.
  55822. **
  55823. ** If shared cache is disabled, then all btree mutex routines, including
  55824. ** the ones below, are no-ops and are null #defines in btree.h.
  55825. */
  55826. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55827. p->pBt->db = p->db;
  55828. }
  55829. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55830. int i;
  55831. for(i=0; i<db->nDb; i++){
  55832. Btree *p = db->aDb[i].pBt;
  55833. if( p ){
  55834. p->pBt->db = p->db;
  55835. }
  55836. }
  55837. }
  55838. #endif /* if SQLITE_THREADSAFE */
  55839. #ifndef SQLITE_OMIT_INCRBLOB
  55840. /*
  55841. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  55842. **
  55843. ** These entry points are used by incremental I/O only. Enter() is required
  55844. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  55845. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  55846. */
  55847. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  55848. sqlite3BtreeEnter(pCur->pBtree);
  55849. }
  55850. # if SQLITE_THREADSAFE
  55851. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  55852. sqlite3BtreeLeave(pCur->pBtree);
  55853. }
  55854. # endif
  55855. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  55856. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  55857. /************** End of btmutex.c *********************************************/
  55858. /************** Begin file btree.c *******************************************/
  55859. /*
  55860. ** 2004 April 6
  55861. **
  55862. ** The author disclaims copyright to this source code. In place of
  55863. ** a legal notice, here is a blessing:
  55864. **
  55865. ** May you do good and not evil.
  55866. ** May you find forgiveness for yourself and forgive others.
  55867. ** May you share freely, never taking more than you give.
  55868. **
  55869. *************************************************************************
  55870. ** This file implements an external (disk-based) database using BTrees.
  55871. ** See the header comment on "btreeInt.h" for additional information.
  55872. ** Including a description of file format and an overview of operation.
  55873. */
  55874. /* #include "btreeInt.h" */
  55875. /*
  55876. ** The header string that appears at the beginning of every
  55877. ** SQLite database.
  55878. */
  55879. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  55880. /*
  55881. ** Set this global variable to 1 to enable tracing using the TRACE
  55882. ** macro.
  55883. */
  55884. #if 0
  55885. int sqlite3BtreeTrace=1; /* True to enable tracing */
  55886. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  55887. #else
  55888. # define TRACE(X)
  55889. #endif
  55890. /*
  55891. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  55892. ** But if the value is zero, make it 65536.
  55893. **
  55894. ** This routine is used to extract the "offset to cell content area" value
  55895. ** from the header of a btree page. If the page size is 65536 and the page
  55896. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  55897. ** This routine makes the necessary adjustment to 65536.
  55898. */
  55899. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  55900. /*
  55901. ** Values passed as the 5th argument to allocateBtreePage()
  55902. */
  55903. #define BTALLOC_ANY 0 /* Allocate any page */
  55904. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  55905. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  55906. /*
  55907. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  55908. ** defined, or 0 if it is. For example:
  55909. **
  55910. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  55911. */
  55912. #ifndef SQLITE_OMIT_AUTOVACUUM
  55913. #define IfNotOmitAV(expr) (expr)
  55914. #else
  55915. #define IfNotOmitAV(expr) 0
  55916. #endif
  55917. #ifndef SQLITE_OMIT_SHARED_CACHE
  55918. /*
  55919. ** A list of BtShared objects that are eligible for participation
  55920. ** in shared cache. This variable has file scope during normal builds,
  55921. ** but the test harness needs to access it so we make it global for
  55922. ** test builds.
  55923. **
  55924. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  55925. */
  55926. #ifdef SQLITE_TEST
  55927. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55928. #else
  55929. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55930. #endif
  55931. #endif /* SQLITE_OMIT_SHARED_CACHE */
  55932. #ifndef SQLITE_OMIT_SHARED_CACHE
  55933. /*
  55934. ** Enable or disable the shared pager and schema features.
  55935. **
  55936. ** This routine has no effect on existing database connections.
  55937. ** The shared cache setting effects only future calls to
  55938. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  55939. */
  55940. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  55941. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  55942. return SQLITE_OK;
  55943. }
  55944. #endif
  55945. #ifdef SQLITE_OMIT_SHARED_CACHE
  55946. /*
  55947. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  55948. ** and clearAllSharedCacheTableLocks()
  55949. ** manipulate entries in the BtShared.pLock linked list used to store
  55950. ** shared-cache table level locks. If the library is compiled with the
  55951. ** shared-cache feature disabled, then there is only ever one user
  55952. ** of each BtShared structure and so this locking is not necessary.
  55953. ** So define the lock related functions as no-ops.
  55954. */
  55955. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  55956. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  55957. #define clearAllSharedCacheTableLocks(a)
  55958. #define downgradeAllSharedCacheTableLocks(a)
  55959. #define hasSharedCacheTableLock(a,b,c,d) 1
  55960. #define hasReadConflicts(a, b) 0
  55961. #endif
  55962. #ifndef SQLITE_OMIT_SHARED_CACHE
  55963. #ifdef SQLITE_DEBUG
  55964. /*
  55965. **** This function is only used as part of an assert() statement. ***
  55966. **
  55967. ** Check to see if pBtree holds the required locks to read or write to the
  55968. ** table with root page iRoot. Return 1 if it does and 0 if not.
  55969. **
  55970. ** For example, when writing to a table with root-page iRoot via
  55971. ** Btree connection pBtree:
  55972. **
  55973. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  55974. **
  55975. ** When writing to an index that resides in a sharable database, the
  55976. ** caller should have first obtained a lock specifying the root page of
  55977. ** the corresponding table. This makes things a bit more complicated,
  55978. ** as this module treats each table as a separate structure. To determine
  55979. ** the table corresponding to the index being written, this
  55980. ** function has to search through the database schema.
  55981. **
  55982. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  55983. ** hold a write-lock on the schema table (root page 1). This is also
  55984. ** acceptable.
  55985. */
  55986. static int hasSharedCacheTableLock(
  55987. Btree *pBtree, /* Handle that must hold lock */
  55988. Pgno iRoot, /* Root page of b-tree */
  55989. int isIndex, /* True if iRoot is the root of an index b-tree */
  55990. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  55991. ){
  55992. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  55993. Pgno iTab = 0;
  55994. BtLock *pLock;
  55995. /* If this database is not shareable, or if the client is reading
  55996. ** and has the read-uncommitted flag set, then no lock is required.
  55997. ** Return true immediately.
  55998. */
  55999. if( (pBtree->sharable==0)
  56000. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  56001. ){
  56002. return 1;
  56003. }
  56004. /* If the client is reading or writing an index and the schema is
  56005. ** not loaded, then it is too difficult to actually check to see if
  56006. ** the correct locks are held. So do not bother - just return true.
  56007. ** This case does not come up very often anyhow.
  56008. */
  56009. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  56010. return 1;
  56011. }
  56012. /* Figure out the root-page that the lock should be held on. For table
  56013. ** b-trees, this is just the root page of the b-tree being read or
  56014. ** written. For index b-trees, it is the root page of the associated
  56015. ** table. */
  56016. if( isIndex ){
  56017. HashElem *p;
  56018. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  56019. Index *pIdx = (Index *)sqliteHashData(p);
  56020. if( pIdx->tnum==(int)iRoot ){
  56021. if( iTab ){
  56022. /* Two or more indexes share the same root page. There must
  56023. ** be imposter tables. So just return true. The assert is not
  56024. ** useful in that case. */
  56025. return 1;
  56026. }
  56027. iTab = pIdx->pTable->tnum;
  56028. }
  56029. }
  56030. }else{
  56031. iTab = iRoot;
  56032. }
  56033. /* Search for the required lock. Either a write-lock on root-page iTab, a
  56034. ** write-lock on the schema table, or (if the client is reading) a
  56035. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  56036. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  56037. if( pLock->pBtree==pBtree
  56038. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  56039. && pLock->eLock>=eLockType
  56040. ){
  56041. return 1;
  56042. }
  56043. }
  56044. /* Failed to find the required lock. */
  56045. return 0;
  56046. }
  56047. #endif /* SQLITE_DEBUG */
  56048. #ifdef SQLITE_DEBUG
  56049. /*
  56050. **** This function may be used as part of assert() statements only. ****
  56051. **
  56052. ** Return true if it would be illegal for pBtree to write into the
  56053. ** table or index rooted at iRoot because other shared connections are
  56054. ** simultaneously reading that same table or index.
  56055. **
  56056. ** It is illegal for pBtree to write if some other Btree object that
  56057. ** shares the same BtShared object is currently reading or writing
  56058. ** the iRoot table. Except, if the other Btree object has the
  56059. ** read-uncommitted flag set, then it is OK for the other object to
  56060. ** have a read cursor.
  56061. **
  56062. ** For example, before writing to any part of the table or index
  56063. ** rooted at page iRoot, one should call:
  56064. **
  56065. ** assert( !hasReadConflicts(pBtree, iRoot) );
  56066. */
  56067. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  56068. BtCursor *p;
  56069. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  56070. if( p->pgnoRoot==iRoot
  56071. && p->pBtree!=pBtree
  56072. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  56073. ){
  56074. return 1;
  56075. }
  56076. }
  56077. return 0;
  56078. }
  56079. #endif /* #ifdef SQLITE_DEBUG */
  56080. /*
  56081. ** Query to see if Btree handle p may obtain a lock of type eLock
  56082. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  56083. ** SQLITE_OK if the lock may be obtained (by calling
  56084. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  56085. */
  56086. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  56087. BtShared *pBt = p->pBt;
  56088. BtLock *pIter;
  56089. assert( sqlite3BtreeHoldsMutex(p) );
  56090. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  56091. assert( p->db!=0 );
  56092. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  56093. /* If requesting a write-lock, then the Btree must have an open write
  56094. ** transaction on this file. And, obviously, for this to be so there
  56095. ** must be an open write transaction on the file itself.
  56096. */
  56097. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  56098. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  56099. /* This routine is a no-op if the shared-cache is not enabled */
  56100. if( !p->sharable ){
  56101. return SQLITE_OK;
  56102. }
  56103. /* If some other connection is holding an exclusive lock, the
  56104. ** requested lock may not be obtained.
  56105. */
  56106. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  56107. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  56108. return SQLITE_LOCKED_SHAREDCACHE;
  56109. }
  56110. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  56111. /* The condition (pIter->eLock!=eLock) in the following if(...)
  56112. ** statement is a simplification of:
  56113. **
  56114. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  56115. **
  56116. ** since we know that if eLock==WRITE_LOCK, then no other connection
  56117. ** may hold a WRITE_LOCK on any table in this file (since there can
  56118. ** only be a single writer).
  56119. */
  56120. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  56121. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  56122. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  56123. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  56124. if( eLock==WRITE_LOCK ){
  56125. assert( p==pBt->pWriter );
  56126. pBt->btsFlags |= BTS_PENDING;
  56127. }
  56128. return SQLITE_LOCKED_SHAREDCACHE;
  56129. }
  56130. }
  56131. return SQLITE_OK;
  56132. }
  56133. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  56134. #ifndef SQLITE_OMIT_SHARED_CACHE
  56135. /*
  56136. ** Add a lock on the table with root-page iTable to the shared-btree used
  56137. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  56138. ** WRITE_LOCK.
  56139. **
  56140. ** This function assumes the following:
  56141. **
  56142. ** (a) The specified Btree object p is connected to a sharable
  56143. ** database (one with the BtShared.sharable flag set), and
  56144. **
  56145. ** (b) No other Btree objects hold a lock that conflicts
  56146. ** with the requested lock (i.e. querySharedCacheTableLock() has
  56147. ** already been called and returned SQLITE_OK).
  56148. **
  56149. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  56150. ** is returned if a malloc attempt fails.
  56151. */
  56152. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  56153. BtShared *pBt = p->pBt;
  56154. BtLock *pLock = 0;
  56155. BtLock *pIter;
  56156. assert( sqlite3BtreeHoldsMutex(p) );
  56157. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  56158. assert( p->db!=0 );
  56159. /* A connection with the read-uncommitted flag set will never try to
  56160. ** obtain a read-lock using this function. The only read-lock obtained
  56161. ** by a connection in read-uncommitted mode is on the sqlite_master
  56162. ** table, and that lock is obtained in BtreeBeginTrans(). */
  56163. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  56164. /* This function should only be called on a sharable b-tree after it
  56165. ** has been determined that no other b-tree holds a conflicting lock. */
  56166. assert( p->sharable );
  56167. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  56168. /* First search the list for an existing lock on this table. */
  56169. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  56170. if( pIter->iTable==iTable && pIter->pBtree==p ){
  56171. pLock = pIter;
  56172. break;
  56173. }
  56174. }
  56175. /* If the above search did not find a BtLock struct associating Btree p
  56176. ** with table iTable, allocate one and link it into the list.
  56177. */
  56178. if( !pLock ){
  56179. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  56180. if( !pLock ){
  56181. return SQLITE_NOMEM_BKPT;
  56182. }
  56183. pLock->iTable = iTable;
  56184. pLock->pBtree = p;
  56185. pLock->pNext = pBt->pLock;
  56186. pBt->pLock = pLock;
  56187. }
  56188. /* Set the BtLock.eLock variable to the maximum of the current lock
  56189. ** and the requested lock. This means if a write-lock was already held
  56190. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  56191. */
  56192. assert( WRITE_LOCK>READ_LOCK );
  56193. if( eLock>pLock->eLock ){
  56194. pLock->eLock = eLock;
  56195. }
  56196. return SQLITE_OK;
  56197. }
  56198. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  56199. #ifndef SQLITE_OMIT_SHARED_CACHE
  56200. /*
  56201. ** Release all the table locks (locks obtained via calls to
  56202. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  56203. **
  56204. ** This function assumes that Btree p has an open read or write
  56205. ** transaction. If it does not, then the BTS_PENDING flag
  56206. ** may be incorrectly cleared.
  56207. */
  56208. static void clearAllSharedCacheTableLocks(Btree *p){
  56209. BtShared *pBt = p->pBt;
  56210. BtLock **ppIter = &pBt->pLock;
  56211. assert( sqlite3BtreeHoldsMutex(p) );
  56212. assert( p->sharable || 0==*ppIter );
  56213. assert( p->inTrans>0 );
  56214. while( *ppIter ){
  56215. BtLock *pLock = *ppIter;
  56216. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  56217. assert( pLock->pBtree->inTrans>=pLock->eLock );
  56218. if( pLock->pBtree==p ){
  56219. *ppIter = pLock->pNext;
  56220. assert( pLock->iTable!=1 || pLock==&p->lock );
  56221. if( pLock->iTable!=1 ){
  56222. sqlite3_free(pLock);
  56223. }
  56224. }else{
  56225. ppIter = &pLock->pNext;
  56226. }
  56227. }
  56228. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  56229. if( pBt->pWriter==p ){
  56230. pBt->pWriter = 0;
  56231. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  56232. }else if( pBt->nTransaction==2 ){
  56233. /* This function is called when Btree p is concluding its
  56234. ** transaction. If there currently exists a writer, and p is not
  56235. ** that writer, then the number of locks held by connections other
  56236. ** than the writer must be about to drop to zero. In this case
  56237. ** set the BTS_PENDING flag to 0.
  56238. **
  56239. ** If there is not currently a writer, then BTS_PENDING must
  56240. ** be zero already. So this next line is harmless in that case.
  56241. */
  56242. pBt->btsFlags &= ~BTS_PENDING;
  56243. }
  56244. }
  56245. /*
  56246. ** This function changes all write-locks held by Btree p into read-locks.
  56247. */
  56248. static void downgradeAllSharedCacheTableLocks(Btree *p){
  56249. BtShared *pBt = p->pBt;
  56250. if( pBt->pWriter==p ){
  56251. BtLock *pLock;
  56252. pBt->pWriter = 0;
  56253. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  56254. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  56255. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  56256. pLock->eLock = READ_LOCK;
  56257. }
  56258. }
  56259. }
  56260. #endif /* SQLITE_OMIT_SHARED_CACHE */
  56261. static void releasePage(MemPage *pPage); /* Forward reference */
  56262. static void releasePageOne(MemPage *pPage); /* Forward reference */
  56263. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  56264. /*
  56265. ***** This routine is used inside of assert() only ****
  56266. **
  56267. ** Verify that the cursor holds the mutex on its BtShared
  56268. */
  56269. #ifdef SQLITE_DEBUG
  56270. static int cursorHoldsMutex(BtCursor *p){
  56271. return sqlite3_mutex_held(p->pBt->mutex);
  56272. }
  56273. /* Verify that the cursor and the BtShared agree about what is the current
  56274. ** database connetion. This is important in shared-cache mode. If the database
  56275. ** connection pointers get out-of-sync, it is possible for routines like
  56276. ** btreeInitPage() to reference an stale connection pointer that references a
  56277. ** a connection that has already closed. This routine is used inside assert()
  56278. ** statements only and for the purpose of double-checking that the btree code
  56279. ** does keep the database connection pointers up-to-date.
  56280. */
  56281. static int cursorOwnsBtShared(BtCursor *p){
  56282. assert( cursorHoldsMutex(p) );
  56283. return (p->pBtree->db==p->pBt->db);
  56284. }
  56285. #endif
  56286. /*
  56287. ** Invalidate the overflow cache of the cursor passed as the first argument.
  56288. ** on the shared btree structure pBt.
  56289. */
  56290. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  56291. /*
  56292. ** Invalidate the overflow page-list cache for all cursors opened
  56293. ** on the shared btree structure pBt.
  56294. */
  56295. static void invalidateAllOverflowCache(BtShared *pBt){
  56296. BtCursor *p;
  56297. assert( sqlite3_mutex_held(pBt->mutex) );
  56298. for(p=pBt->pCursor; p; p=p->pNext){
  56299. invalidateOverflowCache(p);
  56300. }
  56301. }
  56302. #ifndef SQLITE_OMIT_INCRBLOB
  56303. /*
  56304. ** This function is called before modifying the contents of a table
  56305. ** to invalidate any incrblob cursors that are open on the
  56306. ** row or one of the rows being modified.
  56307. **
  56308. ** If argument isClearTable is true, then the entire contents of the
  56309. ** table is about to be deleted. In this case invalidate all incrblob
  56310. ** cursors open on any row within the table with root-page pgnoRoot.
  56311. **
  56312. ** Otherwise, if argument isClearTable is false, then the row with
  56313. ** rowid iRow is being replaced or deleted. In this case invalidate
  56314. ** only those incrblob cursors open on that specific row.
  56315. */
  56316. static void invalidateIncrblobCursors(
  56317. Btree *pBtree, /* The database file to check */
  56318. Pgno pgnoRoot, /* The table that might be changing */
  56319. i64 iRow, /* The rowid that might be changing */
  56320. int isClearTable /* True if all rows are being deleted */
  56321. ){
  56322. BtCursor *p;
  56323. if( pBtree->hasIncrblobCur==0 ) return;
  56324. assert( sqlite3BtreeHoldsMutex(pBtree) );
  56325. pBtree->hasIncrblobCur = 0;
  56326. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  56327. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  56328. pBtree->hasIncrblobCur = 1;
  56329. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  56330. p->eState = CURSOR_INVALID;
  56331. }
  56332. }
  56333. }
  56334. }
  56335. #else
  56336. /* Stub function when INCRBLOB is omitted */
  56337. #define invalidateIncrblobCursors(w,x,y,z)
  56338. #endif /* SQLITE_OMIT_INCRBLOB */
  56339. /*
  56340. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  56341. ** when a page that previously contained data becomes a free-list leaf
  56342. ** page.
  56343. **
  56344. ** The BtShared.pHasContent bitvec exists to work around an obscure
  56345. ** bug caused by the interaction of two useful IO optimizations surrounding
  56346. ** free-list leaf pages:
  56347. **
  56348. ** 1) When all data is deleted from a page and the page becomes
  56349. ** a free-list leaf page, the page is not written to the database
  56350. ** (as free-list leaf pages contain no meaningful data). Sometimes
  56351. ** such a page is not even journalled (as it will not be modified,
  56352. ** why bother journalling it?).
  56353. **
  56354. ** 2) When a free-list leaf page is reused, its content is not read
  56355. ** from the database or written to the journal file (why should it
  56356. ** be, if it is not at all meaningful?).
  56357. **
  56358. ** By themselves, these optimizations work fine and provide a handy
  56359. ** performance boost to bulk delete or insert operations. However, if
  56360. ** a page is moved to the free-list and then reused within the same
  56361. ** transaction, a problem comes up. If the page is not journalled when
  56362. ** it is moved to the free-list and it is also not journalled when it
  56363. ** is extracted from the free-list and reused, then the original data
  56364. ** may be lost. In the event of a rollback, it may not be possible
  56365. ** to restore the database to its original configuration.
  56366. **
  56367. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  56368. ** moved to become a free-list leaf page, the corresponding bit is
  56369. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  56370. ** optimization 2 above is omitted if the corresponding bit is already
  56371. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  56372. ** at the end of every transaction.
  56373. */
  56374. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  56375. int rc = SQLITE_OK;
  56376. if( !pBt->pHasContent ){
  56377. assert( pgno<=pBt->nPage );
  56378. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  56379. if( !pBt->pHasContent ){
  56380. rc = SQLITE_NOMEM_BKPT;
  56381. }
  56382. }
  56383. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  56384. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  56385. }
  56386. return rc;
  56387. }
  56388. /*
  56389. ** Query the BtShared.pHasContent vector.
  56390. **
  56391. ** This function is called when a free-list leaf page is removed from the
  56392. ** free-list for reuse. It returns false if it is safe to retrieve the
  56393. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  56394. */
  56395. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  56396. Bitvec *p = pBt->pHasContent;
  56397. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  56398. }
  56399. /*
  56400. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  56401. ** invoked at the conclusion of each write-transaction.
  56402. */
  56403. static void btreeClearHasContent(BtShared *pBt){
  56404. sqlite3BitvecDestroy(pBt->pHasContent);
  56405. pBt->pHasContent = 0;
  56406. }
  56407. /*
  56408. ** Release all of the apPage[] pages for a cursor.
  56409. */
  56410. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  56411. int i;
  56412. if( pCur->iPage>=0 ){
  56413. for(i=0; i<pCur->iPage; i++){
  56414. releasePageNotNull(pCur->apPage[i]);
  56415. }
  56416. releasePageNotNull(pCur->pPage);
  56417. pCur->iPage = -1;
  56418. }
  56419. }
  56420. /*
  56421. ** The cursor passed as the only argument must point to a valid entry
  56422. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  56423. ** function saves the current cursor key in variables pCur->nKey and
  56424. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  56425. ** code otherwise.
  56426. **
  56427. ** If the cursor is open on an intkey table, then the integer key
  56428. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  56429. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  56430. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  56431. ** the key.
  56432. */
  56433. static int saveCursorKey(BtCursor *pCur){
  56434. int rc = SQLITE_OK;
  56435. assert( CURSOR_VALID==pCur->eState );
  56436. assert( 0==pCur->pKey );
  56437. assert( cursorHoldsMutex(pCur) );
  56438. if( pCur->curIntKey ){
  56439. /* Only the rowid is required for a table btree */
  56440. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  56441. }else{
  56442. /* For an index btree, save the complete key content */
  56443. void *pKey;
  56444. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  56445. pKey = sqlite3Malloc( pCur->nKey );
  56446. if( pKey ){
  56447. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  56448. if( rc==SQLITE_OK ){
  56449. pCur->pKey = pKey;
  56450. }else{
  56451. sqlite3_free(pKey);
  56452. }
  56453. }else{
  56454. rc = SQLITE_NOMEM_BKPT;
  56455. }
  56456. }
  56457. assert( !pCur->curIntKey || !pCur->pKey );
  56458. return rc;
  56459. }
  56460. /*
  56461. ** Save the current cursor position in the variables BtCursor.nKey
  56462. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  56463. **
  56464. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  56465. ** prior to calling this routine.
  56466. */
  56467. static int saveCursorPosition(BtCursor *pCur){
  56468. int rc;
  56469. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  56470. assert( 0==pCur->pKey );
  56471. assert( cursorHoldsMutex(pCur) );
  56472. if( pCur->eState==CURSOR_SKIPNEXT ){
  56473. pCur->eState = CURSOR_VALID;
  56474. }else{
  56475. pCur->skipNext = 0;
  56476. }
  56477. rc = saveCursorKey(pCur);
  56478. if( rc==SQLITE_OK ){
  56479. btreeReleaseAllCursorPages(pCur);
  56480. pCur->eState = CURSOR_REQUIRESEEK;
  56481. }
  56482. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  56483. return rc;
  56484. }
  56485. /* Forward reference */
  56486. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  56487. /*
  56488. ** Save the positions of all cursors (except pExcept) that are open on
  56489. ** the table with root-page iRoot. "Saving the cursor position" means that
  56490. ** the location in the btree is remembered in such a way that it can be
  56491. ** moved back to the same spot after the btree has been modified. This
  56492. ** routine is called just before cursor pExcept is used to modify the
  56493. ** table, for example in BtreeDelete() or BtreeInsert().
  56494. **
  56495. ** If there are two or more cursors on the same btree, then all such
  56496. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  56497. ** routine enforces that rule. This routine only needs to be called in
  56498. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  56499. **
  56500. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  56501. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  56502. ** pointless call to this routine.
  56503. **
  56504. ** Implementation note: This routine merely checks to see if any cursors
  56505. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  56506. ** event that cursors are in need to being saved.
  56507. */
  56508. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  56509. BtCursor *p;
  56510. assert( sqlite3_mutex_held(pBt->mutex) );
  56511. assert( pExcept==0 || pExcept->pBt==pBt );
  56512. for(p=pBt->pCursor; p; p=p->pNext){
  56513. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  56514. }
  56515. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  56516. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  56517. return SQLITE_OK;
  56518. }
  56519. /* This helper routine to saveAllCursors does the actual work of saving
  56520. ** the cursors if and when a cursor is found that actually requires saving.
  56521. ** The common case is that no cursors need to be saved, so this routine is
  56522. ** broken out from its caller to avoid unnecessary stack pointer movement.
  56523. */
  56524. static int SQLITE_NOINLINE saveCursorsOnList(
  56525. BtCursor *p, /* The first cursor that needs saving */
  56526. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  56527. BtCursor *pExcept /* Do not save this cursor */
  56528. ){
  56529. do{
  56530. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  56531. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  56532. int rc = saveCursorPosition(p);
  56533. if( SQLITE_OK!=rc ){
  56534. return rc;
  56535. }
  56536. }else{
  56537. testcase( p->iPage>=0 );
  56538. btreeReleaseAllCursorPages(p);
  56539. }
  56540. }
  56541. p = p->pNext;
  56542. }while( p );
  56543. return SQLITE_OK;
  56544. }
  56545. /*
  56546. ** Clear the current cursor position.
  56547. */
  56548. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  56549. assert( cursorHoldsMutex(pCur) );
  56550. sqlite3_free(pCur->pKey);
  56551. pCur->pKey = 0;
  56552. pCur->eState = CURSOR_INVALID;
  56553. }
  56554. /*
  56555. ** In this version of BtreeMoveto, pKey is a packed index record
  56556. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  56557. ** record and then call BtreeMovetoUnpacked() to do the work.
  56558. */
  56559. static int btreeMoveto(
  56560. BtCursor *pCur, /* Cursor open on the btree to be searched */
  56561. const void *pKey, /* Packed key if the btree is an index */
  56562. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  56563. int bias, /* Bias search to the high end */
  56564. int *pRes /* Write search results here */
  56565. ){
  56566. int rc; /* Status code */
  56567. UnpackedRecord *pIdxKey; /* Unpacked index key */
  56568. if( pKey ){
  56569. assert( nKey==(i64)(int)nKey );
  56570. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  56571. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  56572. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  56573. if( pIdxKey->nField==0 ){
  56574. rc = SQLITE_CORRUPT_BKPT;
  56575. goto moveto_done;
  56576. }
  56577. }else{
  56578. pIdxKey = 0;
  56579. }
  56580. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  56581. moveto_done:
  56582. if( pIdxKey ){
  56583. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  56584. }
  56585. return rc;
  56586. }
  56587. /*
  56588. ** Restore the cursor to the position it was in (or as close to as possible)
  56589. ** when saveCursorPosition() was called. Note that this call deletes the
  56590. ** saved position info stored by saveCursorPosition(), so there can be
  56591. ** at most one effective restoreCursorPosition() call after each
  56592. ** saveCursorPosition().
  56593. */
  56594. static int btreeRestoreCursorPosition(BtCursor *pCur){
  56595. int rc;
  56596. int skipNext;
  56597. assert( cursorOwnsBtShared(pCur) );
  56598. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  56599. if( pCur->eState==CURSOR_FAULT ){
  56600. return pCur->skipNext;
  56601. }
  56602. pCur->eState = CURSOR_INVALID;
  56603. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  56604. if( rc==SQLITE_OK ){
  56605. sqlite3_free(pCur->pKey);
  56606. pCur->pKey = 0;
  56607. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  56608. pCur->skipNext |= skipNext;
  56609. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  56610. pCur->eState = CURSOR_SKIPNEXT;
  56611. }
  56612. }
  56613. return rc;
  56614. }
  56615. #define restoreCursorPosition(p) \
  56616. (p->eState>=CURSOR_REQUIRESEEK ? \
  56617. btreeRestoreCursorPosition(p) : \
  56618. SQLITE_OK)
  56619. /*
  56620. ** Determine whether or not a cursor has moved from the position where
  56621. ** it was last placed, or has been invalidated for any other reason.
  56622. ** Cursors can move when the row they are pointing at is deleted out
  56623. ** from under them, for example. Cursor might also move if a btree
  56624. ** is rebalanced.
  56625. **
  56626. ** Calling this routine with a NULL cursor pointer returns false.
  56627. **
  56628. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  56629. ** back to where it ought to be if this routine returns true.
  56630. */
  56631. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  56632. return pCur->eState!=CURSOR_VALID;
  56633. }
  56634. /*
  56635. ** Return a pointer to a fake BtCursor object that will always answer
  56636. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  56637. ** cursor returned must not be used with any other Btree interface.
  56638. */
  56639. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  56640. static u8 fakeCursor = CURSOR_VALID;
  56641. assert( offsetof(BtCursor, eState)==0 );
  56642. return (BtCursor*)&fakeCursor;
  56643. }
  56644. /*
  56645. ** This routine restores a cursor back to its original position after it
  56646. ** has been moved by some outside activity (such as a btree rebalance or
  56647. ** a row having been deleted out from under the cursor).
  56648. **
  56649. ** On success, the *pDifferentRow parameter is false if the cursor is left
  56650. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  56651. ** was pointing to has been deleted, forcing the cursor to point to some
  56652. ** nearby row.
  56653. **
  56654. ** This routine should only be called for a cursor that just returned
  56655. ** TRUE from sqlite3BtreeCursorHasMoved().
  56656. */
  56657. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  56658. int rc;
  56659. assert( pCur!=0 );
  56660. assert( pCur->eState!=CURSOR_VALID );
  56661. rc = restoreCursorPosition(pCur);
  56662. if( rc ){
  56663. *pDifferentRow = 1;
  56664. return rc;
  56665. }
  56666. if( pCur->eState!=CURSOR_VALID ){
  56667. *pDifferentRow = 1;
  56668. }else{
  56669. assert( pCur->skipNext==0 );
  56670. *pDifferentRow = 0;
  56671. }
  56672. return SQLITE_OK;
  56673. }
  56674. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  56675. /*
  56676. ** Provide hints to the cursor. The particular hint given (and the type
  56677. ** and number of the varargs parameters) is determined by the eHintType
  56678. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  56679. */
  56680. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  56681. /* Used only by system that substitute their own storage engine */
  56682. }
  56683. #endif
  56684. /*
  56685. ** Provide flag hints to the cursor.
  56686. */
  56687. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  56688. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  56689. pCur->hints = x;
  56690. }
  56691. #ifndef SQLITE_OMIT_AUTOVACUUM
  56692. /*
  56693. ** Given a page number of a regular database page, return the page
  56694. ** number for the pointer-map page that contains the entry for the
  56695. ** input page number.
  56696. **
  56697. ** Return 0 (not a valid page) for pgno==1 since there is
  56698. ** no pointer map associated with page 1. The integrity_check logic
  56699. ** requires that ptrmapPageno(*,1)!=1.
  56700. */
  56701. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  56702. int nPagesPerMapPage;
  56703. Pgno iPtrMap, ret;
  56704. assert( sqlite3_mutex_held(pBt->mutex) );
  56705. if( pgno<2 ) return 0;
  56706. nPagesPerMapPage = (pBt->usableSize/5)+1;
  56707. iPtrMap = (pgno-2)/nPagesPerMapPage;
  56708. ret = (iPtrMap*nPagesPerMapPage) + 2;
  56709. if( ret==PENDING_BYTE_PAGE(pBt) ){
  56710. ret++;
  56711. }
  56712. return ret;
  56713. }
  56714. /*
  56715. ** Write an entry into the pointer map.
  56716. **
  56717. ** This routine updates the pointer map entry for page number 'key'
  56718. ** so that it maps to type 'eType' and parent page number 'pgno'.
  56719. **
  56720. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  56721. ** a no-op. If an error occurs, the appropriate error code is written
  56722. ** into *pRC.
  56723. */
  56724. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  56725. DbPage *pDbPage; /* The pointer map page */
  56726. u8 *pPtrmap; /* The pointer map data */
  56727. Pgno iPtrmap; /* The pointer map page number */
  56728. int offset; /* Offset in pointer map page */
  56729. int rc; /* Return code from subfunctions */
  56730. if( *pRC ) return;
  56731. assert( sqlite3_mutex_held(pBt->mutex) );
  56732. /* The master-journal page number must never be used as a pointer map page */
  56733. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  56734. assert( pBt->autoVacuum );
  56735. if( key==0 ){
  56736. *pRC = SQLITE_CORRUPT_BKPT;
  56737. return;
  56738. }
  56739. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56740. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56741. if( rc!=SQLITE_OK ){
  56742. *pRC = rc;
  56743. return;
  56744. }
  56745. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56746. if( offset<0 ){
  56747. *pRC = SQLITE_CORRUPT_BKPT;
  56748. goto ptrmap_exit;
  56749. }
  56750. assert( offset <= (int)pBt->usableSize-5 );
  56751. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56752. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  56753. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  56754. *pRC= rc = sqlite3PagerWrite(pDbPage);
  56755. if( rc==SQLITE_OK ){
  56756. pPtrmap[offset] = eType;
  56757. put4byte(&pPtrmap[offset+1], parent);
  56758. }
  56759. }
  56760. ptrmap_exit:
  56761. sqlite3PagerUnref(pDbPage);
  56762. }
  56763. /*
  56764. ** Read an entry from the pointer map.
  56765. **
  56766. ** This routine retrieves the pointer map entry for page 'key', writing
  56767. ** the type and parent page number to *pEType and *pPgno respectively.
  56768. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  56769. */
  56770. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  56771. DbPage *pDbPage; /* The pointer map page */
  56772. int iPtrmap; /* Pointer map page index */
  56773. u8 *pPtrmap; /* Pointer map page data */
  56774. int offset; /* Offset of entry in pointer map */
  56775. int rc;
  56776. assert( sqlite3_mutex_held(pBt->mutex) );
  56777. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56778. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56779. if( rc!=0 ){
  56780. return rc;
  56781. }
  56782. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56783. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56784. if( offset<0 ){
  56785. sqlite3PagerUnref(pDbPage);
  56786. return SQLITE_CORRUPT_BKPT;
  56787. }
  56788. assert( offset <= (int)pBt->usableSize-5 );
  56789. assert( pEType!=0 );
  56790. *pEType = pPtrmap[offset];
  56791. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  56792. sqlite3PagerUnref(pDbPage);
  56793. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  56794. return SQLITE_OK;
  56795. }
  56796. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  56797. #define ptrmapPut(w,x,y,z,rc)
  56798. #define ptrmapGet(w,x,y,z) SQLITE_OK
  56799. #define ptrmapPutOvflPtr(x, y, rc)
  56800. #endif
  56801. /*
  56802. ** Given a btree page and a cell index (0 means the first cell on
  56803. ** the page, 1 means the second cell, and so forth) return a pointer
  56804. ** to the cell content.
  56805. **
  56806. ** findCellPastPtr() does the same except it skips past the initial
  56807. ** 4-byte child pointer found on interior pages, if there is one.
  56808. **
  56809. ** This routine works only for pages that do not contain overflow cells.
  56810. */
  56811. #define findCell(P,I) \
  56812. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56813. #define findCellPastPtr(P,I) \
  56814. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56815. /*
  56816. ** This is common tail processing for btreeParseCellPtr() and
  56817. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  56818. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  56819. ** structure.
  56820. */
  56821. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  56822. MemPage *pPage, /* Page containing the cell */
  56823. u8 *pCell, /* Pointer to the cell text. */
  56824. CellInfo *pInfo /* Fill in this structure */
  56825. ){
  56826. /* If the payload will not fit completely on the local page, we have
  56827. ** to decide how much to store locally and how much to spill onto
  56828. ** overflow pages. The strategy is to minimize the amount of unused
  56829. ** space on overflow pages while keeping the amount of local storage
  56830. ** in between minLocal and maxLocal.
  56831. **
  56832. ** Warning: changing the way overflow payload is distributed in any
  56833. ** way will result in an incompatible file format.
  56834. */
  56835. int minLocal; /* Minimum amount of payload held locally */
  56836. int maxLocal; /* Maximum amount of payload held locally */
  56837. int surplus; /* Overflow payload available for local storage */
  56838. minLocal = pPage->minLocal;
  56839. maxLocal = pPage->maxLocal;
  56840. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  56841. testcase( surplus==maxLocal );
  56842. testcase( surplus==maxLocal+1 );
  56843. if( surplus <= maxLocal ){
  56844. pInfo->nLocal = (u16)surplus;
  56845. }else{
  56846. pInfo->nLocal = (u16)minLocal;
  56847. }
  56848. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  56849. }
  56850. /*
  56851. ** The following routines are implementations of the MemPage.xParseCell()
  56852. ** method.
  56853. **
  56854. ** Parse a cell content block and fill in the CellInfo structure.
  56855. **
  56856. ** btreeParseCellPtr() => table btree leaf nodes
  56857. ** btreeParseCellNoPayload() => table btree internal nodes
  56858. ** btreeParseCellPtrIndex() => index btree nodes
  56859. **
  56860. ** There is also a wrapper function btreeParseCell() that works for
  56861. ** all MemPage types and that references the cell by index rather than
  56862. ** by pointer.
  56863. */
  56864. static void btreeParseCellPtrNoPayload(
  56865. MemPage *pPage, /* Page containing the cell */
  56866. u8 *pCell, /* Pointer to the cell text. */
  56867. CellInfo *pInfo /* Fill in this structure */
  56868. ){
  56869. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56870. assert( pPage->leaf==0 );
  56871. assert( pPage->childPtrSize==4 );
  56872. #ifndef SQLITE_DEBUG
  56873. UNUSED_PARAMETER(pPage);
  56874. #endif
  56875. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  56876. pInfo->nPayload = 0;
  56877. pInfo->nLocal = 0;
  56878. pInfo->pPayload = 0;
  56879. return;
  56880. }
  56881. static void btreeParseCellPtr(
  56882. MemPage *pPage, /* Page containing the cell */
  56883. u8 *pCell, /* Pointer to the cell text. */
  56884. CellInfo *pInfo /* Fill in this structure */
  56885. ){
  56886. u8 *pIter; /* For scanning through pCell */
  56887. u32 nPayload; /* Number of bytes of cell payload */
  56888. u64 iKey; /* Extracted Key value */
  56889. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56890. assert( pPage->leaf==0 || pPage->leaf==1 );
  56891. assert( pPage->intKeyLeaf );
  56892. assert( pPage->childPtrSize==0 );
  56893. pIter = pCell;
  56894. /* The next block of code is equivalent to:
  56895. **
  56896. ** pIter += getVarint32(pIter, nPayload);
  56897. **
  56898. ** The code is inlined to avoid a function call.
  56899. */
  56900. nPayload = *pIter;
  56901. if( nPayload>=0x80 ){
  56902. u8 *pEnd = &pIter[8];
  56903. nPayload &= 0x7f;
  56904. do{
  56905. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56906. }while( (*pIter)>=0x80 && pIter<pEnd );
  56907. }
  56908. pIter++;
  56909. /* The next block of code is equivalent to:
  56910. **
  56911. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  56912. **
  56913. ** The code is inlined to avoid a function call.
  56914. */
  56915. iKey = *pIter;
  56916. if( iKey>=0x80 ){
  56917. u8 *pEnd = &pIter[7];
  56918. iKey &= 0x7f;
  56919. while(1){
  56920. iKey = (iKey<<7) | (*++pIter & 0x7f);
  56921. if( (*pIter)<0x80 ) break;
  56922. if( pIter>=pEnd ){
  56923. iKey = (iKey<<8) | *++pIter;
  56924. break;
  56925. }
  56926. }
  56927. }
  56928. pIter++;
  56929. pInfo->nKey = *(i64*)&iKey;
  56930. pInfo->nPayload = nPayload;
  56931. pInfo->pPayload = pIter;
  56932. testcase( nPayload==pPage->maxLocal );
  56933. testcase( nPayload==pPage->maxLocal+1 );
  56934. if( nPayload<=pPage->maxLocal ){
  56935. /* This is the (easy) common case where the entire payload fits
  56936. ** on the local page. No overflow is required.
  56937. */
  56938. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56939. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56940. pInfo->nLocal = (u16)nPayload;
  56941. }else{
  56942. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56943. }
  56944. }
  56945. static void btreeParseCellPtrIndex(
  56946. MemPage *pPage, /* Page containing the cell */
  56947. u8 *pCell, /* Pointer to the cell text. */
  56948. CellInfo *pInfo /* Fill in this structure */
  56949. ){
  56950. u8 *pIter; /* For scanning through pCell */
  56951. u32 nPayload; /* Number of bytes of cell payload */
  56952. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56953. assert( pPage->leaf==0 || pPage->leaf==1 );
  56954. assert( pPage->intKeyLeaf==0 );
  56955. pIter = pCell + pPage->childPtrSize;
  56956. nPayload = *pIter;
  56957. if( nPayload>=0x80 ){
  56958. u8 *pEnd = &pIter[8];
  56959. nPayload &= 0x7f;
  56960. do{
  56961. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56962. }while( *(pIter)>=0x80 && pIter<pEnd );
  56963. }
  56964. pIter++;
  56965. pInfo->nKey = nPayload;
  56966. pInfo->nPayload = nPayload;
  56967. pInfo->pPayload = pIter;
  56968. testcase( nPayload==pPage->maxLocal );
  56969. testcase( nPayload==pPage->maxLocal+1 );
  56970. if( nPayload<=pPage->maxLocal ){
  56971. /* This is the (easy) common case where the entire payload fits
  56972. ** on the local page. No overflow is required.
  56973. */
  56974. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56975. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56976. pInfo->nLocal = (u16)nPayload;
  56977. }else{
  56978. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56979. }
  56980. }
  56981. static void btreeParseCell(
  56982. MemPage *pPage, /* Page containing the cell */
  56983. int iCell, /* The cell index. First cell is 0 */
  56984. CellInfo *pInfo /* Fill in this structure */
  56985. ){
  56986. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  56987. }
  56988. /*
  56989. ** The following routines are implementations of the MemPage.xCellSize
  56990. ** method.
  56991. **
  56992. ** Compute the total number of bytes that a Cell needs in the cell
  56993. ** data area of the btree-page. The return number includes the cell
  56994. ** data header and the local payload, but not any overflow page or
  56995. ** the space used by the cell pointer.
  56996. **
  56997. ** cellSizePtrNoPayload() => table internal nodes
  56998. ** cellSizePtr() => all index nodes & table leaf nodes
  56999. */
  57000. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  57001. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  57002. u8 *pEnd; /* End mark for a varint */
  57003. u32 nSize; /* Size value to return */
  57004. #ifdef SQLITE_DEBUG
  57005. /* The value returned by this function should always be the same as
  57006. ** the (CellInfo.nSize) value found by doing a full parse of the
  57007. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  57008. ** this function verifies that this invariant is not violated. */
  57009. CellInfo debuginfo;
  57010. pPage->xParseCell(pPage, pCell, &debuginfo);
  57011. #endif
  57012. nSize = *pIter;
  57013. if( nSize>=0x80 ){
  57014. pEnd = &pIter[8];
  57015. nSize &= 0x7f;
  57016. do{
  57017. nSize = (nSize<<7) | (*++pIter & 0x7f);
  57018. }while( *(pIter)>=0x80 && pIter<pEnd );
  57019. }
  57020. pIter++;
  57021. if( pPage->intKey ){
  57022. /* pIter now points at the 64-bit integer key value, a variable length
  57023. ** integer. The following block moves pIter to point at the first byte
  57024. ** past the end of the key value. */
  57025. pEnd = &pIter[9];
  57026. while( (*pIter++)&0x80 && pIter<pEnd );
  57027. }
  57028. testcase( nSize==pPage->maxLocal );
  57029. testcase( nSize==pPage->maxLocal+1 );
  57030. if( nSize<=pPage->maxLocal ){
  57031. nSize += (u32)(pIter - pCell);
  57032. if( nSize<4 ) nSize = 4;
  57033. }else{
  57034. int minLocal = pPage->minLocal;
  57035. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  57036. testcase( nSize==pPage->maxLocal );
  57037. testcase( nSize==pPage->maxLocal+1 );
  57038. if( nSize>pPage->maxLocal ){
  57039. nSize = minLocal;
  57040. }
  57041. nSize += 4 + (u16)(pIter - pCell);
  57042. }
  57043. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  57044. return (u16)nSize;
  57045. }
  57046. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  57047. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  57048. u8 *pEnd; /* End mark for a varint */
  57049. #ifdef SQLITE_DEBUG
  57050. /* The value returned by this function should always be the same as
  57051. ** the (CellInfo.nSize) value found by doing a full parse of the
  57052. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  57053. ** this function verifies that this invariant is not violated. */
  57054. CellInfo debuginfo;
  57055. pPage->xParseCell(pPage, pCell, &debuginfo);
  57056. #else
  57057. UNUSED_PARAMETER(pPage);
  57058. #endif
  57059. assert( pPage->childPtrSize==4 );
  57060. pEnd = pIter + 9;
  57061. while( (*pIter++)&0x80 && pIter<pEnd );
  57062. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  57063. return (u16)(pIter - pCell);
  57064. }
  57065. #ifdef SQLITE_DEBUG
  57066. /* This variation on cellSizePtr() is used inside of assert() statements
  57067. ** only. */
  57068. static u16 cellSize(MemPage *pPage, int iCell){
  57069. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  57070. }
  57071. #endif
  57072. #ifndef SQLITE_OMIT_AUTOVACUUM
  57073. /*
  57074. ** If the cell pCell, part of page pPage contains a pointer
  57075. ** to an overflow page, insert an entry into the pointer-map
  57076. ** for the overflow page.
  57077. */
  57078. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  57079. CellInfo info;
  57080. if( *pRC ) return;
  57081. assert( pCell!=0 );
  57082. pPage->xParseCell(pPage, pCell, &info);
  57083. if( info.nLocal<info.nPayload ){
  57084. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  57085. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  57086. }
  57087. }
  57088. #endif
  57089. /*
  57090. ** Defragment the page given. This routine reorganizes cells within the
  57091. ** page so that there are no free-blocks on the free-block list.
  57092. **
  57093. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  57094. ** present in the page after this routine returns.
  57095. **
  57096. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  57097. ** b-tree page so that there are no freeblocks or fragment bytes, all
  57098. ** unused bytes are contained in the unallocated space region, and all
  57099. ** cells are packed tightly at the end of the page.
  57100. */
  57101. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  57102. int i; /* Loop counter */
  57103. int pc; /* Address of the i-th cell */
  57104. int hdr; /* Offset to the page header */
  57105. int size; /* Size of a cell */
  57106. int usableSize; /* Number of usable bytes on a page */
  57107. int cellOffset; /* Offset to the cell pointer array */
  57108. int cbrk; /* Offset to the cell content area */
  57109. int nCell; /* Number of cells on the page */
  57110. unsigned char *data; /* The page data */
  57111. unsigned char *temp; /* Temp area for cell content */
  57112. unsigned char *src; /* Source of content */
  57113. int iCellFirst; /* First allowable cell index */
  57114. int iCellLast; /* Last possible cell index */
  57115. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57116. assert( pPage->pBt!=0 );
  57117. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  57118. assert( pPage->nOverflow==0 );
  57119. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57120. temp = 0;
  57121. src = data = pPage->aData;
  57122. hdr = pPage->hdrOffset;
  57123. cellOffset = pPage->cellOffset;
  57124. nCell = pPage->nCell;
  57125. assert( nCell==get2byte(&data[hdr+3]) );
  57126. iCellFirst = cellOffset + 2*nCell;
  57127. usableSize = pPage->pBt->usableSize;
  57128. /* This block handles pages with two or fewer free blocks and nMaxFrag
  57129. ** or fewer fragmented bytes. In this case it is faster to move the
  57130. ** two (or one) blocks of cells using memmove() and add the required
  57131. ** offsets to each pointer in the cell-pointer array than it is to
  57132. ** reconstruct the entire page. */
  57133. if( (int)data[hdr+7]<=nMaxFrag ){
  57134. int iFree = get2byte(&data[hdr+1]);
  57135. if( iFree ){
  57136. int iFree2 = get2byte(&data[iFree]);
  57137. /* pageFindSlot() has already verified that free blocks are sorted
  57138. ** in order of offset within the page, and that no block extends
  57139. ** past the end of the page. Provided the two free slots do not
  57140. ** overlap, this guarantees that the memmove() calls below will not
  57141. ** overwrite the usableSize byte buffer, even if the database page
  57142. ** is corrupt. */
  57143. assert( iFree2==0 || iFree2>iFree );
  57144. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  57145. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  57146. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  57147. u8 *pEnd = &data[cellOffset + nCell*2];
  57148. u8 *pAddr;
  57149. int sz2 = 0;
  57150. int sz = get2byte(&data[iFree+2]);
  57151. int top = get2byte(&data[hdr+5]);
  57152. if( top>=iFree ){
  57153. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57154. }
  57155. if( iFree2 ){
  57156. assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
  57157. sz2 = get2byte(&data[iFree2+2]);
  57158. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  57159. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  57160. sz += sz2;
  57161. }
  57162. cbrk = top+sz;
  57163. assert( cbrk+(iFree-top) <= usableSize );
  57164. memmove(&data[cbrk], &data[top], iFree-top);
  57165. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  57166. pc = get2byte(pAddr);
  57167. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  57168. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  57169. }
  57170. goto defragment_out;
  57171. }
  57172. }
  57173. }
  57174. cbrk = usableSize;
  57175. iCellLast = usableSize - 4;
  57176. for(i=0; i<nCell; i++){
  57177. u8 *pAddr; /* The i-th cell pointer */
  57178. pAddr = &data[cellOffset + i*2];
  57179. pc = get2byte(pAddr);
  57180. testcase( pc==iCellFirst );
  57181. testcase( pc==iCellLast );
  57182. /* These conditions have already been verified in btreeInitPage()
  57183. ** if PRAGMA cell_size_check=ON.
  57184. */
  57185. if( pc<iCellFirst || pc>iCellLast ){
  57186. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57187. }
  57188. assert( pc>=iCellFirst && pc<=iCellLast );
  57189. size = pPage->xCellSize(pPage, &src[pc]);
  57190. cbrk -= size;
  57191. if( cbrk<iCellFirst || pc+size>usableSize ){
  57192. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57193. }
  57194. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  57195. testcase( cbrk+size==usableSize );
  57196. testcase( pc+size==usableSize );
  57197. put2byte(pAddr, cbrk);
  57198. if( temp==0 ){
  57199. int x;
  57200. if( cbrk==pc ) continue;
  57201. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  57202. x = get2byte(&data[hdr+5]);
  57203. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  57204. src = temp;
  57205. }
  57206. memcpy(&data[cbrk], &src[pc], size);
  57207. }
  57208. data[hdr+7] = 0;
  57209. defragment_out:
  57210. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  57211. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57212. }
  57213. assert( cbrk>=iCellFirst );
  57214. put2byte(&data[hdr+5], cbrk);
  57215. data[hdr+1] = 0;
  57216. data[hdr+2] = 0;
  57217. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  57218. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57219. return SQLITE_OK;
  57220. }
  57221. /*
  57222. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  57223. ** size. If one can be found, return a pointer to the space and remove it
  57224. ** from the free-list.
  57225. **
  57226. ** If no suitable space can be found on the free-list, return NULL.
  57227. **
  57228. ** This function may detect corruption within pPg. If corruption is
  57229. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  57230. **
  57231. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  57232. ** will be ignored if adding the extra space to the fragmentation count
  57233. ** causes the fragmentation count to exceed 60.
  57234. */
  57235. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  57236. const int hdr = pPg->hdrOffset;
  57237. u8 * const aData = pPg->aData;
  57238. int iAddr = hdr + 1;
  57239. int pc = get2byte(&aData[iAddr]);
  57240. int x;
  57241. int usableSize = pPg->pBt->usableSize;
  57242. int size; /* Size of the free slot */
  57243. assert( pc>0 );
  57244. while( pc<=usableSize-4 ){
  57245. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  57246. ** freeblock form a big-endian integer which is the size of the freeblock
  57247. ** in bytes, including the 4-byte header. */
  57248. size = get2byte(&aData[pc+2]);
  57249. if( (x = size - nByte)>=0 ){
  57250. testcase( x==4 );
  57251. testcase( x==3 );
  57252. if( size+pc > usableSize ){
  57253. *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
  57254. return 0;
  57255. }else if( x<4 ){
  57256. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  57257. ** number of bytes in fragments may not exceed 60. */
  57258. if( aData[hdr+7]>57 ) return 0;
  57259. /* Remove the slot from the free-list. Update the number of
  57260. ** fragmented bytes within the page. */
  57261. memcpy(&aData[iAddr], &aData[pc], 2);
  57262. aData[hdr+7] += (u8)x;
  57263. }else{
  57264. /* The slot remains on the free-list. Reduce its size to account
  57265. ** for the portion used by the new allocation. */
  57266. put2byte(&aData[pc+2], x);
  57267. }
  57268. return &aData[pc + x];
  57269. }
  57270. iAddr = pc;
  57271. pc = get2byte(&aData[pc]);
  57272. if( pc<iAddr+size ) break;
  57273. }
  57274. if( pc ){
  57275. *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
  57276. }
  57277. return 0;
  57278. }
  57279. /*
  57280. ** Allocate nByte bytes of space from within the B-Tree page passed
  57281. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  57282. ** of the first byte of allocated space. Return either SQLITE_OK or
  57283. ** an error code (usually SQLITE_CORRUPT).
  57284. **
  57285. ** The caller guarantees that there is sufficient space to make the
  57286. ** allocation. This routine might need to defragment in order to bring
  57287. ** all the space together, however. This routine will avoid using
  57288. ** the first two bytes past the cell pointer area since presumably this
  57289. ** allocation is being made in order to insert a new cell, so we will
  57290. ** also end up needing a new cell pointer.
  57291. */
  57292. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  57293. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  57294. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  57295. int top; /* First byte of cell content area */
  57296. int rc = SQLITE_OK; /* Integer return code */
  57297. int gap; /* First byte of gap between cell pointers and cell content */
  57298. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57299. assert( pPage->pBt );
  57300. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57301. assert( nByte>=0 ); /* Minimum cell size is 4 */
  57302. assert( pPage->nFree>=nByte );
  57303. assert( pPage->nOverflow==0 );
  57304. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  57305. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  57306. gap = pPage->cellOffset + 2*pPage->nCell;
  57307. assert( gap<=65536 );
  57308. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  57309. ** and the reserved space is zero (the usual value for reserved space)
  57310. ** then the cell content offset of an empty page wants to be 65536.
  57311. ** However, that integer is too large to be stored in a 2-byte unsigned
  57312. ** integer, so a value of 0 is used in its place. */
  57313. top = get2byte(&data[hdr+5]);
  57314. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  57315. if( gap>top ){
  57316. if( top==0 && pPage->pBt->usableSize==65536 ){
  57317. top = 65536;
  57318. }else{
  57319. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57320. }
  57321. }
  57322. /* If there is enough space between gap and top for one more cell pointer
  57323. ** array entry offset, and if the freelist is not empty, then search the
  57324. ** freelist looking for a free slot big enough to satisfy the request.
  57325. */
  57326. testcase( gap+2==top );
  57327. testcase( gap+1==top );
  57328. testcase( gap==top );
  57329. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  57330. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  57331. if( pSpace ){
  57332. assert( pSpace>=data && (pSpace - data)<65536 );
  57333. *pIdx = (int)(pSpace - data);
  57334. return SQLITE_OK;
  57335. }else if( rc ){
  57336. return rc;
  57337. }
  57338. }
  57339. /* The request could not be fulfilled using a freelist slot. Check
  57340. ** to see if defragmentation is necessary.
  57341. */
  57342. testcase( gap+2+nByte==top );
  57343. if( gap+2+nByte>top ){
  57344. assert( pPage->nCell>0 || CORRUPT_DB );
  57345. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  57346. if( rc ) return rc;
  57347. top = get2byteNotZero(&data[hdr+5]);
  57348. assert( gap+2+nByte<=top );
  57349. }
  57350. /* Allocate memory from the gap in between the cell pointer array
  57351. ** and the cell content area. The btreeInitPage() call has already
  57352. ** validated the freelist. Given that the freelist is valid, there
  57353. ** is no way that the allocation can extend off the end of the page.
  57354. ** The assert() below verifies the previous sentence.
  57355. */
  57356. top -= nByte;
  57357. put2byte(&data[hdr+5], top);
  57358. assert( top+nByte <= (int)pPage->pBt->usableSize );
  57359. *pIdx = top;
  57360. return SQLITE_OK;
  57361. }
  57362. /*
  57363. ** Return a section of the pPage->aData to the freelist.
  57364. ** The first byte of the new free block is pPage->aData[iStart]
  57365. ** and the size of the block is iSize bytes.
  57366. **
  57367. ** Adjacent freeblocks are coalesced.
  57368. **
  57369. ** Note that even though the freeblock list was checked by btreeInitPage(),
  57370. ** that routine will not detect overlap between cells or freeblocks. Nor
  57371. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  57372. ** at the end of the page. So do additional corruption checks inside this
  57373. ** routine and return SQLITE_CORRUPT if any problems are found.
  57374. */
  57375. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  57376. u16 iPtr; /* Address of ptr to next freeblock */
  57377. u16 iFreeBlk; /* Address of the next freeblock */
  57378. u8 hdr; /* Page header size. 0 or 100 */
  57379. u8 nFrag = 0; /* Reduction in fragmentation */
  57380. u16 iOrigSize = iSize; /* Original value of iSize */
  57381. u16 x; /* Offset to cell content area */
  57382. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  57383. unsigned char *data = pPage->aData; /* Page content */
  57384. assert( pPage->pBt!=0 );
  57385. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57386. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  57387. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  57388. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57389. assert( iSize>=4 ); /* Minimum cell size is 4 */
  57390. assert( iStart<=pPage->pBt->usableSize-4 );
  57391. /* The list of freeblocks must be in ascending order. Find the
  57392. ** spot on the list where iStart should be inserted.
  57393. */
  57394. hdr = pPage->hdrOffset;
  57395. iPtr = hdr + 1;
  57396. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  57397. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  57398. }else{
  57399. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  57400. if( iFreeBlk<iPtr+4 ){
  57401. if( iFreeBlk==0 ) break;
  57402. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57403. }
  57404. iPtr = iFreeBlk;
  57405. }
  57406. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  57407. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57408. }
  57409. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  57410. /* At this point:
  57411. ** iFreeBlk: First freeblock after iStart, or zero if none
  57412. ** iPtr: The address of a pointer to iFreeBlk
  57413. **
  57414. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  57415. */
  57416. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  57417. nFrag = iFreeBlk - iEnd;
  57418. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57419. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  57420. if( iEnd > pPage->pBt->usableSize ){
  57421. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57422. }
  57423. iSize = iEnd - iStart;
  57424. iFreeBlk = get2byte(&data[iFreeBlk]);
  57425. }
  57426. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  57427. ** pointer in the page header) then check to see if iStart should be
  57428. ** coalesced onto the end of iPtr.
  57429. */
  57430. if( iPtr>hdr+1 ){
  57431. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  57432. if( iPtrEnd+3>=iStart ){
  57433. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57434. nFrag += iStart - iPtrEnd;
  57435. iSize = iEnd - iPtr;
  57436. iStart = iPtr;
  57437. }
  57438. }
  57439. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57440. data[hdr+7] -= nFrag;
  57441. }
  57442. x = get2byte(&data[hdr+5]);
  57443. if( iStart<=x ){
  57444. /* The new freeblock is at the beginning of the cell content area,
  57445. ** so just extend the cell content area rather than create another
  57446. ** freelist entry */
  57447. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57448. put2byte(&data[hdr+1], iFreeBlk);
  57449. put2byte(&data[hdr+5], iEnd);
  57450. }else{
  57451. /* Insert the new freeblock into the freelist */
  57452. put2byte(&data[iPtr], iStart);
  57453. }
  57454. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  57455. /* Overwrite deleted information with zeros when the secure_delete
  57456. ** option is enabled */
  57457. memset(&data[iStart], 0, iSize);
  57458. }
  57459. put2byte(&data[iStart], iFreeBlk);
  57460. put2byte(&data[iStart+2], iSize);
  57461. pPage->nFree += iOrigSize;
  57462. return SQLITE_OK;
  57463. }
  57464. /*
  57465. ** Decode the flags byte (the first byte of the header) for a page
  57466. ** and initialize fields of the MemPage structure accordingly.
  57467. **
  57468. ** Only the following combinations are supported. Anything different
  57469. ** indicates a corrupt database files:
  57470. **
  57471. ** PTF_ZERODATA
  57472. ** PTF_ZERODATA | PTF_LEAF
  57473. ** PTF_LEAFDATA | PTF_INTKEY
  57474. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  57475. */
  57476. static int decodeFlags(MemPage *pPage, int flagByte){
  57477. BtShared *pBt; /* A copy of pPage->pBt */
  57478. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  57479. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57480. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  57481. flagByte &= ~PTF_LEAF;
  57482. pPage->childPtrSize = 4-4*pPage->leaf;
  57483. pPage->xCellSize = cellSizePtr;
  57484. pBt = pPage->pBt;
  57485. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  57486. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  57487. ** interior table b-tree page. */
  57488. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  57489. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  57490. ** leaf table b-tree page. */
  57491. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  57492. pPage->intKey = 1;
  57493. if( pPage->leaf ){
  57494. pPage->intKeyLeaf = 1;
  57495. pPage->xParseCell = btreeParseCellPtr;
  57496. }else{
  57497. pPage->intKeyLeaf = 0;
  57498. pPage->xCellSize = cellSizePtrNoPayload;
  57499. pPage->xParseCell = btreeParseCellPtrNoPayload;
  57500. }
  57501. pPage->maxLocal = pBt->maxLeaf;
  57502. pPage->minLocal = pBt->minLeaf;
  57503. }else if( flagByte==PTF_ZERODATA ){
  57504. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  57505. ** interior index b-tree page. */
  57506. assert( (PTF_ZERODATA)==2 );
  57507. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  57508. ** leaf index b-tree page. */
  57509. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  57510. pPage->intKey = 0;
  57511. pPage->intKeyLeaf = 0;
  57512. pPage->xParseCell = btreeParseCellPtrIndex;
  57513. pPage->maxLocal = pBt->maxLocal;
  57514. pPage->minLocal = pBt->minLocal;
  57515. }else{
  57516. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  57517. ** an error. */
  57518. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57519. }
  57520. pPage->max1bytePayload = pBt->max1bytePayload;
  57521. return SQLITE_OK;
  57522. }
  57523. /*
  57524. ** Initialize the auxiliary information for a disk block.
  57525. **
  57526. ** Return SQLITE_OK on success. If we see that the page does
  57527. ** not contain a well-formed database page, then return
  57528. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  57529. ** guarantee that the page is well-formed. It only shows that
  57530. ** we failed to detect any corruption.
  57531. */
  57532. static int btreeInitPage(MemPage *pPage){
  57533. int pc; /* Address of a freeblock within pPage->aData[] */
  57534. u8 hdr; /* Offset to beginning of page header */
  57535. u8 *data; /* Equal to pPage->aData */
  57536. BtShared *pBt; /* The main btree structure */
  57537. int usableSize; /* Amount of usable space on each page */
  57538. u16 cellOffset; /* Offset from start of page to first cell pointer */
  57539. int nFree; /* Number of unused bytes on the page */
  57540. int top; /* First byte of the cell content area */
  57541. int iCellFirst; /* First allowable cell or freeblock offset */
  57542. int iCellLast; /* Last possible cell or freeblock offset */
  57543. assert( pPage->pBt!=0 );
  57544. assert( pPage->pBt->db!=0 );
  57545. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57546. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  57547. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  57548. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  57549. assert( pPage->isInit==0 );
  57550. pBt = pPage->pBt;
  57551. hdr = pPage->hdrOffset;
  57552. data = pPage->aData;
  57553. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  57554. ** the b-tree page type. */
  57555. if( decodeFlags(pPage, data[hdr]) ){
  57556. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57557. }
  57558. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  57559. pPage->maskPage = (u16)(pBt->pageSize - 1);
  57560. pPage->nOverflow = 0;
  57561. usableSize = pBt->usableSize;
  57562. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  57563. pPage->aDataEnd = &data[usableSize];
  57564. pPage->aCellIdx = &data[cellOffset];
  57565. pPage->aDataOfst = &data[pPage->childPtrSize];
  57566. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  57567. ** the start of the cell content area. A zero value for this integer is
  57568. ** interpreted as 65536. */
  57569. top = get2byteNotZero(&data[hdr+5]);
  57570. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  57571. ** number of cells on the page. */
  57572. pPage->nCell = get2byte(&data[hdr+3]);
  57573. if( pPage->nCell>MX_CELL(pBt) ){
  57574. /* To many cells for a single page. The page must be corrupt */
  57575. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57576. }
  57577. testcase( pPage->nCell==MX_CELL(pBt) );
  57578. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  57579. ** possible for a root page of a table that contains no rows) then the
  57580. ** offset to the cell content area will equal the page size minus the
  57581. ** bytes of reserved space. */
  57582. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  57583. /* A malformed database page might cause us to read past the end
  57584. ** of page when parsing a cell.
  57585. **
  57586. ** The following block of code checks early to see if a cell extends
  57587. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  57588. ** returned if it does.
  57589. */
  57590. iCellFirst = cellOffset + 2*pPage->nCell;
  57591. iCellLast = usableSize - 4;
  57592. if( pBt->db->flags & SQLITE_CellSizeCk ){
  57593. int i; /* Index into the cell pointer array */
  57594. int sz; /* Size of a cell */
  57595. if( !pPage->leaf ) iCellLast--;
  57596. for(i=0; i<pPage->nCell; i++){
  57597. pc = get2byteAligned(&data[cellOffset+i*2]);
  57598. testcase( pc==iCellFirst );
  57599. testcase( pc==iCellLast );
  57600. if( pc<iCellFirst || pc>iCellLast ){
  57601. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57602. }
  57603. sz = pPage->xCellSize(pPage, &data[pc]);
  57604. testcase( pc+sz==usableSize );
  57605. if( pc+sz>usableSize ){
  57606. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57607. }
  57608. }
  57609. if( !pPage->leaf ) iCellLast++;
  57610. }
  57611. /* Compute the total free space on the page
  57612. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  57613. ** start of the first freeblock on the page, or is zero if there are no
  57614. ** freeblocks. */
  57615. pc = get2byte(&data[hdr+1]);
  57616. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  57617. if( pc>0 ){
  57618. u32 next, size;
  57619. if( pc<iCellFirst ){
  57620. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  57621. ** always be at least one cell before the first freeblock.
  57622. */
  57623. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57624. }
  57625. while( 1 ){
  57626. if( pc>iCellLast ){
  57627. /* Freeblock off the end of the page */
  57628. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57629. }
  57630. next = get2byte(&data[pc]);
  57631. size = get2byte(&data[pc+2]);
  57632. nFree = nFree + size;
  57633. if( next<=pc+size+3 ) break;
  57634. pc = next;
  57635. }
  57636. if( next>0 ){
  57637. /* Freeblock not in ascending order */
  57638. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57639. }
  57640. if( pc+size>(unsigned int)usableSize ){
  57641. /* Last freeblock extends past page end */
  57642. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57643. }
  57644. }
  57645. /* At this point, nFree contains the sum of the offset to the start
  57646. ** of the cell-content area plus the number of free bytes within
  57647. ** the cell-content area. If this is greater than the usable-size
  57648. ** of the page, then the page must be corrupted. This check also
  57649. ** serves to verify that the offset to the start of the cell-content
  57650. ** area, according to the page header, lies within the page.
  57651. */
  57652. if( nFree>usableSize ){
  57653. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  57654. }
  57655. pPage->nFree = (u16)(nFree - iCellFirst);
  57656. pPage->isInit = 1;
  57657. return SQLITE_OK;
  57658. }
  57659. /*
  57660. ** Set up a raw page so that it looks like a database page holding
  57661. ** no entries.
  57662. */
  57663. static void zeroPage(MemPage *pPage, int flags){
  57664. unsigned char *data = pPage->aData;
  57665. BtShared *pBt = pPage->pBt;
  57666. u8 hdr = pPage->hdrOffset;
  57667. u16 first;
  57668. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  57669. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57670. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  57671. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57672. assert( sqlite3_mutex_held(pBt->mutex) );
  57673. if( pBt->btsFlags & BTS_FAST_SECURE ){
  57674. memset(&data[hdr], 0, pBt->usableSize - hdr);
  57675. }
  57676. data[hdr] = (char)flags;
  57677. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  57678. memset(&data[hdr+1], 0, 4);
  57679. data[hdr+7] = 0;
  57680. put2byte(&data[hdr+5], pBt->usableSize);
  57681. pPage->nFree = (u16)(pBt->usableSize - first);
  57682. decodeFlags(pPage, flags);
  57683. pPage->cellOffset = first;
  57684. pPage->aDataEnd = &data[pBt->usableSize];
  57685. pPage->aCellIdx = &data[first];
  57686. pPage->aDataOfst = &data[pPage->childPtrSize];
  57687. pPage->nOverflow = 0;
  57688. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  57689. pPage->maskPage = (u16)(pBt->pageSize - 1);
  57690. pPage->nCell = 0;
  57691. pPage->isInit = 1;
  57692. }
  57693. /*
  57694. ** Convert a DbPage obtained from the pager into a MemPage used by
  57695. ** the btree layer.
  57696. */
  57697. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  57698. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57699. if( pgno!=pPage->pgno ){
  57700. pPage->aData = sqlite3PagerGetData(pDbPage);
  57701. pPage->pDbPage = pDbPage;
  57702. pPage->pBt = pBt;
  57703. pPage->pgno = pgno;
  57704. pPage->hdrOffset = pgno==1 ? 100 : 0;
  57705. }
  57706. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  57707. return pPage;
  57708. }
  57709. /*
  57710. ** Get a page from the pager. Initialize the MemPage.pBt and
  57711. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  57712. **
  57713. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  57714. ** about the content of the page at this time. So do not go to the disk
  57715. ** to fetch the content. Just fill in the content with zeros for now.
  57716. ** If in the future we call sqlite3PagerWrite() on this page, that
  57717. ** means we have started to be concerned about content and the disk
  57718. ** read should occur at that point.
  57719. */
  57720. static int btreeGetPage(
  57721. BtShared *pBt, /* The btree */
  57722. Pgno pgno, /* Number of the page to fetch */
  57723. MemPage **ppPage, /* Return the page in this parameter */
  57724. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57725. ){
  57726. int rc;
  57727. DbPage *pDbPage;
  57728. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  57729. assert( sqlite3_mutex_held(pBt->mutex) );
  57730. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  57731. if( rc ) return rc;
  57732. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  57733. return SQLITE_OK;
  57734. }
  57735. /*
  57736. ** Retrieve a page from the pager cache. If the requested page is not
  57737. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  57738. ** MemPage.aData elements if needed.
  57739. */
  57740. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  57741. DbPage *pDbPage;
  57742. assert( sqlite3_mutex_held(pBt->mutex) );
  57743. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  57744. if( pDbPage ){
  57745. return btreePageFromDbPage(pDbPage, pgno, pBt);
  57746. }
  57747. return 0;
  57748. }
  57749. /*
  57750. ** Return the size of the database file in pages. If there is any kind of
  57751. ** error, return ((unsigned int)-1).
  57752. */
  57753. static Pgno btreePagecount(BtShared *pBt){
  57754. return pBt->nPage;
  57755. }
  57756. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  57757. assert( sqlite3BtreeHoldsMutex(p) );
  57758. assert( ((p->pBt->nPage)&0x80000000)==0 );
  57759. return btreePagecount(p->pBt);
  57760. }
  57761. /*
  57762. ** Get a page from the pager and initialize it.
  57763. **
  57764. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  57765. ** call. Do additional sanity checking on the page in this case.
  57766. ** And if the fetch fails, this routine must decrement pCur->iPage.
  57767. **
  57768. ** The page is fetched as read-write unless pCur is not NULL and is
  57769. ** a read-only cursor.
  57770. **
  57771. ** If an error occurs, then *ppPage is undefined. It
  57772. ** may remain unchanged, or it may be set to an invalid value.
  57773. */
  57774. static int getAndInitPage(
  57775. BtShared *pBt, /* The database file */
  57776. Pgno pgno, /* Number of the page to get */
  57777. MemPage **ppPage, /* Write the page pointer here */
  57778. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  57779. int bReadOnly /* True for a read-only page */
  57780. ){
  57781. int rc;
  57782. DbPage *pDbPage;
  57783. assert( sqlite3_mutex_held(pBt->mutex) );
  57784. assert( pCur==0 || ppPage==&pCur->pPage );
  57785. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  57786. assert( pCur==0 || pCur->iPage>0 );
  57787. if( pgno>btreePagecount(pBt) ){
  57788. rc = SQLITE_CORRUPT_BKPT;
  57789. goto getAndInitPage_error;
  57790. }
  57791. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  57792. if( rc ){
  57793. goto getAndInitPage_error;
  57794. }
  57795. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57796. if( (*ppPage)->isInit==0 ){
  57797. btreePageFromDbPage(pDbPage, pgno, pBt);
  57798. rc = btreeInitPage(*ppPage);
  57799. if( rc!=SQLITE_OK ){
  57800. releasePage(*ppPage);
  57801. goto getAndInitPage_error;
  57802. }
  57803. }
  57804. assert( (*ppPage)->pgno==pgno );
  57805. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  57806. /* If obtaining a child page for a cursor, we must verify that the page is
  57807. ** compatible with the root page. */
  57808. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  57809. rc = SQLITE_CORRUPT_PGNO(pgno);
  57810. releasePage(*ppPage);
  57811. goto getAndInitPage_error;
  57812. }
  57813. return SQLITE_OK;
  57814. getAndInitPage_error:
  57815. if( pCur ){
  57816. pCur->iPage--;
  57817. pCur->pPage = pCur->apPage[pCur->iPage];
  57818. }
  57819. testcase( pgno==0 );
  57820. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  57821. return rc;
  57822. }
  57823. /*
  57824. ** Release a MemPage. This should be called once for each prior
  57825. ** call to btreeGetPage.
  57826. **
  57827. ** Page1 is a special case and must be released using releasePageOne().
  57828. */
  57829. static void releasePageNotNull(MemPage *pPage){
  57830. assert( pPage->aData );
  57831. assert( pPage->pBt );
  57832. assert( pPage->pDbPage!=0 );
  57833. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57834. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  57835. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57836. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  57837. }
  57838. static void releasePage(MemPage *pPage){
  57839. if( pPage ) releasePageNotNull(pPage);
  57840. }
  57841. static void releasePageOne(MemPage *pPage){
  57842. assert( pPage!=0 );
  57843. assert( pPage->aData );
  57844. assert( pPage->pBt );
  57845. assert( pPage->pDbPage!=0 );
  57846. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57847. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  57848. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57849. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  57850. }
  57851. /*
  57852. ** Get an unused page.
  57853. **
  57854. ** This works just like btreeGetPage() with the addition:
  57855. **
  57856. ** * If the page is already in use for some other purpose, immediately
  57857. ** release it and return an SQLITE_CURRUPT error.
  57858. ** * Make sure the isInit flag is clear
  57859. */
  57860. static int btreeGetUnusedPage(
  57861. BtShared *pBt, /* The btree */
  57862. Pgno pgno, /* Number of the page to fetch */
  57863. MemPage **ppPage, /* Return the page in this parameter */
  57864. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57865. ){
  57866. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  57867. if( rc==SQLITE_OK ){
  57868. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  57869. releasePage(*ppPage);
  57870. *ppPage = 0;
  57871. return SQLITE_CORRUPT_BKPT;
  57872. }
  57873. (*ppPage)->isInit = 0;
  57874. }else{
  57875. *ppPage = 0;
  57876. }
  57877. return rc;
  57878. }
  57879. /*
  57880. ** During a rollback, when the pager reloads information into the cache
  57881. ** so that the cache is restored to its original state at the start of
  57882. ** the transaction, for each page restored this routine is called.
  57883. **
  57884. ** This routine needs to reset the extra data section at the end of the
  57885. ** page to agree with the restored data.
  57886. */
  57887. static void pageReinit(DbPage *pData){
  57888. MemPage *pPage;
  57889. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  57890. assert( sqlite3PagerPageRefcount(pData)>0 );
  57891. if( pPage->isInit ){
  57892. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57893. pPage->isInit = 0;
  57894. if( sqlite3PagerPageRefcount(pData)>1 ){
  57895. /* pPage might not be a btree page; it might be an overflow page
  57896. ** or ptrmap page or a free page. In those cases, the following
  57897. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  57898. ** But no harm is done by this. And it is very important that
  57899. ** btreeInitPage() be called on every btree page so we make
  57900. ** the call for every page that comes in for re-initing. */
  57901. btreeInitPage(pPage);
  57902. }
  57903. }
  57904. }
  57905. /*
  57906. ** Invoke the busy handler for a btree.
  57907. */
  57908. static int btreeInvokeBusyHandler(void *pArg){
  57909. BtShared *pBt = (BtShared*)pArg;
  57910. assert( pBt->db );
  57911. assert( sqlite3_mutex_held(pBt->db->mutex) );
  57912. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  57913. }
  57914. /*
  57915. ** Open a database file.
  57916. **
  57917. ** zFilename is the name of the database file. If zFilename is NULL
  57918. ** then an ephemeral database is created. The ephemeral database might
  57919. ** be exclusively in memory, or it might use a disk-based memory cache.
  57920. ** Either way, the ephemeral database will be automatically deleted
  57921. ** when sqlite3BtreeClose() is called.
  57922. **
  57923. ** If zFilename is ":memory:" then an in-memory database is created
  57924. ** that is automatically destroyed when it is closed.
  57925. **
  57926. ** The "flags" parameter is a bitmask that might contain bits like
  57927. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  57928. **
  57929. ** If the database is already opened in the same database connection
  57930. ** and we are in shared cache mode, then the open will fail with an
  57931. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  57932. ** objects in the same database connection since doing so will lead
  57933. ** to problems with locking.
  57934. */
  57935. SQLITE_PRIVATE int sqlite3BtreeOpen(
  57936. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  57937. const char *zFilename, /* Name of the file containing the BTree database */
  57938. sqlite3 *db, /* Associated database handle */
  57939. Btree **ppBtree, /* Pointer to new Btree object written here */
  57940. int flags, /* Options */
  57941. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  57942. ){
  57943. BtShared *pBt = 0; /* Shared part of btree structure */
  57944. Btree *p; /* Handle to return */
  57945. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  57946. int rc = SQLITE_OK; /* Result code from this function */
  57947. u8 nReserve; /* Byte of unused space on each page */
  57948. unsigned char zDbHeader[100]; /* Database header content */
  57949. /* True if opening an ephemeral, temporary database */
  57950. const int isTempDb = zFilename==0 || zFilename[0]==0;
  57951. /* Set the variable isMemdb to true for an in-memory database, or
  57952. ** false for a file-based database.
  57953. */
  57954. #ifdef SQLITE_OMIT_MEMORYDB
  57955. const int isMemdb = 0;
  57956. #else
  57957. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  57958. || (isTempDb && sqlite3TempInMemory(db))
  57959. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  57960. #endif
  57961. assert( db!=0 );
  57962. assert( pVfs!=0 );
  57963. assert( sqlite3_mutex_held(db->mutex) );
  57964. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  57965. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  57966. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  57967. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  57968. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  57969. if( isMemdb ){
  57970. flags |= BTREE_MEMORY;
  57971. }
  57972. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  57973. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  57974. }
  57975. p = sqlite3MallocZero(sizeof(Btree));
  57976. if( !p ){
  57977. return SQLITE_NOMEM_BKPT;
  57978. }
  57979. p->inTrans = TRANS_NONE;
  57980. p->db = db;
  57981. #ifndef SQLITE_OMIT_SHARED_CACHE
  57982. p->lock.pBtree = p;
  57983. p->lock.iTable = 1;
  57984. #endif
  57985. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57986. /*
  57987. ** If this Btree is a candidate for shared cache, try to find an
  57988. ** existing BtShared object that we can share with
  57989. */
  57990. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  57991. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  57992. int nFilename = sqlite3Strlen30(zFilename)+1;
  57993. int nFullPathname = pVfs->mxPathname+1;
  57994. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  57995. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  57996. p->sharable = 1;
  57997. if( !zFullPathname ){
  57998. sqlite3_free(p);
  57999. return SQLITE_NOMEM_BKPT;
  58000. }
  58001. if( isMemdb ){
  58002. memcpy(zFullPathname, zFilename, nFilename);
  58003. }else{
  58004. rc = sqlite3OsFullPathname(pVfs, zFilename,
  58005. nFullPathname, zFullPathname);
  58006. if( rc ){
  58007. sqlite3_free(zFullPathname);
  58008. sqlite3_free(p);
  58009. return rc;
  58010. }
  58011. }
  58012. #if SQLITE_THREADSAFE
  58013. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  58014. sqlite3_mutex_enter(mutexOpen);
  58015. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  58016. sqlite3_mutex_enter(mutexShared);
  58017. #endif
  58018. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  58019. assert( pBt->nRef>0 );
  58020. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  58021. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  58022. int iDb;
  58023. for(iDb=db->nDb-1; iDb>=0; iDb--){
  58024. Btree *pExisting = db->aDb[iDb].pBt;
  58025. if( pExisting && pExisting->pBt==pBt ){
  58026. sqlite3_mutex_leave(mutexShared);
  58027. sqlite3_mutex_leave(mutexOpen);
  58028. sqlite3_free(zFullPathname);
  58029. sqlite3_free(p);
  58030. return SQLITE_CONSTRAINT;
  58031. }
  58032. }
  58033. p->pBt = pBt;
  58034. pBt->nRef++;
  58035. break;
  58036. }
  58037. }
  58038. sqlite3_mutex_leave(mutexShared);
  58039. sqlite3_free(zFullPathname);
  58040. }
  58041. #ifdef SQLITE_DEBUG
  58042. else{
  58043. /* In debug mode, we mark all persistent databases as sharable
  58044. ** even when they are not. This exercises the locking code and
  58045. ** gives more opportunity for asserts(sqlite3_mutex_held())
  58046. ** statements to find locking problems.
  58047. */
  58048. p->sharable = 1;
  58049. }
  58050. #endif
  58051. }
  58052. #endif
  58053. if( pBt==0 ){
  58054. /*
  58055. ** The following asserts make sure that structures used by the btree are
  58056. ** the right size. This is to guard against size changes that result
  58057. ** when compiling on a different architecture.
  58058. */
  58059. assert( sizeof(i64)==8 );
  58060. assert( sizeof(u64)==8 );
  58061. assert( sizeof(u32)==4 );
  58062. assert( sizeof(u16)==2 );
  58063. assert( sizeof(Pgno)==4 );
  58064. pBt = sqlite3MallocZero( sizeof(*pBt) );
  58065. if( pBt==0 ){
  58066. rc = SQLITE_NOMEM_BKPT;
  58067. goto btree_open_out;
  58068. }
  58069. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  58070. sizeof(MemPage), flags, vfsFlags, pageReinit);
  58071. if( rc==SQLITE_OK ){
  58072. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  58073. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  58074. }
  58075. if( rc!=SQLITE_OK ){
  58076. goto btree_open_out;
  58077. }
  58078. pBt->openFlags = (u8)flags;
  58079. pBt->db = db;
  58080. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  58081. p->pBt = pBt;
  58082. pBt->pCursor = 0;
  58083. pBt->pPage1 = 0;
  58084. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  58085. #if defined(SQLITE_SECURE_DELETE)
  58086. pBt->btsFlags |= BTS_SECURE_DELETE;
  58087. #elif defined(SQLITE_FAST_SECURE_DELETE)
  58088. pBt->btsFlags |= BTS_OVERWRITE;
  58089. #endif
  58090. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  58091. ** determined by the 2-byte integer located at an offset of 16 bytes from
  58092. ** the beginning of the database file. */
  58093. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  58094. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  58095. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  58096. pBt->pageSize = 0;
  58097. #ifndef SQLITE_OMIT_AUTOVACUUM
  58098. /* If the magic name ":memory:" will create an in-memory database, then
  58099. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  58100. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  58101. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  58102. ** regular file-name. In this case the auto-vacuum applies as per normal.
  58103. */
  58104. if( zFilename && !isMemdb ){
  58105. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  58106. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  58107. }
  58108. #endif
  58109. nReserve = 0;
  58110. }else{
  58111. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  58112. ** determined by the one-byte unsigned integer found at an offset of 20
  58113. ** into the database file header. */
  58114. nReserve = zDbHeader[20];
  58115. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  58116. #ifndef SQLITE_OMIT_AUTOVACUUM
  58117. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  58118. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  58119. #endif
  58120. }
  58121. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  58122. if( rc ) goto btree_open_out;
  58123. pBt->usableSize = pBt->pageSize - nReserve;
  58124. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  58125. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  58126. /* Add the new BtShared object to the linked list sharable BtShareds.
  58127. */
  58128. pBt->nRef = 1;
  58129. if( p->sharable ){
  58130. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  58131. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  58132. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  58133. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  58134. if( pBt->mutex==0 ){
  58135. rc = SQLITE_NOMEM_BKPT;
  58136. goto btree_open_out;
  58137. }
  58138. }
  58139. sqlite3_mutex_enter(mutexShared);
  58140. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  58141. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  58142. sqlite3_mutex_leave(mutexShared);
  58143. }
  58144. #endif
  58145. }
  58146. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  58147. /* If the new Btree uses a sharable pBtShared, then link the new
  58148. ** Btree into the list of all sharable Btrees for the same connection.
  58149. ** The list is kept in ascending order by pBt address.
  58150. */
  58151. if( p->sharable ){
  58152. int i;
  58153. Btree *pSib;
  58154. for(i=0; i<db->nDb; i++){
  58155. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  58156. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  58157. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  58158. p->pNext = pSib;
  58159. p->pPrev = 0;
  58160. pSib->pPrev = p;
  58161. }else{
  58162. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  58163. pSib = pSib->pNext;
  58164. }
  58165. p->pNext = pSib->pNext;
  58166. p->pPrev = pSib;
  58167. if( p->pNext ){
  58168. p->pNext->pPrev = p;
  58169. }
  58170. pSib->pNext = p;
  58171. }
  58172. break;
  58173. }
  58174. }
  58175. }
  58176. #endif
  58177. *ppBtree = p;
  58178. btree_open_out:
  58179. if( rc!=SQLITE_OK ){
  58180. if( pBt && pBt->pPager ){
  58181. sqlite3PagerClose(pBt->pPager, 0);
  58182. }
  58183. sqlite3_free(pBt);
  58184. sqlite3_free(p);
  58185. *ppBtree = 0;
  58186. }else{
  58187. sqlite3_file *pFile;
  58188. /* If the B-Tree was successfully opened, set the pager-cache size to the
  58189. ** default value. Except, when opening on an existing shared pager-cache,
  58190. ** do not change the pager-cache size.
  58191. */
  58192. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  58193. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  58194. }
  58195. pFile = sqlite3PagerFile(pBt->pPager);
  58196. if( pFile->pMethods ){
  58197. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  58198. }
  58199. }
  58200. if( mutexOpen ){
  58201. assert( sqlite3_mutex_held(mutexOpen) );
  58202. sqlite3_mutex_leave(mutexOpen);
  58203. }
  58204. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  58205. return rc;
  58206. }
  58207. /*
  58208. ** Decrement the BtShared.nRef counter. When it reaches zero,
  58209. ** remove the BtShared structure from the sharing list. Return
  58210. ** true if the BtShared.nRef counter reaches zero and return
  58211. ** false if it is still positive.
  58212. */
  58213. static int removeFromSharingList(BtShared *pBt){
  58214. #ifndef SQLITE_OMIT_SHARED_CACHE
  58215. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  58216. BtShared *pList;
  58217. int removed = 0;
  58218. assert( sqlite3_mutex_notheld(pBt->mutex) );
  58219. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  58220. sqlite3_mutex_enter(pMaster);
  58221. pBt->nRef--;
  58222. if( pBt->nRef<=0 ){
  58223. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  58224. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  58225. }else{
  58226. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  58227. while( ALWAYS(pList) && pList->pNext!=pBt ){
  58228. pList=pList->pNext;
  58229. }
  58230. if( ALWAYS(pList) ){
  58231. pList->pNext = pBt->pNext;
  58232. }
  58233. }
  58234. if( SQLITE_THREADSAFE ){
  58235. sqlite3_mutex_free(pBt->mutex);
  58236. }
  58237. removed = 1;
  58238. }
  58239. sqlite3_mutex_leave(pMaster);
  58240. return removed;
  58241. #else
  58242. return 1;
  58243. #endif
  58244. }
  58245. /*
  58246. ** Make sure pBt->pTmpSpace points to an allocation of
  58247. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  58248. ** pointer.
  58249. */
  58250. static void allocateTempSpace(BtShared *pBt){
  58251. if( !pBt->pTmpSpace ){
  58252. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  58253. /* One of the uses of pBt->pTmpSpace is to format cells before
  58254. ** inserting them into a leaf page (function fillInCell()). If
  58255. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  58256. ** by the various routines that manipulate binary cells. Which
  58257. ** can mean that fillInCell() only initializes the first 2 or 3
  58258. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  58259. ** it into a database page. This is not actually a problem, but it
  58260. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  58261. ** data is passed to system call write(). So to avoid this error,
  58262. ** zero the first 4 bytes of temp space here.
  58263. **
  58264. ** Also: Provide four bytes of initialized space before the
  58265. ** beginning of pTmpSpace as an area available to prepend the
  58266. ** left-child pointer to the beginning of a cell.
  58267. */
  58268. if( pBt->pTmpSpace ){
  58269. memset(pBt->pTmpSpace, 0, 8);
  58270. pBt->pTmpSpace += 4;
  58271. }
  58272. }
  58273. }
  58274. /*
  58275. ** Free the pBt->pTmpSpace allocation
  58276. */
  58277. static void freeTempSpace(BtShared *pBt){
  58278. if( pBt->pTmpSpace ){
  58279. pBt->pTmpSpace -= 4;
  58280. sqlite3PageFree(pBt->pTmpSpace);
  58281. pBt->pTmpSpace = 0;
  58282. }
  58283. }
  58284. /*
  58285. ** Close an open database and invalidate all cursors.
  58286. */
  58287. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  58288. BtShared *pBt = p->pBt;
  58289. BtCursor *pCur;
  58290. /* Close all cursors opened via this handle. */
  58291. assert( sqlite3_mutex_held(p->db->mutex) );
  58292. sqlite3BtreeEnter(p);
  58293. pCur = pBt->pCursor;
  58294. while( pCur ){
  58295. BtCursor *pTmp = pCur;
  58296. pCur = pCur->pNext;
  58297. if( pTmp->pBtree==p ){
  58298. sqlite3BtreeCloseCursor(pTmp);
  58299. }
  58300. }
  58301. /* Rollback any active transaction and free the handle structure.
  58302. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  58303. ** this handle.
  58304. */
  58305. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  58306. sqlite3BtreeLeave(p);
  58307. /* If there are still other outstanding references to the shared-btree
  58308. ** structure, return now. The remainder of this procedure cleans
  58309. ** up the shared-btree.
  58310. */
  58311. assert( p->wantToLock==0 && p->locked==0 );
  58312. if( !p->sharable || removeFromSharingList(pBt) ){
  58313. /* The pBt is no longer on the sharing list, so we can access
  58314. ** it without having to hold the mutex.
  58315. **
  58316. ** Clean out and delete the BtShared object.
  58317. */
  58318. assert( !pBt->pCursor );
  58319. sqlite3PagerClose(pBt->pPager, p->db);
  58320. if( pBt->xFreeSchema && pBt->pSchema ){
  58321. pBt->xFreeSchema(pBt->pSchema);
  58322. }
  58323. sqlite3DbFree(0, pBt->pSchema);
  58324. freeTempSpace(pBt);
  58325. sqlite3_free(pBt);
  58326. }
  58327. #ifndef SQLITE_OMIT_SHARED_CACHE
  58328. assert( p->wantToLock==0 );
  58329. assert( p->locked==0 );
  58330. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  58331. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  58332. #endif
  58333. sqlite3_free(p);
  58334. return SQLITE_OK;
  58335. }
  58336. /*
  58337. ** Change the "soft" limit on the number of pages in the cache.
  58338. ** Unused and unmodified pages will be recycled when the number of
  58339. ** pages in the cache exceeds this soft limit. But the size of the
  58340. ** cache is allowed to grow larger than this limit if it contains
  58341. ** dirty pages or pages still in active use.
  58342. */
  58343. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  58344. BtShared *pBt = p->pBt;
  58345. assert( sqlite3_mutex_held(p->db->mutex) );
  58346. sqlite3BtreeEnter(p);
  58347. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  58348. sqlite3BtreeLeave(p);
  58349. return SQLITE_OK;
  58350. }
  58351. /*
  58352. ** Change the "spill" limit on the number of pages in the cache.
  58353. ** If the number of pages exceeds this limit during a write transaction,
  58354. ** the pager might attempt to "spill" pages to the journal early in
  58355. ** order to free up memory.
  58356. **
  58357. ** The value returned is the current spill size. If zero is passed
  58358. ** as an argument, no changes are made to the spill size setting, so
  58359. ** using mxPage of 0 is a way to query the current spill size.
  58360. */
  58361. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  58362. BtShared *pBt = p->pBt;
  58363. int res;
  58364. assert( sqlite3_mutex_held(p->db->mutex) );
  58365. sqlite3BtreeEnter(p);
  58366. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  58367. sqlite3BtreeLeave(p);
  58368. return res;
  58369. }
  58370. #if SQLITE_MAX_MMAP_SIZE>0
  58371. /*
  58372. ** Change the limit on the amount of the database file that may be
  58373. ** memory mapped.
  58374. */
  58375. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  58376. BtShared *pBt = p->pBt;
  58377. assert( sqlite3_mutex_held(p->db->mutex) );
  58378. sqlite3BtreeEnter(p);
  58379. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  58380. sqlite3BtreeLeave(p);
  58381. return SQLITE_OK;
  58382. }
  58383. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  58384. /*
  58385. ** Change the way data is synced to disk in order to increase or decrease
  58386. ** how well the database resists damage due to OS crashes and power
  58387. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  58388. ** there is a high probability of damage) Level 2 is the default. There
  58389. ** is a very low but non-zero probability of damage. Level 3 reduces the
  58390. ** probability of damage to near zero but with a write performance reduction.
  58391. */
  58392. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  58393. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  58394. Btree *p, /* The btree to set the safety level on */
  58395. unsigned pgFlags /* Various PAGER_* flags */
  58396. ){
  58397. BtShared *pBt = p->pBt;
  58398. assert( sqlite3_mutex_held(p->db->mutex) );
  58399. sqlite3BtreeEnter(p);
  58400. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  58401. sqlite3BtreeLeave(p);
  58402. return SQLITE_OK;
  58403. }
  58404. #endif
  58405. /*
  58406. ** Change the default pages size and the number of reserved bytes per page.
  58407. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  58408. ** without changing anything.
  58409. **
  58410. ** The page size must be a power of 2 between 512 and 65536. If the page
  58411. ** size supplied does not meet this constraint then the page size is not
  58412. ** changed.
  58413. **
  58414. ** Page sizes are constrained to be a power of two so that the region
  58415. ** of the database file used for locking (beginning at PENDING_BYTE,
  58416. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  58417. ** at the beginning of a page.
  58418. **
  58419. ** If parameter nReserve is less than zero, then the number of reserved
  58420. ** bytes per page is left unchanged.
  58421. **
  58422. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  58423. ** and autovacuum mode can no longer be changed.
  58424. */
  58425. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  58426. int rc = SQLITE_OK;
  58427. BtShared *pBt = p->pBt;
  58428. assert( nReserve>=-1 && nReserve<=255 );
  58429. sqlite3BtreeEnter(p);
  58430. #if SQLITE_HAS_CODEC
  58431. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  58432. #endif
  58433. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  58434. sqlite3BtreeLeave(p);
  58435. return SQLITE_READONLY;
  58436. }
  58437. if( nReserve<0 ){
  58438. nReserve = pBt->pageSize - pBt->usableSize;
  58439. }
  58440. assert( nReserve>=0 && nReserve<=255 );
  58441. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  58442. ((pageSize-1)&pageSize)==0 ){
  58443. assert( (pageSize & 7)==0 );
  58444. assert( !pBt->pCursor );
  58445. pBt->pageSize = (u32)pageSize;
  58446. freeTempSpace(pBt);
  58447. }
  58448. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  58449. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  58450. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  58451. sqlite3BtreeLeave(p);
  58452. return rc;
  58453. }
  58454. /*
  58455. ** Return the currently defined page size
  58456. */
  58457. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  58458. return p->pBt->pageSize;
  58459. }
  58460. /*
  58461. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  58462. ** may only be called if it is guaranteed that the b-tree mutex is already
  58463. ** held.
  58464. **
  58465. ** This is useful in one special case in the backup API code where it is
  58466. ** known that the shared b-tree mutex is held, but the mutex on the
  58467. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  58468. ** were to be called, it might collide with some other operation on the
  58469. ** database handle that owns *p, causing undefined behavior.
  58470. */
  58471. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  58472. int n;
  58473. assert( sqlite3_mutex_held(p->pBt->mutex) );
  58474. n = p->pBt->pageSize - p->pBt->usableSize;
  58475. return n;
  58476. }
  58477. /*
  58478. ** Return the number of bytes of space at the end of every page that
  58479. ** are intentually left unused. This is the "reserved" space that is
  58480. ** sometimes used by extensions.
  58481. **
  58482. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  58483. ** greater of the current reserved space and the maximum requested
  58484. ** reserve space.
  58485. */
  58486. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  58487. int n;
  58488. sqlite3BtreeEnter(p);
  58489. n = sqlite3BtreeGetReserveNoMutex(p);
  58490. #ifdef SQLITE_HAS_CODEC
  58491. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  58492. #endif
  58493. sqlite3BtreeLeave(p);
  58494. return n;
  58495. }
  58496. /*
  58497. ** Set the maximum page count for a database if mxPage is positive.
  58498. ** No changes are made if mxPage is 0 or negative.
  58499. ** Regardless of the value of mxPage, return the maximum page count.
  58500. */
  58501. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  58502. int n;
  58503. sqlite3BtreeEnter(p);
  58504. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  58505. sqlite3BtreeLeave(p);
  58506. return n;
  58507. }
  58508. /*
  58509. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  58510. **
  58511. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  58512. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  58513. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  58514. ** newFlag==(-1) No changes
  58515. **
  58516. ** This routine acts as a query if newFlag is less than zero
  58517. **
  58518. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  58519. ** freelist leaf pages are not written back to the database. Thus in-page
  58520. ** deleted content is cleared, but freelist deleted content is not.
  58521. **
  58522. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  58523. ** that freelist leaf pages are written back into the database, increasing
  58524. ** the amount of disk I/O.
  58525. */
  58526. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  58527. int b;
  58528. if( p==0 ) return 0;
  58529. sqlite3BtreeEnter(p);
  58530. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  58531. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  58532. if( newFlag>=0 ){
  58533. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  58534. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  58535. }
  58536. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  58537. sqlite3BtreeLeave(p);
  58538. return b;
  58539. }
  58540. /*
  58541. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  58542. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  58543. ** is disabled. The default value for the auto-vacuum property is
  58544. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  58545. */
  58546. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  58547. #ifdef SQLITE_OMIT_AUTOVACUUM
  58548. return SQLITE_READONLY;
  58549. #else
  58550. BtShared *pBt = p->pBt;
  58551. int rc = SQLITE_OK;
  58552. u8 av = (u8)autoVacuum;
  58553. sqlite3BtreeEnter(p);
  58554. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  58555. rc = SQLITE_READONLY;
  58556. }else{
  58557. pBt->autoVacuum = av ?1:0;
  58558. pBt->incrVacuum = av==2 ?1:0;
  58559. }
  58560. sqlite3BtreeLeave(p);
  58561. return rc;
  58562. #endif
  58563. }
  58564. /*
  58565. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  58566. ** enabled 1 is returned. Otherwise 0.
  58567. */
  58568. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  58569. #ifdef SQLITE_OMIT_AUTOVACUUM
  58570. return BTREE_AUTOVACUUM_NONE;
  58571. #else
  58572. int rc;
  58573. sqlite3BtreeEnter(p);
  58574. rc = (
  58575. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  58576. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  58577. BTREE_AUTOVACUUM_INCR
  58578. );
  58579. sqlite3BtreeLeave(p);
  58580. return rc;
  58581. #endif
  58582. }
  58583. /*
  58584. ** If the user has not set the safety-level for this database connection
  58585. ** using "PRAGMA synchronous", and if the safety-level is not already
  58586. ** set to the value passed to this function as the second parameter,
  58587. ** set it so.
  58588. */
  58589. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  58590. && !defined(SQLITE_OMIT_WAL)
  58591. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  58592. sqlite3 *db;
  58593. Db *pDb;
  58594. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  58595. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  58596. if( pDb->bSyncSet==0
  58597. && pDb->safety_level!=safety_level
  58598. && pDb!=&db->aDb[1]
  58599. ){
  58600. pDb->safety_level = safety_level;
  58601. sqlite3PagerSetFlags(pBt->pPager,
  58602. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  58603. }
  58604. }
  58605. }
  58606. #else
  58607. # define setDefaultSyncFlag(pBt,safety_level)
  58608. #endif
  58609. /*
  58610. ** Get a reference to pPage1 of the database file. This will
  58611. ** also acquire a readlock on that file.
  58612. **
  58613. ** SQLITE_OK is returned on success. If the file is not a
  58614. ** well-formed database file, then SQLITE_CORRUPT is returned.
  58615. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  58616. ** is returned if we run out of memory.
  58617. */
  58618. static int lockBtree(BtShared *pBt){
  58619. int rc; /* Result code from subfunctions */
  58620. MemPage *pPage1; /* Page 1 of the database file */
  58621. int nPage; /* Number of pages in the database */
  58622. int nPageFile = 0; /* Number of pages in the database file */
  58623. int nPageHeader; /* Number of pages in the database according to hdr */
  58624. assert( sqlite3_mutex_held(pBt->mutex) );
  58625. assert( pBt->pPage1==0 );
  58626. rc = sqlite3PagerSharedLock(pBt->pPager);
  58627. if( rc!=SQLITE_OK ) return rc;
  58628. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  58629. if( rc!=SQLITE_OK ) return rc;
  58630. /* Do some checking to help insure the file we opened really is
  58631. ** a valid database file.
  58632. */
  58633. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  58634. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  58635. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  58636. nPage = nPageFile;
  58637. }
  58638. if( nPage>0 ){
  58639. u32 pageSize;
  58640. u32 usableSize;
  58641. u8 *page1 = pPage1->aData;
  58642. rc = SQLITE_NOTADB;
  58643. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  58644. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  58645. ** 61 74 20 33 00. */
  58646. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  58647. goto page1_init_failed;
  58648. }
  58649. #ifdef SQLITE_OMIT_WAL
  58650. if( page1[18]>1 ){
  58651. pBt->btsFlags |= BTS_READ_ONLY;
  58652. }
  58653. if( page1[19]>1 ){
  58654. goto page1_init_failed;
  58655. }
  58656. #else
  58657. if( page1[18]>2 ){
  58658. pBt->btsFlags |= BTS_READ_ONLY;
  58659. }
  58660. if( page1[19]>2 ){
  58661. goto page1_init_failed;
  58662. }
  58663. /* If the write version is set to 2, this database should be accessed
  58664. ** in WAL mode. If the log is not already open, open it now. Then
  58665. ** return SQLITE_OK and return without populating BtShared.pPage1.
  58666. ** The caller detects this and calls this function again. This is
  58667. ** required as the version of page 1 currently in the page1 buffer
  58668. ** may not be the latest version - there may be a newer one in the log
  58669. ** file.
  58670. */
  58671. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  58672. int isOpen = 0;
  58673. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  58674. if( rc!=SQLITE_OK ){
  58675. goto page1_init_failed;
  58676. }else{
  58677. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  58678. if( isOpen==0 ){
  58679. releasePageOne(pPage1);
  58680. return SQLITE_OK;
  58681. }
  58682. }
  58683. rc = SQLITE_NOTADB;
  58684. }else{
  58685. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  58686. }
  58687. #endif
  58688. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  58689. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  58690. **
  58691. ** The original design allowed these amounts to vary, but as of
  58692. ** version 3.6.0, we require them to be fixed.
  58693. */
  58694. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  58695. goto page1_init_failed;
  58696. }
  58697. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  58698. ** determined by the 2-byte integer located at an offset of 16 bytes from
  58699. ** the beginning of the database file. */
  58700. pageSize = (page1[16]<<8) | (page1[17]<<16);
  58701. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  58702. ** between 512 and 65536 inclusive. */
  58703. if( ((pageSize-1)&pageSize)!=0
  58704. || pageSize>SQLITE_MAX_PAGE_SIZE
  58705. || pageSize<=256
  58706. ){
  58707. goto page1_init_failed;
  58708. }
  58709. assert( (pageSize & 7)==0 );
  58710. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  58711. ** integer at offset 20 is the number of bytes of space at the end of
  58712. ** each page to reserve for extensions.
  58713. **
  58714. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  58715. ** determined by the one-byte unsigned integer found at an offset of 20
  58716. ** into the database file header. */
  58717. usableSize = pageSize - page1[20];
  58718. if( (u32)pageSize!=pBt->pageSize ){
  58719. /* After reading the first page of the database assuming a page size
  58720. ** of BtShared.pageSize, we have discovered that the page-size is
  58721. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  58722. ** zero and return SQLITE_OK. The caller will call this function
  58723. ** again with the correct page-size.
  58724. */
  58725. releasePageOne(pPage1);
  58726. pBt->usableSize = usableSize;
  58727. pBt->pageSize = pageSize;
  58728. freeTempSpace(pBt);
  58729. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  58730. pageSize-usableSize);
  58731. return rc;
  58732. }
  58733. if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
  58734. rc = SQLITE_CORRUPT_BKPT;
  58735. goto page1_init_failed;
  58736. }
  58737. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  58738. ** be less than 480. In other words, if the page size is 512, then the
  58739. ** reserved space size cannot exceed 32. */
  58740. if( usableSize<480 ){
  58741. goto page1_init_failed;
  58742. }
  58743. pBt->pageSize = pageSize;
  58744. pBt->usableSize = usableSize;
  58745. #ifndef SQLITE_OMIT_AUTOVACUUM
  58746. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  58747. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  58748. #endif
  58749. }
  58750. /* maxLocal is the maximum amount of payload to store locally for
  58751. ** a cell. Make sure it is small enough so that at least minFanout
  58752. ** cells can will fit on one page. We assume a 10-byte page header.
  58753. ** Besides the payload, the cell must store:
  58754. ** 2-byte pointer to the cell
  58755. ** 4-byte child pointer
  58756. ** 9-byte nKey value
  58757. ** 4-byte nData value
  58758. ** 4-byte overflow page pointer
  58759. ** So a cell consists of a 2-byte pointer, a header which is as much as
  58760. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  58761. ** page pointer.
  58762. */
  58763. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  58764. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  58765. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  58766. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  58767. if( pBt->maxLocal>127 ){
  58768. pBt->max1bytePayload = 127;
  58769. }else{
  58770. pBt->max1bytePayload = (u8)pBt->maxLocal;
  58771. }
  58772. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  58773. pBt->pPage1 = pPage1;
  58774. pBt->nPage = nPage;
  58775. return SQLITE_OK;
  58776. page1_init_failed:
  58777. releasePageOne(pPage1);
  58778. pBt->pPage1 = 0;
  58779. return rc;
  58780. }
  58781. #ifndef NDEBUG
  58782. /*
  58783. ** Return the number of cursors open on pBt. This is for use
  58784. ** in assert() expressions, so it is only compiled if NDEBUG is not
  58785. ** defined.
  58786. **
  58787. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  58788. ** false then all cursors are counted.
  58789. **
  58790. ** For the purposes of this routine, a cursor is any cursor that
  58791. ** is capable of reading or writing to the database. Cursors that
  58792. ** have been tripped into the CURSOR_FAULT state are not counted.
  58793. */
  58794. static int countValidCursors(BtShared *pBt, int wrOnly){
  58795. BtCursor *pCur;
  58796. int r = 0;
  58797. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  58798. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  58799. && pCur->eState!=CURSOR_FAULT ) r++;
  58800. }
  58801. return r;
  58802. }
  58803. #endif
  58804. /*
  58805. ** If there are no outstanding cursors and we are not in the middle
  58806. ** of a transaction but there is a read lock on the database, then
  58807. ** this routine unrefs the first page of the database file which
  58808. ** has the effect of releasing the read lock.
  58809. **
  58810. ** If there is a transaction in progress, this routine is a no-op.
  58811. */
  58812. static void unlockBtreeIfUnused(BtShared *pBt){
  58813. assert( sqlite3_mutex_held(pBt->mutex) );
  58814. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  58815. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  58816. MemPage *pPage1 = pBt->pPage1;
  58817. assert( pPage1->aData );
  58818. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  58819. pBt->pPage1 = 0;
  58820. releasePageOne(pPage1);
  58821. }
  58822. }
  58823. /*
  58824. ** If pBt points to an empty file then convert that empty file
  58825. ** into a new empty database by initializing the first page of
  58826. ** the database.
  58827. */
  58828. static int newDatabase(BtShared *pBt){
  58829. MemPage *pP1;
  58830. unsigned char *data;
  58831. int rc;
  58832. assert( sqlite3_mutex_held(pBt->mutex) );
  58833. if( pBt->nPage>0 ){
  58834. return SQLITE_OK;
  58835. }
  58836. pP1 = pBt->pPage1;
  58837. assert( pP1!=0 );
  58838. data = pP1->aData;
  58839. rc = sqlite3PagerWrite(pP1->pDbPage);
  58840. if( rc ) return rc;
  58841. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  58842. assert( sizeof(zMagicHeader)==16 );
  58843. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  58844. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  58845. data[18] = 1;
  58846. data[19] = 1;
  58847. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  58848. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  58849. data[21] = 64;
  58850. data[22] = 32;
  58851. data[23] = 32;
  58852. memset(&data[24], 0, 100-24);
  58853. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  58854. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  58855. #ifndef SQLITE_OMIT_AUTOVACUUM
  58856. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  58857. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  58858. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  58859. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  58860. #endif
  58861. pBt->nPage = 1;
  58862. data[31] = 1;
  58863. return SQLITE_OK;
  58864. }
  58865. /*
  58866. ** Initialize the first page of the database file (creating a database
  58867. ** consisting of a single page and no schema objects). Return SQLITE_OK
  58868. ** if successful, or an SQLite error code otherwise.
  58869. */
  58870. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  58871. int rc;
  58872. sqlite3BtreeEnter(p);
  58873. p->pBt->nPage = 0;
  58874. rc = newDatabase(p->pBt);
  58875. sqlite3BtreeLeave(p);
  58876. return rc;
  58877. }
  58878. /*
  58879. ** Attempt to start a new transaction. A write-transaction
  58880. ** is started if the second argument is nonzero, otherwise a read-
  58881. ** transaction. If the second argument is 2 or more and exclusive
  58882. ** transaction is started, meaning that no other process is allowed
  58883. ** to access the database. A preexisting transaction may not be
  58884. ** upgraded to exclusive by calling this routine a second time - the
  58885. ** exclusivity flag only works for a new transaction.
  58886. **
  58887. ** A write-transaction must be started before attempting any
  58888. ** changes to the database. None of the following routines
  58889. ** will work unless a transaction is started first:
  58890. **
  58891. ** sqlite3BtreeCreateTable()
  58892. ** sqlite3BtreeCreateIndex()
  58893. ** sqlite3BtreeClearTable()
  58894. ** sqlite3BtreeDropTable()
  58895. ** sqlite3BtreeInsert()
  58896. ** sqlite3BtreeDelete()
  58897. ** sqlite3BtreeUpdateMeta()
  58898. **
  58899. ** If an initial attempt to acquire the lock fails because of lock contention
  58900. ** and the database was previously unlocked, then invoke the busy handler
  58901. ** if there is one. But if there was previously a read-lock, do not
  58902. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  58903. ** returned when there is already a read-lock in order to avoid a deadlock.
  58904. **
  58905. ** Suppose there are two processes A and B. A has a read lock and B has
  58906. ** a reserved lock. B tries to promote to exclusive but is blocked because
  58907. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  58908. ** One or the other of the two processes must give way or there can be
  58909. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  58910. ** when A already has a read lock, we encourage A to give up and let B
  58911. ** proceed.
  58912. */
  58913. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  58914. BtShared *pBt = p->pBt;
  58915. int rc = SQLITE_OK;
  58916. sqlite3BtreeEnter(p);
  58917. btreeIntegrity(p);
  58918. /* If the btree is already in a write-transaction, or it
  58919. ** is already in a read-transaction and a read-transaction
  58920. ** is requested, this is a no-op.
  58921. */
  58922. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  58923. goto trans_begun;
  58924. }
  58925. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  58926. /* Write transactions are not possible on a read-only database */
  58927. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  58928. rc = SQLITE_READONLY;
  58929. goto trans_begun;
  58930. }
  58931. #ifndef SQLITE_OMIT_SHARED_CACHE
  58932. {
  58933. sqlite3 *pBlock = 0;
  58934. /* If another database handle has already opened a write transaction
  58935. ** on this shared-btree structure and a second write transaction is
  58936. ** requested, return SQLITE_LOCKED.
  58937. */
  58938. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  58939. || (pBt->btsFlags & BTS_PENDING)!=0
  58940. ){
  58941. pBlock = pBt->pWriter->db;
  58942. }else if( wrflag>1 ){
  58943. BtLock *pIter;
  58944. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58945. if( pIter->pBtree!=p ){
  58946. pBlock = pIter->pBtree->db;
  58947. break;
  58948. }
  58949. }
  58950. }
  58951. if( pBlock ){
  58952. sqlite3ConnectionBlocked(p->db, pBlock);
  58953. rc = SQLITE_LOCKED_SHAREDCACHE;
  58954. goto trans_begun;
  58955. }
  58956. }
  58957. #endif
  58958. /* Any read-only or read-write transaction implies a read-lock on
  58959. ** page 1. So if some other shared-cache client already has a write-lock
  58960. ** on page 1, the transaction cannot be opened. */
  58961. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  58962. if( SQLITE_OK!=rc ) goto trans_begun;
  58963. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  58964. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  58965. do {
  58966. /* Call lockBtree() until either pBt->pPage1 is populated or
  58967. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  58968. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  58969. ** reading page 1 it discovers that the page-size of the database
  58970. ** file is not pBt->pageSize. In this case lockBtree() will update
  58971. ** pBt->pageSize to the page-size of the file on disk.
  58972. */
  58973. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  58974. if( rc==SQLITE_OK && wrflag ){
  58975. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  58976. rc = SQLITE_READONLY;
  58977. }else{
  58978. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  58979. if( rc==SQLITE_OK ){
  58980. rc = newDatabase(pBt);
  58981. }
  58982. }
  58983. }
  58984. if( rc!=SQLITE_OK ){
  58985. unlockBtreeIfUnused(pBt);
  58986. }
  58987. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  58988. btreeInvokeBusyHandler(pBt) );
  58989. if( rc==SQLITE_OK ){
  58990. if( p->inTrans==TRANS_NONE ){
  58991. pBt->nTransaction++;
  58992. #ifndef SQLITE_OMIT_SHARED_CACHE
  58993. if( p->sharable ){
  58994. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  58995. p->lock.eLock = READ_LOCK;
  58996. p->lock.pNext = pBt->pLock;
  58997. pBt->pLock = &p->lock;
  58998. }
  58999. #endif
  59000. }
  59001. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  59002. if( p->inTrans>pBt->inTransaction ){
  59003. pBt->inTransaction = p->inTrans;
  59004. }
  59005. if( wrflag ){
  59006. MemPage *pPage1 = pBt->pPage1;
  59007. #ifndef SQLITE_OMIT_SHARED_CACHE
  59008. assert( !pBt->pWriter );
  59009. pBt->pWriter = p;
  59010. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  59011. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  59012. #endif
  59013. /* If the db-size header field is incorrect (as it may be if an old
  59014. ** client has been writing the database file), update it now. Doing
  59015. ** this sooner rather than later means the database size can safely
  59016. ** re-read the database size from page 1 if a savepoint or transaction
  59017. ** rollback occurs within the transaction.
  59018. */
  59019. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  59020. rc = sqlite3PagerWrite(pPage1->pDbPage);
  59021. if( rc==SQLITE_OK ){
  59022. put4byte(&pPage1->aData[28], pBt->nPage);
  59023. }
  59024. }
  59025. }
  59026. }
  59027. trans_begun:
  59028. if( rc==SQLITE_OK && wrflag ){
  59029. /* This call makes sure that the pager has the correct number of
  59030. ** open savepoints. If the second parameter is greater than 0 and
  59031. ** the sub-journal is not already open, then it will be opened here.
  59032. */
  59033. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  59034. }
  59035. btreeIntegrity(p);
  59036. sqlite3BtreeLeave(p);
  59037. return rc;
  59038. }
  59039. #ifndef SQLITE_OMIT_AUTOVACUUM
  59040. /*
  59041. ** Set the pointer-map entries for all children of page pPage. Also, if
  59042. ** pPage contains cells that point to overflow pages, set the pointer
  59043. ** map entries for the overflow pages as well.
  59044. */
  59045. static int setChildPtrmaps(MemPage *pPage){
  59046. int i; /* Counter variable */
  59047. int nCell; /* Number of cells in page pPage */
  59048. int rc; /* Return code */
  59049. BtShared *pBt = pPage->pBt;
  59050. Pgno pgno = pPage->pgno;
  59051. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59052. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  59053. if( rc!=SQLITE_OK ) return rc;
  59054. nCell = pPage->nCell;
  59055. for(i=0; i<nCell; i++){
  59056. u8 *pCell = findCell(pPage, i);
  59057. ptrmapPutOvflPtr(pPage, pCell, &rc);
  59058. if( !pPage->leaf ){
  59059. Pgno childPgno = get4byte(pCell);
  59060. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  59061. }
  59062. }
  59063. if( !pPage->leaf ){
  59064. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  59065. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  59066. }
  59067. return rc;
  59068. }
  59069. /*
  59070. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  59071. ** that it points to iTo. Parameter eType describes the type of pointer to
  59072. ** be modified, as follows:
  59073. **
  59074. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  59075. ** page of pPage.
  59076. **
  59077. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  59078. ** page pointed to by one of the cells on pPage.
  59079. **
  59080. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  59081. ** overflow page in the list.
  59082. */
  59083. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  59084. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59085. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59086. if( eType==PTRMAP_OVERFLOW2 ){
  59087. /* The pointer is always the first 4 bytes of the page in this case. */
  59088. if( get4byte(pPage->aData)!=iFrom ){
  59089. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  59090. }
  59091. put4byte(pPage->aData, iTo);
  59092. }else{
  59093. int i;
  59094. int nCell;
  59095. int rc;
  59096. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  59097. if( rc ) return rc;
  59098. nCell = pPage->nCell;
  59099. for(i=0; i<nCell; i++){
  59100. u8 *pCell = findCell(pPage, i);
  59101. if( eType==PTRMAP_OVERFLOW1 ){
  59102. CellInfo info;
  59103. pPage->xParseCell(pPage, pCell, &info);
  59104. if( info.nLocal<info.nPayload ){
  59105. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  59106. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  59107. }
  59108. if( iFrom==get4byte(pCell+info.nSize-4) ){
  59109. put4byte(pCell+info.nSize-4, iTo);
  59110. break;
  59111. }
  59112. }
  59113. }else{
  59114. if( get4byte(pCell)==iFrom ){
  59115. put4byte(pCell, iTo);
  59116. break;
  59117. }
  59118. }
  59119. }
  59120. if( i==nCell ){
  59121. if( eType!=PTRMAP_BTREE ||
  59122. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  59123. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  59124. }
  59125. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  59126. }
  59127. }
  59128. return SQLITE_OK;
  59129. }
  59130. /*
  59131. ** Move the open database page pDbPage to location iFreePage in the
  59132. ** database. The pDbPage reference remains valid.
  59133. **
  59134. ** The isCommit flag indicates that there is no need to remember that
  59135. ** the journal needs to be sync()ed before database page pDbPage->pgno
  59136. ** can be written to. The caller has already promised not to write to that
  59137. ** page.
  59138. */
  59139. static int relocatePage(
  59140. BtShared *pBt, /* Btree */
  59141. MemPage *pDbPage, /* Open page to move */
  59142. u8 eType, /* Pointer map 'type' entry for pDbPage */
  59143. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  59144. Pgno iFreePage, /* The location to move pDbPage to */
  59145. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  59146. ){
  59147. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  59148. Pgno iDbPage = pDbPage->pgno;
  59149. Pager *pPager = pBt->pPager;
  59150. int rc;
  59151. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  59152. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  59153. assert( sqlite3_mutex_held(pBt->mutex) );
  59154. assert( pDbPage->pBt==pBt );
  59155. /* Move page iDbPage from its current location to page number iFreePage */
  59156. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  59157. iDbPage, iFreePage, iPtrPage, eType));
  59158. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  59159. if( rc!=SQLITE_OK ){
  59160. return rc;
  59161. }
  59162. pDbPage->pgno = iFreePage;
  59163. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  59164. ** that point to overflow pages. The pointer map entries for all these
  59165. ** pages need to be changed.
  59166. **
  59167. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  59168. ** pointer to a subsequent overflow page. If this is the case, then
  59169. ** the pointer map needs to be updated for the subsequent overflow page.
  59170. */
  59171. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  59172. rc = setChildPtrmaps(pDbPage);
  59173. if( rc!=SQLITE_OK ){
  59174. return rc;
  59175. }
  59176. }else{
  59177. Pgno nextOvfl = get4byte(pDbPage->aData);
  59178. if( nextOvfl!=0 ){
  59179. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  59180. if( rc!=SQLITE_OK ){
  59181. return rc;
  59182. }
  59183. }
  59184. }
  59185. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  59186. ** that it points at iFreePage. Also fix the pointer map entry for
  59187. ** iPtrPage.
  59188. */
  59189. if( eType!=PTRMAP_ROOTPAGE ){
  59190. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  59191. if( rc!=SQLITE_OK ){
  59192. return rc;
  59193. }
  59194. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  59195. if( rc!=SQLITE_OK ){
  59196. releasePage(pPtrPage);
  59197. return rc;
  59198. }
  59199. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  59200. releasePage(pPtrPage);
  59201. if( rc==SQLITE_OK ){
  59202. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  59203. }
  59204. }
  59205. return rc;
  59206. }
  59207. /* Forward declaration required by incrVacuumStep(). */
  59208. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  59209. /*
  59210. ** Perform a single step of an incremental-vacuum. If successful, return
  59211. ** SQLITE_OK. If there is no work to do (and therefore no point in
  59212. ** calling this function again), return SQLITE_DONE. Or, if an error
  59213. ** occurs, return some other error code.
  59214. **
  59215. ** More specifically, this function attempts to re-organize the database so
  59216. ** that the last page of the file currently in use is no longer in use.
  59217. **
  59218. ** Parameter nFin is the number of pages that this database would contain
  59219. ** were this function called until it returns SQLITE_DONE.
  59220. **
  59221. ** If the bCommit parameter is non-zero, this function assumes that the
  59222. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  59223. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  59224. ** operation, or false for an incremental vacuum.
  59225. */
  59226. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  59227. Pgno nFreeList; /* Number of pages still on the free-list */
  59228. int rc;
  59229. assert( sqlite3_mutex_held(pBt->mutex) );
  59230. assert( iLastPg>nFin );
  59231. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  59232. u8 eType;
  59233. Pgno iPtrPage;
  59234. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  59235. if( nFreeList==0 ){
  59236. return SQLITE_DONE;
  59237. }
  59238. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  59239. if( rc!=SQLITE_OK ){
  59240. return rc;
  59241. }
  59242. if( eType==PTRMAP_ROOTPAGE ){
  59243. return SQLITE_CORRUPT_BKPT;
  59244. }
  59245. if( eType==PTRMAP_FREEPAGE ){
  59246. if( bCommit==0 ){
  59247. /* Remove the page from the files free-list. This is not required
  59248. ** if bCommit is non-zero. In that case, the free-list will be
  59249. ** truncated to zero after this function returns, so it doesn't
  59250. ** matter if it still contains some garbage entries.
  59251. */
  59252. Pgno iFreePg;
  59253. MemPage *pFreePg;
  59254. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  59255. if( rc!=SQLITE_OK ){
  59256. return rc;
  59257. }
  59258. assert( iFreePg==iLastPg );
  59259. releasePage(pFreePg);
  59260. }
  59261. } else {
  59262. Pgno iFreePg; /* Index of free page to move pLastPg to */
  59263. MemPage *pLastPg;
  59264. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  59265. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  59266. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  59267. if( rc!=SQLITE_OK ){
  59268. return rc;
  59269. }
  59270. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  59271. ** is swapped with the first free page pulled off the free list.
  59272. **
  59273. ** On the other hand, if bCommit is greater than zero, then keep
  59274. ** looping until a free-page located within the first nFin pages
  59275. ** of the file is found.
  59276. */
  59277. if( bCommit==0 ){
  59278. eMode = BTALLOC_LE;
  59279. iNear = nFin;
  59280. }
  59281. do {
  59282. MemPage *pFreePg;
  59283. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  59284. if( rc!=SQLITE_OK ){
  59285. releasePage(pLastPg);
  59286. return rc;
  59287. }
  59288. releasePage(pFreePg);
  59289. }while( bCommit && iFreePg>nFin );
  59290. assert( iFreePg<iLastPg );
  59291. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  59292. releasePage(pLastPg);
  59293. if( rc!=SQLITE_OK ){
  59294. return rc;
  59295. }
  59296. }
  59297. }
  59298. if( bCommit==0 ){
  59299. do {
  59300. iLastPg--;
  59301. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  59302. pBt->bDoTruncate = 1;
  59303. pBt->nPage = iLastPg;
  59304. }
  59305. return SQLITE_OK;
  59306. }
  59307. /*
  59308. ** The database opened by the first argument is an auto-vacuum database
  59309. ** nOrig pages in size containing nFree free pages. Return the expected
  59310. ** size of the database in pages following an auto-vacuum operation.
  59311. */
  59312. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  59313. int nEntry; /* Number of entries on one ptrmap page */
  59314. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  59315. Pgno nFin; /* Return value */
  59316. nEntry = pBt->usableSize/5;
  59317. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  59318. nFin = nOrig - nFree - nPtrmap;
  59319. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  59320. nFin--;
  59321. }
  59322. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  59323. nFin--;
  59324. }
  59325. return nFin;
  59326. }
  59327. /*
  59328. ** A write-transaction must be opened before calling this function.
  59329. ** It performs a single unit of work towards an incremental vacuum.
  59330. **
  59331. ** If the incremental vacuum is finished after this function has run,
  59332. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  59333. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  59334. */
  59335. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  59336. int rc;
  59337. BtShared *pBt = p->pBt;
  59338. sqlite3BtreeEnter(p);
  59339. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  59340. if( !pBt->autoVacuum ){
  59341. rc = SQLITE_DONE;
  59342. }else{
  59343. Pgno nOrig = btreePagecount(pBt);
  59344. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  59345. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  59346. if( nOrig<nFin ){
  59347. rc = SQLITE_CORRUPT_BKPT;
  59348. }else if( nFree>0 ){
  59349. rc = saveAllCursors(pBt, 0, 0);
  59350. if( rc==SQLITE_OK ){
  59351. invalidateAllOverflowCache(pBt);
  59352. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  59353. }
  59354. if( rc==SQLITE_OK ){
  59355. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  59356. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  59357. }
  59358. }else{
  59359. rc = SQLITE_DONE;
  59360. }
  59361. }
  59362. sqlite3BtreeLeave(p);
  59363. return rc;
  59364. }
  59365. /*
  59366. ** This routine is called prior to sqlite3PagerCommit when a transaction
  59367. ** is committed for an auto-vacuum database.
  59368. **
  59369. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  59370. ** the database file should be truncated to during the commit process.
  59371. ** i.e. the database has been reorganized so that only the first *pnTrunc
  59372. ** pages are in use.
  59373. */
  59374. static int autoVacuumCommit(BtShared *pBt){
  59375. int rc = SQLITE_OK;
  59376. Pager *pPager = pBt->pPager;
  59377. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  59378. assert( sqlite3_mutex_held(pBt->mutex) );
  59379. invalidateAllOverflowCache(pBt);
  59380. assert(pBt->autoVacuum);
  59381. if( !pBt->incrVacuum ){
  59382. Pgno nFin; /* Number of pages in database after autovacuuming */
  59383. Pgno nFree; /* Number of pages on the freelist initially */
  59384. Pgno iFree; /* The next page to be freed */
  59385. Pgno nOrig; /* Database size before freeing */
  59386. nOrig = btreePagecount(pBt);
  59387. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  59388. /* It is not possible to create a database for which the final page
  59389. ** is either a pointer-map page or the pending-byte page. If one
  59390. ** is encountered, this indicates corruption.
  59391. */
  59392. return SQLITE_CORRUPT_BKPT;
  59393. }
  59394. nFree = get4byte(&pBt->pPage1->aData[36]);
  59395. nFin = finalDbSize(pBt, nOrig, nFree);
  59396. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  59397. if( nFin<nOrig ){
  59398. rc = saveAllCursors(pBt, 0, 0);
  59399. }
  59400. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  59401. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  59402. }
  59403. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  59404. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  59405. put4byte(&pBt->pPage1->aData[32], 0);
  59406. put4byte(&pBt->pPage1->aData[36], 0);
  59407. put4byte(&pBt->pPage1->aData[28], nFin);
  59408. pBt->bDoTruncate = 1;
  59409. pBt->nPage = nFin;
  59410. }
  59411. if( rc!=SQLITE_OK ){
  59412. sqlite3PagerRollback(pPager);
  59413. }
  59414. }
  59415. assert( nRef>=sqlite3PagerRefcount(pPager) );
  59416. return rc;
  59417. }
  59418. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  59419. # define setChildPtrmaps(x) SQLITE_OK
  59420. #endif
  59421. /*
  59422. ** This routine does the first phase of a two-phase commit. This routine
  59423. ** causes a rollback journal to be created (if it does not already exist)
  59424. ** and populated with enough information so that if a power loss occurs
  59425. ** the database can be restored to its original state by playing back
  59426. ** the journal. Then the contents of the journal are flushed out to
  59427. ** the disk. After the journal is safely on oxide, the changes to the
  59428. ** database are written into the database file and flushed to oxide.
  59429. ** At the end of this call, the rollback journal still exists on the
  59430. ** disk and we are still holding all locks, so the transaction has not
  59431. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  59432. ** commit process.
  59433. **
  59434. ** This call is a no-op if no write-transaction is currently active on pBt.
  59435. **
  59436. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  59437. ** the name of a master journal file that should be written into the
  59438. ** individual journal file, or is NULL, indicating no master journal file
  59439. ** (single database transaction).
  59440. **
  59441. ** When this is called, the master journal should already have been
  59442. ** created, populated with this journal pointer and synced to disk.
  59443. **
  59444. ** Once this is routine has returned, the only thing required to commit
  59445. ** the write-transaction for this database file is to delete the journal.
  59446. */
  59447. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  59448. int rc = SQLITE_OK;
  59449. if( p->inTrans==TRANS_WRITE ){
  59450. BtShared *pBt = p->pBt;
  59451. sqlite3BtreeEnter(p);
  59452. #ifndef SQLITE_OMIT_AUTOVACUUM
  59453. if( pBt->autoVacuum ){
  59454. rc = autoVacuumCommit(pBt);
  59455. if( rc!=SQLITE_OK ){
  59456. sqlite3BtreeLeave(p);
  59457. return rc;
  59458. }
  59459. }
  59460. if( pBt->bDoTruncate ){
  59461. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  59462. }
  59463. #endif
  59464. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  59465. sqlite3BtreeLeave(p);
  59466. }
  59467. return rc;
  59468. }
  59469. /*
  59470. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  59471. ** at the conclusion of a transaction.
  59472. */
  59473. static void btreeEndTransaction(Btree *p){
  59474. BtShared *pBt = p->pBt;
  59475. sqlite3 *db = p->db;
  59476. assert( sqlite3BtreeHoldsMutex(p) );
  59477. #ifndef SQLITE_OMIT_AUTOVACUUM
  59478. pBt->bDoTruncate = 0;
  59479. #endif
  59480. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  59481. /* If there are other active statements that belong to this database
  59482. ** handle, downgrade to a read-only transaction. The other statements
  59483. ** may still be reading from the database. */
  59484. downgradeAllSharedCacheTableLocks(p);
  59485. p->inTrans = TRANS_READ;
  59486. }else{
  59487. /* If the handle had any kind of transaction open, decrement the
  59488. ** transaction count of the shared btree. If the transaction count
  59489. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  59490. ** call below will unlock the pager. */
  59491. if( p->inTrans!=TRANS_NONE ){
  59492. clearAllSharedCacheTableLocks(p);
  59493. pBt->nTransaction--;
  59494. if( 0==pBt->nTransaction ){
  59495. pBt->inTransaction = TRANS_NONE;
  59496. }
  59497. }
  59498. /* Set the current transaction state to TRANS_NONE and unlock the
  59499. ** pager if this call closed the only read or write transaction. */
  59500. p->inTrans = TRANS_NONE;
  59501. unlockBtreeIfUnused(pBt);
  59502. }
  59503. btreeIntegrity(p);
  59504. }
  59505. /*
  59506. ** Commit the transaction currently in progress.
  59507. **
  59508. ** This routine implements the second phase of a 2-phase commit. The
  59509. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  59510. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  59511. ** routine did all the work of writing information out to disk and flushing the
  59512. ** contents so that they are written onto the disk platter. All this
  59513. ** routine has to do is delete or truncate or zero the header in the
  59514. ** the rollback journal (which causes the transaction to commit) and
  59515. ** drop locks.
  59516. **
  59517. ** Normally, if an error occurs while the pager layer is attempting to
  59518. ** finalize the underlying journal file, this function returns an error and
  59519. ** the upper layer will attempt a rollback. However, if the second argument
  59520. ** is non-zero then this b-tree transaction is part of a multi-file
  59521. ** transaction. In this case, the transaction has already been committed
  59522. ** (by deleting a master journal file) and the caller will ignore this
  59523. ** functions return code. So, even if an error occurs in the pager layer,
  59524. ** reset the b-tree objects internal state to indicate that the write
  59525. ** transaction has been closed. This is quite safe, as the pager will have
  59526. ** transitioned to the error state.
  59527. **
  59528. ** This will release the write lock on the database file. If there
  59529. ** are no active cursors, it also releases the read lock.
  59530. */
  59531. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  59532. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  59533. sqlite3BtreeEnter(p);
  59534. btreeIntegrity(p);
  59535. /* If the handle has a write-transaction open, commit the shared-btrees
  59536. ** transaction and set the shared state to TRANS_READ.
  59537. */
  59538. if( p->inTrans==TRANS_WRITE ){
  59539. int rc;
  59540. BtShared *pBt = p->pBt;
  59541. assert( pBt->inTransaction==TRANS_WRITE );
  59542. assert( pBt->nTransaction>0 );
  59543. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  59544. if( rc!=SQLITE_OK && bCleanup==0 ){
  59545. sqlite3BtreeLeave(p);
  59546. return rc;
  59547. }
  59548. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  59549. pBt->inTransaction = TRANS_READ;
  59550. btreeClearHasContent(pBt);
  59551. }
  59552. btreeEndTransaction(p);
  59553. sqlite3BtreeLeave(p);
  59554. return SQLITE_OK;
  59555. }
  59556. /*
  59557. ** Do both phases of a commit.
  59558. */
  59559. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  59560. int rc;
  59561. sqlite3BtreeEnter(p);
  59562. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  59563. if( rc==SQLITE_OK ){
  59564. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  59565. }
  59566. sqlite3BtreeLeave(p);
  59567. return rc;
  59568. }
  59569. /*
  59570. ** This routine sets the state to CURSOR_FAULT and the error
  59571. ** code to errCode for every cursor on any BtShared that pBtree
  59572. ** references. Or if the writeOnly flag is set to 1, then only
  59573. ** trip write cursors and leave read cursors unchanged.
  59574. **
  59575. ** Every cursor is a candidate to be tripped, including cursors
  59576. ** that belong to other database connections that happen to be
  59577. ** sharing the cache with pBtree.
  59578. **
  59579. ** This routine gets called when a rollback occurs. If the writeOnly
  59580. ** flag is true, then only write-cursors need be tripped - read-only
  59581. ** cursors save their current positions so that they may continue
  59582. ** following the rollback. Or, if writeOnly is false, all cursors are
  59583. ** tripped. In general, writeOnly is false if the transaction being
  59584. ** rolled back modified the database schema. In this case b-tree root
  59585. ** pages may be moved or deleted from the database altogether, making
  59586. ** it unsafe for read cursors to continue.
  59587. **
  59588. ** If the writeOnly flag is true and an error is encountered while
  59589. ** saving the current position of a read-only cursor, all cursors,
  59590. ** including all read-cursors are tripped.
  59591. **
  59592. ** SQLITE_OK is returned if successful, or if an error occurs while
  59593. ** saving a cursor position, an SQLite error code.
  59594. */
  59595. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  59596. BtCursor *p;
  59597. int rc = SQLITE_OK;
  59598. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  59599. if( pBtree ){
  59600. sqlite3BtreeEnter(pBtree);
  59601. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59602. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  59603. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  59604. rc = saveCursorPosition(p);
  59605. if( rc!=SQLITE_OK ){
  59606. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  59607. break;
  59608. }
  59609. }
  59610. }else{
  59611. sqlite3BtreeClearCursor(p);
  59612. p->eState = CURSOR_FAULT;
  59613. p->skipNext = errCode;
  59614. }
  59615. btreeReleaseAllCursorPages(p);
  59616. }
  59617. sqlite3BtreeLeave(pBtree);
  59618. }
  59619. return rc;
  59620. }
  59621. /*
  59622. ** Rollback the transaction in progress.
  59623. **
  59624. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  59625. ** Only write cursors are tripped if writeOnly is true but all cursors are
  59626. ** tripped if writeOnly is false. Any attempt to use
  59627. ** a tripped cursor will result in an error.
  59628. **
  59629. ** This will release the write lock on the database file. If there
  59630. ** are no active cursors, it also releases the read lock.
  59631. */
  59632. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  59633. int rc;
  59634. BtShared *pBt = p->pBt;
  59635. MemPage *pPage1;
  59636. assert( writeOnly==1 || writeOnly==0 );
  59637. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  59638. sqlite3BtreeEnter(p);
  59639. if( tripCode==SQLITE_OK ){
  59640. rc = tripCode = saveAllCursors(pBt, 0, 0);
  59641. if( rc ) writeOnly = 0;
  59642. }else{
  59643. rc = SQLITE_OK;
  59644. }
  59645. if( tripCode ){
  59646. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  59647. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  59648. if( rc2!=SQLITE_OK ) rc = rc2;
  59649. }
  59650. btreeIntegrity(p);
  59651. if( p->inTrans==TRANS_WRITE ){
  59652. int rc2;
  59653. assert( TRANS_WRITE==pBt->inTransaction );
  59654. rc2 = sqlite3PagerRollback(pBt->pPager);
  59655. if( rc2!=SQLITE_OK ){
  59656. rc = rc2;
  59657. }
  59658. /* The rollback may have destroyed the pPage1->aData value. So
  59659. ** call btreeGetPage() on page 1 again to make
  59660. ** sure pPage1->aData is set correctly. */
  59661. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  59662. int nPage = get4byte(28+(u8*)pPage1->aData);
  59663. testcase( nPage==0 );
  59664. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  59665. testcase( pBt->nPage!=nPage );
  59666. pBt->nPage = nPage;
  59667. releasePageOne(pPage1);
  59668. }
  59669. assert( countValidCursors(pBt, 1)==0 );
  59670. pBt->inTransaction = TRANS_READ;
  59671. btreeClearHasContent(pBt);
  59672. }
  59673. btreeEndTransaction(p);
  59674. sqlite3BtreeLeave(p);
  59675. return rc;
  59676. }
  59677. /*
  59678. ** Start a statement subtransaction. The subtransaction can be rolled
  59679. ** back independently of the main transaction. You must start a transaction
  59680. ** before starting a subtransaction. The subtransaction is ended automatically
  59681. ** if the main transaction commits or rolls back.
  59682. **
  59683. ** Statement subtransactions are used around individual SQL statements
  59684. ** that are contained within a BEGIN...COMMIT block. If a constraint
  59685. ** error occurs within the statement, the effect of that one statement
  59686. ** can be rolled back without having to rollback the entire transaction.
  59687. **
  59688. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  59689. ** value passed as the second parameter is the total number of savepoints,
  59690. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  59691. ** are no active savepoints and no other statement-transactions open,
  59692. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  59693. ** using the sqlite3BtreeSavepoint() function.
  59694. */
  59695. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  59696. int rc;
  59697. BtShared *pBt = p->pBt;
  59698. sqlite3BtreeEnter(p);
  59699. assert( p->inTrans==TRANS_WRITE );
  59700. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59701. assert( iStatement>0 );
  59702. assert( iStatement>p->db->nSavepoint );
  59703. assert( pBt->inTransaction==TRANS_WRITE );
  59704. /* At the pager level, a statement transaction is a savepoint with
  59705. ** an index greater than all savepoints created explicitly using
  59706. ** SQL statements. It is illegal to open, release or rollback any
  59707. ** such savepoints while the statement transaction savepoint is active.
  59708. */
  59709. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  59710. sqlite3BtreeLeave(p);
  59711. return rc;
  59712. }
  59713. /*
  59714. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  59715. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  59716. ** savepoint identified by parameter iSavepoint, depending on the value
  59717. ** of op.
  59718. **
  59719. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  59720. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  59721. ** contents of the entire transaction are rolled back. This is different
  59722. ** from a normal transaction rollback, as no locks are released and the
  59723. ** transaction remains open.
  59724. */
  59725. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  59726. int rc = SQLITE_OK;
  59727. if( p && p->inTrans==TRANS_WRITE ){
  59728. BtShared *pBt = p->pBt;
  59729. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  59730. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  59731. sqlite3BtreeEnter(p);
  59732. if( op==SAVEPOINT_ROLLBACK ){
  59733. rc = saveAllCursors(pBt, 0, 0);
  59734. }
  59735. if( rc==SQLITE_OK ){
  59736. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  59737. }
  59738. if( rc==SQLITE_OK ){
  59739. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  59740. pBt->nPage = 0;
  59741. }
  59742. rc = newDatabase(pBt);
  59743. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  59744. /* The database size was written into the offset 28 of the header
  59745. ** when the transaction started, so we know that the value at offset
  59746. ** 28 is nonzero. */
  59747. assert( pBt->nPage>0 );
  59748. }
  59749. sqlite3BtreeLeave(p);
  59750. }
  59751. return rc;
  59752. }
  59753. /*
  59754. ** Create a new cursor for the BTree whose root is on the page
  59755. ** iTable. If a read-only cursor is requested, it is assumed that
  59756. ** the caller already has at least a read-only transaction open
  59757. ** on the database already. If a write-cursor is requested, then
  59758. ** the caller is assumed to have an open write transaction.
  59759. **
  59760. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  59761. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  59762. ** can be used for reading or for writing if other conditions for writing
  59763. ** are also met. These are the conditions that must be met in order
  59764. ** for writing to be allowed:
  59765. **
  59766. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  59767. **
  59768. ** 2: Other database connections that share the same pager cache
  59769. ** but which are not in the READ_UNCOMMITTED state may not have
  59770. ** cursors open with wrFlag==0 on the same table. Otherwise
  59771. ** the changes made by this write cursor would be visible to
  59772. ** the read cursors in the other database connection.
  59773. **
  59774. ** 3: The database must be writable (not on read-only media)
  59775. **
  59776. ** 4: There must be an active transaction.
  59777. **
  59778. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  59779. ** is set. If FORDELETE is set, that is a hint to the implementation that
  59780. ** this cursor will only be used to seek to and delete entries of an index
  59781. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  59782. ** this implementation. But in a hypothetical alternative storage engine
  59783. ** in which index entries are automatically deleted when corresponding table
  59784. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  59785. ** operations on this cursor can be no-ops and all READ operations can
  59786. ** return a null row (2-bytes: 0x01 0x00).
  59787. **
  59788. ** No checking is done to make sure that page iTable really is the
  59789. ** root page of a b-tree. If it is not, then the cursor acquired
  59790. ** will not work correctly.
  59791. **
  59792. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  59793. ** on pCur to initialize the memory space prior to invoking this routine.
  59794. */
  59795. static int btreeCursor(
  59796. Btree *p, /* The btree */
  59797. int iTable, /* Root page of table to open */
  59798. int wrFlag, /* 1 to write. 0 read-only */
  59799. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  59800. BtCursor *pCur /* Space for new cursor */
  59801. ){
  59802. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  59803. BtCursor *pX; /* Looping over other all cursors */
  59804. assert( sqlite3BtreeHoldsMutex(p) );
  59805. assert( wrFlag==0
  59806. || wrFlag==BTREE_WRCSR
  59807. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  59808. );
  59809. /* The following assert statements verify that if this is a sharable
  59810. ** b-tree database, the connection is holding the required table locks,
  59811. ** and that no other connection has any open cursor that conflicts with
  59812. ** this lock. */
  59813. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  59814. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  59815. /* Assert that the caller has opened the required transaction. */
  59816. assert( p->inTrans>TRANS_NONE );
  59817. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  59818. assert( pBt->pPage1 && pBt->pPage1->aData );
  59819. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59820. if( wrFlag ){
  59821. allocateTempSpace(pBt);
  59822. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  59823. }
  59824. if( iTable==1 && btreePagecount(pBt)==0 ){
  59825. assert( wrFlag==0 );
  59826. iTable = 0;
  59827. }
  59828. /* Now that no other errors can occur, finish filling in the BtCursor
  59829. ** variables and link the cursor into the BtShared list. */
  59830. pCur->pgnoRoot = (Pgno)iTable;
  59831. pCur->iPage = -1;
  59832. pCur->pKeyInfo = pKeyInfo;
  59833. pCur->pBtree = p;
  59834. pCur->pBt = pBt;
  59835. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  59836. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  59837. /* If there are two or more cursors on the same btree, then all such
  59838. ** cursors *must* have the BTCF_Multiple flag set. */
  59839. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  59840. if( pX->pgnoRoot==(Pgno)iTable ){
  59841. pX->curFlags |= BTCF_Multiple;
  59842. pCur->curFlags |= BTCF_Multiple;
  59843. }
  59844. }
  59845. pCur->pNext = pBt->pCursor;
  59846. pBt->pCursor = pCur;
  59847. pCur->eState = CURSOR_INVALID;
  59848. return SQLITE_OK;
  59849. }
  59850. SQLITE_PRIVATE int sqlite3BtreeCursor(
  59851. Btree *p, /* The btree */
  59852. int iTable, /* Root page of table to open */
  59853. int wrFlag, /* 1 to write. 0 read-only */
  59854. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  59855. BtCursor *pCur /* Write new cursor here */
  59856. ){
  59857. int rc;
  59858. if( iTable<1 ){
  59859. rc = SQLITE_CORRUPT_BKPT;
  59860. }else{
  59861. sqlite3BtreeEnter(p);
  59862. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  59863. sqlite3BtreeLeave(p);
  59864. }
  59865. return rc;
  59866. }
  59867. /*
  59868. ** Return the size of a BtCursor object in bytes.
  59869. **
  59870. ** This interfaces is needed so that users of cursors can preallocate
  59871. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  59872. ** to users so they cannot do the sizeof() themselves - they must call
  59873. ** this routine.
  59874. */
  59875. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  59876. return ROUND8(sizeof(BtCursor));
  59877. }
  59878. /*
  59879. ** Initialize memory that will be converted into a BtCursor object.
  59880. **
  59881. ** The simple approach here would be to memset() the entire object
  59882. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  59883. ** do not need to be zeroed and they are large, so we can save a lot
  59884. ** of run-time by skipping the initialization of those elements.
  59885. */
  59886. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  59887. memset(p, 0, offsetof(BtCursor, iPage));
  59888. }
  59889. /*
  59890. ** Close a cursor. The read lock on the database file is released
  59891. ** when the last cursor is closed.
  59892. */
  59893. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  59894. Btree *pBtree = pCur->pBtree;
  59895. if( pBtree ){
  59896. BtShared *pBt = pCur->pBt;
  59897. sqlite3BtreeEnter(pBtree);
  59898. assert( pBt->pCursor!=0 );
  59899. if( pBt->pCursor==pCur ){
  59900. pBt->pCursor = pCur->pNext;
  59901. }else{
  59902. BtCursor *pPrev = pBt->pCursor;
  59903. do{
  59904. if( pPrev->pNext==pCur ){
  59905. pPrev->pNext = pCur->pNext;
  59906. break;
  59907. }
  59908. pPrev = pPrev->pNext;
  59909. }while( ALWAYS(pPrev) );
  59910. }
  59911. btreeReleaseAllCursorPages(pCur);
  59912. unlockBtreeIfUnused(pBt);
  59913. sqlite3_free(pCur->aOverflow);
  59914. sqlite3_free(pCur->pKey);
  59915. sqlite3BtreeLeave(pBtree);
  59916. }
  59917. return SQLITE_OK;
  59918. }
  59919. /*
  59920. ** Make sure the BtCursor* given in the argument has a valid
  59921. ** BtCursor.info structure. If it is not already valid, call
  59922. ** btreeParseCell() to fill it in.
  59923. **
  59924. ** BtCursor.info is a cache of the information in the current cell.
  59925. ** Using this cache reduces the number of calls to btreeParseCell().
  59926. */
  59927. #ifndef NDEBUG
  59928. static void assertCellInfo(BtCursor *pCur){
  59929. CellInfo info;
  59930. memset(&info, 0, sizeof(info));
  59931. btreeParseCell(pCur->pPage, pCur->ix, &info);
  59932. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  59933. }
  59934. #else
  59935. #define assertCellInfo(x)
  59936. #endif
  59937. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  59938. if( pCur->info.nSize==0 ){
  59939. pCur->curFlags |= BTCF_ValidNKey;
  59940. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  59941. }else{
  59942. assertCellInfo(pCur);
  59943. }
  59944. }
  59945. #ifndef NDEBUG /* The next routine used only within assert() statements */
  59946. /*
  59947. ** Return true if the given BtCursor is valid. A valid cursor is one
  59948. ** that is currently pointing to a row in a (non-empty) table.
  59949. ** This is a verification routine is used only within assert() statements.
  59950. */
  59951. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  59952. return pCur && pCur->eState==CURSOR_VALID;
  59953. }
  59954. #endif /* NDEBUG */
  59955. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  59956. assert( pCur!=0 );
  59957. return pCur->eState==CURSOR_VALID;
  59958. }
  59959. /*
  59960. ** Return the value of the integer key or "rowid" for a table btree.
  59961. ** This routine is only valid for a cursor that is pointing into a
  59962. ** ordinary table btree. If the cursor points to an index btree or
  59963. ** is invalid, the result of this routine is undefined.
  59964. */
  59965. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  59966. assert( cursorHoldsMutex(pCur) );
  59967. assert( pCur->eState==CURSOR_VALID );
  59968. assert( pCur->curIntKey );
  59969. getCellInfo(pCur);
  59970. return pCur->info.nKey;
  59971. }
  59972. /*
  59973. ** Return the number of bytes of payload for the entry that pCur is
  59974. ** currently pointing to. For table btrees, this will be the amount
  59975. ** of data. For index btrees, this will be the size of the key.
  59976. **
  59977. ** The caller must guarantee that the cursor is pointing to a non-NULL
  59978. ** valid entry. In other words, the calling procedure must guarantee
  59979. ** that the cursor has Cursor.eState==CURSOR_VALID.
  59980. */
  59981. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  59982. assert( cursorHoldsMutex(pCur) );
  59983. assert( pCur->eState==CURSOR_VALID );
  59984. getCellInfo(pCur);
  59985. return pCur->info.nPayload;
  59986. }
  59987. /*
  59988. ** Given the page number of an overflow page in the database (parameter
  59989. ** ovfl), this function finds the page number of the next page in the
  59990. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  59991. ** pointer-map data instead of reading the content of page ovfl to do so.
  59992. **
  59993. ** If an error occurs an SQLite error code is returned. Otherwise:
  59994. **
  59995. ** The page number of the next overflow page in the linked list is
  59996. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  59997. ** list, *pPgnoNext is set to zero.
  59998. **
  59999. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  60000. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  60001. ** reference. It is the responsibility of the caller to call releasePage()
  60002. ** on *ppPage to free the reference. In no reference was obtained (because
  60003. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  60004. ** *ppPage is set to zero.
  60005. */
  60006. static int getOverflowPage(
  60007. BtShared *pBt, /* The database file */
  60008. Pgno ovfl, /* Current overflow page number */
  60009. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  60010. Pgno *pPgnoNext /* OUT: Next overflow page number */
  60011. ){
  60012. Pgno next = 0;
  60013. MemPage *pPage = 0;
  60014. int rc = SQLITE_OK;
  60015. assert( sqlite3_mutex_held(pBt->mutex) );
  60016. assert(pPgnoNext);
  60017. #ifndef SQLITE_OMIT_AUTOVACUUM
  60018. /* Try to find the next page in the overflow list using the
  60019. ** autovacuum pointer-map pages. Guess that the next page in
  60020. ** the overflow list is page number (ovfl+1). If that guess turns
  60021. ** out to be wrong, fall back to loading the data of page
  60022. ** number ovfl to determine the next page number.
  60023. */
  60024. if( pBt->autoVacuum ){
  60025. Pgno pgno;
  60026. Pgno iGuess = ovfl+1;
  60027. u8 eType;
  60028. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  60029. iGuess++;
  60030. }
  60031. if( iGuess<=btreePagecount(pBt) ){
  60032. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  60033. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  60034. next = iGuess;
  60035. rc = SQLITE_DONE;
  60036. }
  60037. }
  60038. }
  60039. #endif
  60040. assert( next==0 || rc==SQLITE_DONE );
  60041. if( rc==SQLITE_OK ){
  60042. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  60043. assert( rc==SQLITE_OK || pPage==0 );
  60044. if( rc==SQLITE_OK ){
  60045. next = get4byte(pPage->aData);
  60046. }
  60047. }
  60048. *pPgnoNext = next;
  60049. if( ppPage ){
  60050. *ppPage = pPage;
  60051. }else{
  60052. releasePage(pPage);
  60053. }
  60054. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  60055. }
  60056. /*
  60057. ** Copy data from a buffer to a page, or from a page to a buffer.
  60058. **
  60059. ** pPayload is a pointer to data stored on database page pDbPage.
  60060. ** If argument eOp is false, then nByte bytes of data are copied
  60061. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  60062. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  60063. ** of data are copied from the buffer pBuf to pPayload.
  60064. **
  60065. ** SQLITE_OK is returned on success, otherwise an error code.
  60066. */
  60067. static int copyPayload(
  60068. void *pPayload, /* Pointer to page data */
  60069. void *pBuf, /* Pointer to buffer */
  60070. int nByte, /* Number of bytes to copy */
  60071. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  60072. DbPage *pDbPage /* Page containing pPayload */
  60073. ){
  60074. if( eOp ){
  60075. /* Copy data from buffer to page (a write operation) */
  60076. int rc = sqlite3PagerWrite(pDbPage);
  60077. if( rc!=SQLITE_OK ){
  60078. return rc;
  60079. }
  60080. memcpy(pPayload, pBuf, nByte);
  60081. }else{
  60082. /* Copy data from page to buffer (a read operation) */
  60083. memcpy(pBuf, pPayload, nByte);
  60084. }
  60085. return SQLITE_OK;
  60086. }
  60087. /*
  60088. ** This function is used to read or overwrite payload information
  60089. ** for the entry that the pCur cursor is pointing to. The eOp
  60090. ** argument is interpreted as follows:
  60091. **
  60092. ** 0: The operation is a read. Populate the overflow cache.
  60093. ** 1: The operation is a write. Populate the overflow cache.
  60094. **
  60095. ** A total of "amt" bytes are read or written beginning at "offset".
  60096. ** Data is read to or from the buffer pBuf.
  60097. **
  60098. ** The content being read or written might appear on the main page
  60099. ** or be scattered out on multiple overflow pages.
  60100. **
  60101. ** If the current cursor entry uses one or more overflow pages
  60102. ** this function may allocate space for and lazily populate
  60103. ** the overflow page-list cache array (BtCursor.aOverflow).
  60104. ** Subsequent calls use this cache to make seeking to the supplied offset
  60105. ** more efficient.
  60106. **
  60107. ** Once an overflow page-list cache has been allocated, it must be
  60108. ** invalidated if some other cursor writes to the same table, or if
  60109. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  60110. ** mode, the following events may invalidate an overflow page-list cache.
  60111. **
  60112. ** * An incremental vacuum,
  60113. ** * A commit in auto_vacuum="full" mode,
  60114. ** * Creating a table (may require moving an overflow page).
  60115. */
  60116. static int accessPayload(
  60117. BtCursor *pCur, /* Cursor pointing to entry to read from */
  60118. u32 offset, /* Begin reading this far into payload */
  60119. u32 amt, /* Read this many bytes */
  60120. unsigned char *pBuf, /* Write the bytes into this buffer */
  60121. int eOp /* zero to read. non-zero to write. */
  60122. ){
  60123. unsigned char *aPayload;
  60124. int rc = SQLITE_OK;
  60125. int iIdx = 0;
  60126. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  60127. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  60128. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  60129. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  60130. #endif
  60131. assert( pPage );
  60132. assert( eOp==0 || eOp==1 );
  60133. assert( pCur->eState==CURSOR_VALID );
  60134. assert( pCur->ix<pPage->nCell );
  60135. assert( cursorHoldsMutex(pCur) );
  60136. getCellInfo(pCur);
  60137. aPayload = pCur->info.pPayload;
  60138. assert( offset+amt <= pCur->info.nPayload );
  60139. assert( aPayload > pPage->aData );
  60140. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  60141. /* Trying to read or write past the end of the data is an error. The
  60142. ** conditional above is really:
  60143. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  60144. ** but is recast into its current form to avoid integer overflow problems
  60145. */
  60146. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  60147. }
  60148. /* Check if data must be read/written to/from the btree page itself. */
  60149. if( offset<pCur->info.nLocal ){
  60150. int a = amt;
  60151. if( a+offset>pCur->info.nLocal ){
  60152. a = pCur->info.nLocal - offset;
  60153. }
  60154. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  60155. offset = 0;
  60156. pBuf += a;
  60157. amt -= a;
  60158. }else{
  60159. offset -= pCur->info.nLocal;
  60160. }
  60161. if( rc==SQLITE_OK && amt>0 ){
  60162. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  60163. Pgno nextPage;
  60164. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  60165. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  60166. **
  60167. ** The aOverflow[] array is sized at one entry for each overflow page
  60168. ** in the overflow chain. The page number of the first overflow page is
  60169. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  60170. ** means "not yet known" (the cache is lazily populated).
  60171. */
  60172. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  60173. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  60174. if( nOvfl>pCur->nOvflAlloc ){
  60175. Pgno *aNew = (Pgno*)sqlite3Realloc(
  60176. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  60177. );
  60178. if( aNew==0 ){
  60179. return SQLITE_NOMEM_BKPT;
  60180. }else{
  60181. pCur->nOvflAlloc = nOvfl*2;
  60182. pCur->aOverflow = aNew;
  60183. }
  60184. }
  60185. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  60186. pCur->curFlags |= BTCF_ValidOvfl;
  60187. }else{
  60188. /* If the overflow page-list cache has been allocated and the
  60189. ** entry for the first required overflow page is valid, skip
  60190. ** directly to it.
  60191. */
  60192. if( pCur->aOverflow[offset/ovflSize] ){
  60193. iIdx = (offset/ovflSize);
  60194. nextPage = pCur->aOverflow[iIdx];
  60195. offset = (offset%ovflSize);
  60196. }
  60197. }
  60198. assert( rc==SQLITE_OK && amt>0 );
  60199. while( nextPage ){
  60200. /* If required, populate the overflow page-list cache. */
  60201. assert( pCur->aOverflow[iIdx]==0
  60202. || pCur->aOverflow[iIdx]==nextPage
  60203. || CORRUPT_DB );
  60204. pCur->aOverflow[iIdx] = nextPage;
  60205. if( offset>=ovflSize ){
  60206. /* The only reason to read this page is to obtain the page
  60207. ** number for the next page in the overflow chain. The page
  60208. ** data is not required. So first try to lookup the overflow
  60209. ** page-list cache, if any, then fall back to the getOverflowPage()
  60210. ** function.
  60211. */
  60212. assert( pCur->curFlags & BTCF_ValidOvfl );
  60213. assert( pCur->pBtree->db==pBt->db );
  60214. if( pCur->aOverflow[iIdx+1] ){
  60215. nextPage = pCur->aOverflow[iIdx+1];
  60216. }else{
  60217. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  60218. }
  60219. offset -= ovflSize;
  60220. }else{
  60221. /* Need to read this page properly. It contains some of the
  60222. ** range of data that is being read (eOp==0) or written (eOp!=0).
  60223. */
  60224. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  60225. sqlite3_file *fd; /* File from which to do direct overflow read */
  60226. #endif
  60227. int a = amt;
  60228. if( a + offset > ovflSize ){
  60229. a = ovflSize - offset;
  60230. }
  60231. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  60232. /* If all the following are true:
  60233. **
  60234. ** 1) this is a read operation, and
  60235. ** 2) data is required from the start of this overflow page, and
  60236. ** 3) there is no open write-transaction, and
  60237. ** 4) the database is file-backed, and
  60238. ** 5) the page is not in the WAL file
  60239. ** 6) at least 4 bytes have already been read into the output buffer
  60240. **
  60241. ** then data can be read directly from the database file into the
  60242. ** output buffer, bypassing the page-cache altogether. This speeds
  60243. ** up loading large records that span many overflow pages.
  60244. */
  60245. if( eOp==0 /* (1) */
  60246. && offset==0 /* (2) */
  60247. && pBt->inTransaction==TRANS_READ /* (3) */
  60248. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
  60249. && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
  60250. && &pBuf[-4]>=pBufStart /* (6) */
  60251. ){
  60252. u8 aSave[4];
  60253. u8 *aWrite = &pBuf[-4];
  60254. assert( aWrite>=pBufStart ); /* due to (6) */
  60255. memcpy(aSave, aWrite, 4);
  60256. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  60257. nextPage = get4byte(aWrite);
  60258. memcpy(aWrite, aSave, 4);
  60259. }else
  60260. #endif
  60261. {
  60262. DbPage *pDbPage;
  60263. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  60264. (eOp==0 ? PAGER_GET_READONLY : 0)
  60265. );
  60266. if( rc==SQLITE_OK ){
  60267. aPayload = sqlite3PagerGetData(pDbPage);
  60268. nextPage = get4byte(aPayload);
  60269. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  60270. sqlite3PagerUnref(pDbPage);
  60271. offset = 0;
  60272. }
  60273. }
  60274. amt -= a;
  60275. if( amt==0 ) return rc;
  60276. pBuf += a;
  60277. }
  60278. if( rc ) break;
  60279. iIdx++;
  60280. }
  60281. }
  60282. if( rc==SQLITE_OK && amt>0 ){
  60283. /* Overflow chain ends prematurely */
  60284. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  60285. }
  60286. return rc;
  60287. }
  60288. /*
  60289. ** Read part of the payload for the row at which that cursor pCur is currently
  60290. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  60291. ** begins at "offset".
  60292. **
  60293. ** pCur can be pointing to either a table or an index b-tree.
  60294. ** If pointing to a table btree, then the content section is read. If
  60295. ** pCur is pointing to an index b-tree then the key section is read.
  60296. **
  60297. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  60298. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  60299. ** cursor might be invalid or might need to be restored before being read.
  60300. **
  60301. ** Return SQLITE_OK on success or an error code if anything goes
  60302. ** wrong. An error is returned if "offset+amt" is larger than
  60303. ** the available payload.
  60304. */
  60305. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  60306. assert( cursorHoldsMutex(pCur) );
  60307. assert( pCur->eState==CURSOR_VALID );
  60308. assert( pCur->iPage>=0 && pCur->pPage );
  60309. assert( pCur->ix<pCur->pPage->nCell );
  60310. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  60311. }
  60312. /*
  60313. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  60314. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  60315. ** interface.
  60316. */
  60317. #ifndef SQLITE_OMIT_INCRBLOB
  60318. static SQLITE_NOINLINE int accessPayloadChecked(
  60319. BtCursor *pCur,
  60320. u32 offset,
  60321. u32 amt,
  60322. void *pBuf
  60323. ){
  60324. int rc;
  60325. if ( pCur->eState==CURSOR_INVALID ){
  60326. return SQLITE_ABORT;
  60327. }
  60328. assert( cursorOwnsBtShared(pCur) );
  60329. rc = btreeRestoreCursorPosition(pCur);
  60330. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  60331. }
  60332. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  60333. if( pCur->eState==CURSOR_VALID ){
  60334. assert( cursorOwnsBtShared(pCur) );
  60335. return accessPayload(pCur, offset, amt, pBuf, 0);
  60336. }else{
  60337. return accessPayloadChecked(pCur, offset, amt, pBuf);
  60338. }
  60339. }
  60340. #endif /* SQLITE_OMIT_INCRBLOB */
  60341. /*
  60342. ** Return a pointer to payload information from the entry that the
  60343. ** pCur cursor is pointing to. The pointer is to the beginning of
  60344. ** the key if index btrees (pPage->intKey==0) and is the data for
  60345. ** table btrees (pPage->intKey==1). The number of bytes of available
  60346. ** key/data is written into *pAmt. If *pAmt==0, then the value
  60347. ** returned will not be a valid pointer.
  60348. **
  60349. ** This routine is an optimization. It is common for the entire key
  60350. ** and data to fit on the local page and for there to be no overflow
  60351. ** pages. When that is so, this routine can be used to access the
  60352. ** key and data without making a copy. If the key and/or data spills
  60353. ** onto overflow pages, then accessPayload() must be used to reassemble
  60354. ** the key/data and copy it into a preallocated buffer.
  60355. **
  60356. ** The pointer returned by this routine looks directly into the cached
  60357. ** page of the database. The data might change or move the next time
  60358. ** any btree routine is called.
  60359. */
  60360. static const void *fetchPayload(
  60361. BtCursor *pCur, /* Cursor pointing to entry to read from */
  60362. u32 *pAmt /* Write the number of available bytes here */
  60363. ){
  60364. int amt;
  60365. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  60366. assert( pCur->eState==CURSOR_VALID );
  60367. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60368. assert( cursorOwnsBtShared(pCur) );
  60369. assert( pCur->ix<pCur->pPage->nCell );
  60370. assert( pCur->info.nSize>0 );
  60371. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  60372. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  60373. amt = pCur->info.nLocal;
  60374. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  60375. /* There is too little space on the page for the expected amount
  60376. ** of local content. Database must be corrupt. */
  60377. assert( CORRUPT_DB );
  60378. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  60379. }
  60380. *pAmt = (u32)amt;
  60381. return (void*)pCur->info.pPayload;
  60382. }
  60383. /*
  60384. ** For the entry that cursor pCur is point to, return as
  60385. ** many bytes of the key or data as are available on the local
  60386. ** b-tree page. Write the number of available bytes into *pAmt.
  60387. **
  60388. ** The pointer returned is ephemeral. The key/data may move
  60389. ** or be destroyed on the next call to any Btree routine,
  60390. ** including calls from other threads against the same cache.
  60391. ** Hence, a mutex on the BtShared should be held prior to calling
  60392. ** this routine.
  60393. **
  60394. ** These routines is used to get quick access to key and data
  60395. ** in the common case where no overflow pages are used.
  60396. */
  60397. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  60398. return fetchPayload(pCur, pAmt);
  60399. }
  60400. /*
  60401. ** Move the cursor down to a new child page. The newPgno argument is the
  60402. ** page number of the child page to move to.
  60403. **
  60404. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  60405. ** the new child page does not match the flags field of the parent (i.e.
  60406. ** if an intkey page appears to be the parent of a non-intkey page, or
  60407. ** vice-versa).
  60408. */
  60409. static int moveToChild(BtCursor *pCur, u32 newPgno){
  60410. BtShared *pBt = pCur->pBt;
  60411. assert( cursorOwnsBtShared(pCur) );
  60412. assert( pCur->eState==CURSOR_VALID );
  60413. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  60414. assert( pCur->iPage>=0 );
  60415. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  60416. return SQLITE_CORRUPT_BKPT;
  60417. }
  60418. pCur->info.nSize = 0;
  60419. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  60420. pCur->aiIdx[pCur->iPage] = pCur->ix;
  60421. pCur->apPage[pCur->iPage] = pCur->pPage;
  60422. pCur->ix = 0;
  60423. pCur->iPage++;
  60424. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  60425. }
  60426. #ifdef SQLITE_DEBUG
  60427. /*
  60428. ** Page pParent is an internal (non-leaf) tree page. This function
  60429. ** asserts that page number iChild is the left-child if the iIdx'th
  60430. ** cell in page pParent. Or, if iIdx is equal to the total number of
  60431. ** cells in pParent, that page number iChild is the right-child of
  60432. ** the page.
  60433. */
  60434. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  60435. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  60436. ** in a corrupt database */
  60437. assert( iIdx<=pParent->nCell );
  60438. if( iIdx==pParent->nCell ){
  60439. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  60440. }else{
  60441. assert( get4byte(findCell(pParent, iIdx))==iChild );
  60442. }
  60443. }
  60444. #else
  60445. # define assertParentIndex(x,y,z)
  60446. #endif
  60447. /*
  60448. ** Move the cursor up to the parent page.
  60449. **
  60450. ** pCur->idx is set to the cell index that contains the pointer
  60451. ** to the page we are coming from. If we are coming from the
  60452. ** right-most child page then pCur->idx is set to one more than
  60453. ** the largest cell index.
  60454. */
  60455. static void moveToParent(BtCursor *pCur){
  60456. MemPage *pLeaf;
  60457. assert( cursorOwnsBtShared(pCur) );
  60458. assert( pCur->eState==CURSOR_VALID );
  60459. assert( pCur->iPage>0 );
  60460. assert( pCur->pPage );
  60461. assertParentIndex(
  60462. pCur->apPage[pCur->iPage-1],
  60463. pCur->aiIdx[pCur->iPage-1],
  60464. pCur->pPage->pgno
  60465. );
  60466. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  60467. pCur->info.nSize = 0;
  60468. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  60469. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  60470. pLeaf = pCur->pPage;
  60471. pCur->pPage = pCur->apPage[--pCur->iPage];
  60472. releasePageNotNull(pLeaf);
  60473. }
  60474. /*
  60475. ** Move the cursor to point to the root page of its b-tree structure.
  60476. **
  60477. ** If the table has a virtual root page, then the cursor is moved to point
  60478. ** to the virtual root page instead of the actual root page. A table has a
  60479. ** virtual root page when the actual root page contains no cells and a
  60480. ** single child page. This can only happen with the table rooted at page 1.
  60481. **
  60482. ** If the b-tree structure is empty, the cursor state is set to
  60483. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  60484. ** the cursor is set to point to the first cell located on the root
  60485. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  60486. **
  60487. ** If this function returns successfully, it may be assumed that the
  60488. ** page-header flags indicate that the [virtual] root-page is the expected
  60489. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  60490. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  60491. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  60492. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  60493. ** b-tree).
  60494. */
  60495. static int moveToRoot(BtCursor *pCur){
  60496. MemPage *pRoot;
  60497. int rc = SQLITE_OK;
  60498. assert( cursorOwnsBtShared(pCur) );
  60499. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  60500. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  60501. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  60502. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  60503. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  60504. if( pCur->iPage>=0 ){
  60505. if( pCur->iPage ){
  60506. releasePageNotNull(pCur->pPage);
  60507. while( --pCur->iPage ){
  60508. releasePageNotNull(pCur->apPage[pCur->iPage]);
  60509. }
  60510. pCur->pPage = pCur->apPage[0];
  60511. goto skip_init;
  60512. }
  60513. }else if( pCur->pgnoRoot==0 ){
  60514. pCur->eState = CURSOR_INVALID;
  60515. return SQLITE_EMPTY;
  60516. }else{
  60517. assert( pCur->iPage==(-1) );
  60518. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  60519. if( pCur->eState==CURSOR_FAULT ){
  60520. assert( pCur->skipNext!=SQLITE_OK );
  60521. return pCur->skipNext;
  60522. }
  60523. sqlite3BtreeClearCursor(pCur);
  60524. }
  60525. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  60526. 0, pCur->curPagerFlags);
  60527. if( rc!=SQLITE_OK ){
  60528. pCur->eState = CURSOR_INVALID;
  60529. return rc;
  60530. }
  60531. pCur->iPage = 0;
  60532. pCur->curIntKey = pCur->pPage->intKey;
  60533. }
  60534. pRoot = pCur->pPage;
  60535. assert( pRoot->pgno==pCur->pgnoRoot );
  60536. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  60537. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  60538. ** NULL, the caller expects a table b-tree. If this is not the case,
  60539. ** return an SQLITE_CORRUPT error.
  60540. **
  60541. ** Earlier versions of SQLite assumed that this test could not fail
  60542. ** if the root page was already loaded when this function was called (i.e.
  60543. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  60544. ** in such a way that page pRoot is linked into a second b-tree table
  60545. ** (or the freelist). */
  60546. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  60547. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  60548. return SQLITE_CORRUPT_PGNO(pCur->pPage->pgno);
  60549. }
  60550. skip_init:
  60551. pCur->ix = 0;
  60552. pCur->info.nSize = 0;
  60553. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  60554. pRoot = pCur->pPage;
  60555. if( pRoot->nCell>0 ){
  60556. pCur->eState = CURSOR_VALID;
  60557. }else if( !pRoot->leaf ){
  60558. Pgno subpage;
  60559. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  60560. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  60561. pCur->eState = CURSOR_VALID;
  60562. rc = moveToChild(pCur, subpage);
  60563. }else{
  60564. pCur->eState = CURSOR_INVALID;
  60565. rc = SQLITE_EMPTY;
  60566. }
  60567. return rc;
  60568. }
  60569. /*
  60570. ** Move the cursor down to the left-most leaf entry beneath the
  60571. ** entry to which it is currently pointing.
  60572. **
  60573. ** The left-most leaf is the one with the smallest key - the first
  60574. ** in ascending order.
  60575. */
  60576. static int moveToLeftmost(BtCursor *pCur){
  60577. Pgno pgno;
  60578. int rc = SQLITE_OK;
  60579. MemPage *pPage;
  60580. assert( cursorOwnsBtShared(pCur) );
  60581. assert( pCur->eState==CURSOR_VALID );
  60582. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  60583. assert( pCur->ix<pPage->nCell );
  60584. pgno = get4byte(findCell(pPage, pCur->ix));
  60585. rc = moveToChild(pCur, pgno);
  60586. }
  60587. return rc;
  60588. }
  60589. /*
  60590. ** Move the cursor down to the right-most leaf entry beneath the
  60591. ** page to which it is currently pointing. Notice the difference
  60592. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  60593. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  60594. ** finds the right-most entry beneath the *page*.
  60595. **
  60596. ** The right-most entry is the one with the largest key - the last
  60597. ** key in ascending order.
  60598. */
  60599. static int moveToRightmost(BtCursor *pCur){
  60600. Pgno pgno;
  60601. int rc = SQLITE_OK;
  60602. MemPage *pPage = 0;
  60603. assert( cursorOwnsBtShared(pCur) );
  60604. assert( pCur->eState==CURSOR_VALID );
  60605. while( !(pPage = pCur->pPage)->leaf ){
  60606. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  60607. pCur->ix = pPage->nCell;
  60608. rc = moveToChild(pCur, pgno);
  60609. if( rc ) return rc;
  60610. }
  60611. pCur->ix = pPage->nCell-1;
  60612. assert( pCur->info.nSize==0 );
  60613. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  60614. return SQLITE_OK;
  60615. }
  60616. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  60617. ** on success. Set *pRes to 0 if the cursor actually points to something
  60618. ** or set *pRes to 1 if the table is empty.
  60619. */
  60620. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  60621. int rc;
  60622. assert( cursorOwnsBtShared(pCur) );
  60623. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60624. rc = moveToRoot(pCur);
  60625. if( rc==SQLITE_OK ){
  60626. assert( pCur->pPage->nCell>0 );
  60627. *pRes = 0;
  60628. rc = moveToLeftmost(pCur);
  60629. }else if( rc==SQLITE_EMPTY ){
  60630. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  60631. *pRes = 1;
  60632. rc = SQLITE_OK;
  60633. }
  60634. return rc;
  60635. }
  60636. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  60637. ** on success. Set *pRes to 0 if the cursor actually points to something
  60638. ** or set *pRes to 1 if the table is empty.
  60639. */
  60640. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  60641. int rc;
  60642. assert( cursorOwnsBtShared(pCur) );
  60643. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60644. /* If the cursor already points to the last entry, this is a no-op. */
  60645. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  60646. #ifdef SQLITE_DEBUG
  60647. /* This block serves to assert() that the cursor really does point
  60648. ** to the last entry in the b-tree. */
  60649. int ii;
  60650. for(ii=0; ii<pCur->iPage; ii++){
  60651. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  60652. }
  60653. assert( pCur->ix==pCur->pPage->nCell-1 );
  60654. assert( pCur->pPage->leaf );
  60655. #endif
  60656. return SQLITE_OK;
  60657. }
  60658. rc = moveToRoot(pCur);
  60659. if( rc==SQLITE_OK ){
  60660. assert( pCur->eState==CURSOR_VALID );
  60661. *pRes = 0;
  60662. rc = moveToRightmost(pCur);
  60663. if( rc==SQLITE_OK ){
  60664. pCur->curFlags |= BTCF_AtLast;
  60665. }else{
  60666. pCur->curFlags &= ~BTCF_AtLast;
  60667. }
  60668. }else if( rc==SQLITE_EMPTY ){
  60669. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  60670. *pRes = 1;
  60671. rc = SQLITE_OK;
  60672. }
  60673. return rc;
  60674. }
  60675. /* Move the cursor so that it points to an entry near the key
  60676. ** specified by pIdxKey or intKey. Return a success code.
  60677. **
  60678. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  60679. ** must be NULL. For index tables, pIdxKey is used and intKey
  60680. ** is ignored.
  60681. **
  60682. ** If an exact match is not found, then the cursor is always
  60683. ** left pointing at a leaf page which would hold the entry if it
  60684. ** were present. The cursor might point to an entry that comes
  60685. ** before or after the key.
  60686. **
  60687. ** An integer is written into *pRes which is the result of
  60688. ** comparing the key with the entry to which the cursor is
  60689. ** pointing. The meaning of the integer written into
  60690. ** *pRes is as follows:
  60691. **
  60692. ** *pRes<0 The cursor is left pointing at an entry that
  60693. ** is smaller than intKey/pIdxKey or if the table is empty
  60694. ** and the cursor is therefore left point to nothing.
  60695. **
  60696. ** *pRes==0 The cursor is left pointing at an entry that
  60697. ** exactly matches intKey/pIdxKey.
  60698. **
  60699. ** *pRes>0 The cursor is left pointing at an entry that
  60700. ** is larger than intKey/pIdxKey.
  60701. **
  60702. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  60703. ** exists an entry in the table that exactly matches pIdxKey.
  60704. */
  60705. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  60706. BtCursor *pCur, /* The cursor to be moved */
  60707. UnpackedRecord *pIdxKey, /* Unpacked index key */
  60708. i64 intKey, /* The table key */
  60709. int biasRight, /* If true, bias the search to the high end */
  60710. int *pRes /* Write search results here */
  60711. ){
  60712. int rc;
  60713. RecordCompare xRecordCompare;
  60714. assert( cursorOwnsBtShared(pCur) );
  60715. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60716. assert( pRes );
  60717. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  60718. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  60719. /* If the cursor is already positioned at the point we are trying
  60720. ** to move to, then just return without doing any work */
  60721. if( pIdxKey==0
  60722. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  60723. ){
  60724. if( pCur->info.nKey==intKey ){
  60725. *pRes = 0;
  60726. return SQLITE_OK;
  60727. }
  60728. if( pCur->info.nKey<intKey ){
  60729. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  60730. *pRes = -1;
  60731. return SQLITE_OK;
  60732. }
  60733. /* If the requested key is one more than the previous key, then
  60734. ** try to get there using sqlite3BtreeNext() rather than a full
  60735. ** binary search. This is an optimization only. The correct answer
  60736. ** is still obtained without this case, only a little more slowely */
  60737. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  60738. *pRes = 0;
  60739. rc = sqlite3BtreeNext(pCur, 0);
  60740. if( rc==SQLITE_OK ){
  60741. getCellInfo(pCur);
  60742. if( pCur->info.nKey==intKey ){
  60743. return SQLITE_OK;
  60744. }
  60745. }else if( rc==SQLITE_DONE ){
  60746. rc = SQLITE_OK;
  60747. }else{
  60748. return rc;
  60749. }
  60750. }
  60751. }
  60752. }
  60753. if( pIdxKey ){
  60754. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  60755. pIdxKey->errCode = 0;
  60756. assert( pIdxKey->default_rc==1
  60757. || pIdxKey->default_rc==0
  60758. || pIdxKey->default_rc==-1
  60759. );
  60760. }else{
  60761. xRecordCompare = 0; /* All keys are integers */
  60762. }
  60763. rc = moveToRoot(pCur);
  60764. if( rc ){
  60765. if( rc==SQLITE_EMPTY ){
  60766. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  60767. *pRes = -1;
  60768. return SQLITE_OK;
  60769. }
  60770. return rc;
  60771. }
  60772. assert( pCur->pPage );
  60773. assert( pCur->pPage->isInit );
  60774. assert( pCur->eState==CURSOR_VALID );
  60775. assert( pCur->pPage->nCell > 0 );
  60776. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  60777. assert( pCur->curIntKey || pIdxKey );
  60778. for(;;){
  60779. int lwr, upr, idx, c;
  60780. Pgno chldPg;
  60781. MemPage *pPage = pCur->pPage;
  60782. u8 *pCell; /* Pointer to current cell in pPage */
  60783. /* pPage->nCell must be greater than zero. If this is the root-page
  60784. ** the cursor would have been INVALID above and this for(;;) loop
  60785. ** not run. If this is not the root-page, then the moveToChild() routine
  60786. ** would have already detected db corruption. Similarly, pPage must
  60787. ** be the right kind (index or table) of b-tree page. Otherwise
  60788. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  60789. assert( pPage->nCell>0 );
  60790. assert( pPage->intKey==(pIdxKey==0) );
  60791. lwr = 0;
  60792. upr = pPage->nCell-1;
  60793. assert( biasRight==0 || biasRight==1 );
  60794. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  60795. pCur->ix = (u16)idx;
  60796. if( xRecordCompare==0 ){
  60797. for(;;){
  60798. i64 nCellKey;
  60799. pCell = findCellPastPtr(pPage, idx);
  60800. if( pPage->intKeyLeaf ){
  60801. while( 0x80 <= *(pCell++) ){
  60802. if( pCell>=pPage->aDataEnd ){
  60803. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  60804. }
  60805. }
  60806. }
  60807. getVarint(pCell, (u64*)&nCellKey);
  60808. if( nCellKey<intKey ){
  60809. lwr = idx+1;
  60810. if( lwr>upr ){ c = -1; break; }
  60811. }else if( nCellKey>intKey ){
  60812. upr = idx-1;
  60813. if( lwr>upr ){ c = +1; break; }
  60814. }else{
  60815. assert( nCellKey==intKey );
  60816. pCur->ix = (u16)idx;
  60817. if( !pPage->leaf ){
  60818. lwr = idx;
  60819. goto moveto_next_layer;
  60820. }else{
  60821. pCur->curFlags |= BTCF_ValidNKey;
  60822. pCur->info.nKey = nCellKey;
  60823. pCur->info.nSize = 0;
  60824. *pRes = 0;
  60825. return SQLITE_OK;
  60826. }
  60827. }
  60828. assert( lwr+upr>=0 );
  60829. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  60830. }
  60831. }else{
  60832. for(;;){
  60833. int nCell; /* Size of the pCell cell in bytes */
  60834. pCell = findCellPastPtr(pPage, idx);
  60835. /* The maximum supported page-size is 65536 bytes. This means that
  60836. ** the maximum number of record bytes stored on an index B-Tree
  60837. ** page is less than 16384 bytes and may be stored as a 2-byte
  60838. ** varint. This information is used to attempt to avoid parsing
  60839. ** the entire cell by checking for the cases where the record is
  60840. ** stored entirely within the b-tree page by inspecting the first
  60841. ** 2 bytes of the cell.
  60842. */
  60843. nCell = pCell[0];
  60844. if( nCell<=pPage->max1bytePayload ){
  60845. /* This branch runs if the record-size field of the cell is a
  60846. ** single byte varint and the record fits entirely on the main
  60847. ** b-tree page. */
  60848. testcase( pCell+nCell+1==pPage->aDataEnd );
  60849. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  60850. }else if( !(pCell[1] & 0x80)
  60851. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  60852. ){
  60853. /* The record-size field is a 2 byte varint and the record
  60854. ** fits entirely on the main b-tree page. */
  60855. testcase( pCell+nCell+2==pPage->aDataEnd );
  60856. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  60857. }else{
  60858. /* The record flows over onto one or more overflow pages. In
  60859. ** this case the whole cell needs to be parsed, a buffer allocated
  60860. ** and accessPayload() used to retrieve the record into the
  60861. ** buffer before VdbeRecordCompare() can be called.
  60862. **
  60863. ** If the record is corrupt, the xRecordCompare routine may read
  60864. ** up to two varints past the end of the buffer. An extra 18
  60865. ** bytes of padding is allocated at the end of the buffer in
  60866. ** case this happens. */
  60867. void *pCellKey;
  60868. u8 * const pCellBody = pCell - pPage->childPtrSize;
  60869. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  60870. nCell = (int)pCur->info.nKey;
  60871. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  60872. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  60873. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  60874. testcase( nCell==2 ); /* Minimum legal index key size */
  60875. if( nCell<2 ){
  60876. rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
  60877. goto moveto_finish;
  60878. }
  60879. pCellKey = sqlite3Malloc( nCell+18 );
  60880. if( pCellKey==0 ){
  60881. rc = SQLITE_NOMEM_BKPT;
  60882. goto moveto_finish;
  60883. }
  60884. pCur->ix = (u16)idx;
  60885. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  60886. pCur->curFlags &= ~BTCF_ValidOvfl;
  60887. if( rc ){
  60888. sqlite3_free(pCellKey);
  60889. goto moveto_finish;
  60890. }
  60891. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  60892. sqlite3_free(pCellKey);
  60893. }
  60894. assert(
  60895. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  60896. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  60897. );
  60898. if( c<0 ){
  60899. lwr = idx+1;
  60900. }else if( c>0 ){
  60901. upr = idx-1;
  60902. }else{
  60903. assert( c==0 );
  60904. *pRes = 0;
  60905. rc = SQLITE_OK;
  60906. pCur->ix = (u16)idx;
  60907. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  60908. goto moveto_finish;
  60909. }
  60910. if( lwr>upr ) break;
  60911. assert( lwr+upr>=0 );
  60912. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  60913. }
  60914. }
  60915. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  60916. assert( pPage->isInit );
  60917. if( pPage->leaf ){
  60918. assert( pCur->ix<pCur->pPage->nCell );
  60919. pCur->ix = (u16)idx;
  60920. *pRes = c;
  60921. rc = SQLITE_OK;
  60922. goto moveto_finish;
  60923. }
  60924. moveto_next_layer:
  60925. if( lwr>=pPage->nCell ){
  60926. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  60927. }else{
  60928. chldPg = get4byte(findCell(pPage, lwr));
  60929. }
  60930. pCur->ix = (u16)lwr;
  60931. rc = moveToChild(pCur, chldPg);
  60932. if( rc ) break;
  60933. }
  60934. moveto_finish:
  60935. pCur->info.nSize = 0;
  60936. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  60937. return rc;
  60938. }
  60939. /*
  60940. ** Return TRUE if the cursor is not pointing at an entry of the table.
  60941. **
  60942. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  60943. ** past the last entry in the table or sqlite3BtreePrev() moves past
  60944. ** the first entry. TRUE is also returned if the table is empty.
  60945. */
  60946. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  60947. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  60948. ** have been deleted? This API will need to change to return an error code
  60949. ** as well as the boolean result value.
  60950. */
  60951. return (CURSOR_VALID!=pCur->eState);
  60952. }
  60953. /*
  60954. ** Return an estimate for the number of rows in the table that pCur is
  60955. ** pointing to. Return a negative number if no estimate is currently
  60956. ** available.
  60957. */
  60958. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  60959. i64 n;
  60960. u8 i;
  60961. assert( cursorOwnsBtShared(pCur) );
  60962. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60963. /* Currently this interface is only called by the OP_IfSmaller
  60964. ** opcode, and it that case the cursor will always be valid and
  60965. ** will always point to a leaf node. */
  60966. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  60967. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  60968. n = pCur->pPage->nCell;
  60969. for(i=0; i<pCur->iPage; i++){
  60970. n *= pCur->apPage[i]->nCell;
  60971. }
  60972. return n;
  60973. }
  60974. /*
  60975. ** Advance the cursor to the next entry in the database.
  60976. ** Return value:
  60977. **
  60978. ** SQLITE_OK success
  60979. ** SQLITE_DONE cursor is already pointing at the last element
  60980. ** otherwise some kind of error occurred
  60981. **
  60982. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  60983. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  60984. ** to the next cell on the current page. The (slower) btreeNext() helper
  60985. ** routine is called when it is necessary to move to a different page or
  60986. ** to restore the cursor.
  60987. **
  60988. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  60989. ** cursor corresponds to an SQL index and this routine could have been
  60990. ** skipped if the SQL index had been a unique index. The F argument
  60991. ** is a hint to the implement. SQLite btree implementation does not use
  60992. ** this hint, but COMDB2 does.
  60993. */
  60994. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  60995. int rc;
  60996. int idx;
  60997. MemPage *pPage;
  60998. assert( cursorOwnsBtShared(pCur) );
  60999. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  61000. if( pCur->eState!=CURSOR_VALID ){
  61001. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  61002. rc = restoreCursorPosition(pCur);
  61003. if( rc!=SQLITE_OK ){
  61004. return rc;
  61005. }
  61006. if( CURSOR_INVALID==pCur->eState ){
  61007. return SQLITE_DONE;
  61008. }
  61009. if( pCur->skipNext ){
  61010. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  61011. pCur->eState = CURSOR_VALID;
  61012. if( pCur->skipNext>0 ){
  61013. pCur->skipNext = 0;
  61014. return SQLITE_OK;
  61015. }
  61016. pCur->skipNext = 0;
  61017. }
  61018. }
  61019. pPage = pCur->pPage;
  61020. idx = ++pCur->ix;
  61021. assert( pPage->isInit );
  61022. /* If the database file is corrupt, it is possible for the value of idx
  61023. ** to be invalid here. This can only occur if a second cursor modifies
  61024. ** the page while cursor pCur is holding a reference to it. Which can
  61025. ** only happen if the database is corrupt in such a way as to link the
  61026. ** page into more than one b-tree structure. */
  61027. testcase( idx>pPage->nCell );
  61028. if( idx>=pPage->nCell ){
  61029. if( !pPage->leaf ){
  61030. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  61031. if( rc ) return rc;
  61032. return moveToLeftmost(pCur);
  61033. }
  61034. do{
  61035. if( pCur->iPage==0 ){
  61036. pCur->eState = CURSOR_INVALID;
  61037. return SQLITE_DONE;
  61038. }
  61039. moveToParent(pCur);
  61040. pPage = pCur->pPage;
  61041. }while( pCur->ix>=pPage->nCell );
  61042. if( pPage->intKey ){
  61043. return sqlite3BtreeNext(pCur, 0);
  61044. }else{
  61045. return SQLITE_OK;
  61046. }
  61047. }
  61048. if( pPage->leaf ){
  61049. return SQLITE_OK;
  61050. }else{
  61051. return moveToLeftmost(pCur);
  61052. }
  61053. }
  61054. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  61055. MemPage *pPage;
  61056. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  61057. assert( cursorOwnsBtShared(pCur) );
  61058. assert( flags==0 || flags==1 );
  61059. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  61060. pCur->info.nSize = 0;
  61061. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  61062. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  61063. pPage = pCur->pPage;
  61064. if( (++pCur->ix)>=pPage->nCell ){
  61065. pCur->ix--;
  61066. return btreeNext(pCur);
  61067. }
  61068. if( pPage->leaf ){
  61069. return SQLITE_OK;
  61070. }else{
  61071. return moveToLeftmost(pCur);
  61072. }
  61073. }
  61074. /*
  61075. ** Step the cursor to the back to the previous entry in the database.
  61076. ** Return values:
  61077. **
  61078. ** SQLITE_OK success
  61079. ** SQLITE_DONE the cursor is already on the first element of the table
  61080. ** otherwise some kind of error occurred
  61081. **
  61082. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  61083. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  61084. ** to the previous cell on the current page. The (slower) btreePrevious()
  61085. ** helper routine is called when it is necessary to move to a different page
  61086. ** or to restore the cursor.
  61087. **
  61088. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  61089. ** the cursor corresponds to an SQL index and this routine could have been
  61090. ** skipped if the SQL index had been a unique index. The F argument is a
  61091. ** hint to the implement. The native SQLite btree implementation does not
  61092. ** use this hint, but COMDB2 does.
  61093. */
  61094. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  61095. int rc;
  61096. MemPage *pPage;
  61097. assert( cursorOwnsBtShared(pCur) );
  61098. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  61099. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  61100. assert( pCur->info.nSize==0 );
  61101. if( pCur->eState!=CURSOR_VALID ){
  61102. rc = restoreCursorPosition(pCur);
  61103. if( rc!=SQLITE_OK ){
  61104. return rc;
  61105. }
  61106. if( CURSOR_INVALID==pCur->eState ){
  61107. return SQLITE_DONE;
  61108. }
  61109. if( pCur->skipNext ){
  61110. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  61111. pCur->eState = CURSOR_VALID;
  61112. if( pCur->skipNext<0 ){
  61113. pCur->skipNext = 0;
  61114. return SQLITE_OK;
  61115. }
  61116. pCur->skipNext = 0;
  61117. }
  61118. }
  61119. pPage = pCur->pPage;
  61120. assert( pPage->isInit );
  61121. if( !pPage->leaf ){
  61122. int idx = pCur->ix;
  61123. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  61124. if( rc ) return rc;
  61125. rc = moveToRightmost(pCur);
  61126. }else{
  61127. while( pCur->ix==0 ){
  61128. if( pCur->iPage==0 ){
  61129. pCur->eState = CURSOR_INVALID;
  61130. return SQLITE_DONE;
  61131. }
  61132. moveToParent(pCur);
  61133. }
  61134. assert( pCur->info.nSize==0 );
  61135. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  61136. pCur->ix--;
  61137. pPage = pCur->pPage;
  61138. if( pPage->intKey && !pPage->leaf ){
  61139. rc = sqlite3BtreePrevious(pCur, 0);
  61140. }else{
  61141. rc = SQLITE_OK;
  61142. }
  61143. }
  61144. return rc;
  61145. }
  61146. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  61147. assert( cursorOwnsBtShared(pCur) );
  61148. assert( flags==0 || flags==1 );
  61149. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  61150. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  61151. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  61152. pCur->info.nSize = 0;
  61153. if( pCur->eState!=CURSOR_VALID
  61154. || pCur->ix==0
  61155. || pCur->pPage->leaf==0
  61156. ){
  61157. return btreePrevious(pCur);
  61158. }
  61159. pCur->ix--;
  61160. return SQLITE_OK;
  61161. }
  61162. /*
  61163. ** Allocate a new page from the database file.
  61164. **
  61165. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  61166. ** has already been called on the new page.) The new page has also
  61167. ** been referenced and the calling routine is responsible for calling
  61168. ** sqlite3PagerUnref() on the new page when it is done.
  61169. **
  61170. ** SQLITE_OK is returned on success. Any other return value indicates
  61171. ** an error. *ppPage is set to NULL in the event of an error.
  61172. **
  61173. ** If the "nearby" parameter is not 0, then an effort is made to
  61174. ** locate a page close to the page number "nearby". This can be used in an
  61175. ** attempt to keep related pages close to each other in the database file,
  61176. ** which in turn can make database access faster.
  61177. **
  61178. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  61179. ** anywhere on the free-list, then it is guaranteed to be returned. If
  61180. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  61181. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  61182. ** are no restrictions on which page is returned.
  61183. */
  61184. static int allocateBtreePage(
  61185. BtShared *pBt, /* The btree */
  61186. MemPage **ppPage, /* Store pointer to the allocated page here */
  61187. Pgno *pPgno, /* Store the page number here */
  61188. Pgno nearby, /* Search for a page near this one */
  61189. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  61190. ){
  61191. MemPage *pPage1;
  61192. int rc;
  61193. u32 n; /* Number of pages on the freelist */
  61194. u32 k; /* Number of leaves on the trunk of the freelist */
  61195. MemPage *pTrunk = 0;
  61196. MemPage *pPrevTrunk = 0;
  61197. Pgno mxPage; /* Total size of the database file */
  61198. assert( sqlite3_mutex_held(pBt->mutex) );
  61199. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  61200. pPage1 = pBt->pPage1;
  61201. mxPage = btreePagecount(pBt);
  61202. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  61203. ** stores stores the total number of pages on the freelist. */
  61204. n = get4byte(&pPage1->aData[36]);
  61205. testcase( n==mxPage-1 );
  61206. if( n>=mxPage ){
  61207. return SQLITE_CORRUPT_BKPT;
  61208. }
  61209. if( n>0 ){
  61210. /* There are pages on the freelist. Reuse one of those pages. */
  61211. Pgno iTrunk;
  61212. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  61213. u32 nSearch = 0; /* Count of the number of search attempts */
  61214. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  61215. ** shows that the page 'nearby' is somewhere on the free-list, then
  61216. ** the entire-list will be searched for that page.
  61217. */
  61218. #ifndef SQLITE_OMIT_AUTOVACUUM
  61219. if( eMode==BTALLOC_EXACT ){
  61220. if( nearby<=mxPage ){
  61221. u8 eType;
  61222. assert( nearby>0 );
  61223. assert( pBt->autoVacuum );
  61224. rc = ptrmapGet(pBt, nearby, &eType, 0);
  61225. if( rc ) return rc;
  61226. if( eType==PTRMAP_FREEPAGE ){
  61227. searchList = 1;
  61228. }
  61229. }
  61230. }else if( eMode==BTALLOC_LE ){
  61231. searchList = 1;
  61232. }
  61233. #endif
  61234. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  61235. ** first free-list trunk page. iPrevTrunk is initially 1.
  61236. */
  61237. rc = sqlite3PagerWrite(pPage1->pDbPage);
  61238. if( rc ) return rc;
  61239. put4byte(&pPage1->aData[36], n-1);
  61240. /* The code within this loop is run only once if the 'searchList' variable
  61241. ** is not true. Otherwise, it runs once for each trunk-page on the
  61242. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  61243. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  61244. */
  61245. do {
  61246. pPrevTrunk = pTrunk;
  61247. if( pPrevTrunk ){
  61248. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  61249. ** is the page number of the next freelist trunk page in the list or
  61250. ** zero if this is the last freelist trunk page. */
  61251. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  61252. }else{
  61253. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  61254. ** stores the page number of the first page of the freelist, or zero if
  61255. ** the freelist is empty. */
  61256. iTrunk = get4byte(&pPage1->aData[32]);
  61257. }
  61258. testcase( iTrunk==mxPage );
  61259. if( iTrunk>mxPage || nSearch++ > n ){
  61260. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  61261. }else{
  61262. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  61263. }
  61264. if( rc ){
  61265. pTrunk = 0;
  61266. goto end_allocate_page;
  61267. }
  61268. assert( pTrunk!=0 );
  61269. assert( pTrunk->aData!=0 );
  61270. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  61271. ** is the number of leaf page pointers to follow. */
  61272. k = get4byte(&pTrunk->aData[4]);
  61273. if( k==0 && !searchList ){
  61274. /* The trunk has no leaves and the list is not being searched.
  61275. ** So extract the trunk page itself and use it as the newly
  61276. ** allocated page */
  61277. assert( pPrevTrunk==0 );
  61278. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  61279. if( rc ){
  61280. goto end_allocate_page;
  61281. }
  61282. *pPgno = iTrunk;
  61283. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  61284. *ppPage = pTrunk;
  61285. pTrunk = 0;
  61286. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  61287. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  61288. /* Value of k is out of range. Database corruption */
  61289. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  61290. goto end_allocate_page;
  61291. #ifndef SQLITE_OMIT_AUTOVACUUM
  61292. }else if( searchList
  61293. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  61294. ){
  61295. /* The list is being searched and this trunk page is the page
  61296. ** to allocate, regardless of whether it has leaves.
  61297. */
  61298. *pPgno = iTrunk;
  61299. *ppPage = pTrunk;
  61300. searchList = 0;
  61301. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  61302. if( rc ){
  61303. goto end_allocate_page;
  61304. }
  61305. if( k==0 ){
  61306. if( !pPrevTrunk ){
  61307. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  61308. }else{
  61309. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  61310. if( rc!=SQLITE_OK ){
  61311. goto end_allocate_page;
  61312. }
  61313. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  61314. }
  61315. }else{
  61316. /* The trunk page is required by the caller but it contains
  61317. ** pointers to free-list leaves. The first leaf becomes a trunk
  61318. ** page in this case.
  61319. */
  61320. MemPage *pNewTrunk;
  61321. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  61322. if( iNewTrunk>mxPage ){
  61323. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  61324. goto end_allocate_page;
  61325. }
  61326. testcase( iNewTrunk==mxPage );
  61327. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  61328. if( rc!=SQLITE_OK ){
  61329. goto end_allocate_page;
  61330. }
  61331. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  61332. if( rc!=SQLITE_OK ){
  61333. releasePage(pNewTrunk);
  61334. goto end_allocate_page;
  61335. }
  61336. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  61337. put4byte(&pNewTrunk->aData[4], k-1);
  61338. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  61339. releasePage(pNewTrunk);
  61340. if( !pPrevTrunk ){
  61341. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  61342. put4byte(&pPage1->aData[32], iNewTrunk);
  61343. }else{
  61344. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  61345. if( rc ){
  61346. goto end_allocate_page;
  61347. }
  61348. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  61349. }
  61350. }
  61351. pTrunk = 0;
  61352. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  61353. #endif
  61354. }else if( k>0 ){
  61355. /* Extract a leaf from the trunk */
  61356. u32 closest;
  61357. Pgno iPage;
  61358. unsigned char *aData = pTrunk->aData;
  61359. if( nearby>0 ){
  61360. u32 i;
  61361. closest = 0;
  61362. if( eMode==BTALLOC_LE ){
  61363. for(i=0; i<k; i++){
  61364. iPage = get4byte(&aData[8+i*4]);
  61365. if( iPage<=nearby ){
  61366. closest = i;
  61367. break;
  61368. }
  61369. }
  61370. }else{
  61371. int dist;
  61372. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  61373. for(i=1; i<k; i++){
  61374. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  61375. if( d2<dist ){
  61376. closest = i;
  61377. dist = d2;
  61378. }
  61379. }
  61380. }
  61381. }else{
  61382. closest = 0;
  61383. }
  61384. iPage = get4byte(&aData[8+closest*4]);
  61385. testcase( iPage==mxPage );
  61386. if( iPage>mxPage ){
  61387. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  61388. goto end_allocate_page;
  61389. }
  61390. testcase( iPage==mxPage );
  61391. if( !searchList
  61392. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  61393. ){
  61394. int noContent;
  61395. *pPgno = iPage;
  61396. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  61397. ": %d more free pages\n",
  61398. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  61399. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  61400. if( rc ) goto end_allocate_page;
  61401. if( closest<k-1 ){
  61402. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  61403. }
  61404. put4byte(&aData[4], k-1);
  61405. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  61406. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  61407. if( rc==SQLITE_OK ){
  61408. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  61409. if( rc!=SQLITE_OK ){
  61410. releasePage(*ppPage);
  61411. *ppPage = 0;
  61412. }
  61413. }
  61414. searchList = 0;
  61415. }
  61416. }
  61417. releasePage(pPrevTrunk);
  61418. pPrevTrunk = 0;
  61419. }while( searchList );
  61420. }else{
  61421. /* There are no pages on the freelist, so append a new page to the
  61422. ** database image.
  61423. **
  61424. ** Normally, new pages allocated by this block can be requested from the
  61425. ** pager layer with the 'no-content' flag set. This prevents the pager
  61426. ** from trying to read the pages content from disk. However, if the
  61427. ** current transaction has already run one or more incremental-vacuum
  61428. ** steps, then the page we are about to allocate may contain content
  61429. ** that is required in the event of a rollback. In this case, do
  61430. ** not set the no-content flag. This causes the pager to load and journal
  61431. ** the current page content before overwriting it.
  61432. **
  61433. ** Note that the pager will not actually attempt to load or journal
  61434. ** content for any page that really does lie past the end of the database
  61435. ** file on disk. So the effects of disabling the no-content optimization
  61436. ** here are confined to those pages that lie between the end of the
  61437. ** database image and the end of the database file.
  61438. */
  61439. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  61440. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61441. if( rc ) return rc;
  61442. pBt->nPage++;
  61443. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  61444. #ifndef SQLITE_OMIT_AUTOVACUUM
  61445. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  61446. /* If *pPgno refers to a pointer-map page, allocate two new pages
  61447. ** at the end of the file instead of one. The first allocated page
  61448. ** becomes a new pointer-map page, the second is used by the caller.
  61449. */
  61450. MemPage *pPg = 0;
  61451. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  61452. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  61453. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  61454. if( rc==SQLITE_OK ){
  61455. rc = sqlite3PagerWrite(pPg->pDbPage);
  61456. releasePage(pPg);
  61457. }
  61458. if( rc ) return rc;
  61459. pBt->nPage++;
  61460. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  61461. }
  61462. #endif
  61463. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  61464. *pPgno = pBt->nPage;
  61465. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  61466. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  61467. if( rc ) return rc;
  61468. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  61469. if( rc!=SQLITE_OK ){
  61470. releasePage(*ppPage);
  61471. *ppPage = 0;
  61472. }
  61473. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  61474. }
  61475. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  61476. end_allocate_page:
  61477. releasePage(pTrunk);
  61478. releasePage(pPrevTrunk);
  61479. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  61480. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  61481. return rc;
  61482. }
  61483. /*
  61484. ** This function is used to add page iPage to the database file free-list.
  61485. ** It is assumed that the page is not already a part of the free-list.
  61486. **
  61487. ** The value passed as the second argument to this function is optional.
  61488. ** If the caller happens to have a pointer to the MemPage object
  61489. ** corresponding to page iPage handy, it may pass it as the second value.
  61490. ** Otherwise, it may pass NULL.
  61491. **
  61492. ** If a pointer to a MemPage object is passed as the second argument,
  61493. ** its reference count is not altered by this function.
  61494. */
  61495. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  61496. MemPage *pTrunk = 0; /* Free-list trunk page */
  61497. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  61498. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  61499. MemPage *pPage; /* Page being freed. May be NULL. */
  61500. int rc; /* Return Code */
  61501. int nFree; /* Initial number of pages on free-list */
  61502. assert( sqlite3_mutex_held(pBt->mutex) );
  61503. assert( CORRUPT_DB || iPage>1 );
  61504. assert( !pMemPage || pMemPage->pgno==iPage );
  61505. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  61506. if( pMemPage ){
  61507. pPage = pMemPage;
  61508. sqlite3PagerRef(pPage->pDbPage);
  61509. }else{
  61510. pPage = btreePageLookup(pBt, iPage);
  61511. }
  61512. /* Increment the free page count on pPage1 */
  61513. rc = sqlite3PagerWrite(pPage1->pDbPage);
  61514. if( rc ) goto freepage_out;
  61515. nFree = get4byte(&pPage1->aData[36]);
  61516. put4byte(&pPage1->aData[36], nFree+1);
  61517. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  61518. /* If the secure_delete option is enabled, then
  61519. ** always fully overwrite deleted information with zeros.
  61520. */
  61521. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  61522. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  61523. ){
  61524. goto freepage_out;
  61525. }
  61526. memset(pPage->aData, 0, pPage->pBt->pageSize);
  61527. }
  61528. /* If the database supports auto-vacuum, write an entry in the pointer-map
  61529. ** to indicate that the page is free.
  61530. */
  61531. if( ISAUTOVACUUM ){
  61532. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  61533. if( rc ) goto freepage_out;
  61534. }
  61535. /* Now manipulate the actual database free-list structure. There are two
  61536. ** possibilities. If the free-list is currently empty, or if the first
  61537. ** trunk page in the free-list is full, then this page will become a
  61538. ** new free-list trunk page. Otherwise, it will become a leaf of the
  61539. ** first trunk page in the current free-list. This block tests if it
  61540. ** is possible to add the page as a new free-list leaf.
  61541. */
  61542. if( nFree!=0 ){
  61543. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  61544. iTrunk = get4byte(&pPage1->aData[32]);
  61545. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  61546. if( rc!=SQLITE_OK ){
  61547. goto freepage_out;
  61548. }
  61549. nLeaf = get4byte(&pTrunk->aData[4]);
  61550. assert( pBt->usableSize>32 );
  61551. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  61552. rc = SQLITE_CORRUPT_BKPT;
  61553. goto freepage_out;
  61554. }
  61555. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  61556. /* In this case there is room on the trunk page to insert the page
  61557. ** being freed as a new leaf.
  61558. **
  61559. ** Note that the trunk page is not really full until it contains
  61560. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  61561. ** coded. But due to a coding error in versions of SQLite prior to
  61562. ** 3.6.0, databases with freelist trunk pages holding more than
  61563. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  61564. ** to maintain backwards compatibility with older versions of SQLite,
  61565. ** we will continue to restrict the number of entries to usableSize/4 - 8
  61566. ** for now. At some point in the future (once everyone has upgraded
  61567. ** to 3.6.0 or later) we should consider fixing the conditional above
  61568. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  61569. **
  61570. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  61571. ** avoid using the last six entries in the freelist trunk page array in
  61572. ** order that database files created by newer versions of SQLite can be
  61573. ** read by older versions of SQLite.
  61574. */
  61575. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  61576. if( rc==SQLITE_OK ){
  61577. put4byte(&pTrunk->aData[4], nLeaf+1);
  61578. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  61579. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  61580. sqlite3PagerDontWrite(pPage->pDbPage);
  61581. }
  61582. rc = btreeSetHasContent(pBt, iPage);
  61583. }
  61584. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  61585. goto freepage_out;
  61586. }
  61587. }
  61588. /* If control flows to this point, then it was not possible to add the
  61589. ** the page being freed as a leaf page of the first trunk in the free-list.
  61590. ** Possibly because the free-list is empty, or possibly because the
  61591. ** first trunk in the free-list is full. Either way, the page being freed
  61592. ** will become the new first trunk page in the free-list.
  61593. */
  61594. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  61595. goto freepage_out;
  61596. }
  61597. rc = sqlite3PagerWrite(pPage->pDbPage);
  61598. if( rc!=SQLITE_OK ){
  61599. goto freepage_out;
  61600. }
  61601. put4byte(pPage->aData, iTrunk);
  61602. put4byte(&pPage->aData[4], 0);
  61603. put4byte(&pPage1->aData[32], iPage);
  61604. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  61605. freepage_out:
  61606. if( pPage ){
  61607. pPage->isInit = 0;
  61608. }
  61609. releasePage(pPage);
  61610. releasePage(pTrunk);
  61611. return rc;
  61612. }
  61613. static void freePage(MemPage *pPage, int *pRC){
  61614. if( (*pRC)==SQLITE_OK ){
  61615. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  61616. }
  61617. }
  61618. /*
  61619. ** Free any overflow pages associated with the given Cell. Write the
  61620. ** local Cell size (the number of bytes on the original page, omitting
  61621. ** overflow) into *pnSize.
  61622. */
  61623. static int clearCell(
  61624. MemPage *pPage, /* The page that contains the Cell */
  61625. unsigned char *pCell, /* First byte of the Cell */
  61626. CellInfo *pInfo /* Size information about the cell */
  61627. ){
  61628. BtShared *pBt;
  61629. Pgno ovflPgno;
  61630. int rc;
  61631. int nOvfl;
  61632. u32 ovflPageSize;
  61633. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61634. pPage->xParseCell(pPage, pCell, pInfo);
  61635. if( pInfo->nLocal==pInfo->nPayload ){
  61636. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  61637. }
  61638. if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
  61639. /* Cell extends past end of page */
  61640. return SQLITE_CORRUPT_PGNO(pPage->pgno);
  61641. }
  61642. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  61643. pBt = pPage->pBt;
  61644. assert( pBt->usableSize > 4 );
  61645. ovflPageSize = pBt->usableSize - 4;
  61646. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  61647. assert( nOvfl>0 ||
  61648. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  61649. );
  61650. while( nOvfl-- ){
  61651. Pgno iNext = 0;
  61652. MemPage *pOvfl = 0;
  61653. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  61654. /* 0 is not a legal page number and page 1 cannot be an
  61655. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  61656. ** file the database must be corrupt. */
  61657. return SQLITE_CORRUPT_BKPT;
  61658. }
  61659. if( nOvfl ){
  61660. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  61661. if( rc ) return rc;
  61662. }
  61663. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  61664. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  61665. ){
  61666. /* There is no reason any cursor should have an outstanding reference
  61667. ** to an overflow page belonging to a cell that is being deleted/updated.
  61668. ** So if there exists more than one reference to this page, then it
  61669. ** must not really be an overflow page and the database must be corrupt.
  61670. ** It is helpful to detect this before calling freePage2(), as
  61671. ** freePage2() may zero the page contents if secure-delete mode is
  61672. ** enabled. If this 'overflow' page happens to be a page that the
  61673. ** caller is iterating through or using in some other way, this
  61674. ** can be problematic.
  61675. */
  61676. rc = SQLITE_CORRUPT_BKPT;
  61677. }else{
  61678. rc = freePage2(pBt, pOvfl, ovflPgno);
  61679. }
  61680. if( pOvfl ){
  61681. sqlite3PagerUnref(pOvfl->pDbPage);
  61682. }
  61683. if( rc ) return rc;
  61684. ovflPgno = iNext;
  61685. }
  61686. return SQLITE_OK;
  61687. }
  61688. /*
  61689. ** Create the byte sequence used to represent a cell on page pPage
  61690. ** and write that byte sequence into pCell[]. Overflow pages are
  61691. ** allocated and filled in as necessary. The calling procedure
  61692. ** is responsible for making sure sufficient space has been allocated
  61693. ** for pCell[].
  61694. **
  61695. ** Note that pCell does not necessary need to point to the pPage->aData
  61696. ** area. pCell might point to some temporary storage. The cell will
  61697. ** be constructed in this temporary area then copied into pPage->aData
  61698. ** later.
  61699. */
  61700. static int fillInCell(
  61701. MemPage *pPage, /* The page that contains the cell */
  61702. unsigned char *pCell, /* Complete text of the cell */
  61703. const BtreePayload *pX, /* Payload with which to construct the cell */
  61704. int *pnSize /* Write cell size here */
  61705. ){
  61706. int nPayload;
  61707. const u8 *pSrc;
  61708. int nSrc, n, rc, mn;
  61709. int spaceLeft;
  61710. MemPage *pToRelease;
  61711. unsigned char *pPrior;
  61712. unsigned char *pPayload;
  61713. BtShared *pBt;
  61714. Pgno pgnoOvfl;
  61715. int nHeader;
  61716. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61717. /* pPage is not necessarily writeable since pCell might be auxiliary
  61718. ** buffer space that is separate from the pPage buffer area */
  61719. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  61720. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61721. /* Fill in the header. */
  61722. nHeader = pPage->childPtrSize;
  61723. if( pPage->intKey ){
  61724. nPayload = pX->nData + pX->nZero;
  61725. pSrc = pX->pData;
  61726. nSrc = pX->nData;
  61727. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  61728. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61729. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  61730. }else{
  61731. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  61732. nSrc = nPayload = (int)pX->nKey;
  61733. pSrc = pX->pKey;
  61734. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61735. }
  61736. /* Fill in the payload */
  61737. pPayload = &pCell[nHeader];
  61738. if( nPayload<=pPage->maxLocal ){
  61739. /* This is the common case where everything fits on the btree page
  61740. ** and no overflow pages are required. */
  61741. n = nHeader + nPayload;
  61742. testcase( n==3 );
  61743. testcase( n==4 );
  61744. if( n<4 ) n = 4;
  61745. *pnSize = n;
  61746. assert( nSrc<=nPayload );
  61747. testcase( nSrc<nPayload );
  61748. memcpy(pPayload, pSrc, nSrc);
  61749. memset(pPayload+nSrc, 0, nPayload-nSrc);
  61750. return SQLITE_OK;
  61751. }
  61752. /* If we reach this point, it means that some of the content will need
  61753. ** to spill onto overflow pages.
  61754. */
  61755. mn = pPage->minLocal;
  61756. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  61757. testcase( n==pPage->maxLocal );
  61758. testcase( n==pPage->maxLocal+1 );
  61759. if( n > pPage->maxLocal ) n = mn;
  61760. spaceLeft = n;
  61761. *pnSize = n + nHeader + 4;
  61762. pPrior = &pCell[nHeader+n];
  61763. pToRelease = 0;
  61764. pgnoOvfl = 0;
  61765. pBt = pPage->pBt;
  61766. /* At this point variables should be set as follows:
  61767. **
  61768. ** nPayload Total payload size in bytes
  61769. ** pPayload Begin writing payload here
  61770. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  61771. ** that means content must spill into overflow pages.
  61772. ** *pnSize Size of the local cell (not counting overflow pages)
  61773. ** pPrior Where to write the pgno of the first overflow page
  61774. **
  61775. ** Use a call to btreeParseCellPtr() to verify that the values above
  61776. ** were computed correctly.
  61777. */
  61778. #ifdef SQLITE_DEBUG
  61779. {
  61780. CellInfo info;
  61781. pPage->xParseCell(pPage, pCell, &info);
  61782. assert( nHeader==(int)(info.pPayload - pCell) );
  61783. assert( info.nKey==pX->nKey );
  61784. assert( *pnSize == info.nSize );
  61785. assert( spaceLeft == info.nLocal );
  61786. }
  61787. #endif
  61788. /* Write the payload into the local Cell and any extra into overflow pages */
  61789. while( 1 ){
  61790. n = nPayload;
  61791. if( n>spaceLeft ) n = spaceLeft;
  61792. /* If pToRelease is not zero than pPayload points into the data area
  61793. ** of pToRelease. Make sure pToRelease is still writeable. */
  61794. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61795. /* If pPayload is part of the data area of pPage, then make sure pPage
  61796. ** is still writeable */
  61797. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  61798. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61799. if( nSrc>=n ){
  61800. memcpy(pPayload, pSrc, n);
  61801. }else if( nSrc>0 ){
  61802. n = nSrc;
  61803. memcpy(pPayload, pSrc, n);
  61804. }else{
  61805. memset(pPayload, 0, n);
  61806. }
  61807. nPayload -= n;
  61808. if( nPayload<=0 ) break;
  61809. pPayload += n;
  61810. pSrc += n;
  61811. nSrc -= n;
  61812. spaceLeft -= n;
  61813. if( spaceLeft==0 ){
  61814. MemPage *pOvfl = 0;
  61815. #ifndef SQLITE_OMIT_AUTOVACUUM
  61816. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  61817. if( pBt->autoVacuum ){
  61818. do{
  61819. pgnoOvfl++;
  61820. } while(
  61821. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  61822. );
  61823. }
  61824. #endif
  61825. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  61826. #ifndef SQLITE_OMIT_AUTOVACUUM
  61827. /* If the database supports auto-vacuum, and the second or subsequent
  61828. ** overflow page is being allocated, add an entry to the pointer-map
  61829. ** for that page now.
  61830. **
  61831. ** If this is the first overflow page, then write a partial entry
  61832. ** to the pointer-map. If we write nothing to this pointer-map slot,
  61833. ** then the optimistic overflow chain processing in clearCell()
  61834. ** may misinterpret the uninitialized values and delete the
  61835. ** wrong pages from the database.
  61836. */
  61837. if( pBt->autoVacuum && rc==SQLITE_OK ){
  61838. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  61839. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  61840. if( rc ){
  61841. releasePage(pOvfl);
  61842. }
  61843. }
  61844. #endif
  61845. if( rc ){
  61846. releasePage(pToRelease);
  61847. return rc;
  61848. }
  61849. /* If pToRelease is not zero than pPrior points into the data area
  61850. ** of pToRelease. Make sure pToRelease is still writeable. */
  61851. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61852. /* If pPrior is part of the data area of pPage, then make sure pPage
  61853. ** is still writeable */
  61854. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  61855. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61856. put4byte(pPrior, pgnoOvfl);
  61857. releasePage(pToRelease);
  61858. pToRelease = pOvfl;
  61859. pPrior = pOvfl->aData;
  61860. put4byte(pPrior, 0);
  61861. pPayload = &pOvfl->aData[4];
  61862. spaceLeft = pBt->usableSize - 4;
  61863. }
  61864. }
  61865. releasePage(pToRelease);
  61866. return SQLITE_OK;
  61867. }
  61868. /*
  61869. ** Remove the i-th cell from pPage. This routine effects pPage only.
  61870. ** The cell content is not freed or deallocated. It is assumed that
  61871. ** the cell content has been copied someplace else. This routine just
  61872. ** removes the reference to the cell from pPage.
  61873. **
  61874. ** "sz" must be the number of bytes in the cell.
  61875. */
  61876. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  61877. u32 pc; /* Offset to cell content of cell being deleted */
  61878. u8 *data; /* pPage->aData */
  61879. u8 *ptr; /* Used to move bytes around within data[] */
  61880. int rc; /* The return code */
  61881. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  61882. if( *pRC ) return;
  61883. assert( idx>=0 && idx<pPage->nCell );
  61884. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  61885. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61886. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61887. data = pPage->aData;
  61888. ptr = &pPage->aCellIdx[2*idx];
  61889. pc = get2byte(ptr);
  61890. hdr = pPage->hdrOffset;
  61891. testcase( pc==get2byte(&data[hdr+5]) );
  61892. testcase( pc+sz==pPage->pBt->usableSize );
  61893. if( pc+sz > pPage->pBt->usableSize ){
  61894. *pRC = SQLITE_CORRUPT_BKPT;
  61895. return;
  61896. }
  61897. rc = freeSpace(pPage, pc, sz);
  61898. if( rc ){
  61899. *pRC = rc;
  61900. return;
  61901. }
  61902. pPage->nCell--;
  61903. if( pPage->nCell==0 ){
  61904. memset(&data[hdr+1], 0, 4);
  61905. data[hdr+7] = 0;
  61906. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  61907. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  61908. - pPage->childPtrSize - 8;
  61909. }else{
  61910. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  61911. put2byte(&data[hdr+3], pPage->nCell);
  61912. pPage->nFree += 2;
  61913. }
  61914. }
  61915. /*
  61916. ** Insert a new cell on pPage at cell index "i". pCell points to the
  61917. ** content of the cell.
  61918. **
  61919. ** If the cell content will fit on the page, then put it there. If it
  61920. ** will not fit, then make a copy of the cell content into pTemp if
  61921. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  61922. ** in pPage->apOvfl[] and make it point to the cell content (either
  61923. ** in pTemp or the original pCell) and also record its index.
  61924. ** Allocating a new entry in pPage->aCell[] implies that
  61925. ** pPage->nOverflow is incremented.
  61926. **
  61927. ** *pRC must be SQLITE_OK when this routine is called.
  61928. */
  61929. static void insertCell(
  61930. MemPage *pPage, /* Page into which we are copying */
  61931. int i, /* New cell becomes the i-th cell of the page */
  61932. u8 *pCell, /* Content of the new cell */
  61933. int sz, /* Bytes of content in pCell */
  61934. u8 *pTemp, /* Temp storage space for pCell, if needed */
  61935. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  61936. int *pRC /* Read and write return code from here */
  61937. ){
  61938. int idx = 0; /* Where to write new cell content in data[] */
  61939. int j; /* Loop counter */
  61940. u8 *data; /* The content of the whole page */
  61941. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  61942. assert( *pRC==SQLITE_OK );
  61943. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  61944. assert( MX_CELL(pPage->pBt)<=10921 );
  61945. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  61946. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  61947. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  61948. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61949. /* The cell should normally be sized correctly. However, when moving a
  61950. ** malformed cell from a leaf page to an interior page, if the cell size
  61951. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  61952. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  61953. ** the term after the || in the following assert(). */
  61954. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  61955. if( pPage->nOverflow || sz+2>pPage->nFree ){
  61956. if( pTemp ){
  61957. memcpy(pTemp, pCell, sz);
  61958. pCell = pTemp;
  61959. }
  61960. if( iChild ){
  61961. put4byte(pCell, iChild);
  61962. }
  61963. j = pPage->nOverflow++;
  61964. /* Comparison against ArraySize-1 since we hold back one extra slot
  61965. ** as a contingency. In other words, never need more than 3 overflow
  61966. ** slots but 4 are allocated, just to be safe. */
  61967. assert( j < ArraySize(pPage->apOvfl)-1 );
  61968. pPage->apOvfl[j] = pCell;
  61969. pPage->aiOvfl[j] = (u16)i;
  61970. /* When multiple overflows occur, they are always sequential and in
  61971. ** sorted order. This invariants arise because multiple overflows can
  61972. ** only occur when inserting divider cells into the parent page during
  61973. ** balancing, and the dividers are adjacent and sorted.
  61974. */
  61975. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  61976. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  61977. }else{
  61978. int rc = sqlite3PagerWrite(pPage->pDbPage);
  61979. if( rc!=SQLITE_OK ){
  61980. *pRC = rc;
  61981. return;
  61982. }
  61983. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61984. data = pPage->aData;
  61985. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  61986. rc = allocateSpace(pPage, sz, &idx);
  61987. if( rc ){ *pRC = rc; return; }
  61988. /* The allocateSpace() routine guarantees the following properties
  61989. ** if it returns successfully */
  61990. assert( idx >= 0 );
  61991. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  61992. assert( idx+sz <= (int)pPage->pBt->usableSize );
  61993. pPage->nFree -= (u16)(2 + sz);
  61994. memcpy(&data[idx], pCell, sz);
  61995. if( iChild ){
  61996. put4byte(&data[idx], iChild);
  61997. }
  61998. pIns = pPage->aCellIdx + i*2;
  61999. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  62000. put2byte(pIns, idx);
  62001. pPage->nCell++;
  62002. /* increment the cell count */
  62003. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  62004. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  62005. #ifndef SQLITE_OMIT_AUTOVACUUM
  62006. if( pPage->pBt->autoVacuum ){
  62007. /* The cell may contain a pointer to an overflow page. If so, write
  62008. ** the entry for the overflow page into the pointer map.
  62009. */
  62010. ptrmapPutOvflPtr(pPage, pCell, pRC);
  62011. }
  62012. #endif
  62013. }
  62014. }
  62015. /*
  62016. ** A CellArray object contains a cache of pointers and sizes for a
  62017. ** consecutive sequence of cells that might be held on multiple pages.
  62018. */
  62019. typedef struct CellArray CellArray;
  62020. struct CellArray {
  62021. int nCell; /* Number of cells in apCell[] */
  62022. MemPage *pRef; /* Reference page */
  62023. u8 **apCell; /* All cells begin balanced */
  62024. u16 *szCell; /* Local size of all cells in apCell[] */
  62025. };
  62026. /*
  62027. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  62028. ** computed.
  62029. */
  62030. static void populateCellCache(CellArray *p, int idx, int N){
  62031. assert( idx>=0 && idx+N<=p->nCell );
  62032. while( N>0 ){
  62033. assert( p->apCell[idx]!=0 );
  62034. if( p->szCell[idx]==0 ){
  62035. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  62036. }else{
  62037. assert( CORRUPT_DB ||
  62038. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  62039. }
  62040. idx++;
  62041. N--;
  62042. }
  62043. }
  62044. /*
  62045. ** Return the size of the Nth element of the cell array
  62046. */
  62047. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  62048. assert( N>=0 && N<p->nCell );
  62049. assert( p->szCell[N]==0 );
  62050. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  62051. return p->szCell[N];
  62052. }
  62053. static u16 cachedCellSize(CellArray *p, int N){
  62054. assert( N>=0 && N<p->nCell );
  62055. if( p->szCell[N] ) return p->szCell[N];
  62056. return computeCellSize(p, N);
  62057. }
  62058. /*
  62059. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  62060. ** szCell[] array contains the size in bytes of each cell. This function
  62061. ** replaces the current contents of page pPg with the contents of the cell
  62062. ** array.
  62063. **
  62064. ** Some of the cells in apCell[] may currently be stored in pPg. This
  62065. ** function works around problems caused by this by making a copy of any
  62066. ** such cells before overwriting the page data.
  62067. **
  62068. ** The MemPage.nFree field is invalidated by this function. It is the
  62069. ** responsibility of the caller to set it correctly.
  62070. */
  62071. static int rebuildPage(
  62072. MemPage *pPg, /* Edit this page */
  62073. int nCell, /* Final number of cells on page */
  62074. u8 **apCell, /* Array of cells */
  62075. u16 *szCell /* Array of cell sizes */
  62076. ){
  62077. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  62078. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  62079. const int usableSize = pPg->pBt->usableSize;
  62080. u8 * const pEnd = &aData[usableSize];
  62081. int i;
  62082. u8 *pCellptr = pPg->aCellIdx;
  62083. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  62084. u8 *pData;
  62085. i = get2byte(&aData[hdr+5]);
  62086. memcpy(&pTmp[i], &aData[i], usableSize - i);
  62087. pData = pEnd;
  62088. for(i=0; i<nCell; i++){
  62089. u8 *pCell = apCell[i];
  62090. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  62091. pCell = &pTmp[pCell - aData];
  62092. }
  62093. pData -= szCell[i];
  62094. put2byte(pCellptr, (pData - aData));
  62095. pCellptr += 2;
  62096. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  62097. memcpy(pData, pCell, szCell[i]);
  62098. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  62099. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  62100. }
  62101. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  62102. pPg->nCell = nCell;
  62103. pPg->nOverflow = 0;
  62104. put2byte(&aData[hdr+1], 0);
  62105. put2byte(&aData[hdr+3], pPg->nCell);
  62106. put2byte(&aData[hdr+5], pData - aData);
  62107. aData[hdr+7] = 0x00;
  62108. return SQLITE_OK;
  62109. }
  62110. /*
  62111. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  62112. ** contains the size in bytes of each such cell. This function attempts to
  62113. ** add the cells stored in the array to page pPg. If it cannot (because
  62114. ** the page needs to be defragmented before the cells will fit), non-zero
  62115. ** is returned. Otherwise, if the cells are added successfully, zero is
  62116. ** returned.
  62117. **
  62118. ** Argument pCellptr points to the first entry in the cell-pointer array
  62119. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  62120. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  62121. ** cell in the array. It is the responsibility of the caller to ensure
  62122. ** that it is safe to overwrite this part of the cell-pointer array.
  62123. **
  62124. ** When this function is called, *ppData points to the start of the
  62125. ** content area on page pPg. If the size of the content area is extended,
  62126. ** *ppData is updated to point to the new start of the content area
  62127. ** before returning.
  62128. **
  62129. ** Finally, argument pBegin points to the byte immediately following the
  62130. ** end of the space required by this page for the cell-pointer area (for
  62131. ** all cells - not just those inserted by the current call). If the content
  62132. ** area must be extended to before this point in order to accomodate all
  62133. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  62134. */
  62135. static int pageInsertArray(
  62136. MemPage *pPg, /* Page to add cells to */
  62137. u8 *pBegin, /* End of cell-pointer array */
  62138. u8 **ppData, /* IN/OUT: Page content -area pointer */
  62139. u8 *pCellptr, /* Pointer to cell-pointer area */
  62140. int iFirst, /* Index of first cell to add */
  62141. int nCell, /* Number of cells to add to pPg */
  62142. CellArray *pCArray /* Array of cells */
  62143. ){
  62144. int i;
  62145. u8 *aData = pPg->aData;
  62146. u8 *pData = *ppData;
  62147. int iEnd = iFirst + nCell;
  62148. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  62149. for(i=iFirst; i<iEnd; i++){
  62150. int sz, rc;
  62151. u8 *pSlot;
  62152. sz = cachedCellSize(pCArray, i);
  62153. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  62154. if( (pData - pBegin)<sz ) return 1;
  62155. pData -= sz;
  62156. pSlot = pData;
  62157. }
  62158. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  62159. ** database. But they might for a corrupt database. Hence use memmove()
  62160. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  62161. assert( (pSlot+sz)<=pCArray->apCell[i]
  62162. || pSlot>=(pCArray->apCell[i]+sz)
  62163. || CORRUPT_DB );
  62164. memmove(pSlot, pCArray->apCell[i], sz);
  62165. put2byte(pCellptr, (pSlot - aData));
  62166. pCellptr += 2;
  62167. }
  62168. *ppData = pData;
  62169. return 0;
  62170. }
  62171. /*
  62172. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  62173. ** contains the size in bytes of each such cell. This function adds the
  62174. ** space associated with each cell in the array that is currently stored
  62175. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  62176. ** fields of the page are not updated.
  62177. **
  62178. ** This function returns the total number of cells added to the free-list.
  62179. */
  62180. static int pageFreeArray(
  62181. MemPage *pPg, /* Page to edit */
  62182. int iFirst, /* First cell to delete */
  62183. int nCell, /* Cells to delete */
  62184. CellArray *pCArray /* Array of cells */
  62185. ){
  62186. u8 * const aData = pPg->aData;
  62187. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  62188. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  62189. int nRet = 0;
  62190. int i;
  62191. int iEnd = iFirst + nCell;
  62192. u8 *pFree = 0;
  62193. int szFree = 0;
  62194. for(i=iFirst; i<iEnd; i++){
  62195. u8 *pCell = pCArray->apCell[i];
  62196. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  62197. int sz;
  62198. /* No need to use cachedCellSize() here. The sizes of all cells that
  62199. ** are to be freed have already been computing while deciding which
  62200. ** cells need freeing */
  62201. sz = pCArray->szCell[i]; assert( sz>0 );
  62202. if( pFree!=(pCell + sz) ){
  62203. if( pFree ){
  62204. assert( pFree>aData && (pFree - aData)<65536 );
  62205. freeSpace(pPg, (u16)(pFree - aData), szFree);
  62206. }
  62207. pFree = pCell;
  62208. szFree = sz;
  62209. if( pFree+sz>pEnd ) return 0;
  62210. }else{
  62211. pFree = pCell;
  62212. szFree += sz;
  62213. }
  62214. nRet++;
  62215. }
  62216. }
  62217. if( pFree ){
  62218. assert( pFree>aData && (pFree - aData)<65536 );
  62219. freeSpace(pPg, (u16)(pFree - aData), szFree);
  62220. }
  62221. return nRet;
  62222. }
  62223. /*
  62224. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  62225. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  62226. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  62227. ** starting at apCell[iNew].
  62228. **
  62229. ** This routine makes the necessary adjustments to pPg so that it contains
  62230. ** the correct cells after being balanced.
  62231. **
  62232. ** The pPg->nFree field is invalid when this function returns. It is the
  62233. ** responsibility of the caller to set it correctly.
  62234. */
  62235. static int editPage(
  62236. MemPage *pPg, /* Edit this page */
  62237. int iOld, /* Index of first cell currently on page */
  62238. int iNew, /* Index of new first cell on page */
  62239. int nNew, /* Final number of cells on page */
  62240. CellArray *pCArray /* Array of cells and sizes */
  62241. ){
  62242. u8 * const aData = pPg->aData;
  62243. const int hdr = pPg->hdrOffset;
  62244. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  62245. int nCell = pPg->nCell; /* Cells stored on pPg */
  62246. u8 *pData;
  62247. u8 *pCellptr;
  62248. int i;
  62249. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  62250. int iNewEnd = iNew + nNew;
  62251. #ifdef SQLITE_DEBUG
  62252. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  62253. memcpy(pTmp, aData, pPg->pBt->usableSize);
  62254. #endif
  62255. /* Remove cells from the start and end of the page */
  62256. if( iOld<iNew ){
  62257. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  62258. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  62259. nCell -= nShift;
  62260. }
  62261. if( iNewEnd < iOldEnd ){
  62262. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  62263. }
  62264. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  62265. if( pData<pBegin ) goto editpage_fail;
  62266. /* Add cells to the start of the page */
  62267. if( iNew<iOld ){
  62268. int nAdd = MIN(nNew,iOld-iNew);
  62269. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  62270. pCellptr = pPg->aCellIdx;
  62271. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  62272. if( pageInsertArray(
  62273. pPg, pBegin, &pData, pCellptr,
  62274. iNew, nAdd, pCArray
  62275. ) ) goto editpage_fail;
  62276. nCell += nAdd;
  62277. }
  62278. /* Add any overflow cells */
  62279. for(i=0; i<pPg->nOverflow; i++){
  62280. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  62281. if( iCell>=0 && iCell<nNew ){
  62282. pCellptr = &pPg->aCellIdx[iCell * 2];
  62283. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  62284. nCell++;
  62285. if( pageInsertArray(
  62286. pPg, pBegin, &pData, pCellptr,
  62287. iCell+iNew, 1, pCArray
  62288. ) ) goto editpage_fail;
  62289. }
  62290. }
  62291. /* Append cells to the end of the page */
  62292. pCellptr = &pPg->aCellIdx[nCell*2];
  62293. if( pageInsertArray(
  62294. pPg, pBegin, &pData, pCellptr,
  62295. iNew+nCell, nNew-nCell, pCArray
  62296. ) ) goto editpage_fail;
  62297. pPg->nCell = nNew;
  62298. pPg->nOverflow = 0;
  62299. put2byte(&aData[hdr+3], pPg->nCell);
  62300. put2byte(&aData[hdr+5], pData - aData);
  62301. #ifdef SQLITE_DEBUG
  62302. for(i=0; i<nNew && !CORRUPT_DB; i++){
  62303. u8 *pCell = pCArray->apCell[i+iNew];
  62304. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  62305. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  62306. pCell = &pTmp[pCell - aData];
  62307. }
  62308. assert( 0==memcmp(pCell, &aData[iOff],
  62309. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  62310. }
  62311. #endif
  62312. return SQLITE_OK;
  62313. editpage_fail:
  62314. /* Unable to edit this page. Rebuild it from scratch instead. */
  62315. populateCellCache(pCArray, iNew, nNew);
  62316. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  62317. }
  62318. /*
  62319. ** The following parameters determine how many adjacent pages get involved
  62320. ** in a balancing operation. NN is the number of neighbors on either side
  62321. ** of the page that participate in the balancing operation. NB is the
  62322. ** total number of pages that participate, including the target page and
  62323. ** NN neighbors on either side.
  62324. **
  62325. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  62326. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  62327. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  62328. ** The value of NN appears to give the best results overall.
  62329. */
  62330. #define NN 1 /* Number of neighbors on either side of pPage */
  62331. #define NB (NN*2+1) /* Total pages involved in the balance */
  62332. #ifndef SQLITE_OMIT_QUICKBALANCE
  62333. /*
  62334. ** This version of balance() handles the common special case where
  62335. ** a new entry is being inserted on the extreme right-end of the
  62336. ** tree, in other words, when the new entry will become the largest
  62337. ** entry in the tree.
  62338. **
  62339. ** Instead of trying to balance the 3 right-most leaf pages, just add
  62340. ** a new page to the right-hand side and put the one new entry in
  62341. ** that page. This leaves the right side of the tree somewhat
  62342. ** unbalanced. But odds are that we will be inserting new entries
  62343. ** at the end soon afterwards so the nearly empty page will quickly
  62344. ** fill up. On average.
  62345. **
  62346. ** pPage is the leaf page which is the right-most page in the tree.
  62347. ** pParent is its parent. pPage must have a single overflow entry
  62348. ** which is also the right-most entry on the page.
  62349. **
  62350. ** The pSpace buffer is used to store a temporary copy of the divider
  62351. ** cell that will be inserted into pParent. Such a cell consists of a 4
  62352. ** byte page number followed by a variable length integer. In other
  62353. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  62354. ** least 13 bytes in size.
  62355. */
  62356. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  62357. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  62358. MemPage *pNew; /* Newly allocated page */
  62359. int rc; /* Return Code */
  62360. Pgno pgnoNew; /* Page number of pNew */
  62361. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62362. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62363. assert( pPage->nOverflow==1 );
  62364. /* This error condition is now caught prior to reaching this function */
  62365. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  62366. /* Allocate a new page. This page will become the right-sibling of
  62367. ** pPage. Make the parent page writable, so that the new divider cell
  62368. ** may be inserted. If both these operations are successful, proceed.
  62369. */
  62370. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  62371. if( rc==SQLITE_OK ){
  62372. u8 *pOut = &pSpace[4];
  62373. u8 *pCell = pPage->apOvfl[0];
  62374. u16 szCell = pPage->xCellSize(pPage, pCell);
  62375. u8 *pStop;
  62376. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  62377. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  62378. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  62379. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  62380. if( NEVER(rc) ) return rc;
  62381. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  62382. /* If this is an auto-vacuum database, update the pointer map
  62383. ** with entries for the new page, and any pointer from the
  62384. ** cell on the page to an overflow page. If either of these
  62385. ** operations fails, the return code is set, but the contents
  62386. ** of the parent page are still manipulated by thh code below.
  62387. ** That is Ok, at this point the parent page is guaranteed to
  62388. ** be marked as dirty. Returning an error code will cause a
  62389. ** rollback, undoing any changes made to the parent page.
  62390. */
  62391. if( ISAUTOVACUUM ){
  62392. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  62393. if( szCell>pNew->minLocal ){
  62394. ptrmapPutOvflPtr(pNew, pCell, &rc);
  62395. }
  62396. }
  62397. /* Create a divider cell to insert into pParent. The divider cell
  62398. ** consists of a 4-byte page number (the page number of pPage) and
  62399. ** a variable length key value (which must be the same value as the
  62400. ** largest key on pPage).
  62401. **
  62402. ** To find the largest key value on pPage, first find the right-most
  62403. ** cell on pPage. The first two fields of this cell are the
  62404. ** record-length (a variable length integer at most 32-bits in size)
  62405. ** and the key value (a variable length integer, may have any value).
  62406. ** The first of the while(...) loops below skips over the record-length
  62407. ** field. The second while(...) loop copies the key value from the
  62408. ** cell on pPage into the pSpace buffer.
  62409. */
  62410. pCell = findCell(pPage, pPage->nCell-1);
  62411. pStop = &pCell[9];
  62412. while( (*(pCell++)&0x80) && pCell<pStop );
  62413. pStop = &pCell[9];
  62414. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  62415. /* Insert the new divider cell into pParent. */
  62416. if( rc==SQLITE_OK ){
  62417. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  62418. 0, pPage->pgno, &rc);
  62419. }
  62420. /* Set the right-child pointer of pParent to point to the new page. */
  62421. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  62422. /* Release the reference to the new page. */
  62423. releasePage(pNew);
  62424. }
  62425. return rc;
  62426. }
  62427. #endif /* SQLITE_OMIT_QUICKBALANCE */
  62428. #if 0
  62429. /*
  62430. ** This function does not contribute anything to the operation of SQLite.
  62431. ** it is sometimes activated temporarily while debugging code responsible
  62432. ** for setting pointer-map entries.
  62433. */
  62434. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  62435. int i, j;
  62436. for(i=0; i<nPage; i++){
  62437. Pgno n;
  62438. u8 e;
  62439. MemPage *pPage = apPage[i];
  62440. BtShared *pBt = pPage->pBt;
  62441. assert( pPage->isInit );
  62442. for(j=0; j<pPage->nCell; j++){
  62443. CellInfo info;
  62444. u8 *z;
  62445. z = findCell(pPage, j);
  62446. pPage->xParseCell(pPage, z, &info);
  62447. if( info.nLocal<info.nPayload ){
  62448. Pgno ovfl = get4byte(&z[info.nSize-4]);
  62449. ptrmapGet(pBt, ovfl, &e, &n);
  62450. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  62451. }
  62452. if( !pPage->leaf ){
  62453. Pgno child = get4byte(z);
  62454. ptrmapGet(pBt, child, &e, &n);
  62455. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  62456. }
  62457. }
  62458. if( !pPage->leaf ){
  62459. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62460. ptrmapGet(pBt, child, &e, &n);
  62461. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  62462. }
  62463. }
  62464. return 1;
  62465. }
  62466. #endif
  62467. /*
  62468. ** This function is used to copy the contents of the b-tree node stored
  62469. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  62470. ** the pointer-map entries for each child page are updated so that the
  62471. ** parent page stored in the pointer map is page pTo. If pFrom contained
  62472. ** any cells with overflow page pointers, then the corresponding pointer
  62473. ** map entries are also updated so that the parent page is page pTo.
  62474. **
  62475. ** If pFrom is currently carrying any overflow cells (entries in the
  62476. ** MemPage.apOvfl[] array), they are not copied to pTo.
  62477. **
  62478. ** Before returning, page pTo is reinitialized using btreeInitPage().
  62479. **
  62480. ** The performance of this function is not critical. It is only used by
  62481. ** the balance_shallower() and balance_deeper() procedures, neither of
  62482. ** which are called often under normal circumstances.
  62483. */
  62484. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  62485. if( (*pRC)==SQLITE_OK ){
  62486. BtShared * const pBt = pFrom->pBt;
  62487. u8 * const aFrom = pFrom->aData;
  62488. u8 * const aTo = pTo->aData;
  62489. int const iFromHdr = pFrom->hdrOffset;
  62490. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  62491. int rc;
  62492. int iData;
  62493. assert( pFrom->isInit );
  62494. assert( pFrom->nFree>=iToHdr );
  62495. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  62496. /* Copy the b-tree node content from page pFrom to page pTo. */
  62497. iData = get2byte(&aFrom[iFromHdr+5]);
  62498. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  62499. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  62500. /* Reinitialize page pTo so that the contents of the MemPage structure
  62501. ** match the new data. The initialization of pTo can actually fail under
  62502. ** fairly obscure circumstances, even though it is a copy of initialized
  62503. ** page pFrom.
  62504. */
  62505. pTo->isInit = 0;
  62506. rc = btreeInitPage(pTo);
  62507. if( rc!=SQLITE_OK ){
  62508. *pRC = rc;
  62509. return;
  62510. }
  62511. /* If this is an auto-vacuum database, update the pointer-map entries
  62512. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  62513. */
  62514. if( ISAUTOVACUUM ){
  62515. *pRC = setChildPtrmaps(pTo);
  62516. }
  62517. }
  62518. }
  62519. /*
  62520. ** This routine redistributes cells on the iParentIdx'th child of pParent
  62521. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  62522. ** same amount of free space. Usually a single sibling on either side of the
  62523. ** page are used in the balancing, though both siblings might come from one
  62524. ** side if the page is the first or last child of its parent. If the page
  62525. ** has fewer than 2 siblings (something which can only happen if the page
  62526. ** is a root page or a child of a root page) then all available siblings
  62527. ** participate in the balancing.
  62528. **
  62529. ** The number of siblings of the page might be increased or decreased by
  62530. ** one or two in an effort to keep pages nearly full but not over full.
  62531. **
  62532. ** Note that when this routine is called, some of the cells on the page
  62533. ** might not actually be stored in MemPage.aData[]. This can happen
  62534. ** if the page is overfull. This routine ensures that all cells allocated
  62535. ** to the page and its siblings fit into MemPage.aData[] before returning.
  62536. **
  62537. ** In the course of balancing the page and its siblings, cells may be
  62538. ** inserted into or removed from the parent page (pParent). Doing so
  62539. ** may cause the parent page to become overfull or underfull. If this
  62540. ** happens, it is the responsibility of the caller to invoke the correct
  62541. ** balancing routine to fix this problem (see the balance() routine).
  62542. **
  62543. ** If this routine fails for any reason, it might leave the database
  62544. ** in a corrupted state. So if this routine fails, the database should
  62545. ** be rolled back.
  62546. **
  62547. ** The third argument to this function, aOvflSpace, is a pointer to a
  62548. ** buffer big enough to hold one page. If while inserting cells into the parent
  62549. ** page (pParent) the parent page becomes overfull, this buffer is
  62550. ** used to store the parent's overflow cells. Because this function inserts
  62551. ** a maximum of four divider cells into the parent page, and the maximum
  62552. ** size of a cell stored within an internal node is always less than 1/4
  62553. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  62554. ** enough for all overflow cells.
  62555. **
  62556. ** If aOvflSpace is set to a null pointer, this function returns
  62557. ** SQLITE_NOMEM.
  62558. */
  62559. static int balance_nonroot(
  62560. MemPage *pParent, /* Parent page of siblings being balanced */
  62561. int iParentIdx, /* Index of "the page" in pParent */
  62562. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  62563. int isRoot, /* True if pParent is a root-page */
  62564. int bBulk /* True if this call is part of a bulk load */
  62565. ){
  62566. BtShared *pBt; /* The whole database */
  62567. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  62568. int nNew = 0; /* Number of pages in apNew[] */
  62569. int nOld; /* Number of pages in apOld[] */
  62570. int i, j, k; /* Loop counters */
  62571. int nxDiv; /* Next divider slot in pParent->aCell[] */
  62572. int rc = SQLITE_OK; /* The return code */
  62573. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  62574. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  62575. int usableSpace; /* Bytes in pPage beyond the header */
  62576. int pageFlags; /* Value of pPage->aData[0] */
  62577. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  62578. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  62579. int szScratch; /* Size of scratch memory requested */
  62580. MemPage *apOld[NB]; /* pPage and up to two siblings */
  62581. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  62582. u8 *pRight; /* Location in parent of right-sibling pointer */
  62583. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  62584. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  62585. int cntOld[NB+2]; /* Old index in b.apCell[] */
  62586. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  62587. u8 *aSpace1; /* Space for copies of dividers cells */
  62588. Pgno pgno; /* Temp var to store a page number in */
  62589. u8 abDone[NB+2]; /* True after i'th new page is populated */
  62590. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  62591. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  62592. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  62593. CellArray b; /* Parsed information on cells being balanced */
  62594. memset(abDone, 0, sizeof(abDone));
  62595. b.nCell = 0;
  62596. b.apCell = 0;
  62597. pBt = pParent->pBt;
  62598. assert( sqlite3_mutex_held(pBt->mutex) );
  62599. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62600. #if 0
  62601. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  62602. #endif
  62603. /* At this point pParent may have at most one overflow cell. And if
  62604. ** this overflow cell is present, it must be the cell with
  62605. ** index iParentIdx. This scenario comes about when this function
  62606. ** is called (indirectly) from sqlite3BtreeDelete().
  62607. */
  62608. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  62609. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  62610. if( !aOvflSpace ){
  62611. return SQLITE_NOMEM_BKPT;
  62612. }
  62613. /* Find the sibling pages to balance. Also locate the cells in pParent
  62614. ** that divide the siblings. An attempt is made to find NN siblings on
  62615. ** either side of pPage. More siblings are taken from one side, however,
  62616. ** if there are fewer than NN siblings on the other side. If pParent
  62617. ** has NB or fewer children then all children of pParent are taken.
  62618. **
  62619. ** This loop also drops the divider cells from the parent page. This
  62620. ** way, the remainder of the function does not have to deal with any
  62621. ** overflow cells in the parent page, since if any existed they will
  62622. ** have already been removed.
  62623. */
  62624. i = pParent->nOverflow + pParent->nCell;
  62625. if( i<2 ){
  62626. nxDiv = 0;
  62627. }else{
  62628. assert( bBulk==0 || bBulk==1 );
  62629. if( iParentIdx==0 ){
  62630. nxDiv = 0;
  62631. }else if( iParentIdx==i ){
  62632. nxDiv = i-2+bBulk;
  62633. }else{
  62634. nxDiv = iParentIdx-1;
  62635. }
  62636. i = 2-bBulk;
  62637. }
  62638. nOld = i+1;
  62639. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  62640. pRight = &pParent->aData[pParent->hdrOffset+8];
  62641. }else{
  62642. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  62643. }
  62644. pgno = get4byte(pRight);
  62645. while( 1 ){
  62646. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  62647. if( rc ){
  62648. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  62649. goto balance_cleanup;
  62650. }
  62651. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  62652. if( (i--)==0 ) break;
  62653. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  62654. apDiv[i] = pParent->apOvfl[0];
  62655. pgno = get4byte(apDiv[i]);
  62656. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  62657. pParent->nOverflow = 0;
  62658. }else{
  62659. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  62660. pgno = get4byte(apDiv[i]);
  62661. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  62662. /* Drop the cell from the parent page. apDiv[i] still points to
  62663. ** the cell within the parent, even though it has been dropped.
  62664. ** This is safe because dropping a cell only overwrites the first
  62665. ** four bytes of it, and this function does not need the first
  62666. ** four bytes of the divider cell. So the pointer is safe to use
  62667. ** later on.
  62668. **
  62669. ** But not if we are in secure-delete mode. In secure-delete mode,
  62670. ** the dropCell() routine will overwrite the entire cell with zeroes.
  62671. ** In this case, temporarily copy the cell into the aOvflSpace[]
  62672. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  62673. ** is allocated. */
  62674. if( pBt->btsFlags & BTS_FAST_SECURE ){
  62675. int iOff;
  62676. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  62677. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  62678. rc = SQLITE_CORRUPT_BKPT;
  62679. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  62680. goto balance_cleanup;
  62681. }else{
  62682. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  62683. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  62684. }
  62685. }
  62686. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  62687. }
  62688. }
  62689. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  62690. ** alignment */
  62691. nMaxCells = (nMaxCells + 3)&~3;
  62692. /*
  62693. ** Allocate space for memory structures
  62694. */
  62695. szScratch =
  62696. nMaxCells*sizeof(u8*) /* b.apCell */
  62697. + nMaxCells*sizeof(u16) /* b.szCell */
  62698. + pBt->pageSize; /* aSpace1 */
  62699. assert( szScratch<=6*(int)pBt->pageSize );
  62700. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  62701. if( b.apCell==0 ){
  62702. rc = SQLITE_NOMEM_BKPT;
  62703. goto balance_cleanup;
  62704. }
  62705. b.szCell = (u16*)&b.apCell[nMaxCells];
  62706. aSpace1 = (u8*)&b.szCell[nMaxCells];
  62707. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  62708. /*
  62709. ** Load pointers to all cells on sibling pages and the divider cells
  62710. ** into the local b.apCell[] array. Make copies of the divider cells
  62711. ** into space obtained from aSpace1[]. The divider cells have already
  62712. ** been removed from pParent.
  62713. **
  62714. ** If the siblings are on leaf pages, then the child pointers of the
  62715. ** divider cells are stripped from the cells before they are copied
  62716. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  62717. ** child pointers. If siblings are not leaves, then all cell in
  62718. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  62719. ** are alike.
  62720. **
  62721. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  62722. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  62723. */
  62724. b.pRef = apOld[0];
  62725. leafCorrection = b.pRef->leaf*4;
  62726. leafData = b.pRef->intKeyLeaf;
  62727. for(i=0; i<nOld; i++){
  62728. MemPage *pOld = apOld[i];
  62729. int limit = pOld->nCell;
  62730. u8 *aData = pOld->aData;
  62731. u16 maskPage = pOld->maskPage;
  62732. u8 *piCell = aData + pOld->cellOffset;
  62733. u8 *piEnd;
  62734. /* Verify that all sibling pages are of the same "type" (table-leaf,
  62735. ** table-interior, index-leaf, or index-interior).
  62736. */
  62737. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  62738. rc = SQLITE_CORRUPT_BKPT;
  62739. goto balance_cleanup;
  62740. }
  62741. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  62742. ** constains overflow cells, include them in the b.apCell[] array
  62743. ** in the correct spot.
  62744. **
  62745. ** Note that when there are multiple overflow cells, it is always the
  62746. ** case that they are sequential and adjacent. This invariant arises
  62747. ** because multiple overflows can only occurs when inserting divider
  62748. ** cells into a parent on a prior balance, and divider cells are always
  62749. ** adjacent and are inserted in order. There is an assert() tagged
  62750. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  62751. ** invariant.
  62752. **
  62753. ** This must be done in advance. Once the balance starts, the cell
  62754. ** offset section of the btree page will be overwritten and we will no
  62755. ** long be able to find the cells if a pointer to each cell is not saved
  62756. ** first.
  62757. */
  62758. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  62759. if( pOld->nOverflow>0 ){
  62760. limit = pOld->aiOvfl[0];
  62761. for(j=0; j<limit; j++){
  62762. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62763. piCell += 2;
  62764. b.nCell++;
  62765. }
  62766. for(k=0; k<pOld->nOverflow; k++){
  62767. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  62768. b.apCell[b.nCell] = pOld->apOvfl[k];
  62769. b.nCell++;
  62770. }
  62771. }
  62772. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  62773. while( piCell<piEnd ){
  62774. assert( b.nCell<nMaxCells );
  62775. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62776. piCell += 2;
  62777. b.nCell++;
  62778. }
  62779. cntOld[i] = b.nCell;
  62780. if( i<nOld-1 && !leafData){
  62781. u16 sz = (u16)szNew[i];
  62782. u8 *pTemp;
  62783. assert( b.nCell<nMaxCells );
  62784. b.szCell[b.nCell] = sz;
  62785. pTemp = &aSpace1[iSpace1];
  62786. iSpace1 += sz;
  62787. assert( sz<=pBt->maxLocal+23 );
  62788. assert( iSpace1 <= (int)pBt->pageSize );
  62789. memcpy(pTemp, apDiv[i], sz);
  62790. b.apCell[b.nCell] = pTemp+leafCorrection;
  62791. assert( leafCorrection==0 || leafCorrection==4 );
  62792. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  62793. if( !pOld->leaf ){
  62794. assert( leafCorrection==0 );
  62795. assert( pOld->hdrOffset==0 );
  62796. /* The right pointer of the child page pOld becomes the left
  62797. ** pointer of the divider cell */
  62798. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  62799. }else{
  62800. assert( leafCorrection==4 );
  62801. while( b.szCell[b.nCell]<4 ){
  62802. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  62803. ** does exist, pad it with 0x00 bytes. */
  62804. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  62805. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  62806. aSpace1[iSpace1++] = 0x00;
  62807. b.szCell[b.nCell]++;
  62808. }
  62809. }
  62810. b.nCell++;
  62811. }
  62812. }
  62813. /*
  62814. ** Figure out the number of pages needed to hold all b.nCell cells.
  62815. ** Store this number in "k". Also compute szNew[] which is the total
  62816. ** size of all cells on the i-th page and cntNew[] which is the index
  62817. ** in b.apCell[] of the cell that divides page i from page i+1.
  62818. ** cntNew[k] should equal b.nCell.
  62819. **
  62820. ** Values computed by this block:
  62821. **
  62822. ** k: The total number of sibling pages
  62823. ** szNew[i]: Spaced used on the i-th sibling page.
  62824. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  62825. ** the right of the i-th sibling page.
  62826. ** usableSpace: Number of bytes of space available on each sibling.
  62827. **
  62828. */
  62829. usableSpace = pBt->usableSize - 12 + leafCorrection;
  62830. for(i=0; i<nOld; i++){
  62831. MemPage *p = apOld[i];
  62832. szNew[i] = usableSpace - p->nFree;
  62833. for(j=0; j<p->nOverflow; j++){
  62834. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  62835. }
  62836. cntNew[i] = cntOld[i];
  62837. }
  62838. k = nOld;
  62839. for(i=0; i<k; i++){
  62840. int sz;
  62841. while( szNew[i]>usableSpace ){
  62842. if( i+1>=k ){
  62843. k = i+2;
  62844. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  62845. szNew[k-1] = 0;
  62846. cntNew[k-1] = b.nCell;
  62847. }
  62848. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  62849. szNew[i] -= sz;
  62850. if( !leafData ){
  62851. if( cntNew[i]<b.nCell ){
  62852. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62853. }else{
  62854. sz = 0;
  62855. }
  62856. }
  62857. szNew[i+1] += sz;
  62858. cntNew[i]--;
  62859. }
  62860. while( cntNew[i]<b.nCell ){
  62861. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62862. if( szNew[i]+sz>usableSpace ) break;
  62863. szNew[i] += sz;
  62864. cntNew[i]++;
  62865. if( !leafData ){
  62866. if( cntNew[i]<b.nCell ){
  62867. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62868. }else{
  62869. sz = 0;
  62870. }
  62871. }
  62872. szNew[i+1] -= sz;
  62873. }
  62874. if( cntNew[i]>=b.nCell ){
  62875. k = i+1;
  62876. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  62877. rc = SQLITE_CORRUPT_BKPT;
  62878. goto balance_cleanup;
  62879. }
  62880. }
  62881. /*
  62882. ** The packing computed by the previous block is biased toward the siblings
  62883. ** on the left side (siblings with smaller keys). The left siblings are
  62884. ** always nearly full, while the right-most sibling might be nearly empty.
  62885. ** The next block of code attempts to adjust the packing of siblings to
  62886. ** get a better balance.
  62887. **
  62888. ** This adjustment is more than an optimization. The packing above might
  62889. ** be so out of balance as to be illegal. For example, the right-most
  62890. ** sibling might be completely empty. This adjustment is not optional.
  62891. */
  62892. for(i=k-1; i>0; i--){
  62893. int szRight = szNew[i]; /* Size of sibling on the right */
  62894. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  62895. int r; /* Index of right-most cell in left sibling */
  62896. int d; /* Index of first cell to the left of right sibling */
  62897. r = cntNew[i-1] - 1;
  62898. d = r + 1 - leafData;
  62899. (void)cachedCellSize(&b, d);
  62900. do{
  62901. assert( d<nMaxCells );
  62902. assert( r<nMaxCells );
  62903. (void)cachedCellSize(&b, r);
  62904. if( szRight!=0
  62905. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  62906. break;
  62907. }
  62908. szRight += b.szCell[d] + 2;
  62909. szLeft -= b.szCell[r] + 2;
  62910. cntNew[i-1] = r;
  62911. r--;
  62912. d--;
  62913. }while( r>=0 );
  62914. szNew[i] = szRight;
  62915. szNew[i-1] = szLeft;
  62916. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  62917. rc = SQLITE_CORRUPT_BKPT;
  62918. goto balance_cleanup;
  62919. }
  62920. }
  62921. /* Sanity check: For a non-corrupt database file one of the follwing
  62922. ** must be true:
  62923. ** (1) We found one or more cells (cntNew[0])>0), or
  62924. ** (2) pPage is a virtual root page. A virtual root page is when
  62925. ** the real root page is page 1 and we are the only child of
  62926. ** that page.
  62927. */
  62928. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  62929. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  62930. apOld[0]->pgno, apOld[0]->nCell,
  62931. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  62932. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  62933. ));
  62934. /*
  62935. ** Allocate k new pages. Reuse old pages where possible.
  62936. */
  62937. pageFlags = apOld[0]->aData[0];
  62938. for(i=0; i<k; i++){
  62939. MemPage *pNew;
  62940. if( i<nOld ){
  62941. pNew = apNew[i] = apOld[i];
  62942. apOld[i] = 0;
  62943. rc = sqlite3PagerWrite(pNew->pDbPage);
  62944. nNew++;
  62945. if( rc ) goto balance_cleanup;
  62946. }else{
  62947. assert( i>0 );
  62948. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  62949. if( rc ) goto balance_cleanup;
  62950. zeroPage(pNew, pageFlags);
  62951. apNew[i] = pNew;
  62952. nNew++;
  62953. cntOld[i] = b.nCell;
  62954. /* Set the pointer-map entry for the new sibling page. */
  62955. if( ISAUTOVACUUM ){
  62956. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  62957. if( rc!=SQLITE_OK ){
  62958. goto balance_cleanup;
  62959. }
  62960. }
  62961. }
  62962. }
  62963. /*
  62964. ** Reassign page numbers so that the new pages are in ascending order.
  62965. ** This helps to keep entries in the disk file in order so that a scan
  62966. ** of the table is closer to a linear scan through the file. That in turn
  62967. ** helps the operating system to deliver pages from the disk more rapidly.
  62968. **
  62969. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  62970. ** than (NB+2) (a small constant), that should not be a problem.
  62971. **
  62972. ** When NB==3, this one optimization makes the database about 25% faster
  62973. ** for large insertions and deletions.
  62974. */
  62975. for(i=0; i<nNew; i++){
  62976. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  62977. aPgFlags[i] = apNew[i]->pDbPage->flags;
  62978. for(j=0; j<i; j++){
  62979. if( aPgno[j]==aPgno[i] ){
  62980. /* This branch is taken if the set of sibling pages somehow contains
  62981. ** duplicate entries. This can happen if the database is corrupt.
  62982. ** It would be simpler to detect this as part of the loop below, but
  62983. ** we do the detection here in order to avoid populating the pager
  62984. ** cache with two separate objects associated with the same
  62985. ** page number. */
  62986. assert( CORRUPT_DB );
  62987. rc = SQLITE_CORRUPT_BKPT;
  62988. goto balance_cleanup;
  62989. }
  62990. }
  62991. }
  62992. for(i=0; i<nNew; i++){
  62993. int iBest = 0; /* aPgno[] index of page number to use */
  62994. for(j=1; j<nNew; j++){
  62995. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  62996. }
  62997. pgno = aPgOrder[iBest];
  62998. aPgOrder[iBest] = 0xffffffff;
  62999. if( iBest!=i ){
  63000. if( iBest>i ){
  63001. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  63002. }
  63003. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  63004. apNew[i]->pgno = pgno;
  63005. }
  63006. }
  63007. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  63008. "%d(%d nc=%d) %d(%d nc=%d)\n",
  63009. apNew[0]->pgno, szNew[0], cntNew[0],
  63010. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  63011. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  63012. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  63013. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  63014. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  63015. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  63016. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  63017. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  63018. ));
  63019. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  63020. put4byte(pRight, apNew[nNew-1]->pgno);
  63021. /* If the sibling pages are not leaves, ensure that the right-child pointer
  63022. ** of the right-most new sibling page is set to the value that was
  63023. ** originally in the same field of the right-most old sibling page. */
  63024. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  63025. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  63026. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  63027. }
  63028. /* Make any required updates to pointer map entries associated with
  63029. ** cells stored on sibling pages following the balance operation. Pointer
  63030. ** map entries associated with divider cells are set by the insertCell()
  63031. ** routine. The associated pointer map entries are:
  63032. **
  63033. ** a) if the cell contains a reference to an overflow chain, the
  63034. ** entry associated with the first page in the overflow chain, and
  63035. **
  63036. ** b) if the sibling pages are not leaves, the child page associated
  63037. ** with the cell.
  63038. **
  63039. ** If the sibling pages are not leaves, then the pointer map entry
  63040. ** associated with the right-child of each sibling may also need to be
  63041. ** updated. This happens below, after the sibling pages have been
  63042. ** populated, not here.
  63043. */
  63044. if( ISAUTOVACUUM ){
  63045. MemPage *pNew = apNew[0];
  63046. u8 *aOld = pNew->aData;
  63047. int cntOldNext = pNew->nCell + pNew->nOverflow;
  63048. int usableSize = pBt->usableSize;
  63049. int iNew = 0;
  63050. int iOld = 0;
  63051. for(i=0; i<b.nCell; i++){
  63052. u8 *pCell = b.apCell[i];
  63053. if( i==cntOldNext ){
  63054. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  63055. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  63056. aOld = pOld->aData;
  63057. }
  63058. if( i==cntNew[iNew] ){
  63059. pNew = apNew[++iNew];
  63060. if( !leafData ) continue;
  63061. }
  63062. /* Cell pCell is destined for new sibling page pNew. Originally, it
  63063. ** was either part of sibling page iOld (possibly an overflow cell),
  63064. ** or else the divider cell to the left of sibling page iOld. So,
  63065. ** if sibling page iOld had the same page number as pNew, and if
  63066. ** pCell really was a part of sibling page iOld (not a divider or
  63067. ** overflow cell), we can skip updating the pointer map entries. */
  63068. if( iOld>=nNew
  63069. || pNew->pgno!=aPgno[iOld]
  63070. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  63071. ){
  63072. if( !leafCorrection ){
  63073. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  63074. }
  63075. if( cachedCellSize(&b,i)>pNew->minLocal ){
  63076. ptrmapPutOvflPtr(pNew, pCell, &rc);
  63077. }
  63078. if( rc ) goto balance_cleanup;
  63079. }
  63080. }
  63081. }
  63082. /* Insert new divider cells into pParent. */
  63083. for(i=0; i<nNew-1; i++){
  63084. u8 *pCell;
  63085. u8 *pTemp;
  63086. int sz;
  63087. MemPage *pNew = apNew[i];
  63088. j = cntNew[i];
  63089. assert( j<nMaxCells );
  63090. assert( b.apCell[j]!=0 );
  63091. pCell = b.apCell[j];
  63092. sz = b.szCell[j] + leafCorrection;
  63093. pTemp = &aOvflSpace[iOvflSpace];
  63094. if( !pNew->leaf ){
  63095. memcpy(&pNew->aData[8], pCell, 4);
  63096. }else if( leafData ){
  63097. /* If the tree is a leaf-data tree, and the siblings are leaves,
  63098. ** then there is no divider cell in b.apCell[]. Instead, the divider
  63099. ** cell consists of the integer key for the right-most cell of
  63100. ** the sibling-page assembled above only.
  63101. */
  63102. CellInfo info;
  63103. j--;
  63104. pNew->xParseCell(pNew, b.apCell[j], &info);
  63105. pCell = pTemp;
  63106. sz = 4 + putVarint(&pCell[4], info.nKey);
  63107. pTemp = 0;
  63108. }else{
  63109. pCell -= 4;
  63110. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  63111. ** previously stored on a leaf node, and its reported size was 4
  63112. ** bytes, then it may actually be smaller than this
  63113. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  63114. ** any cell). But it is important to pass the correct size to
  63115. ** insertCell(), so reparse the cell now.
  63116. **
  63117. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  63118. ** and WITHOUT ROWID tables with exactly one column which is the
  63119. ** primary key.
  63120. */
  63121. if( b.szCell[j]==4 ){
  63122. assert(leafCorrection==4);
  63123. sz = pParent->xCellSize(pParent, pCell);
  63124. }
  63125. }
  63126. iOvflSpace += sz;
  63127. assert( sz<=pBt->maxLocal+23 );
  63128. assert( iOvflSpace <= (int)pBt->pageSize );
  63129. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  63130. if( rc!=SQLITE_OK ) goto balance_cleanup;
  63131. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  63132. }
  63133. /* Now update the actual sibling pages. The order in which they are updated
  63134. ** is important, as this code needs to avoid disrupting any page from which
  63135. ** cells may still to be read. In practice, this means:
  63136. **
  63137. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  63138. ** then it is not safe to update page apNew[iPg] until after
  63139. ** the left-hand sibling apNew[iPg-1] has been updated.
  63140. **
  63141. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  63142. ** then it is not safe to update page apNew[iPg] until after
  63143. ** the right-hand sibling apNew[iPg+1] has been updated.
  63144. **
  63145. ** If neither of the above apply, the page is safe to update.
  63146. **
  63147. ** The iPg value in the following loop starts at nNew-1 goes down
  63148. ** to 0, then back up to nNew-1 again, thus making two passes over
  63149. ** the pages. On the initial downward pass, only condition (1) above
  63150. ** needs to be tested because (2) will always be true from the previous
  63151. ** step. On the upward pass, both conditions are always true, so the
  63152. ** upwards pass simply processes pages that were missed on the downward
  63153. ** pass.
  63154. */
  63155. for(i=1-nNew; i<nNew; i++){
  63156. int iPg = i<0 ? -i : i;
  63157. assert( iPg>=0 && iPg<nNew );
  63158. if( abDone[iPg] ) continue; /* Skip pages already processed */
  63159. if( i>=0 /* On the upwards pass, or... */
  63160. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  63161. ){
  63162. int iNew;
  63163. int iOld;
  63164. int nNewCell;
  63165. /* Verify condition (1): If cells are moving left, update iPg
  63166. ** only after iPg-1 has already been updated. */
  63167. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  63168. /* Verify condition (2): If cells are moving right, update iPg
  63169. ** only after iPg+1 has already been updated. */
  63170. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  63171. if( iPg==0 ){
  63172. iNew = iOld = 0;
  63173. nNewCell = cntNew[0];
  63174. }else{
  63175. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  63176. iNew = cntNew[iPg-1] + !leafData;
  63177. nNewCell = cntNew[iPg] - iNew;
  63178. }
  63179. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  63180. if( rc ) goto balance_cleanup;
  63181. abDone[iPg]++;
  63182. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  63183. assert( apNew[iPg]->nOverflow==0 );
  63184. assert( apNew[iPg]->nCell==nNewCell );
  63185. }
  63186. }
  63187. /* All pages have been processed exactly once */
  63188. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  63189. assert( nOld>0 );
  63190. assert( nNew>0 );
  63191. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  63192. /* The root page of the b-tree now contains no cells. The only sibling
  63193. ** page is the right-child of the parent. Copy the contents of the
  63194. ** child page into the parent, decreasing the overall height of the
  63195. ** b-tree structure by one. This is described as the "balance-shallower"
  63196. ** sub-algorithm in some documentation.
  63197. **
  63198. ** If this is an auto-vacuum database, the call to copyNodeContent()
  63199. ** sets all pointer-map entries corresponding to database image pages
  63200. ** for which the pointer is stored within the content being copied.
  63201. **
  63202. ** It is critical that the child page be defragmented before being
  63203. ** copied into the parent, because if the parent is page 1 then it will
  63204. ** by smaller than the child due to the database header, and so all the
  63205. ** free space needs to be up front.
  63206. */
  63207. assert( nNew==1 || CORRUPT_DB );
  63208. rc = defragmentPage(apNew[0], -1);
  63209. testcase( rc!=SQLITE_OK );
  63210. assert( apNew[0]->nFree ==
  63211. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  63212. || rc!=SQLITE_OK
  63213. );
  63214. copyNodeContent(apNew[0], pParent, &rc);
  63215. freePage(apNew[0], &rc);
  63216. }else if( ISAUTOVACUUM && !leafCorrection ){
  63217. /* Fix the pointer map entries associated with the right-child of each
  63218. ** sibling page. All other pointer map entries have already been taken
  63219. ** care of. */
  63220. for(i=0; i<nNew; i++){
  63221. u32 key = get4byte(&apNew[i]->aData[8]);
  63222. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  63223. }
  63224. }
  63225. assert( pParent->isInit );
  63226. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  63227. nOld, nNew, b.nCell));
  63228. /* Free any old pages that were not reused as new pages.
  63229. */
  63230. for(i=nNew; i<nOld; i++){
  63231. freePage(apOld[i], &rc);
  63232. }
  63233. #if 0
  63234. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  63235. /* The ptrmapCheckPages() contains assert() statements that verify that
  63236. ** all pointer map pages are set correctly. This is helpful while
  63237. ** debugging. This is usually disabled because a corrupt database may
  63238. ** cause an assert() statement to fail. */
  63239. ptrmapCheckPages(apNew, nNew);
  63240. ptrmapCheckPages(&pParent, 1);
  63241. }
  63242. #endif
  63243. /*
  63244. ** Cleanup before returning.
  63245. */
  63246. balance_cleanup:
  63247. sqlite3StackFree(0, b.apCell);
  63248. for(i=0; i<nOld; i++){
  63249. releasePage(apOld[i]);
  63250. }
  63251. for(i=0; i<nNew; i++){
  63252. releasePage(apNew[i]);
  63253. }
  63254. return rc;
  63255. }
  63256. /*
  63257. ** This function is called when the root page of a b-tree structure is
  63258. ** overfull (has one or more overflow pages).
  63259. **
  63260. ** A new child page is allocated and the contents of the current root
  63261. ** page, including overflow cells, are copied into the child. The root
  63262. ** page is then overwritten to make it an empty page with the right-child
  63263. ** pointer pointing to the new page.
  63264. **
  63265. ** Before returning, all pointer-map entries corresponding to pages
  63266. ** that the new child-page now contains pointers to are updated. The
  63267. ** entry corresponding to the new right-child pointer of the root
  63268. ** page is also updated.
  63269. **
  63270. ** If successful, *ppChild is set to contain a reference to the child
  63271. ** page and SQLITE_OK is returned. In this case the caller is required
  63272. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  63273. ** an error code is returned and *ppChild is set to 0.
  63274. */
  63275. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  63276. int rc; /* Return value from subprocedures */
  63277. MemPage *pChild = 0; /* Pointer to a new child page */
  63278. Pgno pgnoChild = 0; /* Page number of the new child page */
  63279. BtShared *pBt = pRoot->pBt; /* The BTree */
  63280. assert( pRoot->nOverflow>0 );
  63281. assert( sqlite3_mutex_held(pBt->mutex) );
  63282. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  63283. ** page that will become the new right-child of pPage. Copy the contents
  63284. ** of the node stored on pRoot into the new child page.
  63285. */
  63286. rc = sqlite3PagerWrite(pRoot->pDbPage);
  63287. if( rc==SQLITE_OK ){
  63288. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  63289. copyNodeContent(pRoot, pChild, &rc);
  63290. if( ISAUTOVACUUM ){
  63291. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  63292. }
  63293. }
  63294. if( rc ){
  63295. *ppChild = 0;
  63296. releasePage(pChild);
  63297. return rc;
  63298. }
  63299. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  63300. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  63301. assert( pChild->nCell==pRoot->nCell );
  63302. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  63303. /* Copy the overflow cells from pRoot to pChild */
  63304. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  63305. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  63306. memcpy(pChild->apOvfl, pRoot->apOvfl,
  63307. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  63308. pChild->nOverflow = pRoot->nOverflow;
  63309. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  63310. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  63311. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  63312. *ppChild = pChild;
  63313. return SQLITE_OK;
  63314. }
  63315. /*
  63316. ** The page that pCur currently points to has just been modified in
  63317. ** some way. This function figures out if this modification means the
  63318. ** tree needs to be balanced, and if so calls the appropriate balancing
  63319. ** routine. Balancing routines are:
  63320. **
  63321. ** balance_quick()
  63322. ** balance_deeper()
  63323. ** balance_nonroot()
  63324. */
  63325. static int balance(BtCursor *pCur){
  63326. int rc = SQLITE_OK;
  63327. const int nMin = pCur->pBt->usableSize * 2 / 3;
  63328. u8 aBalanceQuickSpace[13];
  63329. u8 *pFree = 0;
  63330. VVA_ONLY( int balance_quick_called = 0 );
  63331. VVA_ONLY( int balance_deeper_called = 0 );
  63332. do {
  63333. int iPage = pCur->iPage;
  63334. MemPage *pPage = pCur->pPage;
  63335. if( iPage==0 ){
  63336. if( pPage->nOverflow ){
  63337. /* The root page of the b-tree is overfull. In this case call the
  63338. ** balance_deeper() function to create a new child for the root-page
  63339. ** and copy the current contents of the root-page to it. The
  63340. ** next iteration of the do-loop will balance the child page.
  63341. */
  63342. assert( balance_deeper_called==0 );
  63343. VVA_ONLY( balance_deeper_called++ );
  63344. rc = balance_deeper(pPage, &pCur->apPage[1]);
  63345. if( rc==SQLITE_OK ){
  63346. pCur->iPage = 1;
  63347. pCur->ix = 0;
  63348. pCur->aiIdx[0] = 0;
  63349. pCur->apPage[0] = pPage;
  63350. pCur->pPage = pCur->apPage[1];
  63351. assert( pCur->pPage->nOverflow );
  63352. }
  63353. }else{
  63354. break;
  63355. }
  63356. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  63357. break;
  63358. }else{
  63359. MemPage * const pParent = pCur->apPage[iPage-1];
  63360. int const iIdx = pCur->aiIdx[iPage-1];
  63361. rc = sqlite3PagerWrite(pParent->pDbPage);
  63362. if( rc==SQLITE_OK ){
  63363. #ifndef SQLITE_OMIT_QUICKBALANCE
  63364. if( pPage->intKeyLeaf
  63365. && pPage->nOverflow==1
  63366. && pPage->aiOvfl[0]==pPage->nCell
  63367. && pParent->pgno!=1
  63368. && pParent->nCell==iIdx
  63369. ){
  63370. /* Call balance_quick() to create a new sibling of pPage on which
  63371. ** to store the overflow cell. balance_quick() inserts a new cell
  63372. ** into pParent, which may cause pParent overflow. If this
  63373. ** happens, the next iteration of the do-loop will balance pParent
  63374. ** use either balance_nonroot() or balance_deeper(). Until this
  63375. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  63376. ** buffer.
  63377. **
  63378. ** The purpose of the following assert() is to check that only a
  63379. ** single call to balance_quick() is made for each call to this
  63380. ** function. If this were not verified, a subtle bug involving reuse
  63381. ** of the aBalanceQuickSpace[] might sneak in.
  63382. */
  63383. assert( balance_quick_called==0 );
  63384. VVA_ONLY( balance_quick_called++ );
  63385. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  63386. }else
  63387. #endif
  63388. {
  63389. /* In this case, call balance_nonroot() to redistribute cells
  63390. ** between pPage and up to 2 of its sibling pages. This involves
  63391. ** modifying the contents of pParent, which may cause pParent to
  63392. ** become overfull or underfull. The next iteration of the do-loop
  63393. ** will balance the parent page to correct this.
  63394. **
  63395. ** If the parent page becomes overfull, the overflow cell or cells
  63396. ** are stored in the pSpace buffer allocated immediately below.
  63397. ** A subsequent iteration of the do-loop will deal with this by
  63398. ** calling balance_nonroot() (balance_deeper() may be called first,
  63399. ** but it doesn't deal with overflow cells - just moves them to a
  63400. ** different page). Once this subsequent call to balance_nonroot()
  63401. ** has completed, it is safe to release the pSpace buffer used by
  63402. ** the previous call, as the overflow cell data will have been
  63403. ** copied either into the body of a database page or into the new
  63404. ** pSpace buffer passed to the latter call to balance_nonroot().
  63405. */
  63406. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  63407. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  63408. pCur->hints&BTREE_BULKLOAD);
  63409. if( pFree ){
  63410. /* If pFree is not NULL, it points to the pSpace buffer used
  63411. ** by a previous call to balance_nonroot(). Its contents are
  63412. ** now stored either on real database pages or within the
  63413. ** new pSpace buffer, so it may be safely freed here. */
  63414. sqlite3PageFree(pFree);
  63415. }
  63416. /* The pSpace buffer will be freed after the next call to
  63417. ** balance_nonroot(), or just before this function returns, whichever
  63418. ** comes first. */
  63419. pFree = pSpace;
  63420. }
  63421. }
  63422. pPage->nOverflow = 0;
  63423. /* The next iteration of the do-loop balances the parent page. */
  63424. releasePage(pPage);
  63425. pCur->iPage--;
  63426. assert( pCur->iPage>=0 );
  63427. pCur->pPage = pCur->apPage[pCur->iPage];
  63428. }
  63429. }while( rc==SQLITE_OK );
  63430. if( pFree ){
  63431. sqlite3PageFree(pFree);
  63432. }
  63433. return rc;
  63434. }
  63435. /*
  63436. ** Insert a new record into the BTree. The content of the new record
  63437. ** is described by the pX object. The pCur cursor is used only to
  63438. ** define what table the record should be inserted into, and is left
  63439. ** pointing at a random location.
  63440. **
  63441. ** For a table btree (used for rowid tables), only the pX.nKey value of
  63442. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  63443. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  63444. ** hold the content of the row.
  63445. **
  63446. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  63447. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  63448. ** pX.pData,nData,nZero fields must be zero.
  63449. **
  63450. ** If the seekResult parameter is non-zero, then a successful call to
  63451. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  63452. ** been performed. In other words, if seekResult!=0 then the cursor
  63453. ** is currently pointing to a cell that will be adjacent to the cell
  63454. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  63455. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  63456. ** that is larger than (pKey,nKey).
  63457. **
  63458. ** If seekResult==0, that means pCur is pointing at some unknown location.
  63459. ** In that case, this routine must seek the cursor to the correct insertion
  63460. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  63461. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  63462. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  63463. ** to decode the key.
  63464. */
  63465. SQLITE_PRIVATE int sqlite3BtreeInsert(
  63466. BtCursor *pCur, /* Insert data into the table of this cursor */
  63467. const BtreePayload *pX, /* Content of the row to be inserted */
  63468. int flags, /* True if this is likely an append */
  63469. int seekResult /* Result of prior MovetoUnpacked() call */
  63470. ){
  63471. int rc;
  63472. int loc = seekResult; /* -1: before desired location +1: after */
  63473. int szNew = 0;
  63474. int idx;
  63475. MemPage *pPage;
  63476. Btree *p = pCur->pBtree;
  63477. BtShared *pBt = p->pBt;
  63478. unsigned char *oldCell;
  63479. unsigned char *newCell = 0;
  63480. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  63481. if( pCur->eState==CURSOR_FAULT ){
  63482. assert( pCur->skipNext!=SQLITE_OK );
  63483. return pCur->skipNext;
  63484. }
  63485. assert( cursorOwnsBtShared(pCur) );
  63486. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  63487. && pBt->inTransaction==TRANS_WRITE
  63488. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63489. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  63490. /* Assert that the caller has been consistent. If this cursor was opened
  63491. ** expecting an index b-tree, then the caller should be inserting blob
  63492. ** keys with no associated data. If the cursor was opened expecting an
  63493. ** intkey table, the caller should be inserting integer keys with a
  63494. ** blob of associated data. */
  63495. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  63496. /* Save the positions of any other cursors open on this table.
  63497. **
  63498. ** In some cases, the call to btreeMoveto() below is a no-op. For
  63499. ** example, when inserting data into a table with auto-generated integer
  63500. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  63501. ** integer key to use. It then calls this function to actually insert the
  63502. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  63503. ** that the cursor is already where it needs to be and returns without
  63504. ** doing any work. To avoid thwarting these optimizations, it is important
  63505. ** not to clear the cursor here.
  63506. */
  63507. if( pCur->curFlags & BTCF_Multiple ){
  63508. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  63509. if( rc ) return rc;
  63510. }
  63511. if( pCur->pKeyInfo==0 ){
  63512. assert( pX->pKey==0 );
  63513. /* If this is an insert into a table b-tree, invalidate any incrblob
  63514. ** cursors open on the row being replaced */
  63515. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  63516. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  63517. ** to a row with the same key as the new entry being inserted. */
  63518. assert( (flags & BTREE_SAVEPOSITION)==0 ||
  63519. ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
  63520. /* If the cursor is currently on the last row and we are appending a
  63521. ** new row onto the end, set the "loc" to avoid an unnecessary
  63522. ** btreeMoveto() call */
  63523. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  63524. loc = 0;
  63525. }else if( loc==0 ){
  63526. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  63527. if( rc ) return rc;
  63528. }
  63529. }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  63530. if( pX->nMem ){
  63531. UnpackedRecord r;
  63532. r.pKeyInfo = pCur->pKeyInfo;
  63533. r.aMem = pX->aMem;
  63534. r.nField = pX->nMem;
  63535. r.default_rc = 0;
  63536. r.errCode = 0;
  63537. r.r1 = 0;
  63538. r.r2 = 0;
  63539. r.eqSeen = 0;
  63540. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  63541. }else{
  63542. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  63543. }
  63544. if( rc ) return rc;
  63545. }
  63546. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  63547. pPage = pCur->pPage;
  63548. assert( pPage->intKey || pX->nKey>=0 );
  63549. assert( pPage->leaf || !pPage->intKey );
  63550. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  63551. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  63552. loc==0 ? "overwrite" : "new entry"));
  63553. assert( pPage->isInit );
  63554. newCell = pBt->pTmpSpace;
  63555. assert( newCell!=0 );
  63556. rc = fillInCell(pPage, newCell, pX, &szNew);
  63557. if( rc ) goto end_insert;
  63558. assert( szNew==pPage->xCellSize(pPage, newCell) );
  63559. assert( szNew <= MX_CELL_SIZE(pBt) );
  63560. idx = pCur->ix;
  63561. if( loc==0 ){
  63562. CellInfo info;
  63563. assert( idx<pPage->nCell );
  63564. rc = sqlite3PagerWrite(pPage->pDbPage);
  63565. if( rc ){
  63566. goto end_insert;
  63567. }
  63568. oldCell = findCell(pPage, idx);
  63569. if( !pPage->leaf ){
  63570. memcpy(newCell, oldCell, 4);
  63571. }
  63572. rc = clearCell(pPage, oldCell, &info);
  63573. if( info.nSize==szNew && info.nLocal==info.nPayload
  63574. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  63575. ){
  63576. /* Overwrite the old cell with the new if they are the same size.
  63577. ** We could also try to do this if the old cell is smaller, then add
  63578. ** the leftover space to the free list. But experiments show that
  63579. ** doing that is no faster then skipping this optimization and just
  63580. ** calling dropCell() and insertCell().
  63581. **
  63582. ** This optimization cannot be used on an autovacuum database if the
  63583. ** new entry uses overflow pages, as the insertCell() call below is
  63584. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  63585. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  63586. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  63587. memcpy(oldCell, newCell, szNew);
  63588. return SQLITE_OK;
  63589. }
  63590. dropCell(pPage, idx, info.nSize, &rc);
  63591. if( rc ) goto end_insert;
  63592. }else if( loc<0 && pPage->nCell>0 ){
  63593. assert( pPage->leaf );
  63594. idx = ++pCur->ix;
  63595. pCur->curFlags &= ~BTCF_ValidNKey;
  63596. }else{
  63597. assert( pPage->leaf );
  63598. }
  63599. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  63600. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  63601. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  63602. /* If no error has occurred and pPage has an overflow cell, call balance()
  63603. ** to redistribute the cells within the tree. Since balance() may move
  63604. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  63605. ** variables.
  63606. **
  63607. ** Previous versions of SQLite called moveToRoot() to move the cursor
  63608. ** back to the root page as balance() used to invalidate the contents
  63609. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  63610. ** set the cursor state to "invalid". This makes common insert operations
  63611. ** slightly faster.
  63612. **
  63613. ** There is a subtle but important optimization here too. When inserting
  63614. ** multiple records into an intkey b-tree using a single cursor (as can
  63615. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  63616. ** is advantageous to leave the cursor pointing to the last entry in
  63617. ** the b-tree if possible. If the cursor is left pointing to the last
  63618. ** entry in the table, and the next row inserted has an integer key
  63619. ** larger than the largest existing key, it is possible to insert the
  63620. ** row without seeking the cursor. This can be a big performance boost.
  63621. */
  63622. pCur->info.nSize = 0;
  63623. if( pPage->nOverflow ){
  63624. assert( rc==SQLITE_OK );
  63625. pCur->curFlags &= ~(BTCF_ValidNKey);
  63626. rc = balance(pCur);
  63627. /* Must make sure nOverflow is reset to zero even if the balance()
  63628. ** fails. Internal data structure corruption will result otherwise.
  63629. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  63630. ** from trying to save the current position of the cursor. */
  63631. pCur->pPage->nOverflow = 0;
  63632. pCur->eState = CURSOR_INVALID;
  63633. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  63634. btreeReleaseAllCursorPages(pCur);
  63635. if( pCur->pKeyInfo ){
  63636. assert( pCur->pKey==0 );
  63637. pCur->pKey = sqlite3Malloc( pX->nKey );
  63638. if( pCur->pKey==0 ){
  63639. rc = SQLITE_NOMEM;
  63640. }else{
  63641. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  63642. }
  63643. }
  63644. pCur->eState = CURSOR_REQUIRESEEK;
  63645. pCur->nKey = pX->nKey;
  63646. }
  63647. }
  63648. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  63649. end_insert:
  63650. return rc;
  63651. }
  63652. /*
  63653. ** Delete the entry that the cursor is pointing to.
  63654. **
  63655. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  63656. ** the cursor is left pointing at an arbitrary location after the delete.
  63657. ** But if that bit is set, then the cursor is left in a state such that
  63658. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  63659. ** as it would have been on if the call to BtreeDelete() had been omitted.
  63660. **
  63661. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  63662. ** associated with a single table entry and its indexes. Only one of those
  63663. ** deletes is considered the "primary" delete. The primary delete occurs
  63664. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  63665. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  63666. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  63667. ** but which might be used by alternative storage engines.
  63668. */
  63669. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  63670. Btree *p = pCur->pBtree;
  63671. BtShared *pBt = p->pBt;
  63672. int rc; /* Return code */
  63673. MemPage *pPage; /* Page to delete cell from */
  63674. unsigned char *pCell; /* Pointer to cell to delete */
  63675. int iCellIdx; /* Index of cell to delete */
  63676. int iCellDepth; /* Depth of node containing pCell */
  63677. CellInfo info; /* Size of the cell being deleted */
  63678. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  63679. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  63680. assert( cursorOwnsBtShared(pCur) );
  63681. assert( pBt->inTransaction==TRANS_WRITE );
  63682. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63683. assert( pCur->curFlags & BTCF_WriteFlag );
  63684. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  63685. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  63686. assert( pCur->ix<pCur->pPage->nCell );
  63687. assert( pCur->eState==CURSOR_VALID );
  63688. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  63689. iCellDepth = pCur->iPage;
  63690. iCellIdx = pCur->ix;
  63691. pPage = pCur->pPage;
  63692. pCell = findCell(pPage, iCellIdx);
  63693. /* If the bPreserve flag is set to true, then the cursor position must
  63694. ** be preserved following this delete operation. If the current delete
  63695. ** will cause a b-tree rebalance, then this is done by saving the cursor
  63696. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  63697. ** returning.
  63698. **
  63699. ** Or, if the current delete will not cause a rebalance, then the cursor
  63700. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  63701. ** before or after the deleted entry. In this case set bSkipnext to true. */
  63702. if( bPreserve ){
  63703. if( !pPage->leaf
  63704. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  63705. ){
  63706. /* A b-tree rebalance will be required after deleting this entry.
  63707. ** Save the cursor key. */
  63708. rc = saveCursorKey(pCur);
  63709. if( rc ) return rc;
  63710. }else{
  63711. bSkipnext = 1;
  63712. }
  63713. }
  63714. /* If the page containing the entry to delete is not a leaf page, move
  63715. ** the cursor to the largest entry in the tree that is smaller than
  63716. ** the entry being deleted. This cell will replace the cell being deleted
  63717. ** from the internal node. The 'previous' entry is used for this instead
  63718. ** of the 'next' entry, as the previous entry is always a part of the
  63719. ** sub-tree headed by the child page of the cell being deleted. This makes
  63720. ** balancing the tree following the delete operation easier. */
  63721. if( !pPage->leaf ){
  63722. rc = sqlite3BtreePrevious(pCur, 0);
  63723. assert( rc!=SQLITE_DONE );
  63724. if( rc ) return rc;
  63725. }
  63726. /* Save the positions of any other cursors open on this table before
  63727. ** making any modifications. */
  63728. if( pCur->curFlags & BTCF_Multiple ){
  63729. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  63730. if( rc ) return rc;
  63731. }
  63732. /* If this is a delete operation to remove a row from a table b-tree,
  63733. ** invalidate any incrblob cursors open on the row being deleted. */
  63734. if( pCur->pKeyInfo==0 ){
  63735. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  63736. }
  63737. /* Make the page containing the entry to be deleted writable. Then free any
  63738. ** overflow pages associated with the entry and finally remove the cell
  63739. ** itself from within the page. */
  63740. rc = sqlite3PagerWrite(pPage->pDbPage);
  63741. if( rc ) return rc;
  63742. rc = clearCell(pPage, pCell, &info);
  63743. dropCell(pPage, iCellIdx, info.nSize, &rc);
  63744. if( rc ) return rc;
  63745. /* If the cell deleted was not located on a leaf page, then the cursor
  63746. ** is currently pointing to the largest entry in the sub-tree headed
  63747. ** by the child-page of the cell that was just deleted from an internal
  63748. ** node. The cell from the leaf node needs to be moved to the internal
  63749. ** node to replace the deleted cell. */
  63750. if( !pPage->leaf ){
  63751. MemPage *pLeaf = pCur->pPage;
  63752. int nCell;
  63753. Pgno n;
  63754. unsigned char *pTmp;
  63755. if( iCellDepth<pCur->iPage-1 ){
  63756. n = pCur->apPage[iCellDepth+1]->pgno;
  63757. }else{
  63758. n = pCur->pPage->pgno;
  63759. }
  63760. pCell = findCell(pLeaf, pLeaf->nCell-1);
  63761. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  63762. nCell = pLeaf->xCellSize(pLeaf, pCell);
  63763. assert( MX_CELL_SIZE(pBt) >= nCell );
  63764. pTmp = pBt->pTmpSpace;
  63765. assert( pTmp!=0 );
  63766. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  63767. if( rc==SQLITE_OK ){
  63768. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  63769. }
  63770. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  63771. if( rc ) return rc;
  63772. }
  63773. /* Balance the tree. If the entry deleted was located on a leaf page,
  63774. ** then the cursor still points to that page. In this case the first
  63775. ** call to balance() repairs the tree, and the if(...) condition is
  63776. ** never true.
  63777. **
  63778. ** Otherwise, if the entry deleted was on an internal node page, then
  63779. ** pCur is pointing to the leaf page from which a cell was removed to
  63780. ** replace the cell deleted from the internal node. This is slightly
  63781. ** tricky as the leaf node may be underfull, and the internal node may
  63782. ** be either under or overfull. In this case run the balancing algorithm
  63783. ** on the leaf node first. If the balance proceeds far enough up the
  63784. ** tree that we can be sure that any problem in the internal node has
  63785. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  63786. ** walk the cursor up the tree to the internal node and balance it as
  63787. ** well. */
  63788. rc = balance(pCur);
  63789. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  63790. releasePageNotNull(pCur->pPage);
  63791. pCur->iPage--;
  63792. while( pCur->iPage>iCellDepth ){
  63793. releasePage(pCur->apPage[pCur->iPage--]);
  63794. }
  63795. pCur->pPage = pCur->apPage[pCur->iPage];
  63796. rc = balance(pCur);
  63797. }
  63798. if( rc==SQLITE_OK ){
  63799. if( bSkipnext ){
  63800. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  63801. assert( pPage==pCur->pPage || CORRUPT_DB );
  63802. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  63803. pCur->eState = CURSOR_SKIPNEXT;
  63804. if( iCellIdx>=pPage->nCell ){
  63805. pCur->skipNext = -1;
  63806. pCur->ix = pPage->nCell-1;
  63807. }else{
  63808. pCur->skipNext = 1;
  63809. }
  63810. }else{
  63811. rc = moveToRoot(pCur);
  63812. if( bPreserve ){
  63813. btreeReleaseAllCursorPages(pCur);
  63814. pCur->eState = CURSOR_REQUIRESEEK;
  63815. }
  63816. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  63817. }
  63818. }
  63819. return rc;
  63820. }
  63821. /*
  63822. ** Create a new BTree table. Write into *piTable the page
  63823. ** number for the root page of the new table.
  63824. **
  63825. ** The type of type is determined by the flags parameter. Only the
  63826. ** following values of flags are currently in use. Other values for
  63827. ** flags might not work:
  63828. **
  63829. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  63830. ** BTREE_ZERODATA Used for SQL indices
  63831. */
  63832. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  63833. BtShared *pBt = p->pBt;
  63834. MemPage *pRoot;
  63835. Pgno pgnoRoot;
  63836. int rc;
  63837. int ptfFlags; /* Page-type flage for the root page of new table */
  63838. assert( sqlite3BtreeHoldsMutex(p) );
  63839. assert( pBt->inTransaction==TRANS_WRITE );
  63840. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63841. #ifdef SQLITE_OMIT_AUTOVACUUM
  63842. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63843. if( rc ){
  63844. return rc;
  63845. }
  63846. #else
  63847. if( pBt->autoVacuum ){
  63848. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  63849. MemPage *pPageMove; /* The page to move to. */
  63850. /* Creating a new table may probably require moving an existing database
  63851. ** to make room for the new tables root page. In case this page turns
  63852. ** out to be an overflow page, delete all overflow page-map caches
  63853. ** held by open cursors.
  63854. */
  63855. invalidateAllOverflowCache(pBt);
  63856. /* Read the value of meta[3] from the database to determine where the
  63857. ** root page of the new table should go. meta[3] is the largest root-page
  63858. ** created so far, so the new root-page is (meta[3]+1).
  63859. */
  63860. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  63861. pgnoRoot++;
  63862. /* The new root-page may not be allocated on a pointer-map page, or the
  63863. ** PENDING_BYTE page.
  63864. */
  63865. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  63866. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  63867. pgnoRoot++;
  63868. }
  63869. assert( pgnoRoot>=3 || CORRUPT_DB );
  63870. testcase( pgnoRoot<3 );
  63871. /* Allocate a page. The page that currently resides at pgnoRoot will
  63872. ** be moved to the allocated page (unless the allocated page happens
  63873. ** to reside at pgnoRoot).
  63874. */
  63875. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  63876. if( rc!=SQLITE_OK ){
  63877. return rc;
  63878. }
  63879. if( pgnoMove!=pgnoRoot ){
  63880. /* pgnoRoot is the page that will be used for the root-page of
  63881. ** the new table (assuming an error did not occur). But we were
  63882. ** allocated pgnoMove. If required (i.e. if it was not allocated
  63883. ** by extending the file), the current page at position pgnoMove
  63884. ** is already journaled.
  63885. */
  63886. u8 eType = 0;
  63887. Pgno iPtrPage = 0;
  63888. /* Save the positions of any open cursors. This is required in
  63889. ** case they are holding a reference to an xFetch reference
  63890. ** corresponding to page pgnoRoot. */
  63891. rc = saveAllCursors(pBt, 0, 0);
  63892. releasePage(pPageMove);
  63893. if( rc!=SQLITE_OK ){
  63894. return rc;
  63895. }
  63896. /* Move the page currently at pgnoRoot to pgnoMove. */
  63897. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63898. if( rc!=SQLITE_OK ){
  63899. return rc;
  63900. }
  63901. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  63902. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  63903. rc = SQLITE_CORRUPT_BKPT;
  63904. }
  63905. if( rc!=SQLITE_OK ){
  63906. releasePage(pRoot);
  63907. return rc;
  63908. }
  63909. assert( eType!=PTRMAP_ROOTPAGE );
  63910. assert( eType!=PTRMAP_FREEPAGE );
  63911. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  63912. releasePage(pRoot);
  63913. /* Obtain the page at pgnoRoot */
  63914. if( rc!=SQLITE_OK ){
  63915. return rc;
  63916. }
  63917. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63918. if( rc!=SQLITE_OK ){
  63919. return rc;
  63920. }
  63921. rc = sqlite3PagerWrite(pRoot->pDbPage);
  63922. if( rc!=SQLITE_OK ){
  63923. releasePage(pRoot);
  63924. return rc;
  63925. }
  63926. }else{
  63927. pRoot = pPageMove;
  63928. }
  63929. /* Update the pointer-map and meta-data with the new root-page number. */
  63930. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  63931. if( rc ){
  63932. releasePage(pRoot);
  63933. return rc;
  63934. }
  63935. /* When the new root page was allocated, page 1 was made writable in
  63936. ** order either to increase the database filesize, or to decrement the
  63937. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  63938. */
  63939. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  63940. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  63941. if( NEVER(rc) ){
  63942. releasePage(pRoot);
  63943. return rc;
  63944. }
  63945. }else{
  63946. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63947. if( rc ) return rc;
  63948. }
  63949. #endif
  63950. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  63951. if( createTabFlags & BTREE_INTKEY ){
  63952. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  63953. }else{
  63954. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  63955. }
  63956. zeroPage(pRoot, ptfFlags);
  63957. sqlite3PagerUnref(pRoot->pDbPage);
  63958. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  63959. *piTable = (int)pgnoRoot;
  63960. return SQLITE_OK;
  63961. }
  63962. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  63963. int rc;
  63964. sqlite3BtreeEnter(p);
  63965. rc = btreeCreateTable(p, piTable, flags);
  63966. sqlite3BtreeLeave(p);
  63967. return rc;
  63968. }
  63969. /*
  63970. ** Erase the given database page and all its children. Return
  63971. ** the page to the freelist.
  63972. */
  63973. static int clearDatabasePage(
  63974. BtShared *pBt, /* The BTree that contains the table */
  63975. Pgno pgno, /* Page number to clear */
  63976. int freePageFlag, /* Deallocate page if true */
  63977. int *pnChange /* Add number of Cells freed to this counter */
  63978. ){
  63979. MemPage *pPage;
  63980. int rc;
  63981. unsigned char *pCell;
  63982. int i;
  63983. int hdr;
  63984. CellInfo info;
  63985. assert( sqlite3_mutex_held(pBt->mutex) );
  63986. if( pgno>btreePagecount(pBt) ){
  63987. return SQLITE_CORRUPT_BKPT;
  63988. }
  63989. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  63990. if( rc ) return rc;
  63991. if( pPage->bBusy ){
  63992. rc = SQLITE_CORRUPT_BKPT;
  63993. goto cleardatabasepage_out;
  63994. }
  63995. pPage->bBusy = 1;
  63996. hdr = pPage->hdrOffset;
  63997. for(i=0; i<pPage->nCell; i++){
  63998. pCell = findCell(pPage, i);
  63999. if( !pPage->leaf ){
  64000. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  64001. if( rc ) goto cleardatabasepage_out;
  64002. }
  64003. rc = clearCell(pPage, pCell, &info);
  64004. if( rc ) goto cleardatabasepage_out;
  64005. }
  64006. if( !pPage->leaf ){
  64007. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  64008. if( rc ) goto cleardatabasepage_out;
  64009. }else if( pnChange ){
  64010. assert( pPage->intKey || CORRUPT_DB );
  64011. testcase( !pPage->intKey );
  64012. *pnChange += pPage->nCell;
  64013. }
  64014. if( freePageFlag ){
  64015. freePage(pPage, &rc);
  64016. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  64017. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  64018. }
  64019. cleardatabasepage_out:
  64020. pPage->bBusy = 0;
  64021. releasePage(pPage);
  64022. return rc;
  64023. }
  64024. /*
  64025. ** Delete all information from a single table in the database. iTable is
  64026. ** the page number of the root of the table. After this routine returns,
  64027. ** the root page is empty, but still exists.
  64028. **
  64029. ** This routine will fail with SQLITE_LOCKED if there are any open
  64030. ** read cursors on the table. Open write cursors are moved to the
  64031. ** root of the table.
  64032. **
  64033. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  64034. ** integer value pointed to by pnChange is incremented by the number of
  64035. ** entries in the table.
  64036. */
  64037. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  64038. int rc;
  64039. BtShared *pBt = p->pBt;
  64040. sqlite3BtreeEnter(p);
  64041. assert( p->inTrans==TRANS_WRITE );
  64042. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  64043. if( SQLITE_OK==rc ){
  64044. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  64045. ** is the root of a table b-tree - if it is not, the following call is
  64046. ** a no-op). */
  64047. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  64048. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  64049. }
  64050. sqlite3BtreeLeave(p);
  64051. return rc;
  64052. }
  64053. /*
  64054. ** Delete all information from the single table that pCur is open on.
  64055. **
  64056. ** This routine only work for pCur on an ephemeral table.
  64057. */
  64058. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  64059. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  64060. }
  64061. /*
  64062. ** Erase all information in a table and add the root of the table to
  64063. ** the freelist. Except, the root of the principle table (the one on
  64064. ** page 1) is never added to the freelist.
  64065. **
  64066. ** This routine will fail with SQLITE_LOCKED if there are any open
  64067. ** cursors on the table.
  64068. **
  64069. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  64070. ** root page in the database file, then the last root page
  64071. ** in the database file is moved into the slot formerly occupied by
  64072. ** iTable and that last slot formerly occupied by the last root page
  64073. ** is added to the freelist instead of iTable. In this say, all
  64074. ** root pages are kept at the beginning of the database file, which
  64075. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  64076. ** page number that used to be the last root page in the file before
  64077. ** the move. If no page gets moved, *piMoved is set to 0.
  64078. ** The last root page is recorded in meta[3] and the value of
  64079. ** meta[3] is updated by this procedure.
  64080. */
  64081. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  64082. int rc;
  64083. MemPage *pPage = 0;
  64084. BtShared *pBt = p->pBt;
  64085. assert( sqlite3BtreeHoldsMutex(p) );
  64086. assert( p->inTrans==TRANS_WRITE );
  64087. assert( iTable>=2 );
  64088. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  64089. if( rc ) return rc;
  64090. rc = sqlite3BtreeClearTable(p, iTable, 0);
  64091. if( rc ){
  64092. releasePage(pPage);
  64093. return rc;
  64094. }
  64095. *piMoved = 0;
  64096. #ifdef SQLITE_OMIT_AUTOVACUUM
  64097. freePage(pPage, &rc);
  64098. releasePage(pPage);
  64099. #else
  64100. if( pBt->autoVacuum ){
  64101. Pgno maxRootPgno;
  64102. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  64103. if( iTable==maxRootPgno ){
  64104. /* If the table being dropped is the table with the largest root-page
  64105. ** number in the database, put the root page on the free list.
  64106. */
  64107. freePage(pPage, &rc);
  64108. releasePage(pPage);
  64109. if( rc!=SQLITE_OK ){
  64110. return rc;
  64111. }
  64112. }else{
  64113. /* The table being dropped does not have the largest root-page
  64114. ** number in the database. So move the page that does into the
  64115. ** gap left by the deleted root-page.
  64116. */
  64117. MemPage *pMove;
  64118. releasePage(pPage);
  64119. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  64120. if( rc!=SQLITE_OK ){
  64121. return rc;
  64122. }
  64123. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  64124. releasePage(pMove);
  64125. if( rc!=SQLITE_OK ){
  64126. return rc;
  64127. }
  64128. pMove = 0;
  64129. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  64130. freePage(pMove, &rc);
  64131. releasePage(pMove);
  64132. if( rc!=SQLITE_OK ){
  64133. return rc;
  64134. }
  64135. *piMoved = maxRootPgno;
  64136. }
  64137. /* Set the new 'max-root-page' value in the database header. This
  64138. ** is the old value less one, less one more if that happens to
  64139. ** be a root-page number, less one again if that is the
  64140. ** PENDING_BYTE_PAGE.
  64141. */
  64142. maxRootPgno--;
  64143. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  64144. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  64145. maxRootPgno--;
  64146. }
  64147. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  64148. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  64149. }else{
  64150. freePage(pPage, &rc);
  64151. releasePage(pPage);
  64152. }
  64153. #endif
  64154. return rc;
  64155. }
  64156. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  64157. int rc;
  64158. sqlite3BtreeEnter(p);
  64159. rc = btreeDropTable(p, iTable, piMoved);
  64160. sqlite3BtreeLeave(p);
  64161. return rc;
  64162. }
  64163. /*
  64164. ** This function may only be called if the b-tree connection already
  64165. ** has a read or write transaction open on the database.
  64166. **
  64167. ** Read the meta-information out of a database file. Meta[0]
  64168. ** is the number of free pages currently in the database. Meta[1]
  64169. ** through meta[15] are available for use by higher layers. Meta[0]
  64170. ** is read-only, the others are read/write.
  64171. **
  64172. ** The schema layer numbers meta values differently. At the schema
  64173. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  64174. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  64175. **
  64176. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  64177. ** of reading the value out of the header, it instead loads the "DataVersion"
  64178. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  64179. ** database file. It is a number computed by the pager. But its access
  64180. ** pattern is the same as header meta values, and so it is convenient to
  64181. ** read it from this routine.
  64182. */
  64183. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  64184. BtShared *pBt = p->pBt;
  64185. sqlite3BtreeEnter(p);
  64186. assert( p->inTrans>TRANS_NONE );
  64187. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  64188. assert( pBt->pPage1 );
  64189. assert( idx>=0 && idx<=15 );
  64190. if( idx==BTREE_DATA_VERSION ){
  64191. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  64192. }else{
  64193. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  64194. }
  64195. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  64196. ** database, mark the database as read-only. */
  64197. #ifdef SQLITE_OMIT_AUTOVACUUM
  64198. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  64199. pBt->btsFlags |= BTS_READ_ONLY;
  64200. }
  64201. #endif
  64202. sqlite3BtreeLeave(p);
  64203. }
  64204. /*
  64205. ** Write meta-information back into the database. Meta[0] is
  64206. ** read-only and may not be written.
  64207. */
  64208. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  64209. BtShared *pBt = p->pBt;
  64210. unsigned char *pP1;
  64211. int rc;
  64212. assert( idx>=1 && idx<=15 );
  64213. sqlite3BtreeEnter(p);
  64214. assert( p->inTrans==TRANS_WRITE );
  64215. assert( pBt->pPage1!=0 );
  64216. pP1 = pBt->pPage1->aData;
  64217. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64218. if( rc==SQLITE_OK ){
  64219. put4byte(&pP1[36 + idx*4], iMeta);
  64220. #ifndef SQLITE_OMIT_AUTOVACUUM
  64221. if( idx==BTREE_INCR_VACUUM ){
  64222. assert( pBt->autoVacuum || iMeta==0 );
  64223. assert( iMeta==0 || iMeta==1 );
  64224. pBt->incrVacuum = (u8)iMeta;
  64225. }
  64226. #endif
  64227. }
  64228. sqlite3BtreeLeave(p);
  64229. return rc;
  64230. }
  64231. #ifndef SQLITE_OMIT_BTREECOUNT
  64232. /*
  64233. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  64234. ** number of entries in the b-tree and write the result to *pnEntry.
  64235. **
  64236. ** SQLITE_OK is returned if the operation is successfully executed.
  64237. ** Otherwise, if an error is encountered (i.e. an IO error or database
  64238. ** corruption) an SQLite error code is returned.
  64239. */
  64240. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  64241. i64 nEntry = 0; /* Value to return in *pnEntry */
  64242. int rc; /* Return code */
  64243. rc = moveToRoot(pCur);
  64244. if( rc==SQLITE_EMPTY ){
  64245. *pnEntry = 0;
  64246. return SQLITE_OK;
  64247. }
  64248. /* Unless an error occurs, the following loop runs one iteration for each
  64249. ** page in the B-Tree structure (not including overflow pages).
  64250. */
  64251. while( rc==SQLITE_OK ){
  64252. int iIdx; /* Index of child node in parent */
  64253. MemPage *pPage; /* Current page of the b-tree */
  64254. /* If this is a leaf page or the tree is not an int-key tree, then
  64255. ** this page contains countable entries. Increment the entry counter
  64256. ** accordingly.
  64257. */
  64258. pPage = pCur->pPage;
  64259. if( pPage->leaf || !pPage->intKey ){
  64260. nEntry += pPage->nCell;
  64261. }
  64262. /* pPage is a leaf node. This loop navigates the cursor so that it
  64263. ** points to the first interior cell that it points to the parent of
  64264. ** the next page in the tree that has not yet been visited. The
  64265. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  64266. ** of the page, or to the number of cells in the page if the next page
  64267. ** to visit is the right-child of its parent.
  64268. **
  64269. ** If all pages in the tree have been visited, return SQLITE_OK to the
  64270. ** caller.
  64271. */
  64272. if( pPage->leaf ){
  64273. do {
  64274. if( pCur->iPage==0 ){
  64275. /* All pages of the b-tree have been visited. Return successfully. */
  64276. *pnEntry = nEntry;
  64277. return moveToRoot(pCur);
  64278. }
  64279. moveToParent(pCur);
  64280. }while ( pCur->ix>=pCur->pPage->nCell );
  64281. pCur->ix++;
  64282. pPage = pCur->pPage;
  64283. }
  64284. /* Descend to the child node of the cell that the cursor currently
  64285. ** points at. This is the right-child if (iIdx==pPage->nCell).
  64286. */
  64287. iIdx = pCur->ix;
  64288. if( iIdx==pPage->nCell ){
  64289. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  64290. }else{
  64291. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  64292. }
  64293. }
  64294. /* An error has occurred. Return an error code. */
  64295. return rc;
  64296. }
  64297. #endif
  64298. /*
  64299. ** Return the pager associated with a BTree. This routine is used for
  64300. ** testing and debugging only.
  64301. */
  64302. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  64303. return p->pBt->pPager;
  64304. }
  64305. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64306. /*
  64307. ** Append a message to the error message string.
  64308. */
  64309. static void checkAppendMsg(
  64310. IntegrityCk *pCheck,
  64311. const char *zFormat,
  64312. ...
  64313. ){
  64314. va_list ap;
  64315. if( !pCheck->mxErr ) return;
  64316. pCheck->mxErr--;
  64317. pCheck->nErr++;
  64318. va_start(ap, zFormat);
  64319. if( pCheck->errMsg.nChar ){
  64320. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  64321. }
  64322. if( pCheck->zPfx ){
  64323. sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  64324. }
  64325. sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
  64326. va_end(ap);
  64327. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  64328. pCheck->mallocFailed = 1;
  64329. }
  64330. }
  64331. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64332. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64333. /*
  64334. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  64335. ** corresponds to page iPg is already set.
  64336. */
  64337. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  64338. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  64339. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  64340. }
  64341. /*
  64342. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  64343. */
  64344. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  64345. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  64346. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  64347. }
  64348. /*
  64349. ** Add 1 to the reference count for page iPage. If this is the second
  64350. ** reference to the page, add an error message to pCheck->zErrMsg.
  64351. ** Return 1 if there are 2 or more references to the page and 0 if
  64352. ** if this is the first reference to the page.
  64353. **
  64354. ** Also check that the page number is in bounds.
  64355. */
  64356. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  64357. if( iPage==0 ) return 1;
  64358. if( iPage>pCheck->nPage ){
  64359. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  64360. return 1;
  64361. }
  64362. if( getPageReferenced(pCheck, iPage) ){
  64363. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  64364. return 1;
  64365. }
  64366. setPageReferenced(pCheck, iPage);
  64367. return 0;
  64368. }
  64369. #ifndef SQLITE_OMIT_AUTOVACUUM
  64370. /*
  64371. ** Check that the entry in the pointer-map for page iChild maps to
  64372. ** page iParent, pointer type ptrType. If not, append an error message
  64373. ** to pCheck.
  64374. */
  64375. static void checkPtrmap(
  64376. IntegrityCk *pCheck, /* Integrity check context */
  64377. Pgno iChild, /* Child page number */
  64378. u8 eType, /* Expected pointer map type */
  64379. Pgno iParent /* Expected pointer map parent page number */
  64380. ){
  64381. int rc;
  64382. u8 ePtrmapType;
  64383. Pgno iPtrmapParent;
  64384. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  64385. if( rc!=SQLITE_OK ){
  64386. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  64387. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  64388. return;
  64389. }
  64390. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  64391. checkAppendMsg(pCheck,
  64392. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  64393. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  64394. }
  64395. }
  64396. #endif
  64397. /*
  64398. ** Check the integrity of the freelist or of an overflow page list.
  64399. ** Verify that the number of pages on the list is N.
  64400. */
  64401. static void checkList(
  64402. IntegrityCk *pCheck, /* Integrity checking context */
  64403. int isFreeList, /* True for a freelist. False for overflow page list */
  64404. int iPage, /* Page number for first page in the list */
  64405. int N /* Expected number of pages in the list */
  64406. ){
  64407. int i;
  64408. int expected = N;
  64409. int iFirst = iPage;
  64410. while( N-- > 0 && pCheck->mxErr ){
  64411. DbPage *pOvflPage;
  64412. unsigned char *pOvflData;
  64413. if( iPage<1 ){
  64414. checkAppendMsg(pCheck,
  64415. "%d of %d pages missing from overflow list starting at %d",
  64416. N+1, expected, iFirst);
  64417. break;
  64418. }
  64419. if( checkRef(pCheck, iPage) ) break;
  64420. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  64421. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  64422. break;
  64423. }
  64424. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  64425. if( isFreeList ){
  64426. int n = get4byte(&pOvflData[4]);
  64427. #ifndef SQLITE_OMIT_AUTOVACUUM
  64428. if( pCheck->pBt->autoVacuum ){
  64429. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  64430. }
  64431. #endif
  64432. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  64433. checkAppendMsg(pCheck,
  64434. "freelist leaf count too big on page %d", iPage);
  64435. N--;
  64436. }else{
  64437. for(i=0; i<n; i++){
  64438. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  64439. #ifndef SQLITE_OMIT_AUTOVACUUM
  64440. if( pCheck->pBt->autoVacuum ){
  64441. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  64442. }
  64443. #endif
  64444. checkRef(pCheck, iFreePage);
  64445. }
  64446. N -= n;
  64447. }
  64448. }
  64449. #ifndef SQLITE_OMIT_AUTOVACUUM
  64450. else{
  64451. /* If this database supports auto-vacuum and iPage is not the last
  64452. ** page in this overflow list, check that the pointer-map entry for
  64453. ** the following page matches iPage.
  64454. */
  64455. if( pCheck->pBt->autoVacuum && N>0 ){
  64456. i = get4byte(pOvflData);
  64457. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  64458. }
  64459. }
  64460. #endif
  64461. iPage = get4byte(pOvflData);
  64462. sqlite3PagerUnref(pOvflPage);
  64463. if( isFreeList && N<(iPage!=0) ){
  64464. checkAppendMsg(pCheck, "free-page count in header is too small");
  64465. }
  64466. }
  64467. }
  64468. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64469. /*
  64470. ** An implementation of a min-heap.
  64471. **
  64472. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  64473. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  64474. ** and aHeap[N*2+1].
  64475. **
  64476. ** The heap property is this: Every node is less than or equal to both
  64477. ** of its daughter nodes. A consequence of the heap property is that the
  64478. ** root node aHeap[1] is always the minimum value currently in the heap.
  64479. **
  64480. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  64481. ** the heap, preserving the heap property. The btreeHeapPull() routine
  64482. ** removes the root element from the heap (the minimum value in the heap)
  64483. ** and then moves other nodes around as necessary to preserve the heap
  64484. ** property.
  64485. **
  64486. ** This heap is used for cell overlap and coverage testing. Each u32
  64487. ** entry represents the span of a cell or freeblock on a btree page.
  64488. ** The upper 16 bits are the index of the first byte of a range and the
  64489. ** lower 16 bits are the index of the last byte of that range.
  64490. */
  64491. static void btreeHeapInsert(u32 *aHeap, u32 x){
  64492. u32 j, i = ++aHeap[0];
  64493. aHeap[i] = x;
  64494. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  64495. x = aHeap[j];
  64496. aHeap[j] = aHeap[i];
  64497. aHeap[i] = x;
  64498. i = j;
  64499. }
  64500. }
  64501. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  64502. u32 j, i, x;
  64503. if( (x = aHeap[0])==0 ) return 0;
  64504. *pOut = aHeap[1];
  64505. aHeap[1] = aHeap[x];
  64506. aHeap[x] = 0xffffffff;
  64507. aHeap[0]--;
  64508. i = 1;
  64509. while( (j = i*2)<=aHeap[0] ){
  64510. if( aHeap[j]>aHeap[j+1] ) j++;
  64511. if( aHeap[i]<aHeap[j] ) break;
  64512. x = aHeap[i];
  64513. aHeap[i] = aHeap[j];
  64514. aHeap[j] = x;
  64515. i = j;
  64516. }
  64517. return 1;
  64518. }
  64519. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64520. /*
  64521. ** Do various sanity checks on a single page of a tree. Return
  64522. ** the tree depth. Root pages return 0. Parents of root pages
  64523. ** return 1, and so forth.
  64524. **
  64525. ** These checks are done:
  64526. **
  64527. ** 1. Make sure that cells and freeblocks do not overlap
  64528. ** but combine to completely cover the page.
  64529. ** 2. Make sure integer cell keys are in order.
  64530. ** 3. Check the integrity of overflow pages.
  64531. ** 4. Recursively call checkTreePage on all children.
  64532. ** 5. Verify that the depth of all children is the same.
  64533. */
  64534. static int checkTreePage(
  64535. IntegrityCk *pCheck, /* Context for the sanity check */
  64536. int iPage, /* Page number of the page to check */
  64537. i64 *piMinKey, /* Write minimum integer primary key here */
  64538. i64 maxKey /* Error if integer primary key greater than this */
  64539. ){
  64540. MemPage *pPage = 0; /* The page being analyzed */
  64541. int i; /* Loop counter */
  64542. int rc; /* Result code from subroutine call */
  64543. int depth = -1, d2; /* Depth of a subtree */
  64544. int pgno; /* Page number */
  64545. int nFrag; /* Number of fragmented bytes on the page */
  64546. int hdr; /* Offset to the page header */
  64547. int cellStart; /* Offset to the start of the cell pointer array */
  64548. int nCell; /* Number of cells */
  64549. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  64550. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  64551. ** False if IPK must be strictly less than maxKey */
  64552. u8 *data; /* Page content */
  64553. u8 *pCell; /* Cell content */
  64554. u8 *pCellIdx; /* Next element of the cell pointer array */
  64555. BtShared *pBt; /* The BtShared object that owns pPage */
  64556. u32 pc; /* Address of a cell */
  64557. u32 usableSize; /* Usable size of the page */
  64558. u32 contentOffset; /* Offset to the start of the cell content area */
  64559. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  64560. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  64561. const char *saved_zPfx = pCheck->zPfx;
  64562. int saved_v1 = pCheck->v1;
  64563. int saved_v2 = pCheck->v2;
  64564. u8 savedIsInit = 0;
  64565. /* Check that the page exists
  64566. */
  64567. pBt = pCheck->pBt;
  64568. usableSize = pBt->usableSize;
  64569. if( iPage==0 ) return 0;
  64570. if( checkRef(pCheck, iPage) ) return 0;
  64571. pCheck->zPfx = "Page %d: ";
  64572. pCheck->v1 = iPage;
  64573. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  64574. checkAppendMsg(pCheck,
  64575. "unable to get the page. error code=%d", rc);
  64576. goto end_of_check;
  64577. }
  64578. /* Clear MemPage.isInit to make sure the corruption detection code in
  64579. ** btreeInitPage() is executed. */
  64580. savedIsInit = pPage->isInit;
  64581. pPage->isInit = 0;
  64582. if( (rc = btreeInitPage(pPage))!=0 ){
  64583. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  64584. checkAppendMsg(pCheck,
  64585. "btreeInitPage() returns error code %d", rc);
  64586. goto end_of_check;
  64587. }
  64588. data = pPage->aData;
  64589. hdr = pPage->hdrOffset;
  64590. /* Set up for cell analysis */
  64591. pCheck->zPfx = "On tree page %d cell %d: ";
  64592. contentOffset = get2byteNotZero(&data[hdr+5]);
  64593. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  64594. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  64595. ** number of cells on the page. */
  64596. nCell = get2byte(&data[hdr+3]);
  64597. assert( pPage->nCell==nCell );
  64598. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  64599. ** immediately follows the b-tree page header. */
  64600. cellStart = hdr + 12 - 4*pPage->leaf;
  64601. assert( pPage->aCellIdx==&data[cellStart] );
  64602. pCellIdx = &data[cellStart + 2*(nCell-1)];
  64603. if( !pPage->leaf ){
  64604. /* Analyze the right-child page of internal pages */
  64605. pgno = get4byte(&data[hdr+8]);
  64606. #ifndef SQLITE_OMIT_AUTOVACUUM
  64607. if( pBt->autoVacuum ){
  64608. pCheck->zPfx = "On page %d at right child: ";
  64609. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  64610. }
  64611. #endif
  64612. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  64613. keyCanBeEqual = 0;
  64614. }else{
  64615. /* For leaf pages, the coverage check will occur in the same loop
  64616. ** as the other cell checks, so initialize the heap. */
  64617. heap = pCheck->heap;
  64618. heap[0] = 0;
  64619. }
  64620. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  64621. ** integer offsets to the cell contents. */
  64622. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  64623. CellInfo info;
  64624. /* Check cell size */
  64625. pCheck->v2 = i;
  64626. assert( pCellIdx==&data[cellStart + i*2] );
  64627. pc = get2byteAligned(pCellIdx);
  64628. pCellIdx -= 2;
  64629. if( pc<contentOffset || pc>usableSize-4 ){
  64630. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  64631. pc, contentOffset, usableSize-4);
  64632. doCoverageCheck = 0;
  64633. continue;
  64634. }
  64635. pCell = &data[pc];
  64636. pPage->xParseCell(pPage, pCell, &info);
  64637. if( pc+info.nSize>usableSize ){
  64638. checkAppendMsg(pCheck, "Extends off end of page");
  64639. doCoverageCheck = 0;
  64640. continue;
  64641. }
  64642. /* Check for integer primary key out of range */
  64643. if( pPage->intKey ){
  64644. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  64645. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  64646. }
  64647. maxKey = info.nKey;
  64648. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  64649. }
  64650. /* Check the content overflow list */
  64651. if( info.nPayload>info.nLocal ){
  64652. int nPage; /* Number of pages on the overflow chain */
  64653. Pgno pgnoOvfl; /* First page of the overflow chain */
  64654. assert( pc + info.nSize - 4 <= usableSize );
  64655. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  64656. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  64657. #ifndef SQLITE_OMIT_AUTOVACUUM
  64658. if( pBt->autoVacuum ){
  64659. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  64660. }
  64661. #endif
  64662. checkList(pCheck, 0, pgnoOvfl, nPage);
  64663. }
  64664. if( !pPage->leaf ){
  64665. /* Check sanity of left child page for internal pages */
  64666. pgno = get4byte(pCell);
  64667. #ifndef SQLITE_OMIT_AUTOVACUUM
  64668. if( pBt->autoVacuum ){
  64669. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  64670. }
  64671. #endif
  64672. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  64673. keyCanBeEqual = 0;
  64674. if( d2!=depth ){
  64675. checkAppendMsg(pCheck, "Child page depth differs");
  64676. depth = d2;
  64677. }
  64678. }else{
  64679. /* Populate the coverage-checking heap for leaf pages */
  64680. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  64681. }
  64682. }
  64683. *piMinKey = maxKey;
  64684. /* Check for complete coverage of the page
  64685. */
  64686. pCheck->zPfx = 0;
  64687. if( doCoverageCheck && pCheck->mxErr>0 ){
  64688. /* For leaf pages, the min-heap has already been initialized and the
  64689. ** cells have already been inserted. But for internal pages, that has
  64690. ** not yet been done, so do it now */
  64691. if( !pPage->leaf ){
  64692. heap = pCheck->heap;
  64693. heap[0] = 0;
  64694. for(i=nCell-1; i>=0; i--){
  64695. u32 size;
  64696. pc = get2byteAligned(&data[cellStart+i*2]);
  64697. size = pPage->xCellSize(pPage, &data[pc]);
  64698. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  64699. }
  64700. }
  64701. /* Add the freeblocks to the min-heap
  64702. **
  64703. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  64704. ** is the offset of the first freeblock, or zero if there are no
  64705. ** freeblocks on the page.
  64706. */
  64707. i = get2byte(&data[hdr+1]);
  64708. while( i>0 ){
  64709. int size, j;
  64710. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  64711. size = get2byte(&data[i+2]);
  64712. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  64713. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  64714. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  64715. ** big-endian integer which is the offset in the b-tree page of the next
  64716. ** freeblock in the chain, or zero if the freeblock is the last on the
  64717. ** chain. */
  64718. j = get2byte(&data[i]);
  64719. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  64720. ** increasing offset. */
  64721. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  64722. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  64723. i = j;
  64724. }
  64725. /* Analyze the min-heap looking for overlap between cells and/or
  64726. ** freeblocks, and counting the number of untracked bytes in nFrag.
  64727. **
  64728. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  64729. ** There is an implied first entry the covers the page header, the cell
  64730. ** pointer index, and the gap between the cell pointer index and the start
  64731. ** of cell content.
  64732. **
  64733. ** The loop below pulls entries from the min-heap in order and compares
  64734. ** the start_address against the previous end_address. If there is an
  64735. ** overlap, that means bytes are used multiple times. If there is a gap,
  64736. ** that gap is added to the fragmentation count.
  64737. */
  64738. nFrag = 0;
  64739. prev = contentOffset - 1; /* Implied first min-heap entry */
  64740. while( btreeHeapPull(heap,&x) ){
  64741. if( (prev&0xffff)>=(x>>16) ){
  64742. checkAppendMsg(pCheck,
  64743. "Multiple uses for byte %u of page %d", x>>16, iPage);
  64744. break;
  64745. }else{
  64746. nFrag += (x>>16) - (prev&0xffff) - 1;
  64747. prev = x;
  64748. }
  64749. }
  64750. nFrag += usableSize - (prev&0xffff) - 1;
  64751. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  64752. ** is stored in the fifth field of the b-tree page header.
  64753. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  64754. ** number of fragmented free bytes within the cell content area.
  64755. */
  64756. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  64757. checkAppendMsg(pCheck,
  64758. "Fragmentation of %d bytes reported as %d on page %d",
  64759. nFrag, data[hdr+7], iPage);
  64760. }
  64761. }
  64762. end_of_check:
  64763. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  64764. releasePage(pPage);
  64765. pCheck->zPfx = saved_zPfx;
  64766. pCheck->v1 = saved_v1;
  64767. pCheck->v2 = saved_v2;
  64768. return depth+1;
  64769. }
  64770. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64771. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64772. /*
  64773. ** This routine does a complete check of the given BTree file. aRoot[] is
  64774. ** an array of pages numbers were each page number is the root page of
  64775. ** a table. nRoot is the number of entries in aRoot.
  64776. **
  64777. ** A read-only or read-write transaction must be opened before calling
  64778. ** this function.
  64779. **
  64780. ** Write the number of error seen in *pnErr. Except for some memory
  64781. ** allocation errors, an error message held in memory obtained from
  64782. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  64783. ** returned. If a memory allocation error occurs, NULL is returned.
  64784. */
  64785. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  64786. Btree *p, /* The btree to be checked */
  64787. int *aRoot, /* An array of root pages numbers for individual trees */
  64788. int nRoot, /* Number of entries in aRoot[] */
  64789. int mxErr, /* Stop reporting errors after this many */
  64790. int *pnErr /* Write number of errors seen to this variable */
  64791. ){
  64792. Pgno i;
  64793. IntegrityCk sCheck;
  64794. BtShared *pBt = p->pBt;
  64795. int savedDbFlags = pBt->db->flags;
  64796. char zErr[100];
  64797. VVA_ONLY( int nRef );
  64798. sqlite3BtreeEnter(p);
  64799. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  64800. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  64801. assert( nRef>=0 );
  64802. sCheck.pBt = pBt;
  64803. sCheck.pPager = pBt->pPager;
  64804. sCheck.nPage = btreePagecount(sCheck.pBt);
  64805. sCheck.mxErr = mxErr;
  64806. sCheck.nErr = 0;
  64807. sCheck.mallocFailed = 0;
  64808. sCheck.zPfx = 0;
  64809. sCheck.v1 = 0;
  64810. sCheck.v2 = 0;
  64811. sCheck.aPgRef = 0;
  64812. sCheck.heap = 0;
  64813. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  64814. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  64815. if( sCheck.nPage==0 ){
  64816. goto integrity_ck_cleanup;
  64817. }
  64818. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  64819. if( !sCheck.aPgRef ){
  64820. sCheck.mallocFailed = 1;
  64821. goto integrity_ck_cleanup;
  64822. }
  64823. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  64824. if( sCheck.heap==0 ){
  64825. sCheck.mallocFailed = 1;
  64826. goto integrity_ck_cleanup;
  64827. }
  64828. i = PENDING_BYTE_PAGE(pBt);
  64829. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  64830. /* Check the integrity of the freelist
  64831. */
  64832. sCheck.zPfx = "Main freelist: ";
  64833. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  64834. get4byte(&pBt->pPage1->aData[36]));
  64835. sCheck.zPfx = 0;
  64836. /* Check all the tables.
  64837. */
  64838. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  64839. pBt->db->flags &= ~SQLITE_CellSizeCk;
  64840. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  64841. i64 notUsed;
  64842. if( aRoot[i]==0 ) continue;
  64843. #ifndef SQLITE_OMIT_AUTOVACUUM
  64844. if( pBt->autoVacuum && aRoot[i]>1 ){
  64845. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  64846. }
  64847. #endif
  64848. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  64849. }
  64850. pBt->db->flags = savedDbFlags;
  64851. /* Make sure every page in the file is referenced
  64852. */
  64853. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  64854. #ifdef SQLITE_OMIT_AUTOVACUUM
  64855. if( getPageReferenced(&sCheck, i)==0 ){
  64856. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64857. }
  64858. #else
  64859. /* If the database supports auto-vacuum, make sure no tables contain
  64860. ** references to pointer-map pages.
  64861. */
  64862. if( getPageReferenced(&sCheck, i)==0 &&
  64863. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  64864. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64865. }
  64866. if( getPageReferenced(&sCheck, i)!=0 &&
  64867. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  64868. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  64869. }
  64870. #endif
  64871. }
  64872. /* Clean up and report errors.
  64873. */
  64874. integrity_ck_cleanup:
  64875. sqlite3PageFree(sCheck.heap);
  64876. sqlite3_free(sCheck.aPgRef);
  64877. if( sCheck.mallocFailed ){
  64878. sqlite3StrAccumReset(&sCheck.errMsg);
  64879. sCheck.nErr++;
  64880. }
  64881. *pnErr = sCheck.nErr;
  64882. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  64883. /* Make sure this analysis did not leave any unref() pages. */
  64884. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  64885. sqlite3BtreeLeave(p);
  64886. return sqlite3StrAccumFinish(&sCheck.errMsg);
  64887. }
  64888. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64889. /*
  64890. ** Return the full pathname of the underlying database file. Return
  64891. ** an empty string if the database is in-memory or a TEMP database.
  64892. **
  64893. ** The pager filename is invariant as long as the pager is
  64894. ** open so it is safe to access without the BtShared mutex.
  64895. */
  64896. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  64897. assert( p->pBt->pPager!=0 );
  64898. return sqlite3PagerFilename(p->pBt->pPager, 1);
  64899. }
  64900. /*
  64901. ** Return the pathname of the journal file for this database. The return
  64902. ** value of this routine is the same regardless of whether the journal file
  64903. ** has been created or not.
  64904. **
  64905. ** The pager journal filename is invariant as long as the pager is
  64906. ** open so it is safe to access without the BtShared mutex.
  64907. */
  64908. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  64909. assert( p->pBt->pPager!=0 );
  64910. return sqlite3PagerJournalname(p->pBt->pPager);
  64911. }
  64912. /*
  64913. ** Return non-zero if a transaction is active.
  64914. */
  64915. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  64916. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  64917. return (p && (p->inTrans==TRANS_WRITE));
  64918. }
  64919. #ifndef SQLITE_OMIT_WAL
  64920. /*
  64921. ** Run a checkpoint on the Btree passed as the first argument.
  64922. **
  64923. ** Return SQLITE_LOCKED if this or any other connection has an open
  64924. ** transaction on the shared-cache the argument Btree is connected to.
  64925. **
  64926. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  64927. */
  64928. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  64929. int rc = SQLITE_OK;
  64930. if( p ){
  64931. BtShared *pBt = p->pBt;
  64932. sqlite3BtreeEnter(p);
  64933. if( pBt->inTransaction!=TRANS_NONE ){
  64934. rc = SQLITE_LOCKED;
  64935. }else{
  64936. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  64937. }
  64938. sqlite3BtreeLeave(p);
  64939. }
  64940. return rc;
  64941. }
  64942. #endif
  64943. /*
  64944. ** Return non-zero if a read (or write) transaction is active.
  64945. */
  64946. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  64947. assert( p );
  64948. assert( sqlite3_mutex_held(p->db->mutex) );
  64949. return p->inTrans!=TRANS_NONE;
  64950. }
  64951. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  64952. assert( p );
  64953. assert( sqlite3_mutex_held(p->db->mutex) );
  64954. return p->nBackup!=0;
  64955. }
  64956. /*
  64957. ** This function returns a pointer to a blob of memory associated with
  64958. ** a single shared-btree. The memory is used by client code for its own
  64959. ** purposes (for example, to store a high-level schema associated with
  64960. ** the shared-btree). The btree layer manages reference counting issues.
  64961. **
  64962. ** The first time this is called on a shared-btree, nBytes bytes of memory
  64963. ** are allocated, zeroed, and returned to the caller. For each subsequent
  64964. ** call the nBytes parameter is ignored and a pointer to the same blob
  64965. ** of memory returned.
  64966. **
  64967. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  64968. ** allocated, a null pointer is returned. If the blob has already been
  64969. ** allocated, it is returned as normal.
  64970. **
  64971. ** Just before the shared-btree is closed, the function passed as the
  64972. ** xFree argument when the memory allocation was made is invoked on the
  64973. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  64974. ** on the memory, the btree layer does that.
  64975. */
  64976. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  64977. BtShared *pBt = p->pBt;
  64978. sqlite3BtreeEnter(p);
  64979. if( !pBt->pSchema && nBytes ){
  64980. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  64981. pBt->xFreeSchema = xFree;
  64982. }
  64983. sqlite3BtreeLeave(p);
  64984. return pBt->pSchema;
  64985. }
  64986. /*
  64987. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  64988. ** btree as the argument handle holds an exclusive lock on the
  64989. ** sqlite_master table. Otherwise SQLITE_OK.
  64990. */
  64991. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  64992. int rc;
  64993. assert( sqlite3_mutex_held(p->db->mutex) );
  64994. sqlite3BtreeEnter(p);
  64995. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  64996. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  64997. sqlite3BtreeLeave(p);
  64998. return rc;
  64999. }
  65000. #ifndef SQLITE_OMIT_SHARED_CACHE
  65001. /*
  65002. ** Obtain a lock on the table whose root page is iTab. The
  65003. ** lock is a write lock if isWritelock is true or a read lock
  65004. ** if it is false.
  65005. */
  65006. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  65007. int rc = SQLITE_OK;
  65008. assert( p->inTrans!=TRANS_NONE );
  65009. if( p->sharable ){
  65010. u8 lockType = READ_LOCK + isWriteLock;
  65011. assert( READ_LOCK+1==WRITE_LOCK );
  65012. assert( isWriteLock==0 || isWriteLock==1 );
  65013. sqlite3BtreeEnter(p);
  65014. rc = querySharedCacheTableLock(p, iTab, lockType);
  65015. if( rc==SQLITE_OK ){
  65016. rc = setSharedCacheTableLock(p, iTab, lockType);
  65017. }
  65018. sqlite3BtreeLeave(p);
  65019. }
  65020. return rc;
  65021. }
  65022. #endif
  65023. #ifndef SQLITE_OMIT_INCRBLOB
  65024. /*
  65025. ** Argument pCsr must be a cursor opened for writing on an
  65026. ** INTKEY table currently pointing at a valid table entry.
  65027. ** This function modifies the data stored as part of that entry.
  65028. **
  65029. ** Only the data content may only be modified, it is not possible to
  65030. ** change the length of the data stored. If this function is called with
  65031. ** parameters that attempt to write past the end of the existing data,
  65032. ** no modifications are made and SQLITE_CORRUPT is returned.
  65033. */
  65034. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  65035. int rc;
  65036. assert( cursorOwnsBtShared(pCsr) );
  65037. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  65038. assert( pCsr->curFlags & BTCF_Incrblob );
  65039. rc = restoreCursorPosition(pCsr);
  65040. if( rc!=SQLITE_OK ){
  65041. return rc;
  65042. }
  65043. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  65044. if( pCsr->eState!=CURSOR_VALID ){
  65045. return SQLITE_ABORT;
  65046. }
  65047. /* Save the positions of all other cursors open on this table. This is
  65048. ** required in case any of them are holding references to an xFetch
  65049. ** version of the b-tree page modified by the accessPayload call below.
  65050. **
  65051. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  65052. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  65053. ** saveAllCursors can only return SQLITE_OK.
  65054. */
  65055. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  65056. assert( rc==SQLITE_OK );
  65057. /* Check some assumptions:
  65058. ** (a) the cursor is open for writing,
  65059. ** (b) there is a read/write transaction open,
  65060. ** (c) the connection holds a write-lock on the table (if required),
  65061. ** (d) there are no conflicting read-locks, and
  65062. ** (e) the cursor points at a valid row of an intKey table.
  65063. */
  65064. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  65065. return SQLITE_READONLY;
  65066. }
  65067. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  65068. && pCsr->pBt->inTransaction==TRANS_WRITE );
  65069. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  65070. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  65071. assert( pCsr->pPage->intKey );
  65072. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  65073. }
  65074. /*
  65075. ** Mark this cursor as an incremental blob cursor.
  65076. */
  65077. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  65078. pCur->curFlags |= BTCF_Incrblob;
  65079. pCur->pBtree->hasIncrblobCur = 1;
  65080. }
  65081. #endif
  65082. /*
  65083. ** Set both the "read version" (single byte at byte offset 18) and
  65084. ** "write version" (single byte at byte offset 19) fields in the database
  65085. ** header to iVersion.
  65086. */
  65087. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  65088. BtShared *pBt = pBtree->pBt;
  65089. int rc; /* Return code */
  65090. assert( iVersion==1 || iVersion==2 );
  65091. /* If setting the version fields to 1, do not automatically open the
  65092. ** WAL connection, even if the version fields are currently set to 2.
  65093. */
  65094. pBt->btsFlags &= ~BTS_NO_WAL;
  65095. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  65096. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  65097. if( rc==SQLITE_OK ){
  65098. u8 *aData = pBt->pPage1->aData;
  65099. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  65100. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  65101. if( rc==SQLITE_OK ){
  65102. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  65103. if( rc==SQLITE_OK ){
  65104. aData[18] = (u8)iVersion;
  65105. aData[19] = (u8)iVersion;
  65106. }
  65107. }
  65108. }
  65109. }
  65110. pBt->btsFlags &= ~BTS_NO_WAL;
  65111. return rc;
  65112. }
  65113. /*
  65114. ** Return true if the cursor has a hint specified. This routine is
  65115. ** only used from within assert() statements
  65116. */
  65117. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  65118. return (pCsr->hints & mask)!=0;
  65119. }
  65120. /*
  65121. ** Return true if the given Btree is read-only.
  65122. */
  65123. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  65124. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  65125. }
  65126. /*
  65127. ** Return the size of the header added to each page by this module.
  65128. */
  65129. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  65130. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  65131. /*
  65132. ** Return true if the Btree passed as the only argument is sharable.
  65133. */
  65134. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  65135. return p->sharable;
  65136. }
  65137. /*
  65138. ** Return the number of connections to the BtShared object accessed by
  65139. ** the Btree handle passed as the only argument. For private caches
  65140. ** this is always 1. For shared caches it may be 1 or greater.
  65141. */
  65142. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  65143. testcase( p->sharable );
  65144. return p->pBt->nRef;
  65145. }
  65146. #endif
  65147. /************** End of btree.c ***********************************************/
  65148. /************** Begin file backup.c ******************************************/
  65149. /*
  65150. ** 2009 January 28
  65151. **
  65152. ** The author disclaims copyright to this source code. In place of
  65153. ** a legal notice, here is a blessing:
  65154. **
  65155. ** May you do good and not evil.
  65156. ** May you find forgiveness for yourself and forgive others.
  65157. ** May you share freely, never taking more than you give.
  65158. **
  65159. *************************************************************************
  65160. ** This file contains the implementation of the sqlite3_backup_XXX()
  65161. ** API functions and the related features.
  65162. */
  65163. /* #include "sqliteInt.h" */
  65164. /* #include "btreeInt.h" */
  65165. /*
  65166. ** Structure allocated for each backup operation.
  65167. */
  65168. struct sqlite3_backup {
  65169. sqlite3* pDestDb; /* Destination database handle */
  65170. Btree *pDest; /* Destination b-tree file */
  65171. u32 iDestSchema; /* Original schema cookie in destination */
  65172. int bDestLocked; /* True once a write-transaction is open on pDest */
  65173. Pgno iNext; /* Page number of the next source page to copy */
  65174. sqlite3* pSrcDb; /* Source database handle */
  65175. Btree *pSrc; /* Source b-tree file */
  65176. int rc; /* Backup process error code */
  65177. /* These two variables are set by every call to backup_step(). They are
  65178. ** read by calls to backup_remaining() and backup_pagecount().
  65179. */
  65180. Pgno nRemaining; /* Number of pages left to copy */
  65181. Pgno nPagecount; /* Total number of pages to copy */
  65182. int isAttached; /* True once backup has been registered with pager */
  65183. sqlite3_backup *pNext; /* Next backup associated with source pager */
  65184. };
  65185. /*
  65186. ** THREAD SAFETY NOTES:
  65187. **
  65188. ** Once it has been created using backup_init(), a single sqlite3_backup
  65189. ** structure may be accessed via two groups of thread-safe entry points:
  65190. **
  65191. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  65192. ** backup_finish(). Both these functions obtain the source database
  65193. ** handle mutex and the mutex associated with the source BtShared
  65194. ** structure, in that order.
  65195. **
  65196. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  65197. ** invoked by the pager layer to report various state changes in
  65198. ** the page cache associated with the source database. The mutex
  65199. ** associated with the source database BtShared structure will always
  65200. ** be held when either of these functions are invoked.
  65201. **
  65202. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  65203. ** backup_pagecount() are not thread-safe functions. If they are called
  65204. ** while some other thread is calling backup_step() or backup_finish(),
  65205. ** the values returned may be invalid. There is no way for a call to
  65206. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  65207. ** or backup_pagecount().
  65208. **
  65209. ** Depending on the SQLite configuration, the database handles and/or
  65210. ** the Btree objects may have their own mutexes that require locking.
  65211. ** Non-sharable Btrees (in-memory databases for example), do not have
  65212. ** associated mutexes.
  65213. */
  65214. /*
  65215. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  65216. ** in connection handle pDb. If such a database cannot be found, return
  65217. ** a NULL pointer and write an error message to pErrorDb.
  65218. **
  65219. ** If the "temp" database is requested, it may need to be opened by this
  65220. ** function. If an error occurs while doing so, return 0 and write an
  65221. ** error message to pErrorDb.
  65222. */
  65223. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  65224. int i = sqlite3FindDbName(pDb, zDb);
  65225. if( i==1 ){
  65226. Parse sParse;
  65227. int rc = 0;
  65228. memset(&sParse, 0, sizeof(sParse));
  65229. sParse.db = pDb;
  65230. if( sqlite3OpenTempDatabase(&sParse) ){
  65231. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  65232. rc = SQLITE_ERROR;
  65233. }
  65234. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  65235. sqlite3ParserReset(&sParse);
  65236. if( rc ){
  65237. return 0;
  65238. }
  65239. }
  65240. if( i<0 ){
  65241. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  65242. return 0;
  65243. }
  65244. return pDb->aDb[i].pBt;
  65245. }
  65246. /*
  65247. ** Attempt to set the page size of the destination to match the page size
  65248. ** of the source.
  65249. */
  65250. static int setDestPgsz(sqlite3_backup *p){
  65251. int rc;
  65252. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  65253. return rc;
  65254. }
  65255. /*
  65256. ** Check that there is no open read-transaction on the b-tree passed as the
  65257. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  65258. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  65259. ** message in database handle db.
  65260. */
  65261. static int checkReadTransaction(sqlite3 *db, Btree *p){
  65262. if( sqlite3BtreeIsInReadTrans(p) ){
  65263. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  65264. return SQLITE_ERROR;
  65265. }
  65266. return SQLITE_OK;
  65267. }
  65268. /*
  65269. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  65270. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  65271. ** a pointer to the new sqlite3_backup object.
  65272. **
  65273. ** If an error occurs, NULL is returned and an error code and error message
  65274. ** stored in database handle pDestDb.
  65275. */
  65276. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  65277. sqlite3* pDestDb, /* Database to write to */
  65278. const char *zDestDb, /* Name of database within pDestDb */
  65279. sqlite3* pSrcDb, /* Database connection to read from */
  65280. const char *zSrcDb /* Name of database within pSrcDb */
  65281. ){
  65282. sqlite3_backup *p; /* Value to return */
  65283. #ifdef SQLITE_ENABLE_API_ARMOR
  65284. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  65285. (void)SQLITE_MISUSE_BKPT;
  65286. return 0;
  65287. }
  65288. #endif
  65289. /* Lock the source database handle. The destination database
  65290. ** handle is not locked in this routine, but it is locked in
  65291. ** sqlite3_backup_step(). The user is required to ensure that no
  65292. ** other thread accesses the destination handle for the duration
  65293. ** of the backup operation. Any attempt to use the destination
  65294. ** database connection while a backup is in progress may cause
  65295. ** a malfunction or a deadlock.
  65296. */
  65297. sqlite3_mutex_enter(pSrcDb->mutex);
  65298. sqlite3_mutex_enter(pDestDb->mutex);
  65299. if( pSrcDb==pDestDb ){
  65300. sqlite3ErrorWithMsg(
  65301. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  65302. );
  65303. p = 0;
  65304. }else {
  65305. /* Allocate space for a new sqlite3_backup object...
  65306. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  65307. ** call to sqlite3_backup_init() and is destroyed by a call to
  65308. ** sqlite3_backup_finish(). */
  65309. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  65310. if( !p ){
  65311. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  65312. }
  65313. }
  65314. /* If the allocation succeeded, populate the new object. */
  65315. if( p ){
  65316. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  65317. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  65318. p->pDestDb = pDestDb;
  65319. p->pSrcDb = pSrcDb;
  65320. p->iNext = 1;
  65321. p->isAttached = 0;
  65322. if( 0==p->pSrc || 0==p->pDest
  65323. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  65324. ){
  65325. /* One (or both) of the named databases did not exist or an OOM
  65326. ** error was hit. Or there is a transaction open on the destination
  65327. ** database. The error has already been written into the pDestDb
  65328. ** handle. All that is left to do here is free the sqlite3_backup
  65329. ** structure. */
  65330. sqlite3_free(p);
  65331. p = 0;
  65332. }
  65333. }
  65334. if( p ){
  65335. p->pSrc->nBackup++;
  65336. }
  65337. sqlite3_mutex_leave(pDestDb->mutex);
  65338. sqlite3_mutex_leave(pSrcDb->mutex);
  65339. return p;
  65340. }
  65341. /*
  65342. ** Argument rc is an SQLite error code. Return true if this error is
  65343. ** considered fatal if encountered during a backup operation. All errors
  65344. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  65345. */
  65346. static int isFatalError(int rc){
  65347. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  65348. }
  65349. /*
  65350. ** Parameter zSrcData points to a buffer containing the data for
  65351. ** page iSrcPg from the source database. Copy this data into the
  65352. ** destination database.
  65353. */
  65354. static int backupOnePage(
  65355. sqlite3_backup *p, /* Backup handle */
  65356. Pgno iSrcPg, /* Source database page to backup */
  65357. const u8 *zSrcData, /* Source database page data */
  65358. int bUpdate /* True for an update, false otherwise */
  65359. ){
  65360. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  65361. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  65362. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  65363. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  65364. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  65365. #ifdef SQLITE_HAS_CODEC
  65366. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  65367. ** guaranteed that the shared-mutex is held by this thread, handle
  65368. ** p->pSrc may not actually be the owner. */
  65369. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  65370. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  65371. #endif
  65372. int rc = SQLITE_OK;
  65373. i64 iOff;
  65374. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  65375. assert( p->bDestLocked );
  65376. assert( !isFatalError(p->rc) );
  65377. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  65378. assert( zSrcData );
  65379. /* Catch the case where the destination is an in-memory database and the
  65380. ** page sizes of the source and destination differ.
  65381. */
  65382. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  65383. rc = SQLITE_READONLY;
  65384. }
  65385. #ifdef SQLITE_HAS_CODEC
  65386. /* Backup is not possible if the page size of the destination is changing
  65387. ** and a codec is in use.
  65388. */
  65389. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  65390. rc = SQLITE_READONLY;
  65391. }
  65392. /* Backup is not possible if the number of bytes of reserve space differ
  65393. ** between source and destination. If there is a difference, try to
  65394. ** fix the destination to agree with the source. If that is not possible,
  65395. ** then the backup cannot proceed.
  65396. */
  65397. if( nSrcReserve!=nDestReserve ){
  65398. u32 newPgsz = nSrcPgsz;
  65399. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  65400. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  65401. }
  65402. #endif
  65403. /* This loop runs once for each destination page spanned by the source
  65404. ** page. For each iteration, variable iOff is set to the byte offset
  65405. ** of the destination page.
  65406. */
  65407. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  65408. DbPage *pDestPg = 0;
  65409. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  65410. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  65411. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  65412. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  65413. ){
  65414. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  65415. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  65416. u8 *zOut = &zDestData[iOff%nDestPgsz];
  65417. /* Copy the data from the source page into the destination page.
  65418. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  65419. ** and the pager code use this trick (clearing the first byte
  65420. ** of the page 'extra' space to invalidate the Btree layers
  65421. ** cached parse of the page). MemPage.isInit is marked
  65422. ** "MUST BE FIRST" for this purpose.
  65423. */
  65424. memcpy(zOut, zIn, nCopy);
  65425. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  65426. if( iOff==0 && bUpdate==0 ){
  65427. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  65428. }
  65429. }
  65430. sqlite3PagerUnref(pDestPg);
  65431. }
  65432. return rc;
  65433. }
  65434. /*
  65435. ** If pFile is currently larger than iSize bytes, then truncate it to
  65436. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  65437. ** this function is a no-op.
  65438. **
  65439. ** Return SQLITE_OK if everything is successful, or an SQLite error
  65440. ** code if an error occurs.
  65441. */
  65442. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  65443. i64 iCurrent;
  65444. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  65445. if( rc==SQLITE_OK && iCurrent>iSize ){
  65446. rc = sqlite3OsTruncate(pFile, iSize);
  65447. }
  65448. return rc;
  65449. }
  65450. /*
  65451. ** Register this backup object with the associated source pager for
  65452. ** callbacks when pages are changed or the cache invalidated.
  65453. */
  65454. static void attachBackupObject(sqlite3_backup *p){
  65455. sqlite3_backup **pp;
  65456. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  65457. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  65458. p->pNext = *pp;
  65459. *pp = p;
  65460. p->isAttached = 1;
  65461. }
  65462. /*
  65463. ** Copy nPage pages from the source b-tree to the destination.
  65464. */
  65465. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  65466. int rc;
  65467. int destMode; /* Destination journal mode */
  65468. int pgszSrc = 0; /* Source page size */
  65469. int pgszDest = 0; /* Destination page size */
  65470. #ifdef SQLITE_ENABLE_API_ARMOR
  65471. if( p==0 ) return SQLITE_MISUSE_BKPT;
  65472. #endif
  65473. sqlite3_mutex_enter(p->pSrcDb->mutex);
  65474. sqlite3BtreeEnter(p->pSrc);
  65475. if( p->pDestDb ){
  65476. sqlite3_mutex_enter(p->pDestDb->mutex);
  65477. }
  65478. rc = p->rc;
  65479. if( !isFatalError(rc) ){
  65480. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  65481. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  65482. int ii; /* Iterator variable */
  65483. int nSrcPage = -1; /* Size of source db in pages */
  65484. int bCloseTrans = 0; /* True if src db requires unlocking */
  65485. /* If the source pager is currently in a write-transaction, return
  65486. ** SQLITE_BUSY immediately.
  65487. */
  65488. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  65489. rc = SQLITE_BUSY;
  65490. }else{
  65491. rc = SQLITE_OK;
  65492. }
  65493. /* If there is no open read-transaction on the source database, open
  65494. ** one now. If a transaction is opened here, then it will be closed
  65495. ** before this function exits.
  65496. */
  65497. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  65498. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  65499. bCloseTrans = 1;
  65500. }
  65501. /* If the destination database has not yet been locked (i.e. if this
  65502. ** is the first call to backup_step() for the current backup operation),
  65503. ** try to set its page size to the same as the source database. This
  65504. ** is especially important on ZipVFS systems, as in that case it is
  65505. ** not possible to create a database file that uses one page size by
  65506. ** writing to it with another. */
  65507. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  65508. rc = SQLITE_NOMEM;
  65509. }
  65510. /* Lock the destination database, if it is not locked already. */
  65511. if( SQLITE_OK==rc && p->bDestLocked==0
  65512. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  65513. ){
  65514. p->bDestLocked = 1;
  65515. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  65516. }
  65517. /* Do not allow backup if the destination database is in WAL mode
  65518. ** and the page sizes are different between source and destination */
  65519. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  65520. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  65521. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  65522. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  65523. rc = SQLITE_READONLY;
  65524. }
  65525. /* Now that there is a read-lock on the source database, query the
  65526. ** source pager for the number of pages in the database.
  65527. */
  65528. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  65529. assert( nSrcPage>=0 );
  65530. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  65531. const Pgno iSrcPg = p->iNext; /* Source page number */
  65532. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  65533. DbPage *pSrcPg; /* Source page object */
  65534. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  65535. if( rc==SQLITE_OK ){
  65536. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  65537. sqlite3PagerUnref(pSrcPg);
  65538. }
  65539. }
  65540. p->iNext++;
  65541. }
  65542. if( rc==SQLITE_OK ){
  65543. p->nPagecount = nSrcPage;
  65544. p->nRemaining = nSrcPage+1-p->iNext;
  65545. if( p->iNext>(Pgno)nSrcPage ){
  65546. rc = SQLITE_DONE;
  65547. }else if( !p->isAttached ){
  65548. attachBackupObject(p);
  65549. }
  65550. }
  65551. /* Update the schema version field in the destination database. This
  65552. ** is to make sure that the schema-version really does change in
  65553. ** the case where the source and destination databases have the
  65554. ** same schema version.
  65555. */
  65556. if( rc==SQLITE_DONE ){
  65557. if( nSrcPage==0 ){
  65558. rc = sqlite3BtreeNewDb(p->pDest);
  65559. nSrcPage = 1;
  65560. }
  65561. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  65562. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  65563. }
  65564. if( rc==SQLITE_OK ){
  65565. if( p->pDestDb ){
  65566. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  65567. }
  65568. if( destMode==PAGER_JOURNALMODE_WAL ){
  65569. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  65570. }
  65571. }
  65572. if( rc==SQLITE_OK ){
  65573. int nDestTruncate;
  65574. /* Set nDestTruncate to the final number of pages in the destination
  65575. ** database. The complication here is that the destination page
  65576. ** size may be different to the source page size.
  65577. **
  65578. ** If the source page size is smaller than the destination page size,
  65579. ** round up. In this case the call to sqlite3OsTruncate() below will
  65580. ** fix the size of the file. However it is important to call
  65581. ** sqlite3PagerTruncateImage() here so that any pages in the
  65582. ** destination file that lie beyond the nDestTruncate page mark are
  65583. ** journalled by PagerCommitPhaseOne() before they are destroyed
  65584. ** by the file truncation.
  65585. */
  65586. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  65587. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  65588. if( pgszSrc<pgszDest ){
  65589. int ratio = pgszDest/pgszSrc;
  65590. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  65591. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  65592. nDestTruncate--;
  65593. }
  65594. }else{
  65595. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  65596. }
  65597. assert( nDestTruncate>0 );
  65598. if( pgszSrc<pgszDest ){
  65599. /* If the source page-size is smaller than the destination page-size,
  65600. ** two extra things may need to happen:
  65601. **
  65602. ** * The destination may need to be truncated, and
  65603. **
  65604. ** * Data stored on the pages immediately following the
  65605. ** pending-byte page in the source database may need to be
  65606. ** copied into the destination database.
  65607. */
  65608. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  65609. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  65610. Pgno iPg;
  65611. int nDstPage;
  65612. i64 iOff;
  65613. i64 iEnd;
  65614. assert( pFile );
  65615. assert( nDestTruncate==0
  65616. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  65617. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  65618. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  65619. ));
  65620. /* This block ensures that all data required to recreate the original
  65621. ** database has been stored in the journal for pDestPager and the
  65622. ** journal synced to disk. So at this point we may safely modify
  65623. ** the database file in any way, knowing that if a power failure
  65624. ** occurs, the original database will be reconstructed from the
  65625. ** journal file. */
  65626. sqlite3PagerPagecount(pDestPager, &nDstPage);
  65627. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  65628. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  65629. DbPage *pPg;
  65630. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  65631. if( rc==SQLITE_OK ){
  65632. rc = sqlite3PagerWrite(pPg);
  65633. sqlite3PagerUnref(pPg);
  65634. }
  65635. }
  65636. }
  65637. if( rc==SQLITE_OK ){
  65638. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  65639. }
  65640. /* Write the extra pages and truncate the database file as required */
  65641. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  65642. for(
  65643. iOff=PENDING_BYTE+pgszSrc;
  65644. rc==SQLITE_OK && iOff<iEnd;
  65645. iOff+=pgszSrc
  65646. ){
  65647. PgHdr *pSrcPg = 0;
  65648. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  65649. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  65650. if( rc==SQLITE_OK ){
  65651. u8 *zData = sqlite3PagerGetData(pSrcPg);
  65652. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  65653. }
  65654. sqlite3PagerUnref(pSrcPg);
  65655. }
  65656. if( rc==SQLITE_OK ){
  65657. rc = backupTruncateFile(pFile, iSize);
  65658. }
  65659. /* Sync the database file to disk. */
  65660. if( rc==SQLITE_OK ){
  65661. rc = sqlite3PagerSync(pDestPager, 0);
  65662. }
  65663. }else{
  65664. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  65665. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  65666. }
  65667. /* Finish committing the transaction to the destination database. */
  65668. if( SQLITE_OK==rc
  65669. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  65670. ){
  65671. rc = SQLITE_DONE;
  65672. }
  65673. }
  65674. }
  65675. /* If bCloseTrans is true, then this function opened a read transaction
  65676. ** on the source database. Close the read transaction here. There is
  65677. ** no need to check the return values of the btree methods here, as
  65678. ** "committing" a read-only transaction cannot fail.
  65679. */
  65680. if( bCloseTrans ){
  65681. TESTONLY( int rc2 );
  65682. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  65683. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  65684. assert( rc2==SQLITE_OK );
  65685. }
  65686. if( rc==SQLITE_IOERR_NOMEM ){
  65687. rc = SQLITE_NOMEM_BKPT;
  65688. }
  65689. p->rc = rc;
  65690. }
  65691. if( p->pDestDb ){
  65692. sqlite3_mutex_leave(p->pDestDb->mutex);
  65693. }
  65694. sqlite3BtreeLeave(p->pSrc);
  65695. sqlite3_mutex_leave(p->pSrcDb->mutex);
  65696. return rc;
  65697. }
  65698. /*
  65699. ** Release all resources associated with an sqlite3_backup* handle.
  65700. */
  65701. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  65702. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  65703. sqlite3 *pSrcDb; /* Source database connection */
  65704. int rc; /* Value to return */
  65705. /* Enter the mutexes */
  65706. if( p==0 ) return SQLITE_OK;
  65707. pSrcDb = p->pSrcDb;
  65708. sqlite3_mutex_enter(pSrcDb->mutex);
  65709. sqlite3BtreeEnter(p->pSrc);
  65710. if( p->pDestDb ){
  65711. sqlite3_mutex_enter(p->pDestDb->mutex);
  65712. }
  65713. /* Detach this backup from the source pager. */
  65714. if( p->pDestDb ){
  65715. p->pSrc->nBackup--;
  65716. }
  65717. if( p->isAttached ){
  65718. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  65719. while( *pp!=p ){
  65720. pp = &(*pp)->pNext;
  65721. }
  65722. *pp = p->pNext;
  65723. }
  65724. /* If a transaction is still open on the Btree, roll it back. */
  65725. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  65726. /* Set the error code of the destination database handle. */
  65727. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  65728. if( p->pDestDb ){
  65729. sqlite3Error(p->pDestDb, rc);
  65730. /* Exit the mutexes and free the backup context structure. */
  65731. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  65732. }
  65733. sqlite3BtreeLeave(p->pSrc);
  65734. if( p->pDestDb ){
  65735. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  65736. ** call to sqlite3_backup_init() and is destroyed by a call to
  65737. ** sqlite3_backup_finish(). */
  65738. sqlite3_free(p);
  65739. }
  65740. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  65741. return rc;
  65742. }
  65743. /*
  65744. ** Return the number of pages still to be backed up as of the most recent
  65745. ** call to sqlite3_backup_step().
  65746. */
  65747. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  65748. #ifdef SQLITE_ENABLE_API_ARMOR
  65749. if( p==0 ){
  65750. (void)SQLITE_MISUSE_BKPT;
  65751. return 0;
  65752. }
  65753. #endif
  65754. return p->nRemaining;
  65755. }
  65756. /*
  65757. ** Return the total number of pages in the source database as of the most
  65758. ** recent call to sqlite3_backup_step().
  65759. */
  65760. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  65761. #ifdef SQLITE_ENABLE_API_ARMOR
  65762. if( p==0 ){
  65763. (void)SQLITE_MISUSE_BKPT;
  65764. return 0;
  65765. }
  65766. #endif
  65767. return p->nPagecount;
  65768. }
  65769. /*
  65770. ** This function is called after the contents of page iPage of the
  65771. ** source database have been modified. If page iPage has already been
  65772. ** copied into the destination database, then the data written to the
  65773. ** destination is now invalidated. The destination copy of iPage needs
  65774. ** to be updated with the new data before the backup operation is
  65775. ** complete.
  65776. **
  65777. ** It is assumed that the mutex associated with the BtShared object
  65778. ** corresponding to the source database is held when this function is
  65779. ** called.
  65780. */
  65781. static SQLITE_NOINLINE void backupUpdate(
  65782. sqlite3_backup *p,
  65783. Pgno iPage,
  65784. const u8 *aData
  65785. ){
  65786. assert( p!=0 );
  65787. do{
  65788. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65789. if( !isFatalError(p->rc) && iPage<p->iNext ){
  65790. /* The backup process p has already copied page iPage. But now it
  65791. ** has been modified by a transaction on the source pager. Copy
  65792. ** the new data into the backup.
  65793. */
  65794. int rc;
  65795. assert( p->pDestDb );
  65796. sqlite3_mutex_enter(p->pDestDb->mutex);
  65797. rc = backupOnePage(p, iPage, aData, 1);
  65798. sqlite3_mutex_leave(p->pDestDb->mutex);
  65799. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  65800. if( rc!=SQLITE_OK ){
  65801. p->rc = rc;
  65802. }
  65803. }
  65804. }while( (p = p->pNext)!=0 );
  65805. }
  65806. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  65807. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  65808. }
  65809. /*
  65810. ** Restart the backup process. This is called when the pager layer
  65811. ** detects that the database has been modified by an external database
  65812. ** connection. In this case there is no way of knowing which of the
  65813. ** pages that have been copied into the destination database are still
  65814. ** valid and which are not, so the entire process needs to be restarted.
  65815. **
  65816. ** It is assumed that the mutex associated with the BtShared object
  65817. ** corresponding to the source database is held when this function is
  65818. ** called.
  65819. */
  65820. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  65821. sqlite3_backup *p; /* Iterator variable */
  65822. for(p=pBackup; p; p=p->pNext){
  65823. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65824. p->iNext = 1;
  65825. }
  65826. }
  65827. #ifndef SQLITE_OMIT_VACUUM
  65828. /*
  65829. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  65830. ** must be active for both files.
  65831. **
  65832. ** The size of file pTo may be reduced by this operation. If anything
  65833. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  65834. ** transaction is committed before returning.
  65835. */
  65836. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  65837. int rc;
  65838. sqlite3_file *pFd; /* File descriptor for database pTo */
  65839. sqlite3_backup b;
  65840. sqlite3BtreeEnter(pTo);
  65841. sqlite3BtreeEnter(pFrom);
  65842. assert( sqlite3BtreeIsInTrans(pTo) );
  65843. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  65844. if( pFd->pMethods ){
  65845. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  65846. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  65847. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  65848. if( rc ) goto copy_finished;
  65849. }
  65850. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  65851. ** to 0. This is used by the implementations of sqlite3_backup_step()
  65852. ** and sqlite3_backup_finish() to detect that they are being called
  65853. ** from this function, not directly by the user.
  65854. */
  65855. memset(&b, 0, sizeof(b));
  65856. b.pSrcDb = pFrom->db;
  65857. b.pSrc = pFrom;
  65858. b.pDest = pTo;
  65859. b.iNext = 1;
  65860. #ifdef SQLITE_HAS_CODEC
  65861. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  65862. #endif
  65863. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  65864. ** file. By passing this as the number of pages to copy to
  65865. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  65866. ** within a single call (unless an error occurs). The assert() statement
  65867. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  65868. ** or an error code. */
  65869. sqlite3_backup_step(&b, 0x7FFFFFFF);
  65870. assert( b.rc!=SQLITE_OK );
  65871. rc = sqlite3_backup_finish(&b);
  65872. if( rc==SQLITE_OK ){
  65873. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  65874. }else{
  65875. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  65876. }
  65877. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  65878. copy_finished:
  65879. sqlite3BtreeLeave(pFrom);
  65880. sqlite3BtreeLeave(pTo);
  65881. return rc;
  65882. }
  65883. #endif /* SQLITE_OMIT_VACUUM */
  65884. /************** End of backup.c **********************************************/
  65885. /************** Begin file vdbemem.c *****************************************/
  65886. /*
  65887. ** 2004 May 26
  65888. **
  65889. ** The author disclaims copyright to this source code. In place of
  65890. ** a legal notice, here is a blessing:
  65891. **
  65892. ** May you do good and not evil.
  65893. ** May you find forgiveness for yourself and forgive others.
  65894. ** May you share freely, never taking more than you give.
  65895. **
  65896. *************************************************************************
  65897. **
  65898. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  65899. ** stores a single value in the VDBE. Mem is an opaque structure visible
  65900. ** only within the VDBE. Interface routines refer to a Mem using the
  65901. ** name sqlite_value
  65902. */
  65903. /* #include "sqliteInt.h" */
  65904. /* #include "vdbeInt.h" */
  65905. #ifdef SQLITE_DEBUG
  65906. /*
  65907. ** Check invariants on a Mem object.
  65908. **
  65909. ** This routine is intended for use inside of assert() statements, like
  65910. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  65911. */
  65912. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  65913. /* If MEM_Dyn is set then Mem.xDel!=0.
  65914. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  65915. */
  65916. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  65917. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  65918. ** ensure that if Mem.szMalloc>0 then it is safe to do
  65919. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  65920. ** That saves a few cycles in inner loops. */
  65921. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  65922. /* Cannot be both MEM_Int and MEM_Real at the same time */
  65923. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  65924. if( p->flags & MEM_Null ){
  65925. /* Cannot be both MEM_Null and some other type */
  65926. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
  65927. |MEM_RowSet|MEM_Frame|MEM_Agg|MEM_Zero))==0 );
  65928. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  65929. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  65930. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  65931. ** set.
  65932. */
  65933. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  65934. /* This is a pointer type. There may be a flag to indicate what to
  65935. ** do with the pointer. */
  65936. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  65937. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  65938. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  65939. /* No other bits set */
  65940. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
  65941. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  65942. }else{
  65943. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  65944. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  65945. }
  65946. }else{
  65947. /* The MEM_Cleared bit is only allowed on NULLs */
  65948. assert( (p->flags & MEM_Cleared)==0 );
  65949. }
  65950. /* The szMalloc field holds the correct memory allocation size */
  65951. assert( p->szMalloc==0
  65952. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  65953. /* If p holds a string or blob, the Mem.z must point to exactly
  65954. ** one of the following:
  65955. **
  65956. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  65957. ** (2) Memory to be freed using Mem.xDel
  65958. ** (3) An ephemeral string or blob
  65959. ** (4) A static string or blob
  65960. */
  65961. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  65962. assert(
  65963. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  65964. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  65965. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  65966. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  65967. );
  65968. }
  65969. return 1;
  65970. }
  65971. #endif
  65972. /*
  65973. ** If pMem is an object with a valid string representation, this routine
  65974. ** ensures the internal encoding for the string representation is
  65975. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  65976. **
  65977. ** If pMem is not a string object, or the encoding of the string
  65978. ** representation is already stored using the requested encoding, then this
  65979. ** routine is a no-op.
  65980. **
  65981. ** SQLITE_OK is returned if the conversion is successful (or not required).
  65982. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  65983. ** between formats.
  65984. */
  65985. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  65986. #ifndef SQLITE_OMIT_UTF16
  65987. int rc;
  65988. #endif
  65989. assert( (pMem->flags&MEM_RowSet)==0 );
  65990. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  65991. || desiredEnc==SQLITE_UTF16BE );
  65992. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  65993. return SQLITE_OK;
  65994. }
  65995. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65996. #ifdef SQLITE_OMIT_UTF16
  65997. return SQLITE_ERROR;
  65998. #else
  65999. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  66000. ** then the encoding of the value may not have changed.
  66001. */
  66002. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  66003. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  66004. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  66005. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  66006. return rc;
  66007. #endif
  66008. }
  66009. /*
  66010. ** Make sure pMem->z points to a writable allocation of at least
  66011. ** min(n,32) bytes.
  66012. **
  66013. ** If the bPreserve argument is true, then copy of the content of
  66014. ** pMem->z into the new allocation. pMem must be either a string or
  66015. ** blob if bPreserve is true. If bPreserve is false, any prior content
  66016. ** in pMem->z is discarded.
  66017. */
  66018. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  66019. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  66020. assert( (pMem->flags&MEM_RowSet)==0 );
  66021. testcase( pMem->db==0 );
  66022. /* If the bPreserve flag is set to true, then the memory cell must already
  66023. ** contain a valid string or blob value. */
  66024. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  66025. testcase( bPreserve && pMem->z==0 );
  66026. assert( pMem->szMalloc==0
  66027. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  66028. if( n<32 ) n = 32;
  66029. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  66030. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  66031. bPreserve = 0;
  66032. }else{
  66033. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  66034. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  66035. }
  66036. if( pMem->zMalloc==0 ){
  66037. sqlite3VdbeMemSetNull(pMem);
  66038. pMem->z = 0;
  66039. pMem->szMalloc = 0;
  66040. return SQLITE_NOMEM_BKPT;
  66041. }else{
  66042. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  66043. }
  66044. if( bPreserve && pMem->z ){
  66045. assert( pMem->z!=pMem->zMalloc );
  66046. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  66047. }
  66048. if( (pMem->flags&MEM_Dyn)!=0 ){
  66049. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  66050. pMem->xDel((void *)(pMem->z));
  66051. }
  66052. pMem->z = pMem->zMalloc;
  66053. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  66054. return SQLITE_OK;
  66055. }
  66056. /*
  66057. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  66058. ** If pMem->zMalloc already meets or exceeds the requested size, this
  66059. ** routine is a no-op.
  66060. **
  66061. ** Any prior string or blob content in the pMem object may be discarded.
  66062. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  66063. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  66064. ** values are preserved.
  66065. **
  66066. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  66067. ** if unable to complete the resizing.
  66068. */
  66069. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  66070. assert( szNew>0 );
  66071. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  66072. if( pMem->szMalloc<szNew ){
  66073. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  66074. }
  66075. assert( (pMem->flags & MEM_Dyn)==0 );
  66076. pMem->z = pMem->zMalloc;
  66077. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  66078. return SQLITE_OK;
  66079. }
  66080. /*
  66081. ** It is already known that pMem contains an unterminated string.
  66082. ** Add the zero terminator.
  66083. */
  66084. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  66085. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  66086. return SQLITE_NOMEM_BKPT;
  66087. }
  66088. pMem->z[pMem->n] = 0;
  66089. pMem->z[pMem->n+1] = 0;
  66090. pMem->flags |= MEM_Term;
  66091. return SQLITE_OK;
  66092. }
  66093. /*
  66094. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  66095. ** MEM.zMalloc, where it can be safely written.
  66096. **
  66097. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  66098. */
  66099. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  66100. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66101. assert( (pMem->flags&MEM_RowSet)==0 );
  66102. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  66103. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  66104. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  66105. int rc = vdbeMemAddTerminator(pMem);
  66106. if( rc ) return rc;
  66107. }
  66108. }
  66109. pMem->flags &= ~MEM_Ephem;
  66110. #ifdef SQLITE_DEBUG
  66111. pMem->pScopyFrom = 0;
  66112. #endif
  66113. return SQLITE_OK;
  66114. }
  66115. /*
  66116. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  66117. ** blob stored in dynamically allocated space.
  66118. */
  66119. #ifndef SQLITE_OMIT_INCRBLOB
  66120. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  66121. int nByte;
  66122. assert( pMem->flags & MEM_Zero );
  66123. assert( pMem->flags&MEM_Blob );
  66124. assert( (pMem->flags&MEM_RowSet)==0 );
  66125. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66126. /* Set nByte to the number of bytes required to store the expanded blob. */
  66127. nByte = pMem->n + pMem->u.nZero;
  66128. if( nByte<=0 ){
  66129. nByte = 1;
  66130. }
  66131. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  66132. return SQLITE_NOMEM_BKPT;
  66133. }
  66134. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  66135. pMem->n += pMem->u.nZero;
  66136. pMem->flags &= ~(MEM_Zero|MEM_Term);
  66137. return SQLITE_OK;
  66138. }
  66139. #endif
  66140. /*
  66141. ** Make sure the given Mem is \u0000 terminated.
  66142. */
  66143. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  66144. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66145. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  66146. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  66147. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  66148. return SQLITE_OK; /* Nothing to do */
  66149. }else{
  66150. return vdbeMemAddTerminator(pMem);
  66151. }
  66152. }
  66153. /*
  66154. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  66155. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  66156. ** is a no-op.
  66157. **
  66158. ** Existing representations MEM_Int and MEM_Real are invalidated if
  66159. ** bForce is true but are retained if bForce is false.
  66160. **
  66161. ** A MEM_Null value will never be passed to this function. This function is
  66162. ** used for converting values to text for returning to the user (i.e. via
  66163. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  66164. ** keys are strings. In the former case a NULL pointer is returned the
  66165. ** user and the latter is an internal programming error.
  66166. */
  66167. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  66168. int fg = pMem->flags;
  66169. const int nByte = 32;
  66170. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66171. assert( !(fg&MEM_Zero) );
  66172. assert( !(fg&(MEM_Str|MEM_Blob)) );
  66173. assert( fg&(MEM_Int|MEM_Real) );
  66174. assert( (pMem->flags&MEM_RowSet)==0 );
  66175. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66176. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  66177. pMem->enc = 0;
  66178. return SQLITE_NOMEM_BKPT;
  66179. }
  66180. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  66181. ** string representation of the value. Then, if the required encoding
  66182. ** is UTF-16le or UTF-16be do a translation.
  66183. **
  66184. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  66185. */
  66186. if( fg & MEM_Int ){
  66187. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  66188. }else{
  66189. assert( fg & MEM_Real );
  66190. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  66191. }
  66192. pMem->n = sqlite3Strlen30(pMem->z);
  66193. pMem->enc = SQLITE_UTF8;
  66194. pMem->flags |= MEM_Str|MEM_Term;
  66195. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  66196. sqlite3VdbeChangeEncoding(pMem, enc);
  66197. return SQLITE_OK;
  66198. }
  66199. /*
  66200. ** Memory cell pMem contains the context of an aggregate function.
  66201. ** This routine calls the finalize method for that function. The
  66202. ** result of the aggregate is stored back into pMem.
  66203. **
  66204. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  66205. ** otherwise.
  66206. */
  66207. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  66208. int rc = SQLITE_OK;
  66209. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  66210. sqlite3_context ctx;
  66211. Mem t;
  66212. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  66213. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66214. memset(&ctx, 0, sizeof(ctx));
  66215. memset(&t, 0, sizeof(t));
  66216. t.flags = MEM_Null;
  66217. t.db = pMem->db;
  66218. ctx.pOut = &t;
  66219. ctx.pMem = pMem;
  66220. ctx.pFunc = pFunc;
  66221. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  66222. assert( (pMem->flags & MEM_Dyn)==0 );
  66223. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  66224. memcpy(pMem, &t, sizeof(t));
  66225. rc = ctx.isError;
  66226. }
  66227. return rc;
  66228. }
  66229. /*
  66230. ** If the memory cell contains a value that must be freed by
  66231. ** invoking the external callback in Mem.xDel, then this routine
  66232. ** will free that value. It also sets Mem.flags to MEM_Null.
  66233. **
  66234. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  66235. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  66236. ** entry point for releasing Mem resources.
  66237. */
  66238. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  66239. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  66240. assert( VdbeMemDynamic(p) );
  66241. if( p->flags&MEM_Agg ){
  66242. sqlite3VdbeMemFinalize(p, p->u.pDef);
  66243. assert( (p->flags & MEM_Agg)==0 );
  66244. testcase( p->flags & MEM_Dyn );
  66245. }
  66246. if( p->flags&MEM_Dyn ){
  66247. assert( (p->flags&MEM_RowSet)==0 );
  66248. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  66249. p->xDel((void *)p->z);
  66250. }else if( p->flags&MEM_RowSet ){
  66251. sqlite3RowSetClear(p->u.pRowSet);
  66252. }else if( p->flags&MEM_Frame ){
  66253. VdbeFrame *pFrame = p->u.pFrame;
  66254. pFrame->pParent = pFrame->v->pDelFrame;
  66255. pFrame->v->pDelFrame = pFrame;
  66256. }
  66257. p->flags = MEM_Null;
  66258. }
  66259. /*
  66260. ** Release memory held by the Mem p, both external memory cleared
  66261. ** by p->xDel and memory in p->zMalloc.
  66262. **
  66263. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  66264. ** the unusual case where there really is memory in p that needs
  66265. ** to be freed.
  66266. */
  66267. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  66268. if( VdbeMemDynamic(p) ){
  66269. vdbeMemClearExternAndSetNull(p);
  66270. }
  66271. if( p->szMalloc ){
  66272. sqlite3DbFreeNN(p->db, p->zMalloc);
  66273. p->szMalloc = 0;
  66274. }
  66275. p->z = 0;
  66276. }
  66277. /*
  66278. ** Release any memory resources held by the Mem. Both the memory that is
  66279. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  66280. **
  66281. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  66282. ** reset a Mem back to its minimum memory utilization.
  66283. **
  66284. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  66285. ** prior to inserting new content into the Mem.
  66286. */
  66287. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  66288. assert( sqlite3VdbeCheckMemInvariants(p) );
  66289. if( VdbeMemDynamic(p) || p->szMalloc ){
  66290. vdbeMemClear(p);
  66291. }
  66292. }
  66293. /*
  66294. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  66295. ** If the double is out of range of a 64-bit signed integer then
  66296. ** return the closest available 64-bit signed integer.
  66297. */
  66298. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  66299. #ifdef SQLITE_OMIT_FLOATING_POINT
  66300. /* When floating-point is omitted, double and int64 are the same thing */
  66301. return r;
  66302. #else
  66303. /*
  66304. ** Many compilers we encounter do not define constants for the
  66305. ** minimum and maximum 64-bit integers, or they define them
  66306. ** inconsistently. And many do not understand the "LL" notation.
  66307. ** So we define our own static constants here using nothing
  66308. ** larger than a 32-bit integer constant.
  66309. */
  66310. static const i64 maxInt = LARGEST_INT64;
  66311. static const i64 minInt = SMALLEST_INT64;
  66312. if( r<=(double)minInt ){
  66313. return minInt;
  66314. }else if( r>=(double)maxInt ){
  66315. return maxInt;
  66316. }else{
  66317. return (i64)r;
  66318. }
  66319. #endif
  66320. }
  66321. /*
  66322. ** Return some kind of integer value which is the best we can do
  66323. ** at representing the value that *pMem describes as an integer.
  66324. ** If pMem is an integer, then the value is exact. If pMem is
  66325. ** a floating-point then the value returned is the integer part.
  66326. ** If pMem is a string or blob, then we make an attempt to convert
  66327. ** it into an integer and return that. If pMem represents an
  66328. ** an SQL-NULL value, return 0.
  66329. **
  66330. ** If pMem represents a string value, its encoding might be changed.
  66331. */
  66332. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  66333. i64 value = 0;
  66334. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  66335. return value;
  66336. }
  66337. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  66338. int flags;
  66339. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66340. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66341. flags = pMem->flags;
  66342. if( flags & MEM_Int ){
  66343. return pMem->u.i;
  66344. }else if( flags & MEM_Real ){
  66345. return doubleToInt64(pMem->u.r);
  66346. }else if( flags & (MEM_Str|MEM_Blob) ){
  66347. assert( pMem->z || pMem->n==0 );
  66348. return memIntValue(pMem);
  66349. }else{
  66350. return 0;
  66351. }
  66352. }
  66353. /*
  66354. ** Return the best representation of pMem that we can get into a
  66355. ** double. If pMem is already a double or an integer, return its
  66356. ** value. If it is a string or blob, try to convert it to a double.
  66357. ** If it is a NULL, return 0.0.
  66358. */
  66359. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  66360. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  66361. double val = (double)0;
  66362. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  66363. return val;
  66364. }
  66365. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  66366. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66367. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66368. if( pMem->flags & MEM_Real ){
  66369. return pMem->u.r;
  66370. }else if( pMem->flags & MEM_Int ){
  66371. return (double)pMem->u.i;
  66372. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  66373. return memRealValue(pMem);
  66374. }else{
  66375. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  66376. return (double)0;
  66377. }
  66378. }
  66379. /*
  66380. ** The MEM structure is already a MEM_Real. Try to also make it a
  66381. ** MEM_Int if we can.
  66382. */
  66383. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  66384. i64 ix;
  66385. assert( pMem->flags & MEM_Real );
  66386. assert( (pMem->flags & MEM_RowSet)==0 );
  66387. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66388. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66389. ix = doubleToInt64(pMem->u.r);
  66390. /* Only mark the value as an integer if
  66391. **
  66392. ** (1) the round-trip conversion real->int->real is a no-op, and
  66393. ** (2) The integer is neither the largest nor the smallest
  66394. ** possible integer (ticket #3922)
  66395. **
  66396. ** The second and third terms in the following conditional enforces
  66397. ** the second condition under the assumption that addition overflow causes
  66398. ** values to wrap around.
  66399. */
  66400. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  66401. pMem->u.i = ix;
  66402. MemSetTypeFlag(pMem, MEM_Int);
  66403. }
  66404. }
  66405. /*
  66406. ** Convert pMem to type integer. Invalidate any prior representations.
  66407. */
  66408. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  66409. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66410. assert( (pMem->flags & MEM_RowSet)==0 );
  66411. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66412. pMem->u.i = sqlite3VdbeIntValue(pMem);
  66413. MemSetTypeFlag(pMem, MEM_Int);
  66414. return SQLITE_OK;
  66415. }
  66416. /*
  66417. ** Convert pMem so that it is of type MEM_Real.
  66418. ** Invalidate any prior representations.
  66419. */
  66420. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  66421. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66422. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66423. pMem->u.r = sqlite3VdbeRealValue(pMem);
  66424. MemSetTypeFlag(pMem, MEM_Real);
  66425. return SQLITE_OK;
  66426. }
  66427. /*
  66428. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  66429. ** Invalidate any prior representations.
  66430. **
  66431. ** Every effort is made to force the conversion, even if the input
  66432. ** is a string that does not look completely like a number. Convert
  66433. ** as much of the string as we can and ignore the rest.
  66434. */
  66435. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  66436. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  66437. int rc;
  66438. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  66439. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66440. rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
  66441. if( rc==0 ){
  66442. MemSetTypeFlag(pMem, MEM_Int);
  66443. }else{
  66444. i64 i = pMem->u.i;
  66445. sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  66446. if( rc==1 && pMem->u.r==(double)i ){
  66447. pMem->u.i = i;
  66448. MemSetTypeFlag(pMem, MEM_Int);
  66449. }else{
  66450. MemSetTypeFlag(pMem, MEM_Real);
  66451. }
  66452. }
  66453. }
  66454. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  66455. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  66456. return SQLITE_OK;
  66457. }
  66458. /*
  66459. ** Cast the datatype of the value in pMem according to the affinity
  66460. ** "aff". Casting is different from applying affinity in that a cast
  66461. ** is forced. In other words, the value is converted into the desired
  66462. ** affinity even if that results in loss of data. This routine is
  66463. ** used (for example) to implement the SQL "cast()" operator.
  66464. */
  66465. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  66466. if( pMem->flags & MEM_Null ) return;
  66467. switch( aff ){
  66468. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  66469. if( (pMem->flags & MEM_Blob)==0 ){
  66470. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  66471. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  66472. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  66473. }else{
  66474. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  66475. }
  66476. break;
  66477. }
  66478. case SQLITE_AFF_NUMERIC: {
  66479. sqlite3VdbeMemNumerify(pMem);
  66480. break;
  66481. }
  66482. case SQLITE_AFF_INTEGER: {
  66483. sqlite3VdbeMemIntegerify(pMem);
  66484. break;
  66485. }
  66486. case SQLITE_AFF_REAL: {
  66487. sqlite3VdbeMemRealify(pMem);
  66488. break;
  66489. }
  66490. default: {
  66491. assert( aff==SQLITE_AFF_TEXT );
  66492. assert( MEM_Str==(MEM_Blob>>3) );
  66493. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  66494. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  66495. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  66496. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  66497. break;
  66498. }
  66499. }
  66500. }
  66501. /*
  66502. ** Initialize bulk memory to be a consistent Mem object.
  66503. **
  66504. ** The minimum amount of initialization feasible is performed.
  66505. */
  66506. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  66507. assert( (flags & ~MEM_TypeMask)==0 );
  66508. pMem->flags = flags;
  66509. pMem->db = db;
  66510. pMem->szMalloc = 0;
  66511. }
  66512. /*
  66513. ** Delete any previous value and set the value stored in *pMem to NULL.
  66514. **
  66515. ** This routine calls the Mem.xDel destructor to dispose of values that
  66516. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  66517. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  66518. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  66519. **
  66520. ** Use this routine to reset the Mem prior to insert a new value.
  66521. **
  66522. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  66523. */
  66524. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  66525. if( VdbeMemDynamic(pMem) ){
  66526. vdbeMemClearExternAndSetNull(pMem);
  66527. }else{
  66528. pMem->flags = MEM_Null;
  66529. }
  66530. }
  66531. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  66532. sqlite3VdbeMemSetNull((Mem*)p);
  66533. }
  66534. /*
  66535. ** Delete any previous value and set the value to be a BLOB of length
  66536. ** n containing all zeros.
  66537. */
  66538. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  66539. sqlite3VdbeMemRelease(pMem);
  66540. pMem->flags = MEM_Blob|MEM_Zero;
  66541. pMem->n = 0;
  66542. if( n<0 ) n = 0;
  66543. pMem->u.nZero = n;
  66544. pMem->enc = SQLITE_UTF8;
  66545. pMem->z = 0;
  66546. }
  66547. /*
  66548. ** The pMem is known to contain content that needs to be destroyed prior
  66549. ** to a value change. So invoke the destructor, then set the value to
  66550. ** a 64-bit integer.
  66551. */
  66552. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  66553. sqlite3VdbeMemSetNull(pMem);
  66554. pMem->u.i = val;
  66555. pMem->flags = MEM_Int;
  66556. }
  66557. /*
  66558. ** Delete any previous value and set the value stored in *pMem to val,
  66559. ** manifest type INTEGER.
  66560. */
  66561. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  66562. if( VdbeMemDynamic(pMem) ){
  66563. vdbeReleaseAndSetInt64(pMem, val);
  66564. }else{
  66565. pMem->u.i = val;
  66566. pMem->flags = MEM_Int;
  66567. }
  66568. }
  66569. /* A no-op destructor */
  66570. static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  66571. /*
  66572. ** Set the value stored in *pMem should already be a NULL.
  66573. ** Also store a pointer to go with it.
  66574. */
  66575. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  66576. Mem *pMem,
  66577. void *pPtr,
  66578. const char *zPType,
  66579. void (*xDestructor)(void*)
  66580. ){
  66581. assert( pMem->flags==MEM_Null );
  66582. pMem->u.zPType = zPType ? zPType : "";
  66583. pMem->z = pPtr;
  66584. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  66585. pMem->eSubtype = 'p';
  66586. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  66587. }
  66588. #ifndef SQLITE_OMIT_FLOATING_POINT
  66589. /*
  66590. ** Delete any previous value and set the value stored in *pMem to val,
  66591. ** manifest type REAL.
  66592. */
  66593. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  66594. sqlite3VdbeMemSetNull(pMem);
  66595. if( !sqlite3IsNaN(val) ){
  66596. pMem->u.r = val;
  66597. pMem->flags = MEM_Real;
  66598. }
  66599. }
  66600. #endif
  66601. /*
  66602. ** Delete any previous value and set the value of pMem to be an
  66603. ** empty boolean index.
  66604. */
  66605. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  66606. sqlite3 *db = pMem->db;
  66607. assert( db!=0 );
  66608. assert( (pMem->flags & MEM_RowSet)==0 );
  66609. sqlite3VdbeMemRelease(pMem);
  66610. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  66611. if( db->mallocFailed ){
  66612. pMem->flags = MEM_Null;
  66613. pMem->szMalloc = 0;
  66614. }else{
  66615. assert( pMem->zMalloc );
  66616. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  66617. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  66618. assert( pMem->u.pRowSet!=0 );
  66619. pMem->flags = MEM_RowSet;
  66620. }
  66621. }
  66622. /*
  66623. ** Return true if the Mem object contains a TEXT or BLOB that is
  66624. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  66625. */
  66626. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  66627. assert( p->db!=0 );
  66628. if( p->flags & (MEM_Str|MEM_Blob) ){
  66629. int n = p->n;
  66630. if( p->flags & MEM_Zero ){
  66631. n += p->u.nZero;
  66632. }
  66633. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  66634. }
  66635. return 0;
  66636. }
  66637. #ifdef SQLITE_DEBUG
  66638. /*
  66639. ** This routine prepares a memory cell for modification by breaking
  66640. ** its link to a shallow copy and by marking any current shallow
  66641. ** copies of this cell as invalid.
  66642. **
  66643. ** This is used for testing and debugging only - to make sure shallow
  66644. ** copies are not misused.
  66645. */
  66646. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  66647. int i;
  66648. Mem *pX;
  66649. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  66650. if( pX->pScopyFrom==pMem ){
  66651. pX->flags |= MEM_Undefined;
  66652. pX->pScopyFrom = 0;
  66653. }
  66654. }
  66655. pMem->pScopyFrom = 0;
  66656. }
  66657. #endif /* SQLITE_DEBUG */
  66658. /*
  66659. ** Make an shallow copy of pFrom into pTo. Prior contents of
  66660. ** pTo are freed. The pFrom->z field is not duplicated. If
  66661. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  66662. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  66663. */
  66664. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  66665. vdbeMemClearExternAndSetNull(pTo);
  66666. assert( !VdbeMemDynamic(pTo) );
  66667. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  66668. }
  66669. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  66670. assert( (pFrom->flags & MEM_RowSet)==0 );
  66671. assert( pTo->db==pFrom->db );
  66672. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  66673. memcpy(pTo, pFrom, MEMCELLSIZE);
  66674. if( (pFrom->flags&MEM_Static)==0 ){
  66675. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  66676. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  66677. pTo->flags |= srcType;
  66678. }
  66679. }
  66680. /*
  66681. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  66682. ** freed before the copy is made.
  66683. */
  66684. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  66685. int rc = SQLITE_OK;
  66686. assert( (pFrom->flags & MEM_RowSet)==0 );
  66687. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  66688. memcpy(pTo, pFrom, MEMCELLSIZE);
  66689. pTo->flags &= ~MEM_Dyn;
  66690. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  66691. if( 0==(pFrom->flags&MEM_Static) ){
  66692. pTo->flags |= MEM_Ephem;
  66693. rc = sqlite3VdbeMemMakeWriteable(pTo);
  66694. }
  66695. }
  66696. return rc;
  66697. }
  66698. /*
  66699. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  66700. ** freed. If pFrom contains ephemeral data, a copy is made.
  66701. **
  66702. ** pFrom contains an SQL NULL when this routine returns.
  66703. */
  66704. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  66705. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  66706. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  66707. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  66708. sqlite3VdbeMemRelease(pTo);
  66709. memcpy(pTo, pFrom, sizeof(Mem));
  66710. pFrom->flags = MEM_Null;
  66711. pFrom->szMalloc = 0;
  66712. }
  66713. /*
  66714. ** Change the value of a Mem to be a string or a BLOB.
  66715. **
  66716. ** The memory management strategy depends on the value of the xDel
  66717. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  66718. ** string is copied into a (possibly existing) buffer managed by the
  66719. ** Mem structure. Otherwise, any existing buffer is freed and the
  66720. ** pointer copied.
  66721. **
  66722. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  66723. ** size limit) then no memory allocation occurs. If the string can be
  66724. ** stored without allocating memory, then it is. If a memory allocation
  66725. ** is required to store the string, then value of pMem is unchanged. In
  66726. ** either case, SQLITE_TOOBIG is returned.
  66727. */
  66728. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  66729. Mem *pMem, /* Memory cell to set to string value */
  66730. const char *z, /* String pointer */
  66731. int n, /* Bytes in string, or negative */
  66732. u8 enc, /* Encoding of z. 0 for BLOBs */
  66733. void (*xDel)(void*) /* Destructor function */
  66734. ){
  66735. int nByte = n; /* New value for pMem->n */
  66736. int iLimit; /* Maximum allowed string or blob size */
  66737. u16 flags = 0; /* New value for pMem->flags */
  66738. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66739. assert( (pMem->flags & MEM_RowSet)==0 );
  66740. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  66741. if( !z ){
  66742. sqlite3VdbeMemSetNull(pMem);
  66743. return SQLITE_OK;
  66744. }
  66745. if( pMem->db ){
  66746. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  66747. }else{
  66748. iLimit = SQLITE_MAX_LENGTH;
  66749. }
  66750. flags = (enc==0?MEM_Blob:MEM_Str);
  66751. if( nByte<0 ){
  66752. assert( enc!=0 );
  66753. if( enc==SQLITE_UTF8 ){
  66754. nByte = 0x7fffffff & (int)strlen(z);
  66755. if( nByte>iLimit ) nByte = iLimit+1;
  66756. }else{
  66757. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  66758. }
  66759. flags |= MEM_Term;
  66760. }
  66761. /* The following block sets the new values of Mem.z and Mem.xDel. It
  66762. ** also sets a flag in local variable "flags" to indicate the memory
  66763. ** management (one of MEM_Dyn or MEM_Static).
  66764. */
  66765. if( xDel==SQLITE_TRANSIENT ){
  66766. int nAlloc = nByte;
  66767. if( flags&MEM_Term ){
  66768. nAlloc += (enc==SQLITE_UTF8?1:2);
  66769. }
  66770. if( nByte>iLimit ){
  66771. return SQLITE_TOOBIG;
  66772. }
  66773. testcase( nAlloc==0 );
  66774. testcase( nAlloc==31 );
  66775. testcase( nAlloc==32 );
  66776. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  66777. return SQLITE_NOMEM_BKPT;
  66778. }
  66779. memcpy(pMem->z, z, nAlloc);
  66780. }else if( xDel==SQLITE_DYNAMIC ){
  66781. sqlite3VdbeMemRelease(pMem);
  66782. pMem->zMalloc = pMem->z = (char *)z;
  66783. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  66784. }else{
  66785. sqlite3VdbeMemRelease(pMem);
  66786. pMem->z = (char *)z;
  66787. pMem->xDel = xDel;
  66788. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  66789. }
  66790. pMem->n = nByte;
  66791. pMem->flags = flags;
  66792. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  66793. #ifndef SQLITE_OMIT_UTF16
  66794. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  66795. return SQLITE_NOMEM_BKPT;
  66796. }
  66797. #endif
  66798. if( nByte>iLimit ){
  66799. return SQLITE_TOOBIG;
  66800. }
  66801. return SQLITE_OK;
  66802. }
  66803. /*
  66804. ** Move data out of a btree key or data field and into a Mem structure.
  66805. ** The data is payload from the entry that pCur is currently pointing
  66806. ** to. offset and amt determine what portion of the data or key to retrieve.
  66807. ** The result is written into the pMem element.
  66808. **
  66809. ** The pMem object must have been initialized. This routine will use
  66810. ** pMem->zMalloc to hold the content from the btree, if possible. New
  66811. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  66812. ** is responsible for making sure that the pMem object is eventually
  66813. ** destroyed.
  66814. **
  66815. ** If this routine fails for any reason (malloc returns NULL or unable
  66816. ** to read from the disk) then the pMem is left in an inconsistent state.
  66817. */
  66818. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  66819. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66820. u32 offset, /* Offset from the start of data to return bytes from. */
  66821. u32 amt, /* Number of bytes to return. */
  66822. Mem *pMem /* OUT: Return data in this Mem structure. */
  66823. ){
  66824. int rc;
  66825. pMem->flags = MEM_Null;
  66826. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  66827. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  66828. if( rc==SQLITE_OK ){
  66829. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  66830. pMem->flags = MEM_Blob;
  66831. pMem->n = (int)amt;
  66832. }else{
  66833. sqlite3VdbeMemRelease(pMem);
  66834. }
  66835. }
  66836. return rc;
  66837. }
  66838. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  66839. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66840. u32 offset, /* Offset from the start of data to return bytes from. */
  66841. u32 amt, /* Number of bytes to return. */
  66842. Mem *pMem /* OUT: Return data in this Mem structure. */
  66843. ){
  66844. char *zData; /* Data from the btree layer */
  66845. u32 available = 0; /* Number of bytes available on the local btree page */
  66846. int rc = SQLITE_OK; /* Return code */
  66847. assert( sqlite3BtreeCursorIsValid(pCur) );
  66848. assert( !VdbeMemDynamic(pMem) );
  66849. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  66850. ** that both the BtShared and database handle mutexes are held. */
  66851. assert( (pMem->flags & MEM_RowSet)==0 );
  66852. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  66853. assert( zData!=0 );
  66854. if( offset+amt<=available ){
  66855. pMem->z = &zData[offset];
  66856. pMem->flags = MEM_Blob|MEM_Ephem;
  66857. pMem->n = (int)amt;
  66858. }else{
  66859. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  66860. }
  66861. return rc;
  66862. }
  66863. /*
  66864. ** The pVal argument is known to be a value other than NULL.
  66865. ** Convert it into a string with encoding enc and return a pointer
  66866. ** to a zero-terminated version of that string.
  66867. */
  66868. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  66869. assert( pVal!=0 );
  66870. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66871. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66872. assert( (pVal->flags & MEM_RowSet)==0 );
  66873. assert( (pVal->flags & (MEM_Null))==0 );
  66874. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  66875. if( ExpandBlob(pVal) ) return 0;
  66876. pVal->flags |= MEM_Str;
  66877. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  66878. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  66879. }
  66880. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  66881. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  66882. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  66883. return 0;
  66884. }
  66885. }
  66886. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  66887. }else{
  66888. sqlite3VdbeMemStringify(pVal, enc, 0);
  66889. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  66890. }
  66891. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  66892. || pVal->db->mallocFailed );
  66893. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  66894. return pVal->z;
  66895. }else{
  66896. return 0;
  66897. }
  66898. }
  66899. /* This function is only available internally, it is not part of the
  66900. ** external API. It works in a similar way to sqlite3_value_text(),
  66901. ** except the data returned is in the encoding specified by the second
  66902. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  66903. ** SQLITE_UTF8.
  66904. **
  66905. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  66906. ** If that is the case, then the result must be aligned on an even byte
  66907. ** boundary.
  66908. */
  66909. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  66910. if( !pVal ) return 0;
  66911. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66912. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66913. assert( (pVal->flags & MEM_RowSet)==0 );
  66914. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  66915. return pVal->z;
  66916. }
  66917. if( pVal->flags&MEM_Null ){
  66918. return 0;
  66919. }
  66920. return valueToText(pVal, enc);
  66921. }
  66922. /*
  66923. ** Create a new sqlite3_value object.
  66924. */
  66925. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  66926. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  66927. if( p ){
  66928. p->flags = MEM_Null;
  66929. p->db = db;
  66930. }
  66931. return p;
  66932. }
  66933. /*
  66934. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  66935. ** valueNew(). See comments above valueNew() for details.
  66936. */
  66937. struct ValueNewStat4Ctx {
  66938. Parse *pParse;
  66939. Index *pIdx;
  66940. UnpackedRecord **ppRec;
  66941. int iVal;
  66942. };
  66943. /*
  66944. ** Allocate and return a pointer to a new sqlite3_value object. If
  66945. ** the second argument to this function is NULL, the object is allocated
  66946. ** by calling sqlite3ValueNew().
  66947. **
  66948. ** Otherwise, if the second argument is non-zero, then this function is
  66949. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  66950. ** already been allocated, allocate the UnpackedRecord structure that
  66951. ** that function will return to its caller here. Then return a pointer to
  66952. ** an sqlite3_value within the UnpackedRecord.a[] array.
  66953. */
  66954. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  66955. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66956. if( p ){
  66957. UnpackedRecord *pRec = p->ppRec[0];
  66958. if( pRec==0 ){
  66959. Index *pIdx = p->pIdx; /* Index being probed */
  66960. int nByte; /* Bytes of space to allocate */
  66961. int i; /* Counter variable */
  66962. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  66963. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  66964. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  66965. if( pRec ){
  66966. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  66967. if( pRec->pKeyInfo ){
  66968. assert( pRec->pKeyInfo->nAllField==nCol );
  66969. assert( pRec->pKeyInfo->enc==ENC(db) );
  66970. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  66971. for(i=0; i<nCol; i++){
  66972. pRec->aMem[i].flags = MEM_Null;
  66973. pRec->aMem[i].db = db;
  66974. }
  66975. }else{
  66976. sqlite3DbFreeNN(db, pRec);
  66977. pRec = 0;
  66978. }
  66979. }
  66980. if( pRec==0 ) return 0;
  66981. p->ppRec[0] = pRec;
  66982. }
  66983. pRec->nField = p->iVal+1;
  66984. return &pRec->aMem[p->iVal];
  66985. }
  66986. #else
  66987. UNUSED_PARAMETER(p);
  66988. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  66989. return sqlite3ValueNew(db);
  66990. }
  66991. /*
  66992. ** The expression object indicated by the second argument is guaranteed
  66993. ** to be a scalar SQL function. If
  66994. **
  66995. ** * all function arguments are SQL literals,
  66996. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  66997. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  66998. **
  66999. ** then this routine attempts to invoke the SQL function. Assuming no
  67000. ** error occurs, output parameter (*ppVal) is set to point to a value
  67001. ** object containing the result before returning SQLITE_OK.
  67002. **
  67003. ** Affinity aff is applied to the result of the function before returning.
  67004. ** If the result is a text value, the sqlite3_value object uses encoding
  67005. ** enc.
  67006. **
  67007. ** If the conditions above are not met, this function returns SQLITE_OK
  67008. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  67009. ** NULL and an SQLite error code returned.
  67010. */
  67011. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67012. static int valueFromFunction(
  67013. sqlite3 *db, /* The database connection */
  67014. Expr *p, /* The expression to evaluate */
  67015. u8 enc, /* Encoding to use */
  67016. u8 aff, /* Affinity to use */
  67017. sqlite3_value **ppVal, /* Write the new value here */
  67018. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  67019. ){
  67020. sqlite3_context ctx; /* Context object for function invocation */
  67021. sqlite3_value **apVal = 0; /* Function arguments */
  67022. int nVal = 0; /* Size of apVal[] array */
  67023. FuncDef *pFunc = 0; /* Function definition */
  67024. sqlite3_value *pVal = 0; /* New value */
  67025. int rc = SQLITE_OK; /* Return code */
  67026. ExprList *pList = 0; /* Function arguments */
  67027. int i; /* Iterator variable */
  67028. assert( pCtx!=0 );
  67029. assert( (p->flags & EP_TokenOnly)==0 );
  67030. pList = p->x.pList;
  67031. if( pList ) nVal = pList->nExpr;
  67032. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  67033. assert( pFunc );
  67034. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  67035. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  67036. ){
  67037. return SQLITE_OK;
  67038. }
  67039. if( pList ){
  67040. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  67041. if( apVal==0 ){
  67042. rc = SQLITE_NOMEM_BKPT;
  67043. goto value_from_function_out;
  67044. }
  67045. for(i=0; i<nVal; i++){
  67046. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  67047. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  67048. }
  67049. }
  67050. pVal = valueNew(db, pCtx);
  67051. if( pVal==0 ){
  67052. rc = SQLITE_NOMEM_BKPT;
  67053. goto value_from_function_out;
  67054. }
  67055. assert( pCtx->pParse->rc==SQLITE_OK );
  67056. memset(&ctx, 0, sizeof(ctx));
  67057. ctx.pOut = pVal;
  67058. ctx.pFunc = pFunc;
  67059. pFunc->xSFunc(&ctx, nVal, apVal);
  67060. if( ctx.isError ){
  67061. rc = ctx.isError;
  67062. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  67063. }else{
  67064. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  67065. assert( rc==SQLITE_OK );
  67066. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  67067. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  67068. rc = SQLITE_TOOBIG;
  67069. pCtx->pParse->nErr++;
  67070. }
  67071. }
  67072. pCtx->pParse->rc = rc;
  67073. value_from_function_out:
  67074. if( rc!=SQLITE_OK ){
  67075. pVal = 0;
  67076. }
  67077. if( apVal ){
  67078. for(i=0; i<nVal; i++){
  67079. sqlite3ValueFree(apVal[i]);
  67080. }
  67081. sqlite3DbFreeNN(db, apVal);
  67082. }
  67083. *ppVal = pVal;
  67084. return rc;
  67085. }
  67086. #else
  67087. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  67088. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  67089. /*
  67090. ** Extract a value from the supplied expression in the manner described
  67091. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  67092. ** using valueNew().
  67093. **
  67094. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  67095. ** has been allocated, it is freed before returning. Or, if pCtx is not
  67096. ** NULL, it is assumed that the caller will free any allocated object
  67097. ** in all cases.
  67098. */
  67099. static int valueFromExpr(
  67100. sqlite3 *db, /* The database connection */
  67101. Expr *pExpr, /* The expression to evaluate */
  67102. u8 enc, /* Encoding to use */
  67103. u8 affinity, /* Affinity to use */
  67104. sqlite3_value **ppVal, /* Write the new value here */
  67105. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  67106. ){
  67107. int op;
  67108. char *zVal = 0;
  67109. sqlite3_value *pVal = 0;
  67110. int negInt = 1;
  67111. const char *zNeg = "";
  67112. int rc = SQLITE_OK;
  67113. assert( pExpr!=0 );
  67114. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  67115. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  67116. /* Compressed expressions only appear when parsing the DEFAULT clause
  67117. ** on a table column definition, and hence only when pCtx==0. This
  67118. ** check ensures that an EP_TokenOnly expression is never passed down
  67119. ** into valueFromFunction(). */
  67120. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  67121. if( op==TK_CAST ){
  67122. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  67123. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  67124. testcase( rc!=SQLITE_OK );
  67125. if( *ppVal ){
  67126. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  67127. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  67128. }
  67129. return rc;
  67130. }
  67131. /* Handle negative integers in a single step. This is needed in the
  67132. ** case when the value is -9223372036854775808.
  67133. */
  67134. if( op==TK_UMINUS
  67135. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  67136. pExpr = pExpr->pLeft;
  67137. op = pExpr->op;
  67138. negInt = -1;
  67139. zNeg = "-";
  67140. }
  67141. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  67142. pVal = valueNew(db, pCtx);
  67143. if( pVal==0 ) goto no_mem;
  67144. if( ExprHasProperty(pExpr, EP_IntValue) ){
  67145. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  67146. }else{
  67147. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  67148. if( zVal==0 ) goto no_mem;
  67149. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  67150. }
  67151. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  67152. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  67153. }else{
  67154. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  67155. }
  67156. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  67157. if( enc!=SQLITE_UTF8 ){
  67158. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  67159. }
  67160. }else if( op==TK_UMINUS ) {
  67161. /* This branch happens for multiple negative signs. Ex: -(-5) */
  67162. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  67163. && pVal!=0
  67164. ){
  67165. sqlite3VdbeMemNumerify(pVal);
  67166. if( pVal->flags & MEM_Real ){
  67167. pVal->u.r = -pVal->u.r;
  67168. }else if( pVal->u.i==SMALLEST_INT64 ){
  67169. pVal->u.r = -(double)SMALLEST_INT64;
  67170. MemSetTypeFlag(pVal, MEM_Real);
  67171. }else{
  67172. pVal->u.i = -pVal->u.i;
  67173. }
  67174. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  67175. }
  67176. }else if( op==TK_NULL ){
  67177. pVal = valueNew(db, pCtx);
  67178. if( pVal==0 ) goto no_mem;
  67179. sqlite3VdbeMemNumerify(pVal);
  67180. }
  67181. #ifndef SQLITE_OMIT_BLOB_LITERAL
  67182. else if( op==TK_BLOB ){
  67183. int nVal;
  67184. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  67185. assert( pExpr->u.zToken[1]=='\'' );
  67186. pVal = valueNew(db, pCtx);
  67187. if( !pVal ) goto no_mem;
  67188. zVal = &pExpr->u.zToken[2];
  67189. nVal = sqlite3Strlen30(zVal)-1;
  67190. assert( zVal[nVal]=='\'' );
  67191. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  67192. 0, SQLITE_DYNAMIC);
  67193. }
  67194. #endif
  67195. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67196. else if( op==TK_FUNCTION && pCtx!=0 ){
  67197. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  67198. }
  67199. #endif
  67200. *ppVal = pVal;
  67201. return rc;
  67202. no_mem:
  67203. sqlite3OomFault(db);
  67204. sqlite3DbFree(db, zVal);
  67205. assert( *ppVal==0 );
  67206. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67207. if( pCtx==0 ) sqlite3ValueFree(pVal);
  67208. #else
  67209. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  67210. #endif
  67211. return SQLITE_NOMEM_BKPT;
  67212. }
  67213. /*
  67214. ** Create a new sqlite3_value object, containing the value of pExpr.
  67215. **
  67216. ** This only works for very simple expressions that consist of one constant
  67217. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  67218. ** be converted directly into a value, then the value is allocated and
  67219. ** a pointer written to *ppVal. The caller is responsible for deallocating
  67220. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  67221. ** cannot be converted to a value, then *ppVal is set to NULL.
  67222. */
  67223. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  67224. sqlite3 *db, /* The database connection */
  67225. Expr *pExpr, /* The expression to evaluate */
  67226. u8 enc, /* Encoding to use */
  67227. u8 affinity, /* Affinity to use */
  67228. sqlite3_value **ppVal /* Write the new value here */
  67229. ){
  67230. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  67231. }
  67232. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67233. /*
  67234. ** The implementation of the sqlite_record() function. This function accepts
  67235. ** a single argument of any type. The return value is a formatted database
  67236. ** record (a blob) containing the argument value.
  67237. **
  67238. ** This is used to convert the value stored in the 'sample' column of the
  67239. ** sqlite_stat3 table to the record format SQLite uses internally.
  67240. */
  67241. static void recordFunc(
  67242. sqlite3_context *context,
  67243. int argc,
  67244. sqlite3_value **argv
  67245. ){
  67246. const int file_format = 1;
  67247. u32 iSerial; /* Serial type */
  67248. int nSerial; /* Bytes of space for iSerial as varint */
  67249. u32 nVal; /* Bytes of space required for argv[0] */
  67250. int nRet;
  67251. sqlite3 *db;
  67252. u8 *aRet;
  67253. UNUSED_PARAMETER( argc );
  67254. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  67255. nSerial = sqlite3VarintLen(iSerial);
  67256. db = sqlite3_context_db_handle(context);
  67257. nRet = 1 + nSerial + nVal;
  67258. aRet = sqlite3DbMallocRawNN(db, nRet);
  67259. if( aRet==0 ){
  67260. sqlite3_result_error_nomem(context);
  67261. }else{
  67262. aRet[0] = nSerial+1;
  67263. putVarint32(&aRet[1], iSerial);
  67264. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  67265. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  67266. sqlite3DbFreeNN(db, aRet);
  67267. }
  67268. }
  67269. /*
  67270. ** Register built-in functions used to help read ANALYZE data.
  67271. */
  67272. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  67273. static FuncDef aAnalyzeTableFuncs[] = {
  67274. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  67275. };
  67276. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  67277. }
  67278. /*
  67279. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  67280. **
  67281. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  67282. ** pAlloc if one does not exist and the new value is added to the
  67283. ** UnpackedRecord object.
  67284. **
  67285. ** A value is extracted in the following cases:
  67286. **
  67287. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  67288. **
  67289. ** * The expression is a bound variable, and this is a reprepare, or
  67290. **
  67291. ** * The expression is a literal value.
  67292. **
  67293. ** On success, *ppVal is made to point to the extracted value. The caller
  67294. ** is responsible for ensuring that the value is eventually freed.
  67295. */
  67296. static int stat4ValueFromExpr(
  67297. Parse *pParse, /* Parse context */
  67298. Expr *pExpr, /* The expression to extract a value from */
  67299. u8 affinity, /* Affinity to use */
  67300. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  67301. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  67302. ){
  67303. int rc = SQLITE_OK;
  67304. sqlite3_value *pVal = 0;
  67305. sqlite3 *db = pParse->db;
  67306. /* Skip over any TK_COLLATE nodes */
  67307. pExpr = sqlite3ExprSkipCollate(pExpr);
  67308. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  67309. if( !pExpr ){
  67310. pVal = valueNew(db, pAlloc);
  67311. if( pVal ){
  67312. sqlite3VdbeMemSetNull((Mem*)pVal);
  67313. }
  67314. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  67315. Vdbe *v;
  67316. int iBindVar = pExpr->iColumn;
  67317. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  67318. if( (v = pParse->pReprepare)!=0 ){
  67319. pVal = valueNew(db, pAlloc);
  67320. if( pVal ){
  67321. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  67322. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  67323. pVal->db = pParse->db;
  67324. }
  67325. }
  67326. }else{
  67327. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  67328. }
  67329. assert( pVal==0 || pVal->db==db );
  67330. *ppVal = pVal;
  67331. return rc;
  67332. }
  67333. /*
  67334. ** This function is used to allocate and populate UnpackedRecord
  67335. ** structures intended to be compared against sample index keys stored
  67336. ** in the sqlite_stat4 table.
  67337. **
  67338. ** A single call to this function populates zero or more fields of the
  67339. ** record starting with field iVal (fields are numbered from left to
  67340. ** right starting with 0). A single field is populated if:
  67341. **
  67342. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  67343. **
  67344. ** * The expression is a bound variable, and this is a reprepare, or
  67345. **
  67346. ** * The sqlite3ValueFromExpr() function is able to extract a value
  67347. ** from the expression (i.e. the expression is a literal value).
  67348. **
  67349. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  67350. ** vector components that match either of the two latter criteria listed
  67351. ** above.
  67352. **
  67353. ** Before any value is appended to the record, the affinity of the
  67354. ** corresponding column within index pIdx is applied to it. Before
  67355. ** this function returns, output parameter *pnExtract is set to the
  67356. ** number of values appended to the record.
  67357. **
  67358. ** When this function is called, *ppRec must either point to an object
  67359. ** allocated by an earlier call to this function, or must be NULL. If it
  67360. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  67361. ** is allocated (and *ppRec set to point to it) before returning.
  67362. **
  67363. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  67364. ** error if a value cannot be extracted from pExpr. If an error does
  67365. ** occur, an SQLite error code is returned.
  67366. */
  67367. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  67368. Parse *pParse, /* Parse context */
  67369. Index *pIdx, /* Index being probed */
  67370. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  67371. Expr *pExpr, /* The expression to extract a value from */
  67372. int nElem, /* Maximum number of values to append */
  67373. int iVal, /* Array element to populate */
  67374. int *pnExtract /* OUT: Values appended to the record */
  67375. ){
  67376. int rc = SQLITE_OK;
  67377. int nExtract = 0;
  67378. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  67379. int i;
  67380. struct ValueNewStat4Ctx alloc;
  67381. alloc.pParse = pParse;
  67382. alloc.pIdx = pIdx;
  67383. alloc.ppRec = ppRec;
  67384. for(i=0; i<nElem; i++){
  67385. sqlite3_value *pVal = 0;
  67386. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  67387. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  67388. alloc.iVal = iVal+i;
  67389. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  67390. if( !pVal ) break;
  67391. nExtract++;
  67392. }
  67393. }
  67394. *pnExtract = nExtract;
  67395. return rc;
  67396. }
  67397. /*
  67398. ** Attempt to extract a value from expression pExpr using the methods
  67399. ** as described for sqlite3Stat4ProbeSetValue() above.
  67400. **
  67401. ** If successful, set *ppVal to point to a new value object and return
  67402. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  67403. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  67404. ** does occur, return an SQLite error code. The final value of *ppVal
  67405. ** is undefined in this case.
  67406. */
  67407. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  67408. Parse *pParse, /* Parse context */
  67409. Expr *pExpr, /* The expression to extract a value from */
  67410. u8 affinity, /* Affinity to use */
  67411. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  67412. ){
  67413. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  67414. }
  67415. /*
  67416. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  67417. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  67418. ** sqlite3_value object is allocated.
  67419. **
  67420. ** If *ppVal is initially NULL then the caller is responsible for
  67421. ** ensuring that the value written into *ppVal is eventually freed.
  67422. */
  67423. SQLITE_PRIVATE int sqlite3Stat4Column(
  67424. sqlite3 *db, /* Database handle */
  67425. const void *pRec, /* Pointer to buffer containing record */
  67426. int nRec, /* Size of buffer pRec in bytes */
  67427. int iCol, /* Column to extract */
  67428. sqlite3_value **ppVal /* OUT: Extracted value */
  67429. ){
  67430. u32 t; /* a column type code */
  67431. int nHdr; /* Size of the header in the record */
  67432. int iHdr; /* Next unread header byte */
  67433. int iField; /* Next unread data byte */
  67434. int szField; /* Size of the current data field */
  67435. int i; /* Column index */
  67436. u8 *a = (u8*)pRec; /* Typecast byte array */
  67437. Mem *pMem = *ppVal; /* Write result into this Mem object */
  67438. assert( iCol>0 );
  67439. iHdr = getVarint32(a, nHdr);
  67440. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  67441. iField = nHdr;
  67442. for(i=0; i<=iCol; i++){
  67443. iHdr += getVarint32(&a[iHdr], t);
  67444. testcase( iHdr==nHdr );
  67445. testcase( iHdr==nHdr+1 );
  67446. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  67447. szField = sqlite3VdbeSerialTypeLen(t);
  67448. iField += szField;
  67449. }
  67450. testcase( iField==nRec );
  67451. testcase( iField==nRec+1 );
  67452. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  67453. if( pMem==0 ){
  67454. pMem = *ppVal = sqlite3ValueNew(db);
  67455. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  67456. }
  67457. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  67458. pMem->enc = ENC(db);
  67459. return SQLITE_OK;
  67460. }
  67461. /*
  67462. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  67463. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  67464. ** the object.
  67465. */
  67466. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  67467. if( pRec ){
  67468. int i;
  67469. int nCol = pRec->pKeyInfo->nAllField;
  67470. Mem *aMem = pRec->aMem;
  67471. sqlite3 *db = aMem[0].db;
  67472. for(i=0; i<nCol; i++){
  67473. sqlite3VdbeMemRelease(&aMem[i]);
  67474. }
  67475. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  67476. sqlite3DbFreeNN(db, pRec);
  67477. }
  67478. }
  67479. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  67480. /*
  67481. ** Change the string value of an sqlite3_value object
  67482. */
  67483. SQLITE_PRIVATE void sqlite3ValueSetStr(
  67484. sqlite3_value *v, /* Value to be set */
  67485. int n, /* Length of string z */
  67486. const void *z, /* Text of the new string */
  67487. u8 enc, /* Encoding to use */
  67488. void (*xDel)(void*) /* Destructor for the string */
  67489. ){
  67490. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  67491. }
  67492. /*
  67493. ** Free an sqlite3_value object
  67494. */
  67495. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  67496. if( !v ) return;
  67497. sqlite3VdbeMemRelease((Mem *)v);
  67498. sqlite3DbFreeNN(((Mem*)v)->db, v);
  67499. }
  67500. /*
  67501. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  67502. ** sqlite3_value object assuming that it uses the encoding "enc".
  67503. ** The valueBytes() routine is a helper function.
  67504. */
  67505. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  67506. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  67507. }
  67508. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  67509. Mem *p = (Mem*)pVal;
  67510. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  67511. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  67512. return p->n;
  67513. }
  67514. if( (p->flags & MEM_Blob)!=0 ){
  67515. if( p->flags & MEM_Zero ){
  67516. return p->n + p->u.nZero;
  67517. }else{
  67518. return p->n;
  67519. }
  67520. }
  67521. if( p->flags & MEM_Null ) return 0;
  67522. return valueBytes(pVal, enc);
  67523. }
  67524. /************** End of vdbemem.c *********************************************/
  67525. /************** Begin file vdbeaux.c *****************************************/
  67526. /*
  67527. ** 2003 September 6
  67528. **
  67529. ** The author disclaims copyright to this source code. In place of
  67530. ** a legal notice, here is a blessing:
  67531. **
  67532. ** May you do good and not evil.
  67533. ** May you find forgiveness for yourself and forgive others.
  67534. ** May you share freely, never taking more than you give.
  67535. **
  67536. *************************************************************************
  67537. ** This file contains code used for creating, destroying, and populating
  67538. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  67539. */
  67540. /* #include "sqliteInt.h" */
  67541. /* #include "vdbeInt.h" */
  67542. /*
  67543. ** Create a new virtual database engine.
  67544. */
  67545. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  67546. sqlite3 *db = pParse->db;
  67547. Vdbe *p;
  67548. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  67549. if( p==0 ) return 0;
  67550. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  67551. p->db = db;
  67552. if( db->pVdbe ){
  67553. db->pVdbe->pPrev = p;
  67554. }
  67555. p->pNext = db->pVdbe;
  67556. p->pPrev = 0;
  67557. db->pVdbe = p;
  67558. p->magic = VDBE_MAGIC_INIT;
  67559. p->pParse = pParse;
  67560. pParse->pVdbe = p;
  67561. assert( pParse->aLabel==0 );
  67562. assert( pParse->nLabel==0 );
  67563. assert( pParse->nOpAlloc==0 );
  67564. assert( pParse->szOpAlloc==0 );
  67565. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  67566. return p;
  67567. }
  67568. /*
  67569. ** Change the error string stored in Vdbe.zErrMsg
  67570. */
  67571. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  67572. va_list ap;
  67573. sqlite3DbFree(p->db, p->zErrMsg);
  67574. va_start(ap, zFormat);
  67575. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  67576. va_end(ap);
  67577. }
  67578. /*
  67579. ** Remember the SQL string for a prepared statement.
  67580. */
  67581. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  67582. if( p==0 ) return;
  67583. p->prepFlags = prepFlags;
  67584. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  67585. p->expmask = 0;
  67586. }
  67587. assert( p->zSql==0 );
  67588. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  67589. }
  67590. /*
  67591. ** Swap all content between two VDBE structures.
  67592. */
  67593. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  67594. Vdbe tmp, *pTmp;
  67595. char *zTmp;
  67596. assert( pA->db==pB->db );
  67597. tmp = *pA;
  67598. *pA = *pB;
  67599. *pB = tmp;
  67600. pTmp = pA->pNext;
  67601. pA->pNext = pB->pNext;
  67602. pB->pNext = pTmp;
  67603. pTmp = pA->pPrev;
  67604. pA->pPrev = pB->pPrev;
  67605. pB->pPrev = pTmp;
  67606. zTmp = pA->zSql;
  67607. pA->zSql = pB->zSql;
  67608. pB->zSql = zTmp;
  67609. pB->expmask = pA->expmask;
  67610. pB->prepFlags = pA->prepFlags;
  67611. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  67612. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  67613. }
  67614. /*
  67615. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  67616. ** than its current size. nOp is guaranteed to be less than or equal
  67617. ** to 1024/sizeof(Op).
  67618. **
  67619. ** If an out-of-memory error occurs while resizing the array, return
  67620. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  67621. ** unchanged (this is so that any opcodes already allocated can be
  67622. ** correctly deallocated along with the rest of the Vdbe).
  67623. */
  67624. static int growOpArray(Vdbe *v, int nOp){
  67625. VdbeOp *pNew;
  67626. Parse *p = v->pParse;
  67627. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  67628. ** more frequent reallocs and hence provide more opportunities for
  67629. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  67630. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  67631. ** by the minimum* amount required until the size reaches 512. Normal
  67632. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  67633. ** size of the op array or add 1KB of space, whichever is smaller. */
  67634. #ifdef SQLITE_TEST_REALLOC_STRESS
  67635. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  67636. #else
  67637. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  67638. UNUSED_PARAMETER(nOp);
  67639. #endif
  67640. /* Ensure that the size of a VDBE does not grow too large */
  67641. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  67642. sqlite3OomFault(p->db);
  67643. return SQLITE_NOMEM;
  67644. }
  67645. assert( nOp<=(1024/sizeof(Op)) );
  67646. assert( nNew>=(p->nOpAlloc+nOp) );
  67647. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  67648. if( pNew ){
  67649. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  67650. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  67651. v->aOp = pNew;
  67652. }
  67653. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  67654. }
  67655. #ifdef SQLITE_DEBUG
  67656. /* This routine is just a convenient place to set a breakpoint that will
  67657. ** fire after each opcode is inserted and displayed using
  67658. ** "PRAGMA vdbe_addoptrace=on".
  67659. */
  67660. static void test_addop_breakpoint(void){
  67661. static int n = 0;
  67662. n++;
  67663. }
  67664. #endif
  67665. /*
  67666. ** Add a new instruction to the list of instructions current in the
  67667. ** VDBE. Return the address of the new instruction.
  67668. **
  67669. ** Parameters:
  67670. **
  67671. ** p Pointer to the VDBE
  67672. **
  67673. ** op The opcode for this instruction
  67674. **
  67675. ** p1, p2, p3 Operands
  67676. **
  67677. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  67678. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  67679. ** operand.
  67680. */
  67681. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  67682. assert( p->pParse->nOpAlloc<=p->nOp );
  67683. if( growOpArray(p, 1) ) return 1;
  67684. assert( p->pParse->nOpAlloc>p->nOp );
  67685. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67686. }
  67687. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  67688. int i;
  67689. VdbeOp *pOp;
  67690. i = p->nOp;
  67691. assert( p->magic==VDBE_MAGIC_INIT );
  67692. assert( op>=0 && op<0xff );
  67693. if( p->pParse->nOpAlloc<=i ){
  67694. return growOp3(p, op, p1, p2, p3);
  67695. }
  67696. p->nOp++;
  67697. pOp = &p->aOp[i];
  67698. pOp->opcode = (u8)op;
  67699. pOp->p5 = 0;
  67700. pOp->p1 = p1;
  67701. pOp->p2 = p2;
  67702. pOp->p3 = p3;
  67703. pOp->p4.p = 0;
  67704. pOp->p4type = P4_NOTUSED;
  67705. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67706. pOp->zComment = 0;
  67707. #endif
  67708. #ifdef SQLITE_DEBUG
  67709. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  67710. int jj, kk;
  67711. Parse *pParse = p->pParse;
  67712. for(jj=kk=0; jj<pParse->nColCache; jj++){
  67713. struct yColCache *x = pParse->aColCache + jj;
  67714. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  67715. kk++;
  67716. }
  67717. if( kk ) printf("\n");
  67718. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  67719. test_addop_breakpoint();
  67720. }
  67721. #endif
  67722. #ifdef VDBE_PROFILE
  67723. pOp->cycles = 0;
  67724. pOp->cnt = 0;
  67725. #endif
  67726. #ifdef SQLITE_VDBE_COVERAGE
  67727. pOp->iSrcLine = 0;
  67728. #endif
  67729. return i;
  67730. }
  67731. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  67732. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  67733. }
  67734. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  67735. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  67736. }
  67737. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  67738. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  67739. }
  67740. /* Generate code for an unconditional jump to instruction iDest
  67741. */
  67742. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  67743. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  67744. }
  67745. /* Generate code to cause the string zStr to be loaded into
  67746. ** register iDest
  67747. */
  67748. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  67749. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  67750. }
  67751. /*
  67752. ** Generate code that initializes multiple registers to string or integer
  67753. ** constants. The registers begin with iDest and increase consecutively.
  67754. ** One register is initialized for each characgter in zTypes[]. For each
  67755. ** "s" character in zTypes[], the register is a string if the argument is
  67756. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  67757. ** in zTypes[], the register is initialized to an integer.
  67758. **
  67759. ** If the input string does not end with "X" then an OP_ResultRow instruction
  67760. ** is generated for the values inserted.
  67761. */
  67762. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  67763. va_list ap;
  67764. int i;
  67765. char c;
  67766. va_start(ap, zTypes);
  67767. for(i=0; (c = zTypes[i])!=0; i++){
  67768. if( c=='s' ){
  67769. const char *z = va_arg(ap, const char*);
  67770. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  67771. }else if( c=='i' ){
  67772. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  67773. }else{
  67774. goto skip_op_resultrow;
  67775. }
  67776. }
  67777. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  67778. skip_op_resultrow:
  67779. va_end(ap);
  67780. }
  67781. /*
  67782. ** Add an opcode that includes the p4 value as a pointer.
  67783. */
  67784. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  67785. Vdbe *p, /* Add the opcode to this VM */
  67786. int op, /* The new opcode */
  67787. int p1, /* The P1 operand */
  67788. int p2, /* The P2 operand */
  67789. int p3, /* The P3 operand */
  67790. const char *zP4, /* The P4 operand */
  67791. int p4type /* P4 operand type */
  67792. ){
  67793. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67794. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  67795. return addr;
  67796. }
  67797. /*
  67798. ** Add an opcode that includes the p4 value with a P4_INT64 or
  67799. ** P4_REAL type.
  67800. */
  67801. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  67802. Vdbe *p, /* Add the opcode to this VM */
  67803. int op, /* The new opcode */
  67804. int p1, /* The P1 operand */
  67805. int p2, /* The P2 operand */
  67806. int p3, /* The P3 operand */
  67807. const u8 *zP4, /* The P4 operand */
  67808. int p4type /* P4 operand type */
  67809. ){
  67810. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  67811. if( p4copy ) memcpy(p4copy, zP4, 8);
  67812. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  67813. }
  67814. /*
  67815. ** Add an OP_ParseSchema opcode. This routine is broken out from
  67816. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  67817. ** as having been used.
  67818. **
  67819. ** The zWhere string must have been obtained from sqlite3_malloc().
  67820. ** This routine will take ownership of the allocated memory.
  67821. */
  67822. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  67823. int j;
  67824. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  67825. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  67826. }
  67827. /*
  67828. ** Add an opcode that includes the p4 value as an integer.
  67829. */
  67830. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  67831. Vdbe *p, /* Add the opcode to this VM */
  67832. int op, /* The new opcode */
  67833. int p1, /* The P1 operand */
  67834. int p2, /* The P2 operand */
  67835. int p3, /* The P3 operand */
  67836. int p4 /* The P4 operand as an integer */
  67837. ){
  67838. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67839. if( p->db->mallocFailed==0 ){
  67840. VdbeOp *pOp = &p->aOp[addr];
  67841. pOp->p4type = P4_INT32;
  67842. pOp->p4.i = p4;
  67843. }
  67844. return addr;
  67845. }
  67846. /* Insert the end of a co-routine
  67847. */
  67848. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  67849. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  67850. /* Clear the temporary register cache, thereby ensuring that each
  67851. ** co-routine has its own independent set of registers, because co-routines
  67852. ** might expect their registers to be preserved across an OP_Yield, and
  67853. ** that could cause problems if two or more co-routines are using the same
  67854. ** temporary register.
  67855. */
  67856. v->pParse->nTempReg = 0;
  67857. v->pParse->nRangeReg = 0;
  67858. }
  67859. /*
  67860. ** Create a new symbolic label for an instruction that has yet to be
  67861. ** coded. The symbolic label is really just a negative number. The
  67862. ** label can be used as the P2 value of an operation. Later, when
  67863. ** the label is resolved to a specific address, the VDBE will scan
  67864. ** through its operation list and change all values of P2 which match
  67865. ** the label into the resolved address.
  67866. **
  67867. ** The VDBE knows that a P2 value is a label because labels are
  67868. ** always negative and P2 values are suppose to be non-negative.
  67869. ** Hence, a negative P2 value is a label that has yet to be resolved.
  67870. **
  67871. ** Zero is returned if a malloc() fails.
  67872. */
  67873. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  67874. Parse *p = v->pParse;
  67875. int i = p->nLabel++;
  67876. assert( v->magic==VDBE_MAGIC_INIT );
  67877. if( (i & (i-1))==0 ){
  67878. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  67879. (i*2+1)*sizeof(p->aLabel[0]));
  67880. }
  67881. if( p->aLabel ){
  67882. p->aLabel[i] = -1;
  67883. }
  67884. return ADDR(i);
  67885. }
  67886. /*
  67887. ** Resolve label "x" to be the address of the next instruction to
  67888. ** be inserted. The parameter "x" must have been obtained from
  67889. ** a prior call to sqlite3VdbeMakeLabel().
  67890. */
  67891. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  67892. Parse *p = v->pParse;
  67893. int j = ADDR(x);
  67894. assert( v->magic==VDBE_MAGIC_INIT );
  67895. assert( j<p->nLabel );
  67896. assert( j>=0 );
  67897. if( p->aLabel ){
  67898. p->aLabel[j] = v->nOp;
  67899. }
  67900. }
  67901. /*
  67902. ** Mark the VDBE as one that can only be run one time.
  67903. */
  67904. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  67905. p->runOnlyOnce = 1;
  67906. }
  67907. /*
  67908. ** Mark the VDBE as one that can only be run multiple times.
  67909. */
  67910. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  67911. p->runOnlyOnce = 0;
  67912. }
  67913. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  67914. /*
  67915. ** The following type and function are used to iterate through all opcodes
  67916. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  67917. ** invoke directly or indirectly. It should be used as follows:
  67918. **
  67919. ** Op *pOp;
  67920. ** VdbeOpIter sIter;
  67921. **
  67922. ** memset(&sIter, 0, sizeof(sIter));
  67923. ** sIter.v = v; // v is of type Vdbe*
  67924. ** while( (pOp = opIterNext(&sIter)) ){
  67925. ** // Do something with pOp
  67926. ** }
  67927. ** sqlite3DbFree(v->db, sIter.apSub);
  67928. **
  67929. */
  67930. typedef struct VdbeOpIter VdbeOpIter;
  67931. struct VdbeOpIter {
  67932. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  67933. SubProgram **apSub; /* Array of subprograms */
  67934. int nSub; /* Number of entries in apSub */
  67935. int iAddr; /* Address of next instruction to return */
  67936. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  67937. };
  67938. static Op *opIterNext(VdbeOpIter *p){
  67939. Vdbe *v = p->v;
  67940. Op *pRet = 0;
  67941. Op *aOp;
  67942. int nOp;
  67943. if( p->iSub<=p->nSub ){
  67944. if( p->iSub==0 ){
  67945. aOp = v->aOp;
  67946. nOp = v->nOp;
  67947. }else{
  67948. aOp = p->apSub[p->iSub-1]->aOp;
  67949. nOp = p->apSub[p->iSub-1]->nOp;
  67950. }
  67951. assert( p->iAddr<nOp );
  67952. pRet = &aOp[p->iAddr];
  67953. p->iAddr++;
  67954. if( p->iAddr==nOp ){
  67955. p->iSub++;
  67956. p->iAddr = 0;
  67957. }
  67958. if( pRet->p4type==P4_SUBPROGRAM ){
  67959. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  67960. int j;
  67961. for(j=0; j<p->nSub; j++){
  67962. if( p->apSub[j]==pRet->p4.pProgram ) break;
  67963. }
  67964. if( j==p->nSub ){
  67965. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  67966. if( !p->apSub ){
  67967. pRet = 0;
  67968. }else{
  67969. p->apSub[p->nSub++] = pRet->p4.pProgram;
  67970. }
  67971. }
  67972. }
  67973. }
  67974. return pRet;
  67975. }
  67976. /*
  67977. ** Check if the program stored in the VM associated with pParse may
  67978. ** throw an ABORT exception (causing the statement, but not entire transaction
  67979. ** to be rolled back). This condition is true if the main program or any
  67980. ** sub-programs contains any of the following:
  67981. **
  67982. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67983. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67984. ** * OP_Destroy
  67985. ** * OP_VUpdate
  67986. ** * OP_VRename
  67987. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  67988. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  67989. ** (for CREATE TABLE AS SELECT ...)
  67990. **
  67991. ** Then check that the value of Parse.mayAbort is true if an
  67992. ** ABORT may be thrown, or false otherwise. Return true if it does
  67993. ** match, or false otherwise. This function is intended to be used as
  67994. ** part of an assert statement in the compiler. Similar to:
  67995. **
  67996. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  67997. */
  67998. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  67999. int hasAbort = 0;
  68000. int hasFkCounter = 0;
  68001. int hasCreateTable = 0;
  68002. int hasInitCoroutine = 0;
  68003. Op *pOp;
  68004. VdbeOpIter sIter;
  68005. memset(&sIter, 0, sizeof(sIter));
  68006. sIter.v = v;
  68007. while( (pOp = opIterNext(&sIter))!=0 ){
  68008. int opcode = pOp->opcode;
  68009. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  68010. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  68011. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  68012. ){
  68013. hasAbort = 1;
  68014. break;
  68015. }
  68016. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  68017. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  68018. #ifndef SQLITE_OMIT_FOREIGN_KEY
  68019. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  68020. hasFkCounter = 1;
  68021. }
  68022. #endif
  68023. }
  68024. sqlite3DbFree(v->db, sIter.apSub);
  68025. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  68026. ** If malloc failed, then the while() loop above may not have iterated
  68027. ** through all opcodes and hasAbort may be set incorrectly. Return
  68028. ** true for this case to prevent the assert() in the callers frame
  68029. ** from failing. */
  68030. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  68031. || (hasCreateTable && hasInitCoroutine) );
  68032. }
  68033. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  68034. /*
  68035. ** This routine is called after all opcodes have been inserted. It loops
  68036. ** through all the opcodes and fixes up some details.
  68037. **
  68038. ** (1) For each jump instruction with a negative P2 value (a label)
  68039. ** resolve the P2 value to an actual address.
  68040. **
  68041. ** (2) Compute the maximum number of arguments used by any SQL function
  68042. ** and store that value in *pMaxFuncArgs.
  68043. **
  68044. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  68045. ** indicate what the prepared statement actually does.
  68046. **
  68047. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  68048. **
  68049. ** (5) Reclaim the memory allocated for storing labels.
  68050. **
  68051. ** This routine will only function correctly if the mkopcodeh.tcl generator
  68052. ** script numbers the opcodes correctly. Changes to this routine must be
  68053. ** coordinated with changes to mkopcodeh.tcl.
  68054. */
  68055. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  68056. int nMaxArgs = *pMaxFuncArgs;
  68057. Op *pOp;
  68058. Parse *pParse = p->pParse;
  68059. int *aLabel = pParse->aLabel;
  68060. p->readOnly = 1;
  68061. p->bIsReader = 0;
  68062. pOp = &p->aOp[p->nOp-1];
  68063. while(1){
  68064. /* Only JUMP opcodes and the short list of special opcodes in the switch
  68065. ** below need to be considered. The mkopcodeh.tcl generator script groups
  68066. ** all these opcodes together near the front of the opcode list. Skip
  68067. ** any opcode that does not need processing by virtual of the fact that
  68068. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  68069. */
  68070. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  68071. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  68072. ** cases from this switch! */
  68073. switch( pOp->opcode ){
  68074. case OP_Transaction: {
  68075. if( pOp->p2!=0 ) p->readOnly = 0;
  68076. /* fall thru */
  68077. }
  68078. case OP_AutoCommit:
  68079. case OP_Savepoint: {
  68080. p->bIsReader = 1;
  68081. break;
  68082. }
  68083. #ifndef SQLITE_OMIT_WAL
  68084. case OP_Checkpoint:
  68085. #endif
  68086. case OP_Vacuum:
  68087. case OP_JournalMode: {
  68088. p->readOnly = 0;
  68089. p->bIsReader = 1;
  68090. break;
  68091. }
  68092. case OP_Next:
  68093. case OP_NextIfOpen:
  68094. case OP_SorterNext: {
  68095. pOp->p4.xAdvance = sqlite3BtreeNext;
  68096. pOp->p4type = P4_ADVANCE;
  68097. /* The code generator never codes any of these opcodes as a jump
  68098. ** to a label. They are always coded as a jump backwards to a
  68099. ** known address */
  68100. assert( pOp->p2>=0 );
  68101. break;
  68102. }
  68103. case OP_Prev:
  68104. case OP_PrevIfOpen: {
  68105. pOp->p4.xAdvance = sqlite3BtreePrevious;
  68106. pOp->p4type = P4_ADVANCE;
  68107. /* The code generator never codes any of these opcodes as a jump
  68108. ** to a label. They are always coded as a jump backwards to a
  68109. ** known address */
  68110. assert( pOp->p2>=0 );
  68111. break;
  68112. }
  68113. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68114. case OP_VUpdate: {
  68115. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  68116. break;
  68117. }
  68118. case OP_VFilter: {
  68119. int n;
  68120. assert( (pOp - p->aOp) >= 3 );
  68121. assert( pOp[-1].opcode==OP_Integer );
  68122. n = pOp[-1].p1;
  68123. if( n>nMaxArgs ) nMaxArgs = n;
  68124. /* Fall through into the default case */
  68125. }
  68126. #endif
  68127. default: {
  68128. if( pOp->p2<0 ){
  68129. /* The mkopcodeh.tcl script has so arranged things that the only
  68130. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  68131. ** have non-negative values for P2. */
  68132. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  68133. assert( ADDR(pOp->p2)<pParse->nLabel );
  68134. pOp->p2 = aLabel[ADDR(pOp->p2)];
  68135. }
  68136. break;
  68137. }
  68138. }
  68139. /* The mkopcodeh.tcl script has so arranged things that the only
  68140. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  68141. ** have non-negative values for P2. */
  68142. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  68143. }
  68144. if( pOp==p->aOp ) break;
  68145. pOp--;
  68146. }
  68147. sqlite3DbFree(p->db, pParse->aLabel);
  68148. pParse->aLabel = 0;
  68149. pParse->nLabel = 0;
  68150. *pMaxFuncArgs = nMaxArgs;
  68151. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  68152. }
  68153. /*
  68154. ** Return the address of the next instruction to be inserted.
  68155. */
  68156. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  68157. assert( p->magic==VDBE_MAGIC_INIT );
  68158. return p->nOp;
  68159. }
  68160. /*
  68161. ** Verify that at least N opcode slots are available in p without
  68162. ** having to malloc for more space (except when compiled using
  68163. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  68164. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  68165. ** fail due to a OOM fault and hence that the return value from
  68166. ** sqlite3VdbeAddOpList() will always be non-NULL.
  68167. */
  68168. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  68169. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  68170. assert( p->nOp + N <= p->pParse->nOpAlloc );
  68171. }
  68172. #endif
  68173. /*
  68174. ** Verify that the VM passed as the only argument does not contain
  68175. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  68176. ** by code in pragma.c to ensure that the implementation of certain
  68177. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  68178. ** script.
  68179. */
  68180. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  68181. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  68182. int i;
  68183. for(i=0; i<p->nOp; i++){
  68184. assert( p->aOp[i].opcode!=OP_ResultRow );
  68185. }
  68186. }
  68187. #endif
  68188. /*
  68189. ** This function returns a pointer to the array of opcodes associated with
  68190. ** the Vdbe passed as the first argument. It is the callers responsibility
  68191. ** to arrange for the returned array to be eventually freed using the
  68192. ** vdbeFreeOpArray() function.
  68193. **
  68194. ** Before returning, *pnOp is set to the number of entries in the returned
  68195. ** array. Also, *pnMaxArg is set to the larger of its current value and
  68196. ** the number of entries in the Vdbe.apArg[] array required to execute the
  68197. ** returned program.
  68198. */
  68199. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  68200. VdbeOp *aOp = p->aOp;
  68201. assert( aOp && !p->db->mallocFailed );
  68202. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  68203. assert( DbMaskAllZero(p->btreeMask) );
  68204. resolveP2Values(p, pnMaxArg);
  68205. *pnOp = p->nOp;
  68206. p->aOp = 0;
  68207. return aOp;
  68208. }
  68209. /*
  68210. ** Add a whole list of operations to the operation stack. Return a
  68211. ** pointer to the first operation inserted.
  68212. **
  68213. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  68214. ** so that the jump target is relative to the first operation inserted.
  68215. */
  68216. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  68217. Vdbe *p, /* Add opcodes to the prepared statement */
  68218. int nOp, /* Number of opcodes to add */
  68219. VdbeOpList const *aOp, /* The opcodes to be added */
  68220. int iLineno /* Source-file line number of first opcode */
  68221. ){
  68222. int i;
  68223. VdbeOp *pOut, *pFirst;
  68224. assert( nOp>0 );
  68225. assert( p->magic==VDBE_MAGIC_INIT );
  68226. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  68227. return 0;
  68228. }
  68229. pFirst = pOut = &p->aOp[p->nOp];
  68230. for(i=0; i<nOp; i++, aOp++, pOut++){
  68231. pOut->opcode = aOp->opcode;
  68232. pOut->p1 = aOp->p1;
  68233. pOut->p2 = aOp->p2;
  68234. assert( aOp->p2>=0 );
  68235. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  68236. pOut->p2 += p->nOp;
  68237. }
  68238. pOut->p3 = aOp->p3;
  68239. pOut->p4type = P4_NOTUSED;
  68240. pOut->p4.p = 0;
  68241. pOut->p5 = 0;
  68242. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68243. pOut->zComment = 0;
  68244. #endif
  68245. #ifdef SQLITE_VDBE_COVERAGE
  68246. pOut->iSrcLine = iLineno+i;
  68247. #else
  68248. (void)iLineno;
  68249. #endif
  68250. #ifdef SQLITE_DEBUG
  68251. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  68252. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  68253. }
  68254. #endif
  68255. }
  68256. p->nOp += nOp;
  68257. return pFirst;
  68258. }
  68259. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  68260. /*
  68261. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  68262. */
  68263. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  68264. Vdbe *p, /* VM to add scanstatus() to */
  68265. int addrExplain, /* Address of OP_Explain (or 0) */
  68266. int addrLoop, /* Address of loop counter */
  68267. int addrVisit, /* Address of rows visited counter */
  68268. LogEst nEst, /* Estimated number of output rows */
  68269. const char *zName /* Name of table or index being scanned */
  68270. ){
  68271. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  68272. ScanStatus *aNew;
  68273. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  68274. if( aNew ){
  68275. ScanStatus *pNew = &aNew[p->nScan++];
  68276. pNew->addrExplain = addrExplain;
  68277. pNew->addrLoop = addrLoop;
  68278. pNew->addrVisit = addrVisit;
  68279. pNew->nEst = nEst;
  68280. pNew->zName = sqlite3DbStrDup(p->db, zName);
  68281. p->aScan = aNew;
  68282. }
  68283. }
  68284. #endif
  68285. /*
  68286. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  68287. ** for a specific instruction.
  68288. */
  68289. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  68290. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  68291. }
  68292. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  68293. sqlite3VdbeGetOp(p,addr)->p1 = val;
  68294. }
  68295. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  68296. sqlite3VdbeGetOp(p,addr)->p2 = val;
  68297. }
  68298. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  68299. sqlite3VdbeGetOp(p,addr)->p3 = val;
  68300. }
  68301. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  68302. assert( p->nOp>0 || p->db->mallocFailed );
  68303. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  68304. }
  68305. /*
  68306. ** Change the P2 operand of instruction addr so that it points to
  68307. ** the address of the next instruction to be coded.
  68308. */
  68309. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  68310. sqlite3VdbeChangeP2(p, addr, p->nOp);
  68311. }
  68312. /*
  68313. ** If the input FuncDef structure is ephemeral, then free it. If
  68314. ** the FuncDef is not ephermal, then do nothing.
  68315. */
  68316. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  68317. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  68318. sqlite3DbFreeNN(db, pDef);
  68319. }
  68320. }
  68321. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  68322. /*
  68323. ** Delete a P4 value if necessary.
  68324. */
  68325. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  68326. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  68327. sqlite3DbFreeNN(db, p);
  68328. }
  68329. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  68330. freeEphemeralFunction(db, p->pFunc);
  68331. sqlite3DbFreeNN(db, p);
  68332. }
  68333. static void freeP4(sqlite3 *db, int p4type, void *p4){
  68334. assert( db );
  68335. switch( p4type ){
  68336. case P4_FUNCCTX: {
  68337. freeP4FuncCtx(db, (sqlite3_context*)p4);
  68338. break;
  68339. }
  68340. case P4_REAL:
  68341. case P4_INT64:
  68342. case P4_DYNAMIC:
  68343. case P4_INTARRAY: {
  68344. sqlite3DbFree(db, p4);
  68345. break;
  68346. }
  68347. case P4_KEYINFO: {
  68348. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  68349. break;
  68350. }
  68351. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  68352. case P4_EXPR: {
  68353. sqlite3ExprDelete(db, (Expr*)p4);
  68354. break;
  68355. }
  68356. #endif
  68357. case P4_FUNCDEF: {
  68358. freeEphemeralFunction(db, (FuncDef*)p4);
  68359. break;
  68360. }
  68361. case P4_MEM: {
  68362. if( db->pnBytesFreed==0 ){
  68363. sqlite3ValueFree((sqlite3_value*)p4);
  68364. }else{
  68365. freeP4Mem(db, (Mem*)p4);
  68366. }
  68367. break;
  68368. }
  68369. case P4_VTAB : {
  68370. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  68371. break;
  68372. }
  68373. }
  68374. }
  68375. /*
  68376. ** Free the space allocated for aOp and any p4 values allocated for the
  68377. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  68378. ** nOp entries.
  68379. */
  68380. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  68381. if( aOp ){
  68382. Op *pOp;
  68383. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  68384. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  68385. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68386. sqlite3DbFree(db, pOp->zComment);
  68387. #endif
  68388. }
  68389. sqlite3DbFreeNN(db, aOp);
  68390. }
  68391. }
  68392. /*
  68393. ** Link the SubProgram object passed as the second argument into the linked
  68394. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  68395. ** objects when the VM is no longer required.
  68396. */
  68397. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  68398. p->pNext = pVdbe->pProgram;
  68399. pVdbe->pProgram = p;
  68400. }
  68401. /*
  68402. ** Change the opcode at addr into OP_Noop
  68403. */
  68404. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  68405. VdbeOp *pOp;
  68406. if( p->db->mallocFailed ) return 0;
  68407. assert( addr>=0 && addr<p->nOp );
  68408. pOp = &p->aOp[addr];
  68409. freeP4(p->db, pOp->p4type, pOp->p4.p);
  68410. pOp->p4type = P4_NOTUSED;
  68411. pOp->p4.z = 0;
  68412. pOp->opcode = OP_Noop;
  68413. return 1;
  68414. }
  68415. /*
  68416. ** If the last opcode is "op" and it is not a jump destination,
  68417. ** then remove it. Return true if and only if an opcode was removed.
  68418. */
  68419. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  68420. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  68421. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  68422. }else{
  68423. return 0;
  68424. }
  68425. }
  68426. /*
  68427. ** Change the value of the P4 operand for a specific instruction.
  68428. ** This routine is useful when a large program is loaded from a
  68429. ** static array using sqlite3VdbeAddOpList but we want to make a
  68430. ** few minor changes to the program.
  68431. **
  68432. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  68433. ** the string is made into memory obtained from sqlite3_malloc().
  68434. ** A value of n==0 means copy bytes of zP4 up to and including the
  68435. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  68436. **
  68437. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  68438. ** to a string or structure that is guaranteed to exist for the lifetime of
  68439. ** the Vdbe. In these cases we can just copy the pointer.
  68440. **
  68441. ** If addr<0 then change P4 on the most recently inserted instruction.
  68442. */
  68443. static void SQLITE_NOINLINE vdbeChangeP4Full(
  68444. Vdbe *p,
  68445. Op *pOp,
  68446. const char *zP4,
  68447. int n
  68448. ){
  68449. if( pOp->p4type ){
  68450. freeP4(p->db, pOp->p4type, pOp->p4.p);
  68451. pOp->p4type = 0;
  68452. pOp->p4.p = 0;
  68453. }
  68454. if( n<0 ){
  68455. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  68456. }else{
  68457. if( n==0 ) n = sqlite3Strlen30(zP4);
  68458. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  68459. pOp->p4type = P4_DYNAMIC;
  68460. }
  68461. }
  68462. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  68463. Op *pOp;
  68464. sqlite3 *db;
  68465. assert( p!=0 );
  68466. db = p->db;
  68467. assert( p->magic==VDBE_MAGIC_INIT );
  68468. assert( p->aOp!=0 || db->mallocFailed );
  68469. if( db->mallocFailed ){
  68470. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  68471. return;
  68472. }
  68473. assert( p->nOp>0 );
  68474. assert( addr<p->nOp );
  68475. if( addr<0 ){
  68476. addr = p->nOp - 1;
  68477. }
  68478. pOp = &p->aOp[addr];
  68479. if( n>=0 || pOp->p4type ){
  68480. vdbeChangeP4Full(p, pOp, zP4, n);
  68481. return;
  68482. }
  68483. if( n==P4_INT32 ){
  68484. /* Note: this cast is safe, because the origin data point was an int
  68485. ** that was cast to a (const char *). */
  68486. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  68487. pOp->p4type = P4_INT32;
  68488. }else if( zP4!=0 ){
  68489. assert( n<0 );
  68490. pOp->p4.p = (void*)zP4;
  68491. pOp->p4type = (signed char)n;
  68492. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  68493. }
  68494. }
  68495. /*
  68496. ** Change the P4 operand of the most recently coded instruction
  68497. ** to the value defined by the arguments. This is a high-speed
  68498. ** version of sqlite3VdbeChangeP4().
  68499. **
  68500. ** The P4 operand must not have been previously defined. And the new
  68501. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  68502. ** those cases.
  68503. */
  68504. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  68505. VdbeOp *pOp;
  68506. assert( n!=P4_INT32 && n!=P4_VTAB );
  68507. assert( n<=0 );
  68508. if( p->db->mallocFailed ){
  68509. freeP4(p->db, n, pP4);
  68510. }else{
  68511. assert( pP4!=0 );
  68512. assert( p->nOp>0 );
  68513. pOp = &p->aOp[p->nOp-1];
  68514. assert( pOp->p4type==P4_NOTUSED );
  68515. pOp->p4type = n;
  68516. pOp->p4.p = pP4;
  68517. }
  68518. }
  68519. /*
  68520. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  68521. ** index given.
  68522. */
  68523. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  68524. Vdbe *v = pParse->pVdbe;
  68525. KeyInfo *pKeyInfo;
  68526. assert( v!=0 );
  68527. assert( pIdx!=0 );
  68528. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  68529. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  68530. }
  68531. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68532. /*
  68533. ** Change the comment on the most recently coded instruction. Or
  68534. ** insert a No-op and add the comment to that new instruction. This
  68535. ** makes the code easier to read during debugging. None of this happens
  68536. ** in a production build.
  68537. */
  68538. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  68539. assert( p->nOp>0 || p->aOp==0 );
  68540. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  68541. if( p->nOp ){
  68542. assert( p->aOp );
  68543. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  68544. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  68545. }
  68546. }
  68547. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  68548. va_list ap;
  68549. if( p ){
  68550. va_start(ap, zFormat);
  68551. vdbeVComment(p, zFormat, ap);
  68552. va_end(ap);
  68553. }
  68554. }
  68555. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  68556. va_list ap;
  68557. if( p ){
  68558. sqlite3VdbeAddOp0(p, OP_Noop);
  68559. va_start(ap, zFormat);
  68560. vdbeVComment(p, zFormat, ap);
  68561. va_end(ap);
  68562. }
  68563. }
  68564. #endif /* NDEBUG */
  68565. #ifdef SQLITE_VDBE_COVERAGE
  68566. /*
  68567. ** Set the value if the iSrcLine field for the previously coded instruction.
  68568. */
  68569. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  68570. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  68571. }
  68572. #endif /* SQLITE_VDBE_COVERAGE */
  68573. /*
  68574. ** Return the opcode for a given address. If the address is -1, then
  68575. ** return the most recently inserted opcode.
  68576. **
  68577. ** If a memory allocation error has occurred prior to the calling of this
  68578. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  68579. ** is readable but not writable, though it is cast to a writable value.
  68580. ** The return of a dummy opcode allows the call to continue functioning
  68581. ** after an OOM fault without having to check to see if the return from
  68582. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  68583. ** dummy will never be written to. This is verified by code inspection and
  68584. ** by running with Valgrind.
  68585. */
  68586. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  68587. /* C89 specifies that the constant "dummy" will be initialized to all
  68588. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  68589. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  68590. assert( p->magic==VDBE_MAGIC_INIT );
  68591. if( addr<0 ){
  68592. addr = p->nOp - 1;
  68593. }
  68594. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  68595. if( p->db->mallocFailed ){
  68596. return (VdbeOp*)&dummy;
  68597. }else{
  68598. return &p->aOp[addr];
  68599. }
  68600. }
  68601. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  68602. /*
  68603. ** Return an integer value for one of the parameters to the opcode pOp
  68604. ** determined by character c.
  68605. */
  68606. static int translateP(char c, const Op *pOp){
  68607. if( c=='1' ) return pOp->p1;
  68608. if( c=='2' ) return pOp->p2;
  68609. if( c=='3' ) return pOp->p3;
  68610. if( c=='4' ) return pOp->p4.i;
  68611. return pOp->p5;
  68612. }
  68613. /*
  68614. ** Compute a string for the "comment" field of a VDBE opcode listing.
  68615. **
  68616. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  68617. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  68618. ** absence of other comments, this synopsis becomes the comment on the opcode.
  68619. ** Some translation occurs:
  68620. **
  68621. ** "PX" -> "r[X]"
  68622. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  68623. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  68624. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  68625. */
  68626. static int displayComment(
  68627. const Op *pOp, /* The opcode to be commented */
  68628. const char *zP4, /* Previously obtained value for P4 */
  68629. char *zTemp, /* Write result here */
  68630. int nTemp /* Space available in zTemp[] */
  68631. ){
  68632. const char *zOpName;
  68633. const char *zSynopsis;
  68634. int nOpName;
  68635. int ii, jj;
  68636. char zAlt[50];
  68637. zOpName = sqlite3OpcodeName(pOp->opcode);
  68638. nOpName = sqlite3Strlen30(zOpName);
  68639. if( zOpName[nOpName+1] ){
  68640. int seenCom = 0;
  68641. char c;
  68642. zSynopsis = zOpName += nOpName + 1;
  68643. if( strncmp(zSynopsis,"IF ",3)==0 ){
  68644. if( pOp->p5 & SQLITE_STOREP2 ){
  68645. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  68646. }else{
  68647. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  68648. }
  68649. zSynopsis = zAlt;
  68650. }
  68651. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  68652. if( c=='P' ){
  68653. c = zSynopsis[++ii];
  68654. if( c=='4' ){
  68655. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  68656. }else if( c=='X' ){
  68657. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  68658. seenCom = 1;
  68659. }else{
  68660. int v1 = translateP(c, pOp);
  68661. int v2;
  68662. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  68663. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  68664. ii += 3;
  68665. jj += sqlite3Strlen30(zTemp+jj);
  68666. v2 = translateP(zSynopsis[ii], pOp);
  68667. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  68668. ii += 2;
  68669. v2++;
  68670. }
  68671. if( v2>1 ){
  68672. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  68673. }
  68674. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  68675. ii += 4;
  68676. }
  68677. }
  68678. jj += sqlite3Strlen30(zTemp+jj);
  68679. }else{
  68680. zTemp[jj++] = c;
  68681. }
  68682. }
  68683. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  68684. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  68685. jj += sqlite3Strlen30(zTemp+jj);
  68686. }
  68687. if( jj<nTemp ) zTemp[jj] = 0;
  68688. }else if( pOp->zComment ){
  68689. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  68690. jj = sqlite3Strlen30(zTemp);
  68691. }else{
  68692. zTemp[0] = 0;
  68693. jj = 0;
  68694. }
  68695. return jj;
  68696. }
  68697. #endif /* SQLITE_DEBUG */
  68698. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  68699. /*
  68700. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  68701. ** that can be displayed in the P4 column of EXPLAIN output.
  68702. */
  68703. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  68704. const char *zOp = 0;
  68705. switch( pExpr->op ){
  68706. case TK_STRING:
  68707. sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
  68708. break;
  68709. case TK_INTEGER:
  68710. sqlite3XPrintf(p, "%d", pExpr->u.iValue);
  68711. break;
  68712. case TK_NULL:
  68713. sqlite3XPrintf(p, "NULL");
  68714. break;
  68715. case TK_REGISTER: {
  68716. sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
  68717. break;
  68718. }
  68719. case TK_COLUMN: {
  68720. if( pExpr->iColumn<0 ){
  68721. sqlite3XPrintf(p, "rowid");
  68722. }else{
  68723. sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
  68724. }
  68725. break;
  68726. }
  68727. case TK_LT: zOp = "LT"; break;
  68728. case TK_LE: zOp = "LE"; break;
  68729. case TK_GT: zOp = "GT"; break;
  68730. case TK_GE: zOp = "GE"; break;
  68731. case TK_NE: zOp = "NE"; break;
  68732. case TK_EQ: zOp = "EQ"; break;
  68733. case TK_IS: zOp = "IS"; break;
  68734. case TK_ISNOT: zOp = "ISNOT"; break;
  68735. case TK_AND: zOp = "AND"; break;
  68736. case TK_OR: zOp = "OR"; break;
  68737. case TK_PLUS: zOp = "ADD"; break;
  68738. case TK_STAR: zOp = "MUL"; break;
  68739. case TK_MINUS: zOp = "SUB"; break;
  68740. case TK_REM: zOp = "REM"; break;
  68741. case TK_BITAND: zOp = "BITAND"; break;
  68742. case TK_BITOR: zOp = "BITOR"; break;
  68743. case TK_SLASH: zOp = "DIV"; break;
  68744. case TK_LSHIFT: zOp = "LSHIFT"; break;
  68745. case TK_RSHIFT: zOp = "RSHIFT"; break;
  68746. case TK_CONCAT: zOp = "CONCAT"; break;
  68747. case TK_UMINUS: zOp = "MINUS"; break;
  68748. case TK_UPLUS: zOp = "PLUS"; break;
  68749. case TK_BITNOT: zOp = "BITNOT"; break;
  68750. case TK_NOT: zOp = "NOT"; break;
  68751. case TK_ISNULL: zOp = "ISNULL"; break;
  68752. case TK_NOTNULL: zOp = "NOTNULL"; break;
  68753. default:
  68754. sqlite3XPrintf(p, "%s", "expr");
  68755. break;
  68756. }
  68757. if( zOp ){
  68758. sqlite3XPrintf(p, "%s(", zOp);
  68759. displayP4Expr(p, pExpr->pLeft);
  68760. if( pExpr->pRight ){
  68761. sqlite3StrAccumAppend(p, ",", 1);
  68762. displayP4Expr(p, pExpr->pRight);
  68763. }
  68764. sqlite3StrAccumAppend(p, ")", 1);
  68765. }
  68766. }
  68767. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  68768. #if VDBE_DISPLAY_P4
  68769. /*
  68770. ** Compute a string that describes the P4 parameter for an opcode.
  68771. ** Use zTemp for any required temporary buffer space.
  68772. */
  68773. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  68774. char *zP4 = zTemp;
  68775. StrAccum x;
  68776. assert( nTemp>=20 );
  68777. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  68778. switch( pOp->p4type ){
  68779. case P4_KEYINFO: {
  68780. int j;
  68781. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  68782. assert( pKeyInfo->aSortOrder!=0 );
  68783. sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
  68784. for(j=0; j<pKeyInfo->nKeyField; j++){
  68785. CollSeq *pColl = pKeyInfo->aColl[j];
  68786. const char *zColl = pColl ? pColl->zName : "";
  68787. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  68788. sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  68789. }
  68790. sqlite3StrAccumAppend(&x, ")", 1);
  68791. break;
  68792. }
  68793. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  68794. case P4_EXPR: {
  68795. displayP4Expr(&x, pOp->p4.pExpr);
  68796. break;
  68797. }
  68798. #endif
  68799. case P4_COLLSEQ: {
  68800. CollSeq *pColl = pOp->p4.pColl;
  68801. sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
  68802. break;
  68803. }
  68804. case P4_FUNCDEF: {
  68805. FuncDef *pDef = pOp->p4.pFunc;
  68806. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68807. break;
  68808. }
  68809. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68810. case P4_FUNCCTX: {
  68811. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  68812. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68813. break;
  68814. }
  68815. #endif
  68816. case P4_INT64: {
  68817. sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
  68818. break;
  68819. }
  68820. case P4_INT32: {
  68821. sqlite3XPrintf(&x, "%d", pOp->p4.i);
  68822. break;
  68823. }
  68824. case P4_REAL: {
  68825. sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
  68826. break;
  68827. }
  68828. case P4_MEM: {
  68829. Mem *pMem = pOp->p4.pMem;
  68830. if( pMem->flags & MEM_Str ){
  68831. zP4 = pMem->z;
  68832. }else if( pMem->flags & MEM_Int ){
  68833. sqlite3XPrintf(&x, "%lld", pMem->u.i);
  68834. }else if( pMem->flags & MEM_Real ){
  68835. sqlite3XPrintf(&x, "%.16g", pMem->u.r);
  68836. }else if( pMem->flags & MEM_Null ){
  68837. zP4 = "NULL";
  68838. }else{
  68839. assert( pMem->flags & MEM_Blob );
  68840. zP4 = "(blob)";
  68841. }
  68842. break;
  68843. }
  68844. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68845. case P4_VTAB: {
  68846. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  68847. sqlite3XPrintf(&x, "vtab:%p", pVtab);
  68848. break;
  68849. }
  68850. #endif
  68851. case P4_INTARRAY: {
  68852. int i;
  68853. int *ai = pOp->p4.ai;
  68854. int n = ai[0]; /* The first element of an INTARRAY is always the
  68855. ** count of the number of elements to follow */
  68856. for(i=1; i<=n; i++){
  68857. sqlite3XPrintf(&x, ",%d", ai[i]);
  68858. }
  68859. zTemp[0] = '[';
  68860. sqlite3StrAccumAppend(&x, "]", 1);
  68861. break;
  68862. }
  68863. case P4_SUBPROGRAM: {
  68864. sqlite3XPrintf(&x, "program");
  68865. break;
  68866. }
  68867. case P4_ADVANCE: {
  68868. zTemp[0] = 0;
  68869. break;
  68870. }
  68871. case P4_TABLE: {
  68872. sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
  68873. break;
  68874. }
  68875. default: {
  68876. zP4 = pOp->p4.z;
  68877. if( zP4==0 ){
  68878. zP4 = zTemp;
  68879. zTemp[0] = 0;
  68880. }
  68881. }
  68882. }
  68883. sqlite3StrAccumFinish(&x);
  68884. assert( zP4!=0 );
  68885. return zP4;
  68886. }
  68887. #endif /* VDBE_DISPLAY_P4 */
  68888. /*
  68889. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  68890. **
  68891. ** The prepared statements need to know in advance the complete set of
  68892. ** attached databases that will be use. A mask of these databases
  68893. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  68894. ** p->btreeMask of databases that will require a lock.
  68895. */
  68896. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  68897. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  68898. assert( i<(int)sizeof(p->btreeMask)*8 );
  68899. DbMaskSet(p->btreeMask, i);
  68900. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  68901. DbMaskSet(p->lockMask, i);
  68902. }
  68903. }
  68904. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  68905. /*
  68906. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  68907. ** this routine obtains the mutex associated with each BtShared structure
  68908. ** that may be accessed by the VM passed as an argument. In doing so it also
  68909. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  68910. ** that the correct busy-handler callback is invoked if required.
  68911. **
  68912. ** If SQLite is not threadsafe but does support shared-cache mode, then
  68913. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  68914. ** of all of BtShared structures accessible via the database handle
  68915. ** associated with the VM.
  68916. **
  68917. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  68918. ** function is a no-op.
  68919. **
  68920. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  68921. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  68922. ** corresponding to btrees that use shared cache. Then the runtime of
  68923. ** this routine is N*N. But as N is rarely more than 1, this should not
  68924. ** be a problem.
  68925. */
  68926. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  68927. int i;
  68928. sqlite3 *db;
  68929. Db *aDb;
  68930. int nDb;
  68931. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68932. db = p->db;
  68933. aDb = db->aDb;
  68934. nDb = db->nDb;
  68935. for(i=0; i<nDb; i++){
  68936. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68937. sqlite3BtreeEnter(aDb[i].pBt);
  68938. }
  68939. }
  68940. }
  68941. #endif
  68942. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  68943. /*
  68944. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  68945. */
  68946. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  68947. int i;
  68948. sqlite3 *db;
  68949. Db *aDb;
  68950. int nDb;
  68951. db = p->db;
  68952. aDb = db->aDb;
  68953. nDb = db->nDb;
  68954. for(i=0; i<nDb; i++){
  68955. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68956. sqlite3BtreeLeave(aDb[i].pBt);
  68957. }
  68958. }
  68959. }
  68960. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  68961. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68962. vdbeLeave(p);
  68963. }
  68964. #endif
  68965. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  68966. /*
  68967. ** Print a single opcode. This routine is used for debugging only.
  68968. */
  68969. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  68970. char *zP4;
  68971. char zPtr[50];
  68972. char zCom[100];
  68973. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  68974. if( pOut==0 ) pOut = stdout;
  68975. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  68976. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68977. displayComment(pOp, zP4, zCom, sizeof(zCom));
  68978. #else
  68979. zCom[0] = 0;
  68980. #endif
  68981. /* NB: The sqlite3OpcodeName() function is implemented by code created
  68982. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  68983. ** information from the vdbe.c source text */
  68984. fprintf(pOut, zFormat1, pc,
  68985. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  68986. zCom
  68987. );
  68988. fflush(pOut);
  68989. }
  68990. #endif
  68991. /*
  68992. ** Initialize an array of N Mem element.
  68993. */
  68994. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  68995. while( (N--)>0 ){
  68996. p->db = db;
  68997. p->flags = flags;
  68998. p->szMalloc = 0;
  68999. #ifdef SQLITE_DEBUG
  69000. p->pScopyFrom = 0;
  69001. #endif
  69002. p++;
  69003. }
  69004. }
  69005. /*
  69006. ** Release an array of N Mem elements
  69007. */
  69008. static void releaseMemArray(Mem *p, int N){
  69009. if( p && N ){
  69010. Mem *pEnd = &p[N];
  69011. sqlite3 *db = p->db;
  69012. if( db->pnBytesFreed ){
  69013. do{
  69014. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  69015. }while( (++p)<pEnd );
  69016. return;
  69017. }
  69018. do{
  69019. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  69020. assert( sqlite3VdbeCheckMemInvariants(p) );
  69021. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  69022. ** that takes advantage of the fact that the memory cell value is
  69023. ** being set to NULL after releasing any dynamic resources.
  69024. **
  69025. ** The justification for duplicating code is that according to
  69026. ** callgrind, this causes a certain test case to hit the CPU 4.7
  69027. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  69028. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  69029. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  69030. ** with no indexes using a single prepared INSERT statement, bind()
  69031. ** and reset(). Inserts are grouped into a transaction.
  69032. */
  69033. testcase( p->flags & MEM_Agg );
  69034. testcase( p->flags & MEM_Dyn );
  69035. testcase( p->flags & MEM_Frame );
  69036. testcase( p->flags & MEM_RowSet );
  69037. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  69038. sqlite3VdbeMemRelease(p);
  69039. }else if( p->szMalloc ){
  69040. sqlite3DbFreeNN(db, p->zMalloc);
  69041. p->szMalloc = 0;
  69042. }
  69043. p->flags = MEM_Undefined;
  69044. }while( (++p)<pEnd );
  69045. }
  69046. }
  69047. /*
  69048. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  69049. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  69050. */
  69051. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  69052. int i;
  69053. Mem *aMem = VdbeFrameMem(p);
  69054. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  69055. for(i=0; i<p->nChildCsr; i++){
  69056. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  69057. }
  69058. releaseMemArray(aMem, p->nChildMem);
  69059. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  69060. sqlite3DbFree(p->v->db, p);
  69061. }
  69062. #ifndef SQLITE_OMIT_EXPLAIN
  69063. /*
  69064. ** Give a listing of the program in the virtual machine.
  69065. **
  69066. ** The interface is the same as sqlite3VdbeExec(). But instead of
  69067. ** running the code, it invokes the callback once for each instruction.
  69068. ** This feature is used to implement "EXPLAIN".
  69069. **
  69070. ** When p->explain==1, each instruction is listed. When
  69071. ** p->explain==2, only OP_Explain instructions are listed and these
  69072. ** are shown in a different format. p->explain==2 is used to implement
  69073. ** EXPLAIN QUERY PLAN.
  69074. **
  69075. ** When p->explain==1, first the main program is listed, then each of
  69076. ** the trigger subprograms are listed one by one.
  69077. */
  69078. SQLITE_PRIVATE int sqlite3VdbeList(
  69079. Vdbe *p /* The VDBE */
  69080. ){
  69081. int nRow; /* Stop when row count reaches this */
  69082. int nSub = 0; /* Number of sub-vdbes seen so far */
  69083. SubProgram **apSub = 0; /* Array of sub-vdbes */
  69084. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  69085. sqlite3 *db = p->db; /* The database connection */
  69086. int i; /* Loop counter */
  69087. int rc = SQLITE_OK; /* Return code */
  69088. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  69089. assert( p->explain );
  69090. assert( p->magic==VDBE_MAGIC_RUN );
  69091. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  69092. /* Even though this opcode does not use dynamic strings for
  69093. ** the result, result columns may become dynamic if the user calls
  69094. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  69095. */
  69096. releaseMemArray(pMem, 8);
  69097. p->pResultSet = 0;
  69098. if( p->rc==SQLITE_NOMEM_BKPT ){
  69099. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  69100. ** sqlite3_column_text16() failed. */
  69101. sqlite3OomFault(db);
  69102. return SQLITE_ERROR;
  69103. }
  69104. /* When the number of output rows reaches nRow, that means the
  69105. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  69106. ** nRow is the sum of the number of rows in the main program, plus
  69107. ** the sum of the number of rows in all trigger subprograms encountered
  69108. ** so far. The nRow value will increase as new trigger subprograms are
  69109. ** encountered, but p->pc will eventually catch up to nRow.
  69110. */
  69111. nRow = p->nOp;
  69112. if( p->explain==1 ){
  69113. /* The first 8 memory cells are used for the result set. So we will
  69114. ** commandeer the 9th cell to use as storage for an array of pointers
  69115. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  69116. ** cells. */
  69117. assert( p->nMem>9 );
  69118. pSub = &p->aMem[9];
  69119. if( pSub->flags&MEM_Blob ){
  69120. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  69121. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  69122. nSub = pSub->n/sizeof(Vdbe*);
  69123. apSub = (SubProgram **)pSub->z;
  69124. }
  69125. for(i=0; i<nSub; i++){
  69126. nRow += apSub[i]->nOp;
  69127. }
  69128. }
  69129. do{
  69130. i = p->pc++;
  69131. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  69132. if( i>=nRow ){
  69133. p->rc = SQLITE_OK;
  69134. rc = SQLITE_DONE;
  69135. }else if( db->u1.isInterrupted ){
  69136. p->rc = SQLITE_INTERRUPT;
  69137. rc = SQLITE_ERROR;
  69138. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  69139. }else{
  69140. char *zP4;
  69141. Op *pOp;
  69142. if( i<p->nOp ){
  69143. /* The output line number is small enough that we are still in the
  69144. ** main program. */
  69145. pOp = &p->aOp[i];
  69146. }else{
  69147. /* We are currently listing subprograms. Figure out which one and
  69148. ** pick up the appropriate opcode. */
  69149. int j;
  69150. i -= p->nOp;
  69151. for(j=0; i>=apSub[j]->nOp; j++){
  69152. i -= apSub[j]->nOp;
  69153. }
  69154. pOp = &apSub[j]->aOp[i];
  69155. }
  69156. if( p->explain==1 ){
  69157. pMem->flags = MEM_Int;
  69158. pMem->u.i = i; /* Program counter */
  69159. pMem++;
  69160. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  69161. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  69162. assert( pMem->z!=0 );
  69163. pMem->n = sqlite3Strlen30(pMem->z);
  69164. pMem->enc = SQLITE_UTF8;
  69165. pMem++;
  69166. /* When an OP_Program opcode is encounter (the only opcode that has
  69167. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  69168. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  69169. ** has not already been seen.
  69170. */
  69171. if( pOp->p4type==P4_SUBPROGRAM ){
  69172. int nByte = (nSub+1)*sizeof(SubProgram*);
  69173. int j;
  69174. for(j=0; j<nSub; j++){
  69175. if( apSub[j]==pOp->p4.pProgram ) break;
  69176. }
  69177. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  69178. apSub = (SubProgram **)pSub->z;
  69179. apSub[nSub++] = pOp->p4.pProgram;
  69180. pSub->flags |= MEM_Blob;
  69181. pSub->n = nSub*sizeof(SubProgram*);
  69182. }
  69183. }
  69184. }
  69185. pMem->flags = MEM_Int;
  69186. pMem->u.i = pOp->p1; /* P1 */
  69187. pMem++;
  69188. pMem->flags = MEM_Int;
  69189. pMem->u.i = pOp->p2; /* P2 */
  69190. pMem++;
  69191. pMem->flags = MEM_Int;
  69192. pMem->u.i = pOp->p3; /* P3 */
  69193. pMem++;
  69194. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  69195. assert( p->db->mallocFailed );
  69196. return SQLITE_ERROR;
  69197. }
  69198. pMem->flags = MEM_Str|MEM_Term;
  69199. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  69200. if( zP4!=pMem->z ){
  69201. pMem->n = 0;
  69202. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  69203. }else{
  69204. assert( pMem->z!=0 );
  69205. pMem->n = sqlite3Strlen30(pMem->z);
  69206. pMem->enc = SQLITE_UTF8;
  69207. }
  69208. pMem++;
  69209. if( p->explain==1 ){
  69210. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  69211. assert( p->db->mallocFailed );
  69212. return SQLITE_ERROR;
  69213. }
  69214. pMem->flags = MEM_Str|MEM_Term;
  69215. pMem->n = 2;
  69216. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  69217. pMem->enc = SQLITE_UTF8;
  69218. pMem++;
  69219. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  69220. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  69221. assert( p->db->mallocFailed );
  69222. return SQLITE_ERROR;
  69223. }
  69224. pMem->flags = MEM_Str|MEM_Term;
  69225. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  69226. pMem->enc = SQLITE_UTF8;
  69227. #else
  69228. pMem->flags = MEM_Null; /* Comment */
  69229. #endif
  69230. }
  69231. p->nResColumn = 8 - 4*(p->explain-1);
  69232. p->pResultSet = &p->aMem[1];
  69233. p->rc = SQLITE_OK;
  69234. rc = SQLITE_ROW;
  69235. }
  69236. return rc;
  69237. }
  69238. #endif /* SQLITE_OMIT_EXPLAIN */
  69239. #ifdef SQLITE_DEBUG
  69240. /*
  69241. ** Print the SQL that was used to generate a VDBE program.
  69242. */
  69243. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  69244. const char *z = 0;
  69245. if( p->zSql ){
  69246. z = p->zSql;
  69247. }else if( p->nOp>=1 ){
  69248. const VdbeOp *pOp = &p->aOp[0];
  69249. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  69250. z = pOp->p4.z;
  69251. while( sqlite3Isspace(*z) ) z++;
  69252. }
  69253. }
  69254. if( z ) printf("SQL: [%s]\n", z);
  69255. }
  69256. #endif
  69257. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  69258. /*
  69259. ** Print an IOTRACE message showing SQL content.
  69260. */
  69261. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  69262. int nOp = p->nOp;
  69263. VdbeOp *pOp;
  69264. if( sqlite3IoTrace==0 ) return;
  69265. if( nOp<1 ) return;
  69266. pOp = &p->aOp[0];
  69267. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  69268. int i, j;
  69269. char z[1000];
  69270. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  69271. for(i=0; sqlite3Isspace(z[i]); i++){}
  69272. for(j=0; z[i]; i++){
  69273. if( sqlite3Isspace(z[i]) ){
  69274. if( z[i-1]!=' ' ){
  69275. z[j++] = ' ';
  69276. }
  69277. }else{
  69278. z[j++] = z[i];
  69279. }
  69280. }
  69281. z[j] = 0;
  69282. sqlite3IoTrace("SQL %s\n", z);
  69283. }
  69284. }
  69285. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  69286. /* An instance of this object describes bulk memory available for use
  69287. ** by subcomponents of a prepared statement. Space is allocated out
  69288. ** of a ReusableSpace object by the allocSpace() routine below.
  69289. */
  69290. struct ReusableSpace {
  69291. u8 *pSpace; /* Available memory */
  69292. int nFree; /* Bytes of available memory */
  69293. int nNeeded; /* Total bytes that could not be allocated */
  69294. };
  69295. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  69296. ** from the ReusableSpace object. Return a pointer to the allocated
  69297. ** memory on success. If insufficient memory is available in the
  69298. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  69299. ** value by the amount needed and return NULL.
  69300. **
  69301. ** If pBuf is not initially NULL, that means that the memory has already
  69302. ** been allocated by a prior call to this routine, so just return a copy
  69303. ** of pBuf and leave ReusableSpace unchanged.
  69304. **
  69305. ** This allocator is employed to repurpose unused slots at the end of the
  69306. ** opcode array of prepared state for other memory needs of the prepared
  69307. ** statement.
  69308. */
  69309. static void *allocSpace(
  69310. struct ReusableSpace *p, /* Bulk memory available for allocation */
  69311. void *pBuf, /* Pointer to a prior allocation */
  69312. int nByte /* Bytes of memory needed */
  69313. ){
  69314. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  69315. if( pBuf==0 ){
  69316. nByte = ROUND8(nByte);
  69317. if( nByte <= p->nFree ){
  69318. p->nFree -= nByte;
  69319. pBuf = &p->pSpace[p->nFree];
  69320. }else{
  69321. p->nNeeded += nByte;
  69322. }
  69323. }
  69324. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  69325. return pBuf;
  69326. }
  69327. /*
  69328. ** Rewind the VDBE back to the beginning in preparation for
  69329. ** running it.
  69330. */
  69331. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  69332. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  69333. int i;
  69334. #endif
  69335. assert( p!=0 );
  69336. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  69337. /* There should be at least one opcode.
  69338. */
  69339. assert( p->nOp>0 );
  69340. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  69341. p->magic = VDBE_MAGIC_RUN;
  69342. #ifdef SQLITE_DEBUG
  69343. for(i=0; i<p->nMem; i++){
  69344. assert( p->aMem[i].db==p->db );
  69345. }
  69346. #endif
  69347. p->pc = -1;
  69348. p->rc = SQLITE_OK;
  69349. p->errorAction = OE_Abort;
  69350. p->nChange = 0;
  69351. p->cacheCtr = 1;
  69352. p->minWriteFileFormat = 255;
  69353. p->iStatement = 0;
  69354. p->nFkConstraint = 0;
  69355. #ifdef VDBE_PROFILE
  69356. for(i=0; i<p->nOp; i++){
  69357. p->aOp[i].cnt = 0;
  69358. p->aOp[i].cycles = 0;
  69359. }
  69360. #endif
  69361. }
  69362. /*
  69363. ** Prepare a virtual machine for execution for the first time after
  69364. ** creating the virtual machine. This involves things such
  69365. ** as allocating registers and initializing the program counter.
  69366. ** After the VDBE has be prepped, it can be executed by one or more
  69367. ** calls to sqlite3VdbeExec().
  69368. **
  69369. ** This function may be called exactly once on each virtual machine.
  69370. ** After this routine is called the VM has been "packaged" and is ready
  69371. ** to run. After this routine is called, further calls to
  69372. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  69373. ** the Vdbe from the Parse object that helped generate it so that the
  69374. ** the Vdbe becomes an independent entity and the Parse object can be
  69375. ** destroyed.
  69376. **
  69377. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  69378. ** to its initial state after it has been run.
  69379. */
  69380. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  69381. Vdbe *p, /* The VDBE */
  69382. Parse *pParse /* Parsing context */
  69383. ){
  69384. sqlite3 *db; /* The database connection */
  69385. int nVar; /* Number of parameters */
  69386. int nMem; /* Number of VM memory registers */
  69387. int nCursor; /* Number of cursors required */
  69388. int nArg; /* Number of arguments in subprograms */
  69389. int n; /* Loop counter */
  69390. struct ReusableSpace x; /* Reusable bulk memory */
  69391. assert( p!=0 );
  69392. assert( p->nOp>0 );
  69393. assert( pParse!=0 );
  69394. assert( p->magic==VDBE_MAGIC_INIT );
  69395. assert( pParse==p->pParse );
  69396. db = p->db;
  69397. assert( db->mallocFailed==0 );
  69398. nVar = pParse->nVar;
  69399. nMem = pParse->nMem;
  69400. nCursor = pParse->nTab;
  69401. nArg = pParse->nMaxArg;
  69402. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  69403. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  69404. ** space at the end of aMem[] for cursors 1 and greater.
  69405. ** See also: allocateCursor().
  69406. */
  69407. nMem += nCursor;
  69408. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  69409. /* Figure out how much reusable memory is available at the end of the
  69410. ** opcode array. This extra memory will be reallocated for other elements
  69411. ** of the prepared statement.
  69412. */
  69413. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  69414. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  69415. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  69416. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  69417. assert( x.nFree>=0 );
  69418. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  69419. resolveP2Values(p, &nArg);
  69420. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  69421. if( pParse->explain && nMem<10 ){
  69422. nMem = 10;
  69423. }
  69424. p->expired = 0;
  69425. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  69426. ** passes. On the first pass, we try to reuse unused memory at the
  69427. ** end of the opcode array. If we are unable to satisfy all memory
  69428. ** requirements by reusing the opcode array tail, then the second
  69429. ** pass will fill in the remainder using a fresh memory allocation.
  69430. **
  69431. ** This two-pass approach that reuses as much memory as possible from
  69432. ** the leftover memory at the end of the opcode array. This can significantly
  69433. ** reduce the amount of memory held by a prepared statement.
  69434. */
  69435. do {
  69436. x.nNeeded = 0;
  69437. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  69438. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  69439. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  69440. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  69441. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69442. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  69443. #endif
  69444. if( x.nNeeded==0 ) break;
  69445. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  69446. x.nFree = x.nNeeded;
  69447. }while( !db->mallocFailed );
  69448. p->pVList = pParse->pVList;
  69449. pParse->pVList = 0;
  69450. p->explain = pParse->explain;
  69451. if( db->mallocFailed ){
  69452. p->nVar = 0;
  69453. p->nCursor = 0;
  69454. p->nMem = 0;
  69455. }else{
  69456. p->nCursor = nCursor;
  69457. p->nVar = (ynVar)nVar;
  69458. initMemArray(p->aVar, nVar, db, MEM_Null);
  69459. p->nMem = nMem;
  69460. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  69461. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  69462. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69463. memset(p->anExec, 0, p->nOp*sizeof(i64));
  69464. #endif
  69465. }
  69466. sqlite3VdbeRewind(p);
  69467. }
  69468. /*
  69469. ** Close a VDBE cursor and release all the resources that cursor
  69470. ** happens to hold.
  69471. */
  69472. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  69473. if( pCx==0 ){
  69474. return;
  69475. }
  69476. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  69477. switch( pCx->eCurType ){
  69478. case CURTYPE_SORTER: {
  69479. sqlite3VdbeSorterClose(p->db, pCx);
  69480. break;
  69481. }
  69482. case CURTYPE_BTREE: {
  69483. if( pCx->isEphemeral ){
  69484. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  69485. /* The pCx->pCursor will be close automatically, if it exists, by
  69486. ** the call above. */
  69487. }else{
  69488. assert( pCx->uc.pCursor!=0 );
  69489. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  69490. }
  69491. break;
  69492. }
  69493. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69494. case CURTYPE_VTAB: {
  69495. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  69496. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  69497. assert( pVCur->pVtab->nRef>0 );
  69498. pVCur->pVtab->nRef--;
  69499. pModule->xClose(pVCur);
  69500. break;
  69501. }
  69502. #endif
  69503. }
  69504. }
  69505. /*
  69506. ** Close all cursors in the current frame.
  69507. */
  69508. static void closeCursorsInFrame(Vdbe *p){
  69509. if( p->apCsr ){
  69510. int i;
  69511. for(i=0; i<p->nCursor; i++){
  69512. VdbeCursor *pC = p->apCsr[i];
  69513. if( pC ){
  69514. sqlite3VdbeFreeCursor(p, pC);
  69515. p->apCsr[i] = 0;
  69516. }
  69517. }
  69518. }
  69519. }
  69520. /*
  69521. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  69522. ** is used, for example, when a trigger sub-program is halted to restore
  69523. ** control to the main program.
  69524. */
  69525. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  69526. Vdbe *v = pFrame->v;
  69527. closeCursorsInFrame(v);
  69528. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69529. v->anExec = pFrame->anExec;
  69530. #endif
  69531. v->aOp = pFrame->aOp;
  69532. v->nOp = pFrame->nOp;
  69533. v->aMem = pFrame->aMem;
  69534. v->nMem = pFrame->nMem;
  69535. v->apCsr = pFrame->apCsr;
  69536. v->nCursor = pFrame->nCursor;
  69537. v->db->lastRowid = pFrame->lastRowid;
  69538. v->nChange = pFrame->nChange;
  69539. v->db->nChange = pFrame->nDbChange;
  69540. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  69541. v->pAuxData = pFrame->pAuxData;
  69542. pFrame->pAuxData = 0;
  69543. return pFrame->pc;
  69544. }
  69545. /*
  69546. ** Close all cursors.
  69547. **
  69548. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  69549. ** cell array. This is necessary as the memory cell array may contain
  69550. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  69551. ** open cursors.
  69552. */
  69553. static void closeAllCursors(Vdbe *p){
  69554. if( p->pFrame ){
  69555. VdbeFrame *pFrame;
  69556. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  69557. sqlite3VdbeFrameRestore(pFrame);
  69558. p->pFrame = 0;
  69559. p->nFrame = 0;
  69560. }
  69561. assert( p->nFrame==0 );
  69562. closeCursorsInFrame(p);
  69563. if( p->aMem ){
  69564. releaseMemArray(p->aMem, p->nMem);
  69565. }
  69566. while( p->pDelFrame ){
  69567. VdbeFrame *pDel = p->pDelFrame;
  69568. p->pDelFrame = pDel->pParent;
  69569. sqlite3VdbeFrameDelete(pDel);
  69570. }
  69571. /* Delete any auxdata allocations made by the VM */
  69572. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  69573. assert( p->pAuxData==0 );
  69574. }
  69575. /*
  69576. ** Set the number of result columns that will be returned by this SQL
  69577. ** statement. This is now set at compile time, rather than during
  69578. ** execution of the vdbe program so that sqlite3_column_count() can
  69579. ** be called on an SQL statement before sqlite3_step().
  69580. */
  69581. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  69582. int n;
  69583. sqlite3 *db = p->db;
  69584. if( p->nResColumn ){
  69585. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  69586. sqlite3DbFree(db, p->aColName);
  69587. }
  69588. n = nResColumn*COLNAME_N;
  69589. p->nResColumn = (u16)nResColumn;
  69590. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  69591. if( p->aColName==0 ) return;
  69592. initMemArray(p->aColName, n, db, MEM_Null);
  69593. }
  69594. /*
  69595. ** Set the name of the idx'th column to be returned by the SQL statement.
  69596. ** zName must be a pointer to a nul terminated string.
  69597. **
  69598. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  69599. **
  69600. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  69601. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  69602. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  69603. */
  69604. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  69605. Vdbe *p, /* Vdbe being configured */
  69606. int idx, /* Index of column zName applies to */
  69607. int var, /* One of the COLNAME_* constants */
  69608. const char *zName, /* Pointer to buffer containing name */
  69609. void (*xDel)(void*) /* Memory management strategy for zName */
  69610. ){
  69611. int rc;
  69612. Mem *pColName;
  69613. assert( idx<p->nResColumn );
  69614. assert( var<COLNAME_N );
  69615. if( p->db->mallocFailed ){
  69616. assert( !zName || xDel!=SQLITE_DYNAMIC );
  69617. return SQLITE_NOMEM_BKPT;
  69618. }
  69619. assert( p->aColName!=0 );
  69620. pColName = &(p->aColName[idx+var*p->nResColumn]);
  69621. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  69622. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  69623. return rc;
  69624. }
  69625. /*
  69626. ** A read or write transaction may or may not be active on database handle
  69627. ** db. If a transaction is active, commit it. If there is a
  69628. ** write-transaction spanning more than one database file, this routine
  69629. ** takes care of the master journal trickery.
  69630. */
  69631. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  69632. int i;
  69633. int nTrans = 0; /* Number of databases with an active write-transaction
  69634. ** that are candidates for a two-phase commit using a
  69635. ** master-journal */
  69636. int rc = SQLITE_OK;
  69637. int needXcommit = 0;
  69638. #ifdef SQLITE_OMIT_VIRTUALTABLE
  69639. /* With this option, sqlite3VtabSync() is defined to be simply
  69640. ** SQLITE_OK so p is not used.
  69641. */
  69642. UNUSED_PARAMETER(p);
  69643. #endif
  69644. /* Before doing anything else, call the xSync() callback for any
  69645. ** virtual module tables written in this transaction. This has to
  69646. ** be done before determining whether a master journal file is
  69647. ** required, as an xSync() callback may add an attached database
  69648. ** to the transaction.
  69649. */
  69650. rc = sqlite3VtabSync(db, p);
  69651. /* This loop determines (a) if the commit hook should be invoked and
  69652. ** (b) how many database files have open write transactions, not
  69653. ** including the temp database. (b) is important because if more than
  69654. ** one database file has an open write transaction, a master journal
  69655. ** file is required for an atomic commit.
  69656. */
  69657. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69658. Btree *pBt = db->aDb[i].pBt;
  69659. if( sqlite3BtreeIsInTrans(pBt) ){
  69660. /* Whether or not a database might need a master journal depends upon
  69661. ** its journal mode (among other things). This matrix determines which
  69662. ** journal modes use a master journal and which do not */
  69663. static const u8 aMJNeeded[] = {
  69664. /* DELETE */ 1,
  69665. /* PERSIST */ 1,
  69666. /* OFF */ 0,
  69667. /* TRUNCATE */ 1,
  69668. /* MEMORY */ 0,
  69669. /* WAL */ 0
  69670. };
  69671. Pager *pPager; /* Pager associated with pBt */
  69672. needXcommit = 1;
  69673. sqlite3BtreeEnter(pBt);
  69674. pPager = sqlite3BtreePager(pBt);
  69675. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  69676. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  69677. ){
  69678. assert( i!=1 );
  69679. nTrans++;
  69680. }
  69681. rc = sqlite3PagerExclusiveLock(pPager);
  69682. sqlite3BtreeLeave(pBt);
  69683. }
  69684. }
  69685. if( rc!=SQLITE_OK ){
  69686. return rc;
  69687. }
  69688. /* If there are any write-transactions at all, invoke the commit hook */
  69689. if( needXcommit && db->xCommitCallback ){
  69690. rc = db->xCommitCallback(db->pCommitArg);
  69691. if( rc ){
  69692. return SQLITE_CONSTRAINT_COMMITHOOK;
  69693. }
  69694. }
  69695. /* The simple case - no more than one database file (not counting the
  69696. ** TEMP database) has a transaction active. There is no need for the
  69697. ** master-journal.
  69698. **
  69699. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  69700. ** string, it means the main database is :memory: or a temp file. In
  69701. ** that case we do not support atomic multi-file commits, so use the
  69702. ** simple case then too.
  69703. */
  69704. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  69705. || nTrans<=1
  69706. ){
  69707. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69708. Btree *pBt = db->aDb[i].pBt;
  69709. if( pBt ){
  69710. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  69711. }
  69712. }
  69713. /* Do the commit only if all databases successfully complete phase 1.
  69714. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  69715. ** IO error while deleting or truncating a journal file. It is unlikely,
  69716. ** but could happen. In this case abandon processing and return the error.
  69717. */
  69718. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69719. Btree *pBt = db->aDb[i].pBt;
  69720. if( pBt ){
  69721. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  69722. }
  69723. }
  69724. if( rc==SQLITE_OK ){
  69725. sqlite3VtabCommit(db);
  69726. }
  69727. }
  69728. /* The complex case - There is a multi-file write-transaction active.
  69729. ** This requires a master journal file to ensure the transaction is
  69730. ** committed atomically.
  69731. */
  69732. #ifndef SQLITE_OMIT_DISKIO
  69733. else{
  69734. sqlite3_vfs *pVfs = db->pVfs;
  69735. char *zMaster = 0; /* File-name for the master journal */
  69736. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  69737. sqlite3_file *pMaster = 0;
  69738. i64 offset = 0;
  69739. int res;
  69740. int retryCount = 0;
  69741. int nMainFile;
  69742. /* Select a master journal file name */
  69743. nMainFile = sqlite3Strlen30(zMainFile);
  69744. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  69745. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  69746. do {
  69747. u32 iRandom;
  69748. if( retryCount ){
  69749. if( retryCount>100 ){
  69750. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  69751. sqlite3OsDelete(pVfs, zMaster, 0);
  69752. break;
  69753. }else if( retryCount==1 ){
  69754. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  69755. }
  69756. }
  69757. retryCount++;
  69758. sqlite3_randomness(sizeof(iRandom), &iRandom);
  69759. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  69760. (iRandom>>8)&0xffffff, iRandom&0xff);
  69761. /* The antipenultimate character of the master journal name must
  69762. ** be "9" to avoid name collisions when using 8+3 filenames. */
  69763. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  69764. sqlite3FileSuffix3(zMainFile, zMaster);
  69765. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  69766. }while( rc==SQLITE_OK && res );
  69767. if( rc==SQLITE_OK ){
  69768. /* Open the master journal. */
  69769. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  69770. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  69771. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  69772. );
  69773. }
  69774. if( rc!=SQLITE_OK ){
  69775. sqlite3DbFree(db, zMaster);
  69776. return rc;
  69777. }
  69778. /* Write the name of each database file in the transaction into the new
  69779. ** master journal file. If an error occurs at this point close
  69780. ** and delete the master journal file. All the individual journal files
  69781. ** still have 'null' as the master journal pointer, so they will roll
  69782. ** back independently if a failure occurs.
  69783. */
  69784. for(i=0; i<db->nDb; i++){
  69785. Btree *pBt = db->aDb[i].pBt;
  69786. if( sqlite3BtreeIsInTrans(pBt) ){
  69787. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  69788. if( zFile==0 ){
  69789. continue; /* Ignore TEMP and :memory: databases */
  69790. }
  69791. assert( zFile[0]!=0 );
  69792. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  69793. offset += sqlite3Strlen30(zFile)+1;
  69794. if( rc!=SQLITE_OK ){
  69795. sqlite3OsCloseFree(pMaster);
  69796. sqlite3OsDelete(pVfs, zMaster, 0);
  69797. sqlite3DbFree(db, zMaster);
  69798. return rc;
  69799. }
  69800. }
  69801. }
  69802. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  69803. ** flag is set this is not required.
  69804. */
  69805. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  69806. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  69807. ){
  69808. sqlite3OsCloseFree(pMaster);
  69809. sqlite3OsDelete(pVfs, zMaster, 0);
  69810. sqlite3DbFree(db, zMaster);
  69811. return rc;
  69812. }
  69813. /* Sync all the db files involved in the transaction. The same call
  69814. ** sets the master journal pointer in each individual journal. If
  69815. ** an error occurs here, do not delete the master journal file.
  69816. **
  69817. ** If the error occurs during the first call to
  69818. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  69819. ** master journal file will be orphaned. But we cannot delete it,
  69820. ** in case the master journal file name was written into the journal
  69821. ** file before the failure occurred.
  69822. */
  69823. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69824. Btree *pBt = db->aDb[i].pBt;
  69825. if( pBt ){
  69826. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  69827. }
  69828. }
  69829. sqlite3OsCloseFree(pMaster);
  69830. assert( rc!=SQLITE_BUSY );
  69831. if( rc!=SQLITE_OK ){
  69832. sqlite3DbFree(db, zMaster);
  69833. return rc;
  69834. }
  69835. /* Delete the master journal file. This commits the transaction. After
  69836. ** doing this the directory is synced again before any individual
  69837. ** transaction files are deleted.
  69838. */
  69839. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  69840. sqlite3DbFree(db, zMaster);
  69841. zMaster = 0;
  69842. if( rc ){
  69843. return rc;
  69844. }
  69845. /* All files and directories have already been synced, so the following
  69846. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  69847. ** deleting or truncating journals. If something goes wrong while
  69848. ** this is happening we don't really care. The integrity of the
  69849. ** transaction is already guaranteed, but some stray 'cold' journals
  69850. ** may be lying around. Returning an error code won't help matters.
  69851. */
  69852. disable_simulated_io_errors();
  69853. sqlite3BeginBenignMalloc();
  69854. for(i=0; i<db->nDb; i++){
  69855. Btree *pBt = db->aDb[i].pBt;
  69856. if( pBt ){
  69857. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  69858. }
  69859. }
  69860. sqlite3EndBenignMalloc();
  69861. enable_simulated_io_errors();
  69862. sqlite3VtabCommit(db);
  69863. }
  69864. #endif
  69865. return rc;
  69866. }
  69867. /*
  69868. ** This routine checks that the sqlite3.nVdbeActive count variable
  69869. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  69870. ** currently active. An assertion fails if the two counts do not match.
  69871. ** This is an internal self-check only - it is not an essential processing
  69872. ** step.
  69873. **
  69874. ** This is a no-op if NDEBUG is defined.
  69875. */
  69876. #ifndef NDEBUG
  69877. static void checkActiveVdbeCnt(sqlite3 *db){
  69878. Vdbe *p;
  69879. int cnt = 0;
  69880. int nWrite = 0;
  69881. int nRead = 0;
  69882. p = db->pVdbe;
  69883. while( p ){
  69884. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  69885. cnt++;
  69886. if( p->readOnly==0 ) nWrite++;
  69887. if( p->bIsReader ) nRead++;
  69888. }
  69889. p = p->pNext;
  69890. }
  69891. assert( cnt==db->nVdbeActive );
  69892. assert( nWrite==db->nVdbeWrite );
  69893. assert( nRead==db->nVdbeRead );
  69894. }
  69895. #else
  69896. #define checkActiveVdbeCnt(x)
  69897. #endif
  69898. /*
  69899. ** If the Vdbe passed as the first argument opened a statement-transaction,
  69900. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  69901. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  69902. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  69903. ** statement transaction is committed.
  69904. **
  69905. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  69906. ** Otherwise SQLITE_OK.
  69907. */
  69908. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  69909. sqlite3 *const db = p->db;
  69910. int rc = SQLITE_OK;
  69911. int i;
  69912. const int iSavepoint = p->iStatement-1;
  69913. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  69914. assert( db->nStatement>0 );
  69915. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  69916. for(i=0; i<db->nDb; i++){
  69917. int rc2 = SQLITE_OK;
  69918. Btree *pBt = db->aDb[i].pBt;
  69919. if( pBt ){
  69920. if( eOp==SAVEPOINT_ROLLBACK ){
  69921. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  69922. }
  69923. if( rc2==SQLITE_OK ){
  69924. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  69925. }
  69926. if( rc==SQLITE_OK ){
  69927. rc = rc2;
  69928. }
  69929. }
  69930. }
  69931. db->nStatement--;
  69932. p->iStatement = 0;
  69933. if( rc==SQLITE_OK ){
  69934. if( eOp==SAVEPOINT_ROLLBACK ){
  69935. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  69936. }
  69937. if( rc==SQLITE_OK ){
  69938. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  69939. }
  69940. }
  69941. /* If the statement transaction is being rolled back, also restore the
  69942. ** database handles deferred constraint counter to the value it had when
  69943. ** the statement transaction was opened. */
  69944. if( eOp==SAVEPOINT_ROLLBACK ){
  69945. db->nDeferredCons = p->nStmtDefCons;
  69946. db->nDeferredImmCons = p->nStmtDefImmCons;
  69947. }
  69948. return rc;
  69949. }
  69950. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  69951. if( p->db->nStatement && p->iStatement ){
  69952. return vdbeCloseStatement(p, eOp);
  69953. }
  69954. return SQLITE_OK;
  69955. }
  69956. /*
  69957. ** This function is called when a transaction opened by the database
  69958. ** handle associated with the VM passed as an argument is about to be
  69959. ** committed. If there are outstanding deferred foreign key constraint
  69960. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  69961. **
  69962. ** If there are outstanding FK violations and this function returns
  69963. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  69964. ** and write an error message to it. Then return SQLITE_ERROR.
  69965. */
  69966. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69967. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  69968. sqlite3 *db = p->db;
  69969. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  69970. || (!deferred && p->nFkConstraint>0)
  69971. ){
  69972. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  69973. p->errorAction = OE_Abort;
  69974. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  69975. return SQLITE_ERROR;
  69976. }
  69977. return SQLITE_OK;
  69978. }
  69979. #endif
  69980. /*
  69981. ** This routine is called the when a VDBE tries to halt. If the VDBE
  69982. ** has made changes and is in autocommit mode, then commit those
  69983. ** changes. If a rollback is needed, then do the rollback.
  69984. **
  69985. ** This routine is the only way to move the state of a VM from
  69986. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  69987. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  69988. **
  69989. ** Return an error code. If the commit could not complete because of
  69990. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  69991. ** means the close did not happen and needs to be repeated.
  69992. */
  69993. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  69994. int rc; /* Used to store transient return codes */
  69995. sqlite3 *db = p->db;
  69996. /* This function contains the logic that determines if a statement or
  69997. ** transaction will be committed or rolled back as a result of the
  69998. ** execution of this virtual machine.
  69999. **
  70000. ** If any of the following errors occur:
  70001. **
  70002. ** SQLITE_NOMEM
  70003. ** SQLITE_IOERR
  70004. ** SQLITE_FULL
  70005. ** SQLITE_INTERRUPT
  70006. **
  70007. ** Then the internal cache might have been left in an inconsistent
  70008. ** state. We need to rollback the statement transaction, if there is
  70009. ** one, or the complete transaction if there is no statement transaction.
  70010. */
  70011. if( p->magic!=VDBE_MAGIC_RUN ){
  70012. return SQLITE_OK;
  70013. }
  70014. if( db->mallocFailed ){
  70015. p->rc = SQLITE_NOMEM_BKPT;
  70016. }
  70017. closeAllCursors(p);
  70018. checkActiveVdbeCnt(db);
  70019. /* No commit or rollback needed if the program never started or if the
  70020. ** SQL statement does not read or write a database file. */
  70021. if( p->pc>=0 && p->bIsReader ){
  70022. int mrc; /* Primary error code from p->rc */
  70023. int eStatementOp = 0;
  70024. int isSpecialError; /* Set to true if a 'special' error */
  70025. /* Lock all btrees used by the statement */
  70026. sqlite3VdbeEnter(p);
  70027. /* Check for one of the special errors */
  70028. mrc = p->rc & 0xff;
  70029. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  70030. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  70031. if( isSpecialError ){
  70032. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  70033. ** no rollback is necessary. Otherwise, at least a savepoint
  70034. ** transaction must be rolled back to restore the database to a
  70035. ** consistent state.
  70036. **
  70037. ** Even if the statement is read-only, it is important to perform
  70038. ** a statement or transaction rollback operation. If the error
  70039. ** occurred while writing to the journal, sub-journal or database
  70040. ** file as part of an effort to free up cache space (see function
  70041. ** pagerStress() in pager.c), the rollback is required to restore
  70042. ** the pager to a consistent state.
  70043. */
  70044. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  70045. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  70046. eStatementOp = SAVEPOINT_ROLLBACK;
  70047. }else{
  70048. /* We are forced to roll back the active transaction. Before doing
  70049. ** so, abort any other statements this handle currently has active.
  70050. */
  70051. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  70052. sqlite3CloseSavepoints(db);
  70053. db->autoCommit = 1;
  70054. p->nChange = 0;
  70055. }
  70056. }
  70057. }
  70058. /* Check for immediate foreign key violations. */
  70059. if( p->rc==SQLITE_OK ){
  70060. sqlite3VdbeCheckFk(p, 0);
  70061. }
  70062. /* If the auto-commit flag is set and this is the only active writer
  70063. ** VM, then we do either a commit or rollback of the current transaction.
  70064. **
  70065. ** Note: This block also runs if one of the special errors handled
  70066. ** above has occurred.
  70067. */
  70068. if( !sqlite3VtabInSync(db)
  70069. && db->autoCommit
  70070. && db->nVdbeWrite==(p->readOnly==0)
  70071. ){
  70072. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  70073. rc = sqlite3VdbeCheckFk(p, 1);
  70074. if( rc!=SQLITE_OK ){
  70075. if( NEVER(p->readOnly) ){
  70076. sqlite3VdbeLeave(p);
  70077. return SQLITE_ERROR;
  70078. }
  70079. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  70080. }else{
  70081. /* The auto-commit flag is true, the vdbe program was successful
  70082. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  70083. ** key constraints to hold up the transaction. This means a commit
  70084. ** is required. */
  70085. rc = vdbeCommit(db, p);
  70086. }
  70087. if( rc==SQLITE_BUSY && p->readOnly ){
  70088. sqlite3VdbeLeave(p);
  70089. return SQLITE_BUSY;
  70090. }else if( rc!=SQLITE_OK ){
  70091. p->rc = rc;
  70092. sqlite3RollbackAll(db, SQLITE_OK);
  70093. p->nChange = 0;
  70094. }else{
  70095. db->nDeferredCons = 0;
  70096. db->nDeferredImmCons = 0;
  70097. db->flags &= ~SQLITE_DeferFKs;
  70098. sqlite3CommitInternalChanges(db);
  70099. }
  70100. }else{
  70101. sqlite3RollbackAll(db, SQLITE_OK);
  70102. p->nChange = 0;
  70103. }
  70104. db->nStatement = 0;
  70105. }else if( eStatementOp==0 ){
  70106. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  70107. eStatementOp = SAVEPOINT_RELEASE;
  70108. }else if( p->errorAction==OE_Abort ){
  70109. eStatementOp = SAVEPOINT_ROLLBACK;
  70110. }else{
  70111. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  70112. sqlite3CloseSavepoints(db);
  70113. db->autoCommit = 1;
  70114. p->nChange = 0;
  70115. }
  70116. }
  70117. /* If eStatementOp is non-zero, then a statement transaction needs to
  70118. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  70119. ** do so. If this operation returns an error, and the current statement
  70120. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  70121. ** current statement error code.
  70122. */
  70123. if( eStatementOp ){
  70124. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  70125. if( rc ){
  70126. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  70127. p->rc = rc;
  70128. sqlite3DbFree(db, p->zErrMsg);
  70129. p->zErrMsg = 0;
  70130. }
  70131. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  70132. sqlite3CloseSavepoints(db);
  70133. db->autoCommit = 1;
  70134. p->nChange = 0;
  70135. }
  70136. }
  70137. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  70138. ** has been rolled back, update the database connection change-counter.
  70139. */
  70140. if( p->changeCntOn ){
  70141. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  70142. sqlite3VdbeSetChanges(db, p->nChange);
  70143. }else{
  70144. sqlite3VdbeSetChanges(db, 0);
  70145. }
  70146. p->nChange = 0;
  70147. }
  70148. /* Release the locks */
  70149. sqlite3VdbeLeave(p);
  70150. }
  70151. /* We have successfully halted and closed the VM. Record this fact. */
  70152. if( p->pc>=0 ){
  70153. db->nVdbeActive--;
  70154. if( !p->readOnly ) db->nVdbeWrite--;
  70155. if( p->bIsReader ) db->nVdbeRead--;
  70156. assert( db->nVdbeActive>=db->nVdbeRead );
  70157. assert( db->nVdbeRead>=db->nVdbeWrite );
  70158. assert( db->nVdbeWrite>=0 );
  70159. }
  70160. p->magic = VDBE_MAGIC_HALT;
  70161. checkActiveVdbeCnt(db);
  70162. if( db->mallocFailed ){
  70163. p->rc = SQLITE_NOMEM_BKPT;
  70164. }
  70165. /* If the auto-commit flag is set to true, then any locks that were held
  70166. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  70167. ** to invoke any required unlock-notify callbacks.
  70168. */
  70169. if( db->autoCommit ){
  70170. sqlite3ConnectionUnlocked(db);
  70171. }
  70172. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  70173. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  70174. }
  70175. /*
  70176. ** Each VDBE holds the result of the most recent sqlite3_step() call
  70177. ** in p->rc. This routine sets that result back to SQLITE_OK.
  70178. */
  70179. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  70180. p->rc = SQLITE_OK;
  70181. }
  70182. /*
  70183. ** Copy the error code and error message belonging to the VDBE passed
  70184. ** as the first argument to its database handle (so that they will be
  70185. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  70186. **
  70187. ** This function does not clear the VDBE error code or message, just
  70188. ** copies them to the database handle.
  70189. */
  70190. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  70191. sqlite3 *db = p->db;
  70192. int rc = p->rc;
  70193. if( p->zErrMsg ){
  70194. db->bBenignMalloc++;
  70195. sqlite3BeginBenignMalloc();
  70196. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  70197. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  70198. sqlite3EndBenignMalloc();
  70199. db->bBenignMalloc--;
  70200. }else if( db->pErr ){
  70201. sqlite3ValueSetNull(db->pErr);
  70202. }
  70203. db->errCode = rc;
  70204. return rc;
  70205. }
  70206. #ifdef SQLITE_ENABLE_SQLLOG
  70207. /*
  70208. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  70209. ** invoke it.
  70210. */
  70211. static void vdbeInvokeSqllog(Vdbe *v){
  70212. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  70213. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  70214. assert( v->db->init.busy==0 );
  70215. if( zExpanded ){
  70216. sqlite3GlobalConfig.xSqllog(
  70217. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  70218. );
  70219. sqlite3DbFree(v->db, zExpanded);
  70220. }
  70221. }
  70222. }
  70223. #else
  70224. # define vdbeInvokeSqllog(x)
  70225. #endif
  70226. /*
  70227. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  70228. ** Write any error messages into *pzErrMsg. Return the result code.
  70229. **
  70230. ** After this routine is run, the VDBE should be ready to be executed
  70231. ** again.
  70232. **
  70233. ** To look at it another way, this routine resets the state of the
  70234. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  70235. ** VDBE_MAGIC_INIT.
  70236. */
  70237. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  70238. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  70239. int i;
  70240. #endif
  70241. sqlite3 *db;
  70242. db = p->db;
  70243. /* If the VM did not run to completion or if it encountered an
  70244. ** error, then it might not have been halted properly. So halt
  70245. ** it now.
  70246. */
  70247. sqlite3VdbeHalt(p);
  70248. /* If the VDBE has be run even partially, then transfer the error code
  70249. ** and error message from the VDBE into the main database structure. But
  70250. ** if the VDBE has just been set to run but has not actually executed any
  70251. ** instructions yet, leave the main database error information unchanged.
  70252. */
  70253. if( p->pc>=0 ){
  70254. vdbeInvokeSqllog(p);
  70255. sqlite3VdbeTransferError(p);
  70256. if( p->runOnlyOnce ) p->expired = 1;
  70257. }else if( p->rc && p->expired ){
  70258. /* The expired flag was set on the VDBE before the first call
  70259. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  70260. ** called), set the database error in this case as well.
  70261. */
  70262. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  70263. }
  70264. /* Reset register contents and reclaim error message memory.
  70265. */
  70266. #ifdef SQLITE_DEBUG
  70267. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  70268. ** Vdbe.aMem[] arrays have already been cleaned up. */
  70269. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  70270. if( p->aMem ){
  70271. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  70272. }
  70273. #endif
  70274. sqlite3DbFree(db, p->zErrMsg);
  70275. p->zErrMsg = 0;
  70276. p->pResultSet = 0;
  70277. /* Save profiling information from this VDBE run.
  70278. */
  70279. #ifdef VDBE_PROFILE
  70280. {
  70281. FILE *out = fopen("vdbe_profile.out", "a");
  70282. if( out ){
  70283. fprintf(out, "---- ");
  70284. for(i=0; i<p->nOp; i++){
  70285. fprintf(out, "%02x", p->aOp[i].opcode);
  70286. }
  70287. fprintf(out, "\n");
  70288. if( p->zSql ){
  70289. char c, pc = 0;
  70290. fprintf(out, "-- ");
  70291. for(i=0; (c = p->zSql[i])!=0; i++){
  70292. if( pc=='\n' ) fprintf(out, "-- ");
  70293. putc(c, out);
  70294. pc = c;
  70295. }
  70296. if( pc!='\n' ) fprintf(out, "\n");
  70297. }
  70298. for(i=0; i<p->nOp; i++){
  70299. char zHdr[100];
  70300. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  70301. p->aOp[i].cnt,
  70302. p->aOp[i].cycles,
  70303. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  70304. );
  70305. fprintf(out, "%s", zHdr);
  70306. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  70307. }
  70308. fclose(out);
  70309. }
  70310. }
  70311. #endif
  70312. p->magic = VDBE_MAGIC_RESET;
  70313. return p->rc & db->errMask;
  70314. }
  70315. /*
  70316. ** Clean up and delete a VDBE after execution. Return an integer which is
  70317. ** the result code. Write any error message text into *pzErrMsg.
  70318. */
  70319. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  70320. int rc = SQLITE_OK;
  70321. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  70322. rc = sqlite3VdbeReset(p);
  70323. assert( (rc & p->db->errMask)==rc );
  70324. }
  70325. sqlite3VdbeDelete(p);
  70326. return rc;
  70327. }
  70328. /*
  70329. ** If parameter iOp is less than zero, then invoke the destructor for
  70330. ** all auxiliary data pointers currently cached by the VM passed as
  70331. ** the first argument.
  70332. **
  70333. ** Or, if iOp is greater than or equal to zero, then the destructor is
  70334. ** only invoked for those auxiliary data pointers created by the user
  70335. ** function invoked by the OP_Function opcode at instruction iOp of
  70336. ** VM pVdbe, and only then if:
  70337. **
  70338. ** * the associated function parameter is the 32nd or later (counting
  70339. ** from left to right), or
  70340. **
  70341. ** * the corresponding bit in argument mask is clear (where the first
  70342. ** function parameter corresponds to bit 0 etc.).
  70343. */
  70344. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  70345. while( *pp ){
  70346. AuxData *pAux = *pp;
  70347. if( (iOp<0)
  70348. || (pAux->iAuxOp==iOp
  70349. && pAux->iAuxArg>=0
  70350. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  70351. ){
  70352. testcase( pAux->iAuxArg==31 );
  70353. if( pAux->xDeleteAux ){
  70354. pAux->xDeleteAux(pAux->pAux);
  70355. }
  70356. *pp = pAux->pNextAux;
  70357. sqlite3DbFree(db, pAux);
  70358. }else{
  70359. pp= &pAux->pNextAux;
  70360. }
  70361. }
  70362. }
  70363. /*
  70364. ** Free all memory associated with the Vdbe passed as the second argument,
  70365. ** except for object itself, which is preserved.
  70366. **
  70367. ** The difference between this function and sqlite3VdbeDelete() is that
  70368. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  70369. ** the database connection and frees the object itself.
  70370. */
  70371. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  70372. SubProgram *pSub, *pNext;
  70373. assert( p->db==0 || p->db==db );
  70374. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  70375. for(pSub=p->pProgram; pSub; pSub=pNext){
  70376. pNext = pSub->pNext;
  70377. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  70378. sqlite3DbFree(db, pSub);
  70379. }
  70380. if( p->magic!=VDBE_MAGIC_INIT ){
  70381. releaseMemArray(p->aVar, p->nVar);
  70382. sqlite3DbFree(db, p->pVList);
  70383. sqlite3DbFree(db, p->pFree);
  70384. }
  70385. vdbeFreeOpArray(db, p->aOp, p->nOp);
  70386. sqlite3DbFree(db, p->aColName);
  70387. sqlite3DbFree(db, p->zSql);
  70388. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  70389. {
  70390. int i;
  70391. for(i=0; i<p->nScan; i++){
  70392. sqlite3DbFree(db, p->aScan[i].zName);
  70393. }
  70394. sqlite3DbFree(db, p->aScan);
  70395. }
  70396. #endif
  70397. }
  70398. /*
  70399. ** Delete an entire VDBE.
  70400. */
  70401. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  70402. sqlite3 *db;
  70403. if( NEVER(p==0) ) return;
  70404. db = p->db;
  70405. assert( sqlite3_mutex_held(db->mutex) );
  70406. sqlite3VdbeClearObject(db, p);
  70407. if( p->pPrev ){
  70408. p->pPrev->pNext = p->pNext;
  70409. }else{
  70410. assert( db->pVdbe==p );
  70411. db->pVdbe = p->pNext;
  70412. }
  70413. if( p->pNext ){
  70414. p->pNext->pPrev = p->pPrev;
  70415. }
  70416. p->magic = VDBE_MAGIC_DEAD;
  70417. p->db = 0;
  70418. sqlite3DbFreeNN(db, p);
  70419. }
  70420. /*
  70421. ** The cursor "p" has a pending seek operation that has not yet been
  70422. ** carried out. Seek the cursor now. If an error occurs, return
  70423. ** the appropriate error code.
  70424. */
  70425. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  70426. int res, rc;
  70427. #ifdef SQLITE_TEST
  70428. extern int sqlite3_search_count;
  70429. #endif
  70430. assert( p->deferredMoveto );
  70431. assert( p->isTable );
  70432. assert( p->eCurType==CURTYPE_BTREE );
  70433. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  70434. if( rc ) return rc;
  70435. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  70436. #ifdef SQLITE_TEST
  70437. sqlite3_search_count++;
  70438. #endif
  70439. p->deferredMoveto = 0;
  70440. p->cacheStatus = CACHE_STALE;
  70441. return SQLITE_OK;
  70442. }
  70443. /*
  70444. ** Something has moved cursor "p" out of place. Maybe the row it was
  70445. ** pointed to was deleted out from under it. Or maybe the btree was
  70446. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  70447. ** is supposed to be pointing. If the row was deleted out from under the
  70448. ** cursor, set the cursor to point to a NULL row.
  70449. */
  70450. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  70451. int isDifferentRow, rc;
  70452. assert( p->eCurType==CURTYPE_BTREE );
  70453. assert( p->uc.pCursor!=0 );
  70454. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  70455. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  70456. p->cacheStatus = CACHE_STALE;
  70457. if( isDifferentRow ) p->nullRow = 1;
  70458. return rc;
  70459. }
  70460. /*
  70461. ** Check to ensure that the cursor is valid. Restore the cursor
  70462. ** if need be. Return any I/O error from the restore operation.
  70463. */
  70464. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  70465. assert( p->eCurType==CURTYPE_BTREE );
  70466. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  70467. return handleMovedCursor(p);
  70468. }
  70469. return SQLITE_OK;
  70470. }
  70471. /*
  70472. ** Make sure the cursor p is ready to read or write the row to which it
  70473. ** was last positioned. Return an error code if an OOM fault or I/O error
  70474. ** prevents us from positioning the cursor to its correct position.
  70475. **
  70476. ** If a MoveTo operation is pending on the given cursor, then do that
  70477. ** MoveTo now. If no move is pending, check to see if the row has been
  70478. ** deleted out from under the cursor and if it has, mark the row as
  70479. ** a NULL row.
  70480. **
  70481. ** If the cursor is already pointing to the correct row and that row has
  70482. ** not been deleted out from under the cursor, then this routine is a no-op.
  70483. */
  70484. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  70485. VdbeCursor *p = *pp;
  70486. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  70487. if( p->deferredMoveto ){
  70488. int iMap;
  70489. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  70490. *pp = p->pAltCursor;
  70491. *piCol = iMap - 1;
  70492. return SQLITE_OK;
  70493. }
  70494. return handleDeferredMoveto(p);
  70495. }
  70496. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  70497. return handleMovedCursor(p);
  70498. }
  70499. return SQLITE_OK;
  70500. }
  70501. /*
  70502. ** The following functions:
  70503. **
  70504. ** sqlite3VdbeSerialType()
  70505. ** sqlite3VdbeSerialTypeLen()
  70506. ** sqlite3VdbeSerialLen()
  70507. ** sqlite3VdbeSerialPut()
  70508. ** sqlite3VdbeSerialGet()
  70509. **
  70510. ** encapsulate the code that serializes values for storage in SQLite
  70511. ** data and index records. Each serialized value consists of a
  70512. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  70513. ** integer, stored as a varint.
  70514. **
  70515. ** In an SQLite index record, the serial type is stored directly before
  70516. ** the blob of data that it corresponds to. In a table record, all serial
  70517. ** types are stored at the start of the record, and the blobs of data at
  70518. ** the end. Hence these functions allow the caller to handle the
  70519. ** serial-type and data blob separately.
  70520. **
  70521. ** The following table describes the various storage classes for data:
  70522. **
  70523. ** serial type bytes of data type
  70524. ** -------------- --------------- ---------------
  70525. ** 0 0 NULL
  70526. ** 1 1 signed integer
  70527. ** 2 2 signed integer
  70528. ** 3 3 signed integer
  70529. ** 4 4 signed integer
  70530. ** 5 6 signed integer
  70531. ** 6 8 signed integer
  70532. ** 7 8 IEEE float
  70533. ** 8 0 Integer constant 0
  70534. ** 9 0 Integer constant 1
  70535. ** 10,11 reserved for expansion
  70536. ** N>=12 and even (N-12)/2 BLOB
  70537. ** N>=13 and odd (N-13)/2 text
  70538. **
  70539. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  70540. ** of SQLite will not understand those serial types.
  70541. */
  70542. /*
  70543. ** Return the serial-type for the value stored in pMem.
  70544. */
  70545. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  70546. int flags = pMem->flags;
  70547. u32 n;
  70548. assert( pLen!=0 );
  70549. if( flags&MEM_Null ){
  70550. *pLen = 0;
  70551. return 0;
  70552. }
  70553. if( flags&MEM_Int ){
  70554. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  70555. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  70556. i64 i = pMem->u.i;
  70557. u64 u;
  70558. if( i<0 ){
  70559. u = ~i;
  70560. }else{
  70561. u = i;
  70562. }
  70563. if( u<=127 ){
  70564. if( (i&1)==i && file_format>=4 ){
  70565. *pLen = 0;
  70566. return 8+(u32)u;
  70567. }else{
  70568. *pLen = 1;
  70569. return 1;
  70570. }
  70571. }
  70572. if( u<=32767 ){ *pLen = 2; return 2; }
  70573. if( u<=8388607 ){ *pLen = 3; return 3; }
  70574. if( u<=2147483647 ){ *pLen = 4; return 4; }
  70575. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  70576. *pLen = 8;
  70577. return 6;
  70578. }
  70579. if( flags&MEM_Real ){
  70580. *pLen = 8;
  70581. return 7;
  70582. }
  70583. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  70584. assert( pMem->n>=0 );
  70585. n = (u32)pMem->n;
  70586. if( flags & MEM_Zero ){
  70587. n += pMem->u.nZero;
  70588. }
  70589. *pLen = n;
  70590. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  70591. }
  70592. /*
  70593. ** The sizes for serial types less than 128
  70594. */
  70595. static const u8 sqlite3SmallTypeSizes[] = {
  70596. /* 0 1 2 3 4 5 6 7 8 9 */
  70597. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  70598. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  70599. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  70600. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  70601. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  70602. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  70603. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  70604. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  70605. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  70606. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  70607. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  70608. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  70609. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  70610. };
  70611. /*
  70612. ** Return the length of the data corresponding to the supplied serial-type.
  70613. */
  70614. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  70615. if( serial_type>=128 ){
  70616. return (serial_type-12)/2;
  70617. }else{
  70618. assert( serial_type<12
  70619. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  70620. return sqlite3SmallTypeSizes[serial_type];
  70621. }
  70622. }
  70623. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  70624. assert( serial_type<128 );
  70625. return sqlite3SmallTypeSizes[serial_type];
  70626. }
  70627. /*
  70628. ** If we are on an architecture with mixed-endian floating
  70629. ** points (ex: ARM7) then swap the lower 4 bytes with the
  70630. ** upper 4 bytes. Return the result.
  70631. **
  70632. ** For most architectures, this is a no-op.
  70633. **
  70634. ** (later): It is reported to me that the mixed-endian problem
  70635. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  70636. ** that early versions of GCC stored the two words of a 64-bit
  70637. ** float in the wrong order. And that error has been propagated
  70638. ** ever since. The blame is not necessarily with GCC, though.
  70639. ** GCC might have just copying the problem from a prior compiler.
  70640. ** I am also told that newer versions of GCC that follow a different
  70641. ** ABI get the byte order right.
  70642. **
  70643. ** Developers using SQLite on an ARM7 should compile and run their
  70644. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  70645. ** enabled, some asserts below will ensure that the byte order of
  70646. ** floating point values is correct.
  70647. **
  70648. ** (2007-08-30) Frank van Vugt has studied this problem closely
  70649. ** and has send his findings to the SQLite developers. Frank
  70650. ** writes that some Linux kernels offer floating point hardware
  70651. ** emulation that uses only 32-bit mantissas instead of a full
  70652. ** 48-bits as required by the IEEE standard. (This is the
  70653. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  70654. ** byte swapping becomes very complicated. To avoid problems,
  70655. ** the necessary byte swapping is carried out using a 64-bit integer
  70656. ** rather than a 64-bit float. Frank assures us that the code here
  70657. ** works for him. We, the developers, have no way to independently
  70658. ** verify this, but Frank seems to know what he is talking about
  70659. ** so we trust him.
  70660. */
  70661. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  70662. static u64 floatSwap(u64 in){
  70663. union {
  70664. u64 r;
  70665. u32 i[2];
  70666. } u;
  70667. u32 t;
  70668. u.r = in;
  70669. t = u.i[0];
  70670. u.i[0] = u.i[1];
  70671. u.i[1] = t;
  70672. return u.r;
  70673. }
  70674. # define swapMixedEndianFloat(X) X = floatSwap(X)
  70675. #else
  70676. # define swapMixedEndianFloat(X)
  70677. #endif
  70678. /*
  70679. ** Write the serialized data blob for the value stored in pMem into
  70680. ** buf. It is assumed that the caller has allocated sufficient space.
  70681. ** Return the number of bytes written.
  70682. **
  70683. ** nBuf is the amount of space left in buf[]. The caller is responsible
  70684. ** for allocating enough space to buf[] to hold the entire field, exclusive
  70685. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  70686. **
  70687. ** Return the number of bytes actually written into buf[]. The number
  70688. ** of bytes in the zero-filled tail is included in the return value only
  70689. ** if those bytes were zeroed in buf[].
  70690. */
  70691. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  70692. u32 len;
  70693. /* Integer and Real */
  70694. if( serial_type<=7 && serial_type>0 ){
  70695. u64 v;
  70696. u32 i;
  70697. if( serial_type==7 ){
  70698. assert( sizeof(v)==sizeof(pMem->u.r) );
  70699. memcpy(&v, &pMem->u.r, sizeof(v));
  70700. swapMixedEndianFloat(v);
  70701. }else{
  70702. v = pMem->u.i;
  70703. }
  70704. len = i = sqlite3SmallTypeSizes[serial_type];
  70705. assert( i>0 );
  70706. do{
  70707. buf[--i] = (u8)(v&0xFF);
  70708. v >>= 8;
  70709. }while( i );
  70710. return len;
  70711. }
  70712. /* String or blob */
  70713. if( serial_type>=12 ){
  70714. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  70715. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  70716. len = pMem->n;
  70717. if( len>0 ) memcpy(buf, pMem->z, len);
  70718. return len;
  70719. }
  70720. /* NULL or constants 0 or 1 */
  70721. return 0;
  70722. }
  70723. /* Input "x" is a sequence of unsigned characters that represent a
  70724. ** big-endian integer. Return the equivalent native integer
  70725. */
  70726. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  70727. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  70728. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  70729. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  70730. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  70731. /*
  70732. ** Deserialize the data blob pointed to by buf as serial type serial_type
  70733. ** and store the result in pMem. Return the number of bytes read.
  70734. **
  70735. ** This function is implemented as two separate routines for performance.
  70736. ** The few cases that require local variables are broken out into a separate
  70737. ** routine so that in most cases the overhead of moving the stack pointer
  70738. ** is avoided.
  70739. */
  70740. static u32 SQLITE_NOINLINE serialGet(
  70741. const unsigned char *buf, /* Buffer to deserialize from */
  70742. u32 serial_type, /* Serial type to deserialize */
  70743. Mem *pMem /* Memory cell to write value into */
  70744. ){
  70745. u64 x = FOUR_BYTE_UINT(buf);
  70746. u32 y = FOUR_BYTE_UINT(buf+4);
  70747. x = (x<<32) + y;
  70748. if( serial_type==6 ){
  70749. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  70750. ** twos-complement integer. */
  70751. pMem->u.i = *(i64*)&x;
  70752. pMem->flags = MEM_Int;
  70753. testcase( pMem->u.i<0 );
  70754. }else{
  70755. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  70756. ** floating point number. */
  70757. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  70758. /* Verify that integers and floating point values use the same
  70759. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  70760. ** defined that 64-bit floating point values really are mixed
  70761. ** endian.
  70762. */
  70763. static const u64 t1 = ((u64)0x3ff00000)<<32;
  70764. static const double r1 = 1.0;
  70765. u64 t2 = t1;
  70766. swapMixedEndianFloat(t2);
  70767. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  70768. #endif
  70769. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  70770. swapMixedEndianFloat(x);
  70771. memcpy(&pMem->u.r, &x, sizeof(x));
  70772. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  70773. }
  70774. return 8;
  70775. }
  70776. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  70777. const unsigned char *buf, /* Buffer to deserialize from */
  70778. u32 serial_type, /* Serial type to deserialize */
  70779. Mem *pMem /* Memory cell to write value into */
  70780. ){
  70781. switch( serial_type ){
  70782. case 10: /* Reserved for future use */
  70783. case 11: /* Reserved for future use */
  70784. case 0: { /* Null */
  70785. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  70786. pMem->flags = MEM_Null;
  70787. break;
  70788. }
  70789. case 1: {
  70790. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  70791. ** integer. */
  70792. pMem->u.i = ONE_BYTE_INT(buf);
  70793. pMem->flags = MEM_Int;
  70794. testcase( pMem->u.i<0 );
  70795. return 1;
  70796. }
  70797. case 2: { /* 2-byte signed integer */
  70798. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  70799. ** twos-complement integer. */
  70800. pMem->u.i = TWO_BYTE_INT(buf);
  70801. pMem->flags = MEM_Int;
  70802. testcase( pMem->u.i<0 );
  70803. return 2;
  70804. }
  70805. case 3: { /* 3-byte signed integer */
  70806. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  70807. ** twos-complement integer. */
  70808. pMem->u.i = THREE_BYTE_INT(buf);
  70809. pMem->flags = MEM_Int;
  70810. testcase( pMem->u.i<0 );
  70811. return 3;
  70812. }
  70813. case 4: { /* 4-byte signed integer */
  70814. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  70815. ** twos-complement integer. */
  70816. pMem->u.i = FOUR_BYTE_INT(buf);
  70817. #ifdef __HP_cc
  70818. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  70819. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  70820. #endif
  70821. pMem->flags = MEM_Int;
  70822. testcase( pMem->u.i<0 );
  70823. return 4;
  70824. }
  70825. case 5: { /* 6-byte signed integer */
  70826. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  70827. ** twos-complement integer. */
  70828. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  70829. pMem->flags = MEM_Int;
  70830. testcase( pMem->u.i<0 );
  70831. return 6;
  70832. }
  70833. case 6: /* 8-byte signed integer */
  70834. case 7: { /* IEEE floating point */
  70835. /* These use local variables, so do them in a separate routine
  70836. ** to avoid having to move the frame pointer in the common case */
  70837. return serialGet(buf,serial_type,pMem);
  70838. }
  70839. case 8: /* Integer 0 */
  70840. case 9: { /* Integer 1 */
  70841. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  70842. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  70843. pMem->u.i = serial_type-8;
  70844. pMem->flags = MEM_Int;
  70845. return 0;
  70846. }
  70847. default: {
  70848. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  70849. ** length.
  70850. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  70851. ** (N-13)/2 bytes in length. */
  70852. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  70853. pMem->z = (char *)buf;
  70854. pMem->n = (serial_type-12)/2;
  70855. pMem->flags = aFlag[serial_type&1];
  70856. return pMem->n;
  70857. }
  70858. }
  70859. return 0;
  70860. }
  70861. /*
  70862. ** This routine is used to allocate sufficient space for an UnpackedRecord
  70863. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  70864. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  70865. **
  70866. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  70867. ** the unaligned buffer passed via the second and third arguments (presumably
  70868. ** stack space). If the former, then *ppFree is set to a pointer that should
  70869. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  70870. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  70871. ** before returning.
  70872. **
  70873. ** If an OOM error occurs, NULL is returned.
  70874. */
  70875. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  70876. KeyInfo *pKeyInfo /* Description of the record */
  70877. ){
  70878. UnpackedRecord *p; /* Unpacked record to return */
  70879. int nByte; /* Number of bytes required for *p */
  70880. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  70881. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  70882. if( !p ) return 0;
  70883. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  70884. assert( pKeyInfo->aSortOrder!=0 );
  70885. p->pKeyInfo = pKeyInfo;
  70886. p->nField = pKeyInfo->nKeyField + 1;
  70887. return p;
  70888. }
  70889. /*
  70890. ** Given the nKey-byte encoding of a record in pKey[], populate the
  70891. ** UnpackedRecord structure indicated by the fourth argument with the
  70892. ** contents of the decoded record.
  70893. */
  70894. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  70895. KeyInfo *pKeyInfo, /* Information about the record format */
  70896. int nKey, /* Size of the binary record */
  70897. const void *pKey, /* The binary record */
  70898. UnpackedRecord *p /* Populate this structure before returning. */
  70899. ){
  70900. const unsigned char *aKey = (const unsigned char *)pKey;
  70901. int d;
  70902. u32 idx; /* Offset in aKey[] to read from */
  70903. u16 u; /* Unsigned loop counter */
  70904. u32 szHdr;
  70905. Mem *pMem = p->aMem;
  70906. p->default_rc = 0;
  70907. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70908. idx = getVarint32(aKey, szHdr);
  70909. d = szHdr;
  70910. u = 0;
  70911. while( idx<szHdr && d<=nKey ){
  70912. u32 serial_type;
  70913. idx += getVarint32(&aKey[idx], serial_type);
  70914. pMem->enc = pKeyInfo->enc;
  70915. pMem->db = pKeyInfo->db;
  70916. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  70917. pMem->szMalloc = 0;
  70918. pMem->z = 0;
  70919. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  70920. pMem++;
  70921. if( (++u)>=p->nField ) break;
  70922. }
  70923. assert( u<=pKeyInfo->nKeyField + 1 );
  70924. p->nField = u;
  70925. }
  70926. #ifdef SQLITE_DEBUG
  70927. /*
  70928. ** This function compares two index or table record keys in the same way
  70929. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  70930. ** this function deserializes and compares values using the
  70931. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  70932. ** in assert() statements to ensure that the optimized code in
  70933. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  70934. **
  70935. ** Return true if the result of comparison is equivalent to desiredResult.
  70936. ** Return false if there is a disagreement.
  70937. */
  70938. static int vdbeRecordCompareDebug(
  70939. int nKey1, const void *pKey1, /* Left key */
  70940. const UnpackedRecord *pPKey2, /* Right key */
  70941. int desiredResult /* Correct answer */
  70942. ){
  70943. u32 d1; /* Offset into aKey[] of next data element */
  70944. u32 idx1; /* Offset into aKey[] of next header element */
  70945. u32 szHdr1; /* Number of bytes in header */
  70946. int i = 0;
  70947. int rc = 0;
  70948. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  70949. KeyInfo *pKeyInfo;
  70950. Mem mem1;
  70951. pKeyInfo = pPKey2->pKeyInfo;
  70952. if( pKeyInfo->db==0 ) return 1;
  70953. mem1.enc = pKeyInfo->enc;
  70954. mem1.db = pKeyInfo->db;
  70955. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  70956. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  70957. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  70958. ** We could initialize it, as shown here, to silence those complaints.
  70959. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  70960. ** the unnecessary initialization has a measurable negative performance
  70961. ** impact, since this routine is a very high runner. And so, we choose
  70962. ** to ignore the compiler warnings and leave this variable uninitialized.
  70963. */
  70964. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  70965. idx1 = getVarint32(aKey1, szHdr1);
  70966. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  70967. d1 = szHdr1;
  70968. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  70969. assert( pKeyInfo->aSortOrder!=0 );
  70970. assert( pKeyInfo->nKeyField>0 );
  70971. assert( idx1<=szHdr1 || CORRUPT_DB );
  70972. do{
  70973. u32 serial_type1;
  70974. /* Read the serial types for the next element in each key. */
  70975. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  70976. /* Verify that there is enough key space remaining to avoid
  70977. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  70978. ** always be greater than or equal to the amount of required key space.
  70979. ** Use that approximation to avoid the more expensive call to
  70980. ** sqlite3VdbeSerialTypeLen() in the common case.
  70981. */
  70982. if( d1+serial_type1+2>(u32)nKey1
  70983. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  70984. ){
  70985. break;
  70986. }
  70987. /* Extract the values to be compared.
  70988. */
  70989. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  70990. /* Do the comparison
  70991. */
  70992. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  70993. if( rc!=0 ){
  70994. assert( mem1.szMalloc==0 ); /* See comment below */
  70995. if( pKeyInfo->aSortOrder[i] ){
  70996. rc = -rc; /* Invert the result for DESC sort order. */
  70997. }
  70998. goto debugCompareEnd;
  70999. }
  71000. i++;
  71001. }while( idx1<szHdr1 && i<pPKey2->nField );
  71002. /* No memory allocation is ever used on mem1. Prove this using
  71003. ** the following assert(). If the assert() fails, it indicates a
  71004. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  71005. */
  71006. assert( mem1.szMalloc==0 );
  71007. /* rc==0 here means that one of the keys ran out of fields and
  71008. ** all the fields up to that point were equal. Return the default_rc
  71009. ** value. */
  71010. rc = pPKey2->default_rc;
  71011. debugCompareEnd:
  71012. if( desiredResult==0 && rc==0 ) return 1;
  71013. if( desiredResult<0 && rc<0 ) return 1;
  71014. if( desiredResult>0 && rc>0 ) return 1;
  71015. if( CORRUPT_DB ) return 1;
  71016. if( pKeyInfo->db->mallocFailed ) return 1;
  71017. return 0;
  71018. }
  71019. #endif
  71020. #ifdef SQLITE_DEBUG
  71021. /*
  71022. ** Count the number of fields (a.k.a. columns) in the record given by
  71023. ** pKey,nKey. The verify that this count is less than or equal to the
  71024. ** limit given by pKeyInfo->nAllField.
  71025. **
  71026. ** If this constraint is not satisfied, it means that the high-speed
  71027. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  71028. ** not work correctly. If this assert() ever fires, it probably means
  71029. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  71030. ** incorrectly.
  71031. */
  71032. static void vdbeAssertFieldCountWithinLimits(
  71033. int nKey, const void *pKey, /* The record to verify */
  71034. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  71035. ){
  71036. int nField = 0;
  71037. u32 szHdr;
  71038. u32 idx;
  71039. u32 notUsed;
  71040. const unsigned char *aKey = (const unsigned char*)pKey;
  71041. if( CORRUPT_DB ) return;
  71042. idx = getVarint32(aKey, szHdr);
  71043. assert( nKey>=0 );
  71044. assert( szHdr<=(u32)nKey );
  71045. while( idx<szHdr ){
  71046. idx += getVarint32(aKey+idx, notUsed);
  71047. nField++;
  71048. }
  71049. assert( nField <= pKeyInfo->nAllField );
  71050. }
  71051. #else
  71052. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  71053. #endif
  71054. /*
  71055. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  71056. ** using the collation sequence pColl. As usual, return a negative , zero
  71057. ** or positive value if *pMem1 is less than, equal to or greater than
  71058. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  71059. */
  71060. static int vdbeCompareMemString(
  71061. const Mem *pMem1,
  71062. const Mem *pMem2,
  71063. const CollSeq *pColl,
  71064. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  71065. ){
  71066. if( pMem1->enc==pColl->enc ){
  71067. /* The strings are already in the correct encoding. Call the
  71068. ** comparison function directly */
  71069. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  71070. }else{
  71071. int rc;
  71072. const void *v1, *v2;
  71073. Mem c1;
  71074. Mem c2;
  71075. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  71076. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  71077. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  71078. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  71079. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  71080. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  71081. if( (v1==0 || v2==0) ){
  71082. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  71083. rc = 0;
  71084. }else{
  71085. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  71086. }
  71087. sqlite3VdbeMemRelease(&c1);
  71088. sqlite3VdbeMemRelease(&c2);
  71089. return rc;
  71090. }
  71091. }
  71092. /*
  71093. ** The input pBlob is guaranteed to be a Blob that is not marked
  71094. ** with MEM_Zero. Return true if it could be a zero-blob.
  71095. */
  71096. static int isAllZero(const char *z, int n){
  71097. int i;
  71098. for(i=0; i<n; i++){
  71099. if( z[i] ) return 0;
  71100. }
  71101. return 1;
  71102. }
  71103. /*
  71104. ** Compare two blobs. Return negative, zero, or positive if the first
  71105. ** is less than, equal to, or greater than the second, respectively.
  71106. ** If one blob is a prefix of the other, then the shorter is the lessor.
  71107. */
  71108. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  71109. int c;
  71110. int n1 = pB1->n;
  71111. int n2 = pB2->n;
  71112. /* It is possible to have a Blob value that has some non-zero content
  71113. ** followed by zero content. But that only comes up for Blobs formed
  71114. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  71115. ** sqlite3MemCompare(). */
  71116. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  71117. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  71118. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  71119. if( pB1->flags & pB2->flags & MEM_Zero ){
  71120. return pB1->u.nZero - pB2->u.nZero;
  71121. }else if( pB1->flags & MEM_Zero ){
  71122. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  71123. return pB1->u.nZero - n2;
  71124. }else{
  71125. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  71126. return n1 - pB2->u.nZero;
  71127. }
  71128. }
  71129. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  71130. if( c ) return c;
  71131. return n1 - n2;
  71132. }
  71133. /*
  71134. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  71135. ** number. Return negative, zero, or positive if the first (i64) is less than,
  71136. ** equal to, or greater than the second (double).
  71137. */
  71138. static int sqlite3IntFloatCompare(i64 i, double r){
  71139. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  71140. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  71141. if( x<r ) return -1;
  71142. if( x>r ) return +1;
  71143. return 0;
  71144. }else{
  71145. i64 y;
  71146. double s;
  71147. if( r<-9223372036854775808.0 ) return +1;
  71148. if( r>9223372036854775807.0 ) return -1;
  71149. y = (i64)r;
  71150. if( i<y ) return -1;
  71151. if( i>y ){
  71152. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  71153. return +1;
  71154. }
  71155. s = (double)i;
  71156. if( s<r ) return -1;
  71157. if( s>r ) return +1;
  71158. return 0;
  71159. }
  71160. }
  71161. /*
  71162. ** Compare the values contained by the two memory cells, returning
  71163. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  71164. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  71165. ** and reals) sorted numerically, followed by text ordered by the collating
  71166. ** sequence pColl and finally blob's ordered by memcmp().
  71167. **
  71168. ** Two NULL values are considered equal by this function.
  71169. */
  71170. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  71171. int f1, f2;
  71172. int combined_flags;
  71173. f1 = pMem1->flags;
  71174. f2 = pMem2->flags;
  71175. combined_flags = f1|f2;
  71176. assert( (combined_flags & MEM_RowSet)==0 );
  71177. /* If one value is NULL, it is less than the other. If both values
  71178. ** are NULL, return 0.
  71179. */
  71180. if( combined_flags&MEM_Null ){
  71181. return (f2&MEM_Null) - (f1&MEM_Null);
  71182. }
  71183. /* At least one of the two values is a number
  71184. */
  71185. if( combined_flags&(MEM_Int|MEM_Real) ){
  71186. if( (f1 & f2 & MEM_Int)!=0 ){
  71187. if( pMem1->u.i < pMem2->u.i ) return -1;
  71188. if( pMem1->u.i > pMem2->u.i ) return +1;
  71189. return 0;
  71190. }
  71191. if( (f1 & f2 & MEM_Real)!=0 ){
  71192. if( pMem1->u.r < pMem2->u.r ) return -1;
  71193. if( pMem1->u.r > pMem2->u.r ) return +1;
  71194. return 0;
  71195. }
  71196. if( (f1&MEM_Int)!=0 ){
  71197. if( (f2&MEM_Real)!=0 ){
  71198. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  71199. }else{
  71200. return -1;
  71201. }
  71202. }
  71203. if( (f1&MEM_Real)!=0 ){
  71204. if( (f2&MEM_Int)!=0 ){
  71205. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  71206. }else{
  71207. return -1;
  71208. }
  71209. }
  71210. return +1;
  71211. }
  71212. /* If one value is a string and the other is a blob, the string is less.
  71213. ** If both are strings, compare using the collating functions.
  71214. */
  71215. if( combined_flags&MEM_Str ){
  71216. if( (f1 & MEM_Str)==0 ){
  71217. return 1;
  71218. }
  71219. if( (f2 & MEM_Str)==0 ){
  71220. return -1;
  71221. }
  71222. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  71223. assert( pMem1->enc==SQLITE_UTF8 ||
  71224. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  71225. /* The collation sequence must be defined at this point, even if
  71226. ** the user deletes the collation sequence after the vdbe program is
  71227. ** compiled (this was not always the case).
  71228. */
  71229. assert( !pColl || pColl->xCmp );
  71230. if( pColl ){
  71231. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  71232. }
  71233. /* If a NULL pointer was passed as the collate function, fall through
  71234. ** to the blob case and use memcmp(). */
  71235. }
  71236. /* Both values must be blobs. Compare using memcmp(). */
  71237. return sqlite3BlobCompare(pMem1, pMem2);
  71238. }
  71239. /*
  71240. ** The first argument passed to this function is a serial-type that
  71241. ** corresponds to an integer - all values between 1 and 9 inclusive
  71242. ** except 7. The second points to a buffer containing an integer value
  71243. ** serialized according to serial_type. This function deserializes
  71244. ** and returns the value.
  71245. */
  71246. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  71247. u32 y;
  71248. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  71249. switch( serial_type ){
  71250. case 0:
  71251. case 1:
  71252. testcase( aKey[0]&0x80 );
  71253. return ONE_BYTE_INT(aKey);
  71254. case 2:
  71255. testcase( aKey[0]&0x80 );
  71256. return TWO_BYTE_INT(aKey);
  71257. case 3:
  71258. testcase( aKey[0]&0x80 );
  71259. return THREE_BYTE_INT(aKey);
  71260. case 4: {
  71261. testcase( aKey[0]&0x80 );
  71262. y = FOUR_BYTE_UINT(aKey);
  71263. return (i64)*(int*)&y;
  71264. }
  71265. case 5: {
  71266. testcase( aKey[0]&0x80 );
  71267. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  71268. }
  71269. case 6: {
  71270. u64 x = FOUR_BYTE_UINT(aKey);
  71271. testcase( aKey[0]&0x80 );
  71272. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  71273. return (i64)*(i64*)&x;
  71274. }
  71275. }
  71276. return (serial_type - 8);
  71277. }
  71278. /*
  71279. ** This function compares the two table rows or index records
  71280. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  71281. ** or positive integer if key1 is less than, equal to or
  71282. ** greater than key2. The {nKey1, pKey1} key must be a blob
  71283. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  71284. ** key must be a parsed key such as obtained from
  71285. ** sqlite3VdbeParseRecord.
  71286. **
  71287. ** If argument bSkip is non-zero, it is assumed that the caller has already
  71288. ** determined that the first fields of the keys are equal.
  71289. **
  71290. ** Key1 and Key2 do not have to contain the same number of fields. If all
  71291. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  71292. ** returned.
  71293. **
  71294. ** If database corruption is discovered, set pPKey2->errCode to
  71295. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  71296. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  71297. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  71298. */
  71299. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  71300. int nKey1, const void *pKey1, /* Left key */
  71301. UnpackedRecord *pPKey2, /* Right key */
  71302. int bSkip /* If true, skip the first field */
  71303. ){
  71304. u32 d1; /* Offset into aKey[] of next data element */
  71305. int i; /* Index of next field to compare */
  71306. u32 szHdr1; /* Size of record header in bytes */
  71307. u32 idx1; /* Offset of first type in header */
  71308. int rc = 0; /* Return value */
  71309. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  71310. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  71311. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  71312. Mem mem1;
  71313. /* If bSkip is true, then the caller has already determined that the first
  71314. ** two elements in the keys are equal. Fix the various stack variables so
  71315. ** that this routine begins comparing at the second field. */
  71316. if( bSkip ){
  71317. u32 s1;
  71318. idx1 = 1 + getVarint32(&aKey1[1], s1);
  71319. szHdr1 = aKey1[0];
  71320. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  71321. i = 1;
  71322. pRhs++;
  71323. }else{
  71324. idx1 = getVarint32(aKey1, szHdr1);
  71325. d1 = szHdr1;
  71326. if( d1>(unsigned)nKey1 ){
  71327. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  71328. return 0; /* Corruption */
  71329. }
  71330. i = 0;
  71331. }
  71332. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  71333. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  71334. || CORRUPT_DB );
  71335. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  71336. assert( pPKey2->pKeyInfo->nKeyField>0 );
  71337. assert( idx1<=szHdr1 || CORRUPT_DB );
  71338. do{
  71339. u32 serial_type;
  71340. /* RHS is an integer */
  71341. if( pRhs->flags & MEM_Int ){
  71342. serial_type = aKey1[idx1];
  71343. testcase( serial_type==12 );
  71344. if( serial_type>=10 ){
  71345. rc = +1;
  71346. }else if( serial_type==0 ){
  71347. rc = -1;
  71348. }else if( serial_type==7 ){
  71349. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  71350. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  71351. }else{
  71352. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  71353. i64 rhs = pRhs->u.i;
  71354. if( lhs<rhs ){
  71355. rc = -1;
  71356. }else if( lhs>rhs ){
  71357. rc = +1;
  71358. }
  71359. }
  71360. }
  71361. /* RHS is real */
  71362. else if( pRhs->flags & MEM_Real ){
  71363. serial_type = aKey1[idx1];
  71364. if( serial_type>=10 ){
  71365. /* Serial types 12 or greater are strings and blobs (greater than
  71366. ** numbers). Types 10 and 11 are currently "reserved for future
  71367. ** use", so it doesn't really matter what the results of comparing
  71368. ** them to numberic values are. */
  71369. rc = +1;
  71370. }else if( serial_type==0 ){
  71371. rc = -1;
  71372. }else{
  71373. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  71374. if( serial_type==7 ){
  71375. if( mem1.u.r<pRhs->u.r ){
  71376. rc = -1;
  71377. }else if( mem1.u.r>pRhs->u.r ){
  71378. rc = +1;
  71379. }
  71380. }else{
  71381. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  71382. }
  71383. }
  71384. }
  71385. /* RHS is a string */
  71386. else if( pRhs->flags & MEM_Str ){
  71387. getVarint32(&aKey1[idx1], serial_type);
  71388. testcase( serial_type==12 );
  71389. if( serial_type<12 ){
  71390. rc = -1;
  71391. }else if( !(serial_type & 0x01) ){
  71392. rc = +1;
  71393. }else{
  71394. mem1.n = (serial_type - 12) / 2;
  71395. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  71396. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  71397. if( (d1+mem1.n) > (unsigned)nKey1 ){
  71398. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  71399. return 0; /* Corruption */
  71400. }else if( pKeyInfo->aColl[i] ){
  71401. mem1.enc = pKeyInfo->enc;
  71402. mem1.db = pKeyInfo->db;
  71403. mem1.flags = MEM_Str;
  71404. mem1.z = (char*)&aKey1[d1];
  71405. rc = vdbeCompareMemString(
  71406. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  71407. );
  71408. }else{
  71409. int nCmp = MIN(mem1.n, pRhs->n);
  71410. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  71411. if( rc==0 ) rc = mem1.n - pRhs->n;
  71412. }
  71413. }
  71414. }
  71415. /* RHS is a blob */
  71416. else if( pRhs->flags & MEM_Blob ){
  71417. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  71418. getVarint32(&aKey1[idx1], serial_type);
  71419. testcase( serial_type==12 );
  71420. if( serial_type<12 || (serial_type & 0x01) ){
  71421. rc = -1;
  71422. }else{
  71423. int nStr = (serial_type - 12) / 2;
  71424. testcase( (d1+nStr)==(unsigned)nKey1 );
  71425. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  71426. if( (d1+nStr) > (unsigned)nKey1 ){
  71427. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  71428. return 0; /* Corruption */
  71429. }else if( pRhs->flags & MEM_Zero ){
  71430. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  71431. rc = 1;
  71432. }else{
  71433. rc = nStr - pRhs->u.nZero;
  71434. }
  71435. }else{
  71436. int nCmp = MIN(nStr, pRhs->n);
  71437. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  71438. if( rc==0 ) rc = nStr - pRhs->n;
  71439. }
  71440. }
  71441. }
  71442. /* RHS is null */
  71443. else{
  71444. serial_type = aKey1[idx1];
  71445. rc = (serial_type!=0);
  71446. }
  71447. if( rc!=0 ){
  71448. if( pKeyInfo->aSortOrder[i] ){
  71449. rc = -rc;
  71450. }
  71451. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  71452. assert( mem1.szMalloc==0 ); /* See comment below */
  71453. return rc;
  71454. }
  71455. i++;
  71456. pRhs++;
  71457. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  71458. idx1 += sqlite3VarintLen(serial_type);
  71459. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  71460. /* No memory allocation is ever used on mem1. Prove this using
  71461. ** the following assert(). If the assert() fails, it indicates a
  71462. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  71463. assert( mem1.szMalloc==0 );
  71464. /* rc==0 here means that one or both of the keys ran out of fields and
  71465. ** all the fields up to that point were equal. Return the default_rc
  71466. ** value. */
  71467. assert( CORRUPT_DB
  71468. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  71469. || pKeyInfo->db->mallocFailed
  71470. );
  71471. pPKey2->eqSeen = 1;
  71472. return pPKey2->default_rc;
  71473. }
  71474. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  71475. int nKey1, const void *pKey1, /* Left key */
  71476. UnpackedRecord *pPKey2 /* Right key */
  71477. ){
  71478. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  71479. }
  71480. /*
  71481. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  71482. ** that (a) the first field of pPKey2 is an integer, and (b) the
  71483. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  71484. ** byte (i.e. is less than 128).
  71485. **
  71486. ** To avoid concerns about buffer overreads, this routine is only used
  71487. ** on schemas where the maximum valid header size is 63 bytes or less.
  71488. */
  71489. static int vdbeRecordCompareInt(
  71490. int nKey1, const void *pKey1, /* Left key */
  71491. UnpackedRecord *pPKey2 /* Right key */
  71492. ){
  71493. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  71494. int serial_type = ((const u8*)pKey1)[1];
  71495. int res;
  71496. u32 y;
  71497. u64 x;
  71498. i64 v;
  71499. i64 lhs;
  71500. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  71501. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  71502. switch( serial_type ){
  71503. case 1: { /* 1-byte signed integer */
  71504. lhs = ONE_BYTE_INT(aKey);
  71505. testcase( lhs<0 );
  71506. break;
  71507. }
  71508. case 2: { /* 2-byte signed integer */
  71509. lhs = TWO_BYTE_INT(aKey);
  71510. testcase( lhs<0 );
  71511. break;
  71512. }
  71513. case 3: { /* 3-byte signed integer */
  71514. lhs = THREE_BYTE_INT(aKey);
  71515. testcase( lhs<0 );
  71516. break;
  71517. }
  71518. case 4: { /* 4-byte signed integer */
  71519. y = FOUR_BYTE_UINT(aKey);
  71520. lhs = (i64)*(int*)&y;
  71521. testcase( lhs<0 );
  71522. break;
  71523. }
  71524. case 5: { /* 6-byte signed integer */
  71525. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  71526. testcase( lhs<0 );
  71527. break;
  71528. }
  71529. case 6: { /* 8-byte signed integer */
  71530. x = FOUR_BYTE_UINT(aKey);
  71531. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  71532. lhs = *(i64*)&x;
  71533. testcase( lhs<0 );
  71534. break;
  71535. }
  71536. case 8:
  71537. lhs = 0;
  71538. break;
  71539. case 9:
  71540. lhs = 1;
  71541. break;
  71542. /* This case could be removed without changing the results of running
  71543. ** this code. Including it causes gcc to generate a faster switch
  71544. ** statement (since the range of switch targets now starts at zero and
  71545. ** is contiguous) but does not cause any duplicate code to be generated
  71546. ** (as gcc is clever enough to combine the two like cases). Other
  71547. ** compilers might be similar. */
  71548. case 0: case 7:
  71549. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  71550. default:
  71551. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  71552. }
  71553. v = pPKey2->aMem[0].u.i;
  71554. if( v>lhs ){
  71555. res = pPKey2->r1;
  71556. }else if( v<lhs ){
  71557. res = pPKey2->r2;
  71558. }else if( pPKey2->nField>1 ){
  71559. /* The first fields of the two keys are equal. Compare the trailing
  71560. ** fields. */
  71561. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  71562. }else{
  71563. /* The first fields of the two keys are equal and there are no trailing
  71564. ** fields. Return pPKey2->default_rc in this case. */
  71565. res = pPKey2->default_rc;
  71566. pPKey2->eqSeen = 1;
  71567. }
  71568. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  71569. return res;
  71570. }
  71571. /*
  71572. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  71573. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  71574. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  71575. ** at the start of (pKey1/nKey1) fits in a single byte.
  71576. */
  71577. static int vdbeRecordCompareString(
  71578. int nKey1, const void *pKey1, /* Left key */
  71579. UnpackedRecord *pPKey2 /* Right key */
  71580. ){
  71581. const u8 *aKey1 = (const u8*)pKey1;
  71582. int serial_type;
  71583. int res;
  71584. assert( pPKey2->aMem[0].flags & MEM_Str );
  71585. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  71586. getVarint32(&aKey1[1], serial_type);
  71587. if( serial_type<12 ){
  71588. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  71589. }else if( !(serial_type & 0x01) ){
  71590. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  71591. }else{
  71592. int nCmp;
  71593. int nStr;
  71594. int szHdr = aKey1[0];
  71595. nStr = (serial_type-12) / 2;
  71596. if( (szHdr + nStr) > nKey1 ){
  71597. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  71598. return 0; /* Corruption */
  71599. }
  71600. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  71601. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  71602. if( res==0 ){
  71603. res = nStr - pPKey2->aMem[0].n;
  71604. if( res==0 ){
  71605. if( pPKey2->nField>1 ){
  71606. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  71607. }else{
  71608. res = pPKey2->default_rc;
  71609. pPKey2->eqSeen = 1;
  71610. }
  71611. }else if( res>0 ){
  71612. res = pPKey2->r2;
  71613. }else{
  71614. res = pPKey2->r1;
  71615. }
  71616. }else if( res>0 ){
  71617. res = pPKey2->r2;
  71618. }else{
  71619. res = pPKey2->r1;
  71620. }
  71621. }
  71622. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  71623. || CORRUPT_DB
  71624. || pPKey2->pKeyInfo->db->mallocFailed
  71625. );
  71626. return res;
  71627. }
  71628. /*
  71629. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  71630. ** suitable for comparing serialized records to the unpacked record passed
  71631. ** as the only argument.
  71632. */
  71633. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  71634. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  71635. ** that the size-of-header varint that occurs at the start of each record
  71636. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  71637. ** also assumes that it is safe to overread a buffer by at least the
  71638. ** maximum possible legal header size plus 8 bytes. Because there is
  71639. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  71640. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  71641. ** limit the size of the header to 64 bytes in cases where the first field
  71642. ** is an integer.
  71643. **
  71644. ** The easiest way to enforce this limit is to consider only records with
  71645. ** 13 fields or less. If the first field is an integer, the maximum legal
  71646. ** header size is (12*5 + 1 + 1) bytes. */
  71647. if( p->pKeyInfo->nAllField<=13 ){
  71648. int flags = p->aMem[0].flags;
  71649. if( p->pKeyInfo->aSortOrder[0] ){
  71650. p->r1 = 1;
  71651. p->r2 = -1;
  71652. }else{
  71653. p->r1 = -1;
  71654. p->r2 = 1;
  71655. }
  71656. if( (flags & MEM_Int) ){
  71657. return vdbeRecordCompareInt;
  71658. }
  71659. testcase( flags & MEM_Real );
  71660. testcase( flags & MEM_Null );
  71661. testcase( flags & MEM_Blob );
  71662. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  71663. assert( flags & MEM_Str );
  71664. return vdbeRecordCompareString;
  71665. }
  71666. }
  71667. return sqlite3VdbeRecordCompare;
  71668. }
  71669. /*
  71670. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  71671. ** Read the rowid (the last field in the record) and store it in *rowid.
  71672. ** Return SQLITE_OK if everything works, or an error code otherwise.
  71673. **
  71674. ** pCur might be pointing to text obtained from a corrupt database file.
  71675. ** So the content cannot be trusted. Do appropriate checks on the content.
  71676. */
  71677. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  71678. i64 nCellKey = 0;
  71679. int rc;
  71680. u32 szHdr; /* Size of the header */
  71681. u32 typeRowid; /* Serial type of the rowid */
  71682. u32 lenRowid; /* Size of the rowid */
  71683. Mem m, v;
  71684. /* Get the size of the index entry. Only indices entries of less
  71685. ** than 2GiB are support - anything large must be database corruption.
  71686. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  71687. ** this code can safely assume that nCellKey is 32-bits
  71688. */
  71689. assert( sqlite3BtreeCursorIsValid(pCur) );
  71690. nCellKey = sqlite3BtreePayloadSize(pCur);
  71691. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  71692. /* Read in the complete content of the index entry */
  71693. sqlite3VdbeMemInit(&m, db, 0);
  71694. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  71695. if( rc ){
  71696. return rc;
  71697. }
  71698. /* The index entry must begin with a header size */
  71699. (void)getVarint32((u8*)m.z, szHdr);
  71700. testcase( szHdr==3 );
  71701. testcase( szHdr==m.n );
  71702. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  71703. goto idx_rowid_corruption;
  71704. }
  71705. /* The last field of the index should be an integer - the ROWID.
  71706. ** Verify that the last entry really is an integer. */
  71707. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  71708. testcase( typeRowid==1 );
  71709. testcase( typeRowid==2 );
  71710. testcase( typeRowid==3 );
  71711. testcase( typeRowid==4 );
  71712. testcase( typeRowid==5 );
  71713. testcase( typeRowid==6 );
  71714. testcase( typeRowid==8 );
  71715. testcase( typeRowid==9 );
  71716. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  71717. goto idx_rowid_corruption;
  71718. }
  71719. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  71720. testcase( (u32)m.n==szHdr+lenRowid );
  71721. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  71722. goto idx_rowid_corruption;
  71723. }
  71724. /* Fetch the integer off the end of the index record */
  71725. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  71726. *rowid = v.u.i;
  71727. sqlite3VdbeMemRelease(&m);
  71728. return SQLITE_OK;
  71729. /* Jump here if database corruption is detected after m has been
  71730. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  71731. idx_rowid_corruption:
  71732. testcase( m.szMalloc!=0 );
  71733. sqlite3VdbeMemRelease(&m);
  71734. return SQLITE_CORRUPT_BKPT;
  71735. }
  71736. /*
  71737. ** Compare the key of the index entry that cursor pC is pointing to against
  71738. ** the key string in pUnpacked. Write into *pRes a number
  71739. ** that is negative, zero, or positive if pC is less than, equal to,
  71740. ** or greater than pUnpacked. Return SQLITE_OK on success.
  71741. **
  71742. ** pUnpacked is either created without a rowid or is truncated so that it
  71743. ** omits the rowid at the end. The rowid at the end of the index entry
  71744. ** is ignored as well. Hence, this routine only compares the prefixes
  71745. ** of the keys prior to the final rowid, not the entire key.
  71746. */
  71747. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  71748. sqlite3 *db, /* Database connection */
  71749. VdbeCursor *pC, /* The cursor to compare against */
  71750. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  71751. int *res /* Write the comparison result here */
  71752. ){
  71753. i64 nCellKey = 0;
  71754. int rc;
  71755. BtCursor *pCur;
  71756. Mem m;
  71757. assert( pC->eCurType==CURTYPE_BTREE );
  71758. pCur = pC->uc.pCursor;
  71759. assert( sqlite3BtreeCursorIsValid(pCur) );
  71760. nCellKey = sqlite3BtreePayloadSize(pCur);
  71761. /* nCellKey will always be between 0 and 0xffffffff because of the way
  71762. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  71763. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  71764. *res = 0;
  71765. return SQLITE_CORRUPT_BKPT;
  71766. }
  71767. sqlite3VdbeMemInit(&m, db, 0);
  71768. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  71769. if( rc ){
  71770. return rc;
  71771. }
  71772. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  71773. sqlite3VdbeMemRelease(&m);
  71774. return SQLITE_OK;
  71775. }
  71776. /*
  71777. ** This routine sets the value to be returned by subsequent calls to
  71778. ** sqlite3_changes() on the database handle 'db'.
  71779. */
  71780. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  71781. assert( sqlite3_mutex_held(db->mutex) );
  71782. db->nChange = nChange;
  71783. db->nTotalChange += nChange;
  71784. }
  71785. /*
  71786. ** Set a flag in the vdbe to update the change counter when it is finalised
  71787. ** or reset.
  71788. */
  71789. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  71790. v->changeCntOn = 1;
  71791. }
  71792. /*
  71793. ** Mark every prepared statement associated with a database connection
  71794. ** as expired.
  71795. **
  71796. ** An expired statement means that recompilation of the statement is
  71797. ** recommend. Statements expire when things happen that make their
  71798. ** programs obsolete. Removing user-defined functions or collating
  71799. ** sequences, or changing an authorization function are the types of
  71800. ** things that make prepared statements obsolete.
  71801. */
  71802. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  71803. Vdbe *p;
  71804. for(p = db->pVdbe; p; p=p->pNext){
  71805. p->expired = 1;
  71806. }
  71807. }
  71808. /*
  71809. ** Return the database associated with the Vdbe.
  71810. */
  71811. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  71812. return v->db;
  71813. }
  71814. /*
  71815. ** Return the SQLITE_PREPARE flags for a Vdbe.
  71816. */
  71817. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  71818. return v->prepFlags;
  71819. }
  71820. /*
  71821. ** Return a pointer to an sqlite3_value structure containing the value bound
  71822. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  71823. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  71824. ** constants) to the value before returning it.
  71825. **
  71826. ** The returned value must be freed by the caller using sqlite3ValueFree().
  71827. */
  71828. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  71829. assert( iVar>0 );
  71830. if( v ){
  71831. Mem *pMem = &v->aVar[iVar-1];
  71832. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  71833. if( 0==(pMem->flags & MEM_Null) ){
  71834. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  71835. if( pRet ){
  71836. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  71837. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  71838. }
  71839. return pRet;
  71840. }
  71841. }
  71842. return 0;
  71843. }
  71844. /*
  71845. ** Configure SQL variable iVar so that binding a new value to it signals
  71846. ** to sqlite3_reoptimize() that re-preparing the statement may result
  71847. ** in a better query plan.
  71848. */
  71849. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  71850. assert( iVar>0 );
  71851. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  71852. if( iVar>=32 ){
  71853. v->expmask |= 0x80000000;
  71854. }else{
  71855. v->expmask |= ((u32)1 << (iVar-1));
  71856. }
  71857. }
  71858. /*
  71859. ** Cause a function to throw an error if it was call from OP_PureFunc
  71860. ** rather than OP_Function.
  71861. **
  71862. ** OP_PureFunc means that the function must be deterministic, and should
  71863. ** throw an error if it is given inputs that would make it non-deterministic.
  71864. ** This routine is invoked by date/time functions that use non-deterministic
  71865. ** features such as 'now'.
  71866. */
  71867. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  71868. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71869. if( pCtx->pVdbe==0 ) return 1;
  71870. #endif
  71871. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  71872. sqlite3_result_error(pCtx,
  71873. "non-deterministic function in index expression or CHECK constraint",
  71874. -1);
  71875. return 0;
  71876. }
  71877. return 1;
  71878. }
  71879. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71880. /*
  71881. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  71882. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  71883. ** in memory obtained from sqlite3DbMalloc).
  71884. */
  71885. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  71886. if( pVtab->zErrMsg ){
  71887. sqlite3 *db = p->db;
  71888. sqlite3DbFree(db, p->zErrMsg);
  71889. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  71890. sqlite3_free(pVtab->zErrMsg);
  71891. pVtab->zErrMsg = 0;
  71892. }
  71893. }
  71894. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71895. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71896. /*
  71897. ** If the second argument is not NULL, release any allocations associated
  71898. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  71899. ** structure itself, using sqlite3DbFree().
  71900. **
  71901. ** This function is used to free UnpackedRecord structures allocated by
  71902. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  71903. */
  71904. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  71905. if( p ){
  71906. int i;
  71907. for(i=0; i<nField; i++){
  71908. Mem *pMem = &p->aMem[i];
  71909. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  71910. }
  71911. sqlite3DbFreeNN(db, p);
  71912. }
  71913. }
  71914. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71915. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71916. /*
  71917. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  71918. ** then cursor passed as the second argument should point to the row about
  71919. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  71920. ** the required value will be read from the row the cursor points to.
  71921. */
  71922. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  71923. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  71924. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  71925. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  71926. const char *zDb, /* Database name */
  71927. Table *pTab, /* Modified table */
  71928. i64 iKey1, /* Initial key value */
  71929. int iReg /* Register for new.* record */
  71930. ){
  71931. sqlite3 *db = v->db;
  71932. i64 iKey2;
  71933. PreUpdate preupdate;
  71934. const char *zTbl = pTab->zName;
  71935. static const u8 fakeSortOrder = 0;
  71936. assert( db->pPreUpdate==0 );
  71937. memset(&preupdate, 0, sizeof(PreUpdate));
  71938. if( HasRowid(pTab)==0 ){
  71939. iKey1 = iKey2 = 0;
  71940. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  71941. }else{
  71942. if( op==SQLITE_UPDATE ){
  71943. iKey2 = v->aMem[iReg].u.i;
  71944. }else{
  71945. iKey2 = iKey1;
  71946. }
  71947. }
  71948. assert( pCsr->nField==pTab->nCol
  71949. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  71950. );
  71951. preupdate.v = v;
  71952. preupdate.pCsr = pCsr;
  71953. preupdate.op = op;
  71954. preupdate.iNewReg = iReg;
  71955. preupdate.keyinfo.db = db;
  71956. preupdate.keyinfo.enc = ENC(db);
  71957. preupdate.keyinfo.nKeyField = pTab->nCol;
  71958. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  71959. preupdate.iKey1 = iKey1;
  71960. preupdate.iKey2 = iKey2;
  71961. preupdate.pTab = pTab;
  71962. db->pPreUpdate = &preupdate;
  71963. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  71964. db->pPreUpdate = 0;
  71965. sqlite3DbFree(db, preupdate.aRecord);
  71966. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  71967. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  71968. if( preupdate.aNew ){
  71969. int i;
  71970. for(i=0; i<pCsr->nField; i++){
  71971. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  71972. }
  71973. sqlite3DbFreeNN(db, preupdate.aNew);
  71974. }
  71975. }
  71976. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71977. /************** End of vdbeaux.c *********************************************/
  71978. /************** Begin file vdbeapi.c *****************************************/
  71979. /*
  71980. ** 2004 May 26
  71981. **
  71982. ** The author disclaims copyright to this source code. In place of
  71983. ** a legal notice, here is a blessing:
  71984. **
  71985. ** May you do good and not evil.
  71986. ** May you find forgiveness for yourself and forgive others.
  71987. ** May you share freely, never taking more than you give.
  71988. **
  71989. *************************************************************************
  71990. **
  71991. ** This file contains code use to implement APIs that are part of the
  71992. ** VDBE.
  71993. */
  71994. /* #include "sqliteInt.h" */
  71995. /* #include "vdbeInt.h" */
  71996. #ifndef SQLITE_OMIT_DEPRECATED
  71997. /*
  71998. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  71999. ** to be recompiled. A statement needs to be recompiled whenever the
  72000. ** execution environment changes in a way that would alter the program
  72001. ** that sqlite3_prepare() generates. For example, if new functions or
  72002. ** collating sequences are registered or if an authorizer function is
  72003. ** added or changed.
  72004. */
  72005. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  72006. Vdbe *p = (Vdbe*)pStmt;
  72007. return p==0 || p->expired;
  72008. }
  72009. #endif
  72010. /*
  72011. ** Check on a Vdbe to make sure it has not been finalized. Log
  72012. ** an error and return true if it has been finalized (or is otherwise
  72013. ** invalid). Return false if it is ok.
  72014. */
  72015. static int vdbeSafety(Vdbe *p){
  72016. if( p->db==0 ){
  72017. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  72018. return 1;
  72019. }else{
  72020. return 0;
  72021. }
  72022. }
  72023. static int vdbeSafetyNotNull(Vdbe *p){
  72024. if( p==0 ){
  72025. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  72026. return 1;
  72027. }else{
  72028. return vdbeSafety(p);
  72029. }
  72030. }
  72031. #ifndef SQLITE_OMIT_TRACE
  72032. /*
  72033. ** Invoke the profile callback. This routine is only called if we already
  72034. ** know that the profile callback is defined and needs to be invoked.
  72035. */
  72036. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  72037. sqlite3_int64 iNow;
  72038. sqlite3_int64 iElapse;
  72039. assert( p->startTime>0 );
  72040. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  72041. assert( db->init.busy==0 );
  72042. assert( p->zSql!=0 );
  72043. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  72044. iElapse = (iNow - p->startTime)*1000000;
  72045. if( db->xProfile ){
  72046. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  72047. }
  72048. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  72049. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  72050. }
  72051. p->startTime = 0;
  72052. }
  72053. /*
  72054. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  72055. ** is needed, and it invokes the callback if it is needed.
  72056. */
  72057. # define checkProfileCallback(DB,P) \
  72058. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  72059. #else
  72060. # define checkProfileCallback(DB,P) /*no-op*/
  72061. #endif
  72062. /*
  72063. ** The following routine destroys a virtual machine that is created by
  72064. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  72065. ** success/failure code that describes the result of executing the virtual
  72066. ** machine.
  72067. **
  72068. ** This routine sets the error code and string returned by
  72069. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  72070. */
  72071. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  72072. int rc;
  72073. if( pStmt==0 ){
  72074. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  72075. ** pointer is a harmless no-op. */
  72076. rc = SQLITE_OK;
  72077. }else{
  72078. Vdbe *v = (Vdbe*)pStmt;
  72079. sqlite3 *db = v->db;
  72080. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  72081. sqlite3_mutex_enter(db->mutex);
  72082. checkProfileCallback(db, v);
  72083. rc = sqlite3VdbeFinalize(v);
  72084. rc = sqlite3ApiExit(db, rc);
  72085. sqlite3LeaveMutexAndCloseZombie(db);
  72086. }
  72087. return rc;
  72088. }
  72089. /*
  72090. ** Terminate the current execution of an SQL statement and reset it
  72091. ** back to its starting state so that it can be reused. A success code from
  72092. ** the prior execution is returned.
  72093. **
  72094. ** This routine sets the error code and string returned by
  72095. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  72096. */
  72097. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  72098. int rc;
  72099. if( pStmt==0 ){
  72100. rc = SQLITE_OK;
  72101. }else{
  72102. Vdbe *v = (Vdbe*)pStmt;
  72103. sqlite3 *db = v->db;
  72104. sqlite3_mutex_enter(db->mutex);
  72105. checkProfileCallback(db, v);
  72106. rc = sqlite3VdbeReset(v);
  72107. sqlite3VdbeRewind(v);
  72108. assert( (rc & (db->errMask))==rc );
  72109. rc = sqlite3ApiExit(db, rc);
  72110. sqlite3_mutex_leave(db->mutex);
  72111. }
  72112. return rc;
  72113. }
  72114. /*
  72115. ** Set all the parameters in the compiled SQL statement to NULL.
  72116. */
  72117. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  72118. int i;
  72119. int rc = SQLITE_OK;
  72120. Vdbe *p = (Vdbe*)pStmt;
  72121. #if SQLITE_THREADSAFE
  72122. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  72123. #endif
  72124. sqlite3_mutex_enter(mutex);
  72125. for(i=0; i<p->nVar; i++){
  72126. sqlite3VdbeMemRelease(&p->aVar[i]);
  72127. p->aVar[i].flags = MEM_Null;
  72128. }
  72129. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  72130. if( p->expmask ){
  72131. p->expired = 1;
  72132. }
  72133. sqlite3_mutex_leave(mutex);
  72134. return rc;
  72135. }
  72136. /**************************** sqlite3_value_ *******************************
  72137. ** The following routines extract information from a Mem or sqlite3_value
  72138. ** structure.
  72139. */
  72140. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  72141. Mem *p = (Mem*)pVal;
  72142. if( p->flags & (MEM_Blob|MEM_Str) ){
  72143. if( ExpandBlob(p)!=SQLITE_OK ){
  72144. assert( p->flags==MEM_Null && p->z==0 );
  72145. return 0;
  72146. }
  72147. p->flags |= MEM_Blob;
  72148. return p->n ? p->z : 0;
  72149. }else{
  72150. return sqlite3_value_text(pVal);
  72151. }
  72152. }
  72153. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  72154. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  72155. }
  72156. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  72157. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  72158. }
  72159. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  72160. return sqlite3VdbeRealValue((Mem*)pVal);
  72161. }
  72162. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  72163. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  72164. }
  72165. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  72166. return sqlite3VdbeIntValue((Mem*)pVal);
  72167. }
  72168. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  72169. Mem *pMem = (Mem*)pVal;
  72170. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  72171. }
  72172. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  72173. Mem *p = (Mem*)pVal;
  72174. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  72175. (MEM_Null|MEM_Term|MEM_Subtype)
  72176. && zPType!=0
  72177. && p->eSubtype=='p'
  72178. && strcmp(p->u.zPType, zPType)==0
  72179. ){
  72180. return (void*)p->z;
  72181. }else{
  72182. return 0;
  72183. }
  72184. }
  72185. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  72186. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  72187. }
  72188. #ifndef SQLITE_OMIT_UTF16
  72189. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  72190. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  72191. }
  72192. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  72193. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  72194. }
  72195. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  72196. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  72197. }
  72198. #endif /* SQLITE_OMIT_UTF16 */
  72199. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  72200. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  72201. ** point number string BLOB NULL
  72202. */
  72203. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  72204. static const u8 aType[] = {
  72205. SQLITE_BLOB, /* 0x00 */
  72206. SQLITE_NULL, /* 0x01 */
  72207. SQLITE_TEXT, /* 0x02 */
  72208. SQLITE_NULL, /* 0x03 */
  72209. SQLITE_INTEGER, /* 0x04 */
  72210. SQLITE_NULL, /* 0x05 */
  72211. SQLITE_INTEGER, /* 0x06 */
  72212. SQLITE_NULL, /* 0x07 */
  72213. SQLITE_FLOAT, /* 0x08 */
  72214. SQLITE_NULL, /* 0x09 */
  72215. SQLITE_FLOAT, /* 0x0a */
  72216. SQLITE_NULL, /* 0x0b */
  72217. SQLITE_INTEGER, /* 0x0c */
  72218. SQLITE_NULL, /* 0x0d */
  72219. SQLITE_INTEGER, /* 0x0e */
  72220. SQLITE_NULL, /* 0x0f */
  72221. SQLITE_BLOB, /* 0x10 */
  72222. SQLITE_NULL, /* 0x11 */
  72223. SQLITE_TEXT, /* 0x12 */
  72224. SQLITE_NULL, /* 0x13 */
  72225. SQLITE_INTEGER, /* 0x14 */
  72226. SQLITE_NULL, /* 0x15 */
  72227. SQLITE_INTEGER, /* 0x16 */
  72228. SQLITE_NULL, /* 0x17 */
  72229. SQLITE_FLOAT, /* 0x18 */
  72230. SQLITE_NULL, /* 0x19 */
  72231. SQLITE_FLOAT, /* 0x1a */
  72232. SQLITE_NULL, /* 0x1b */
  72233. SQLITE_INTEGER, /* 0x1c */
  72234. SQLITE_NULL, /* 0x1d */
  72235. SQLITE_INTEGER, /* 0x1e */
  72236. SQLITE_NULL, /* 0x1f */
  72237. };
  72238. return aType[pVal->flags&MEM_AffMask];
  72239. }
  72240. /* Make a copy of an sqlite3_value object
  72241. */
  72242. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  72243. sqlite3_value *pNew;
  72244. if( pOrig==0 ) return 0;
  72245. pNew = sqlite3_malloc( sizeof(*pNew) );
  72246. if( pNew==0 ) return 0;
  72247. memset(pNew, 0, sizeof(*pNew));
  72248. memcpy(pNew, pOrig, MEMCELLSIZE);
  72249. pNew->flags &= ~MEM_Dyn;
  72250. pNew->db = 0;
  72251. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  72252. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  72253. pNew->flags |= MEM_Ephem;
  72254. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  72255. sqlite3ValueFree(pNew);
  72256. pNew = 0;
  72257. }
  72258. }
  72259. return pNew;
  72260. }
  72261. /* Destroy an sqlite3_value object previously obtained from
  72262. ** sqlite3_value_dup().
  72263. */
  72264. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  72265. sqlite3ValueFree(pOld);
  72266. }
  72267. /**************************** sqlite3_result_ *******************************
  72268. ** The following routines are used by user-defined functions to specify
  72269. ** the function result.
  72270. **
  72271. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  72272. ** result as a string or blob but if the string or blob is too large, it
  72273. ** then sets the error code to SQLITE_TOOBIG
  72274. **
  72275. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  72276. ** on value P is not going to be used and need to be destroyed.
  72277. */
  72278. static void setResultStrOrError(
  72279. sqlite3_context *pCtx, /* Function context */
  72280. const char *z, /* String pointer */
  72281. int n, /* Bytes in string, or negative */
  72282. u8 enc, /* Encoding of z. 0 for BLOBs */
  72283. void (*xDel)(void*) /* Destructor function */
  72284. ){
  72285. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  72286. sqlite3_result_error_toobig(pCtx);
  72287. }
  72288. }
  72289. static int invokeValueDestructor(
  72290. const void *p, /* Value to destroy */
  72291. void (*xDel)(void*), /* The destructor */
  72292. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  72293. ){
  72294. assert( xDel!=SQLITE_DYNAMIC );
  72295. if( xDel==0 ){
  72296. /* noop */
  72297. }else if( xDel==SQLITE_TRANSIENT ){
  72298. /* noop */
  72299. }else{
  72300. xDel((void*)p);
  72301. }
  72302. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  72303. return SQLITE_TOOBIG;
  72304. }
  72305. SQLITE_API void sqlite3_result_blob(
  72306. sqlite3_context *pCtx,
  72307. const void *z,
  72308. int n,
  72309. void (*xDel)(void *)
  72310. ){
  72311. assert( n>=0 );
  72312. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72313. setResultStrOrError(pCtx, z, n, 0, xDel);
  72314. }
  72315. SQLITE_API void sqlite3_result_blob64(
  72316. sqlite3_context *pCtx,
  72317. const void *z,
  72318. sqlite3_uint64 n,
  72319. void (*xDel)(void *)
  72320. ){
  72321. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72322. assert( xDel!=SQLITE_DYNAMIC );
  72323. if( n>0x7fffffff ){
  72324. (void)invokeValueDestructor(z, xDel, pCtx);
  72325. }else{
  72326. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  72327. }
  72328. }
  72329. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  72330. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72331. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  72332. }
  72333. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  72334. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72335. pCtx->isError = SQLITE_ERROR;
  72336. pCtx->fErrorOrAux = 1;
  72337. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  72338. }
  72339. #ifndef SQLITE_OMIT_UTF16
  72340. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  72341. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72342. pCtx->isError = SQLITE_ERROR;
  72343. pCtx->fErrorOrAux = 1;
  72344. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  72345. }
  72346. #endif
  72347. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  72348. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72349. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  72350. }
  72351. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  72352. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72353. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  72354. }
  72355. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  72356. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72357. sqlite3VdbeMemSetNull(pCtx->pOut);
  72358. }
  72359. SQLITE_API void sqlite3_result_pointer(
  72360. sqlite3_context *pCtx,
  72361. void *pPtr,
  72362. const char *zPType,
  72363. void (*xDestructor)(void*)
  72364. ){
  72365. Mem *pOut = pCtx->pOut;
  72366. assert( sqlite3_mutex_held(pOut->db->mutex) );
  72367. sqlite3VdbeMemRelease(pOut);
  72368. pOut->flags = MEM_Null;
  72369. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  72370. }
  72371. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  72372. Mem *pOut = pCtx->pOut;
  72373. assert( sqlite3_mutex_held(pOut->db->mutex) );
  72374. pOut->eSubtype = eSubtype & 0xff;
  72375. pOut->flags |= MEM_Subtype;
  72376. }
  72377. SQLITE_API void sqlite3_result_text(
  72378. sqlite3_context *pCtx,
  72379. const char *z,
  72380. int n,
  72381. void (*xDel)(void *)
  72382. ){
  72383. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72384. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  72385. }
  72386. SQLITE_API void sqlite3_result_text64(
  72387. sqlite3_context *pCtx,
  72388. const char *z,
  72389. sqlite3_uint64 n,
  72390. void (*xDel)(void *),
  72391. unsigned char enc
  72392. ){
  72393. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72394. assert( xDel!=SQLITE_DYNAMIC );
  72395. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  72396. if( n>0x7fffffff ){
  72397. (void)invokeValueDestructor(z, xDel, pCtx);
  72398. }else{
  72399. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  72400. }
  72401. }
  72402. #ifndef SQLITE_OMIT_UTF16
  72403. SQLITE_API void sqlite3_result_text16(
  72404. sqlite3_context *pCtx,
  72405. const void *z,
  72406. int n,
  72407. void (*xDel)(void *)
  72408. ){
  72409. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72410. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  72411. }
  72412. SQLITE_API void sqlite3_result_text16be(
  72413. sqlite3_context *pCtx,
  72414. const void *z,
  72415. int n,
  72416. void (*xDel)(void *)
  72417. ){
  72418. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72419. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  72420. }
  72421. SQLITE_API void sqlite3_result_text16le(
  72422. sqlite3_context *pCtx,
  72423. const void *z,
  72424. int n,
  72425. void (*xDel)(void *)
  72426. ){
  72427. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72428. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  72429. }
  72430. #endif /* SQLITE_OMIT_UTF16 */
  72431. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  72432. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72433. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  72434. }
  72435. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  72436. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72437. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  72438. }
  72439. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  72440. Mem *pOut = pCtx->pOut;
  72441. assert( sqlite3_mutex_held(pOut->db->mutex) );
  72442. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72443. return SQLITE_TOOBIG;
  72444. }
  72445. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  72446. return SQLITE_OK;
  72447. }
  72448. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  72449. pCtx->isError = errCode;
  72450. pCtx->fErrorOrAux = 1;
  72451. #ifdef SQLITE_DEBUG
  72452. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  72453. #endif
  72454. if( pCtx->pOut->flags & MEM_Null ){
  72455. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  72456. SQLITE_UTF8, SQLITE_STATIC);
  72457. }
  72458. }
  72459. /* Force an SQLITE_TOOBIG error. */
  72460. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  72461. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72462. pCtx->isError = SQLITE_TOOBIG;
  72463. pCtx->fErrorOrAux = 1;
  72464. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  72465. SQLITE_UTF8, SQLITE_STATIC);
  72466. }
  72467. /* An SQLITE_NOMEM error. */
  72468. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  72469. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72470. sqlite3VdbeMemSetNull(pCtx->pOut);
  72471. pCtx->isError = SQLITE_NOMEM_BKPT;
  72472. pCtx->fErrorOrAux = 1;
  72473. sqlite3OomFault(pCtx->pOut->db);
  72474. }
  72475. /*
  72476. ** This function is called after a transaction has been committed. It
  72477. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  72478. */
  72479. static int doWalCallbacks(sqlite3 *db){
  72480. int rc = SQLITE_OK;
  72481. #ifndef SQLITE_OMIT_WAL
  72482. int i;
  72483. for(i=0; i<db->nDb; i++){
  72484. Btree *pBt = db->aDb[i].pBt;
  72485. if( pBt ){
  72486. int nEntry;
  72487. sqlite3BtreeEnter(pBt);
  72488. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  72489. sqlite3BtreeLeave(pBt);
  72490. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  72491. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  72492. }
  72493. }
  72494. }
  72495. #endif
  72496. return rc;
  72497. }
  72498. /*
  72499. ** Execute the statement pStmt, either until a row of data is ready, the
  72500. ** statement is completely executed or an error occurs.
  72501. **
  72502. ** This routine implements the bulk of the logic behind the sqlite_step()
  72503. ** API. The only thing omitted is the automatic recompile if a
  72504. ** schema change has occurred. That detail is handled by the
  72505. ** outer sqlite3_step() wrapper procedure.
  72506. */
  72507. static int sqlite3Step(Vdbe *p){
  72508. sqlite3 *db;
  72509. int rc;
  72510. assert(p);
  72511. if( p->magic!=VDBE_MAGIC_RUN ){
  72512. /* We used to require that sqlite3_reset() be called before retrying
  72513. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  72514. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  72515. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  72516. ** This "automatic-reset" change is not technically an incompatibility,
  72517. ** since any application that receives an SQLITE_MISUSE is broken by
  72518. ** definition.
  72519. **
  72520. ** Nevertheless, some published applications that were originally written
  72521. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  72522. ** returns, and those were broken by the automatic-reset change. As a
  72523. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  72524. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  72525. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  72526. ** or SQLITE_BUSY error.
  72527. */
  72528. #ifdef SQLITE_OMIT_AUTORESET
  72529. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  72530. sqlite3_reset((sqlite3_stmt*)p);
  72531. }else{
  72532. return SQLITE_MISUSE_BKPT;
  72533. }
  72534. #else
  72535. sqlite3_reset((sqlite3_stmt*)p);
  72536. #endif
  72537. }
  72538. /* Check that malloc() has not failed. If it has, return early. */
  72539. db = p->db;
  72540. if( db->mallocFailed ){
  72541. p->rc = SQLITE_NOMEM;
  72542. return SQLITE_NOMEM_BKPT;
  72543. }
  72544. if( p->pc<=0 && p->expired ){
  72545. p->rc = SQLITE_SCHEMA;
  72546. rc = SQLITE_ERROR;
  72547. goto end_of_step;
  72548. }
  72549. if( p->pc<0 ){
  72550. /* If there are no other statements currently running, then
  72551. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  72552. ** from interrupting a statement that has not yet started.
  72553. */
  72554. if( db->nVdbeActive==0 ){
  72555. db->u1.isInterrupted = 0;
  72556. }
  72557. assert( db->nVdbeWrite>0 || db->autoCommit==0
  72558. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  72559. );
  72560. #ifndef SQLITE_OMIT_TRACE
  72561. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  72562. && !db->init.busy && p->zSql ){
  72563. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  72564. }else{
  72565. assert( p->startTime==0 );
  72566. }
  72567. #endif
  72568. db->nVdbeActive++;
  72569. if( p->readOnly==0 ) db->nVdbeWrite++;
  72570. if( p->bIsReader ) db->nVdbeRead++;
  72571. p->pc = 0;
  72572. }
  72573. #ifdef SQLITE_DEBUG
  72574. p->rcApp = SQLITE_OK;
  72575. #endif
  72576. #ifndef SQLITE_OMIT_EXPLAIN
  72577. if( p->explain ){
  72578. rc = sqlite3VdbeList(p);
  72579. }else
  72580. #endif /* SQLITE_OMIT_EXPLAIN */
  72581. {
  72582. db->nVdbeExec++;
  72583. rc = sqlite3VdbeExec(p);
  72584. db->nVdbeExec--;
  72585. }
  72586. #ifndef SQLITE_OMIT_TRACE
  72587. /* If the statement completed successfully, invoke the profile callback */
  72588. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  72589. #endif
  72590. if( rc==SQLITE_DONE && db->autoCommit ){
  72591. assert( p->rc==SQLITE_OK );
  72592. p->rc = doWalCallbacks(db);
  72593. if( p->rc!=SQLITE_OK ){
  72594. rc = SQLITE_ERROR;
  72595. }
  72596. }
  72597. db->errCode = rc;
  72598. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  72599. p->rc = SQLITE_NOMEM_BKPT;
  72600. }
  72601. end_of_step:
  72602. /* At this point local variable rc holds the value that should be
  72603. ** returned if this statement was compiled using the legacy
  72604. ** sqlite3_prepare() interface. According to the docs, this can only
  72605. ** be one of the values in the first assert() below. Variable p->rc
  72606. ** contains the value that would be returned if sqlite3_finalize()
  72607. ** were called on statement p.
  72608. */
  72609. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  72610. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  72611. );
  72612. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  72613. if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  72614. && rc!=SQLITE_ROW
  72615. && rc!=SQLITE_DONE
  72616. ){
  72617. /* If this statement was prepared using saved SQL and an
  72618. ** error has occurred, then return the error code in p->rc to the
  72619. ** caller. Set the error code in the database handle to the same value.
  72620. */
  72621. rc = sqlite3VdbeTransferError(p);
  72622. }
  72623. return (rc&db->errMask);
  72624. }
  72625. /*
  72626. ** This is the top-level implementation of sqlite3_step(). Call
  72627. ** sqlite3Step() to do most of the work. If a schema error occurs,
  72628. ** call sqlite3Reprepare() and try again.
  72629. */
  72630. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  72631. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  72632. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  72633. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  72634. sqlite3 *db; /* The database connection */
  72635. if( vdbeSafetyNotNull(v) ){
  72636. return SQLITE_MISUSE_BKPT;
  72637. }
  72638. db = v->db;
  72639. sqlite3_mutex_enter(db->mutex);
  72640. v->doingRerun = 0;
  72641. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  72642. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  72643. int savedPc = v->pc;
  72644. rc = sqlite3Reprepare(v);
  72645. if( rc!=SQLITE_OK ){
  72646. /* This case occurs after failing to recompile an sql statement.
  72647. ** The error message from the SQL compiler has already been loaded
  72648. ** into the database handle. This block copies the error message
  72649. ** from the database handle into the statement and sets the statement
  72650. ** program counter to 0 to ensure that when the statement is
  72651. ** finalized or reset the parser error message is available via
  72652. ** sqlite3_errmsg() and sqlite3_errcode().
  72653. */
  72654. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  72655. sqlite3DbFree(db, v->zErrMsg);
  72656. if( !db->mallocFailed ){
  72657. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  72658. v->rc = rc = sqlite3ApiExit(db, rc);
  72659. } else {
  72660. v->zErrMsg = 0;
  72661. v->rc = rc = SQLITE_NOMEM_BKPT;
  72662. }
  72663. break;
  72664. }
  72665. sqlite3_reset(pStmt);
  72666. if( savedPc>=0 ) v->doingRerun = 1;
  72667. assert( v->expired==0 );
  72668. }
  72669. sqlite3_mutex_leave(db->mutex);
  72670. return rc;
  72671. }
  72672. /*
  72673. ** Extract the user data from a sqlite3_context structure and return a
  72674. ** pointer to it.
  72675. */
  72676. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  72677. assert( p && p->pFunc );
  72678. return p->pFunc->pUserData;
  72679. }
  72680. /*
  72681. ** Extract the user data from a sqlite3_context structure and return a
  72682. ** pointer to it.
  72683. **
  72684. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  72685. ** returns a copy of the pointer to the database connection (the 1st
  72686. ** parameter) of the sqlite3_create_function() and
  72687. ** sqlite3_create_function16() routines that originally registered the
  72688. ** application defined function.
  72689. */
  72690. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  72691. assert( p && p->pOut );
  72692. return p->pOut->db;
  72693. }
  72694. /*
  72695. ** Return the current time for a statement. If the current time
  72696. ** is requested more than once within the same run of a single prepared
  72697. ** statement, the exact same time is returned for each invocation regardless
  72698. ** of the amount of time that elapses between invocations. In other words,
  72699. ** the time returned is always the time of the first call.
  72700. */
  72701. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  72702. int rc;
  72703. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  72704. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  72705. assert( p->pVdbe!=0 );
  72706. #else
  72707. sqlite3_int64 iTime = 0;
  72708. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  72709. #endif
  72710. if( *piTime==0 ){
  72711. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  72712. if( rc ) *piTime = 0;
  72713. }
  72714. return *piTime;
  72715. }
  72716. /*
  72717. ** The following is the implementation of an SQL function that always
  72718. ** fails with an error message stating that the function is used in the
  72719. ** wrong context. The sqlite3_overload_function() API might construct
  72720. ** SQL function that use this routine so that the functions will exist
  72721. ** for name resolution but are actually overloaded by the xFindFunction
  72722. ** method of virtual tables.
  72723. */
  72724. SQLITE_PRIVATE void sqlite3InvalidFunction(
  72725. sqlite3_context *context, /* The function calling context */
  72726. int NotUsed, /* Number of arguments to the function */
  72727. sqlite3_value **NotUsed2 /* Value of each argument */
  72728. ){
  72729. const char *zName = context->pFunc->zName;
  72730. char *zErr;
  72731. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  72732. zErr = sqlite3_mprintf(
  72733. "unable to use function %s in the requested context", zName);
  72734. sqlite3_result_error(context, zErr, -1);
  72735. sqlite3_free(zErr);
  72736. }
  72737. /*
  72738. ** Create a new aggregate context for p and return a pointer to
  72739. ** its pMem->z element.
  72740. */
  72741. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  72742. Mem *pMem = p->pMem;
  72743. assert( (pMem->flags & MEM_Agg)==0 );
  72744. if( nByte<=0 ){
  72745. sqlite3VdbeMemSetNull(pMem);
  72746. pMem->z = 0;
  72747. }else{
  72748. sqlite3VdbeMemClearAndResize(pMem, nByte);
  72749. pMem->flags = MEM_Agg;
  72750. pMem->u.pDef = p->pFunc;
  72751. if( pMem->z ){
  72752. memset(pMem->z, 0, nByte);
  72753. }
  72754. }
  72755. return (void*)pMem->z;
  72756. }
  72757. /*
  72758. ** Allocate or return the aggregate context for a user function. A new
  72759. ** context is allocated on the first call. Subsequent calls return the
  72760. ** same context that was returned on prior calls.
  72761. */
  72762. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  72763. assert( p && p->pFunc && p->pFunc->xFinalize );
  72764. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  72765. testcase( nByte<0 );
  72766. if( (p->pMem->flags & MEM_Agg)==0 ){
  72767. return createAggContext(p, nByte);
  72768. }else{
  72769. return (void*)p->pMem->z;
  72770. }
  72771. }
  72772. /*
  72773. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  72774. ** the user-function defined by pCtx.
  72775. **
  72776. ** The left-most argument is 0.
  72777. **
  72778. ** Undocumented behavior: If iArg is negative then access a cache of
  72779. ** auxiliary data pointers that is available to all functions within a
  72780. ** single prepared statement. The iArg values must match.
  72781. */
  72782. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  72783. AuxData *pAuxData;
  72784. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72785. #if SQLITE_ENABLE_STAT3_OR_STAT4
  72786. if( pCtx->pVdbe==0 ) return 0;
  72787. #else
  72788. assert( pCtx->pVdbe!=0 );
  72789. #endif
  72790. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  72791. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  72792. return pAuxData->pAux;
  72793. }
  72794. }
  72795. return 0;
  72796. }
  72797. /*
  72798. ** Set the auxiliary data pointer and delete function, for the iArg'th
  72799. ** argument to the user-function defined by pCtx. Any previous value is
  72800. ** deleted by calling the delete function specified when it was set.
  72801. **
  72802. ** The left-most argument is 0.
  72803. **
  72804. ** Undocumented behavior: If iArg is negative then make the data available
  72805. ** to all functions within the current prepared statement using iArg as an
  72806. ** access code.
  72807. */
  72808. SQLITE_API void sqlite3_set_auxdata(
  72809. sqlite3_context *pCtx,
  72810. int iArg,
  72811. void *pAux,
  72812. void (*xDelete)(void*)
  72813. ){
  72814. AuxData *pAuxData;
  72815. Vdbe *pVdbe = pCtx->pVdbe;
  72816. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72817. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  72818. if( pVdbe==0 ) goto failed;
  72819. #else
  72820. assert( pVdbe!=0 );
  72821. #endif
  72822. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  72823. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  72824. break;
  72825. }
  72826. }
  72827. if( pAuxData==0 ){
  72828. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  72829. if( !pAuxData ) goto failed;
  72830. pAuxData->iAuxOp = pCtx->iOp;
  72831. pAuxData->iAuxArg = iArg;
  72832. pAuxData->pNextAux = pVdbe->pAuxData;
  72833. pVdbe->pAuxData = pAuxData;
  72834. if( pCtx->fErrorOrAux==0 ){
  72835. pCtx->isError = 0;
  72836. pCtx->fErrorOrAux = 1;
  72837. }
  72838. }else if( pAuxData->xDeleteAux ){
  72839. pAuxData->xDeleteAux(pAuxData->pAux);
  72840. }
  72841. pAuxData->pAux = pAux;
  72842. pAuxData->xDeleteAux = xDelete;
  72843. return;
  72844. failed:
  72845. if( xDelete ){
  72846. xDelete(pAux);
  72847. }
  72848. }
  72849. #ifndef SQLITE_OMIT_DEPRECATED
  72850. /*
  72851. ** Return the number of times the Step function of an aggregate has been
  72852. ** called.
  72853. **
  72854. ** This function is deprecated. Do not use it for new code. It is
  72855. ** provide only to avoid breaking legacy code. New aggregate function
  72856. ** implementations should keep their own counts within their aggregate
  72857. ** context.
  72858. */
  72859. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  72860. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  72861. return p->pMem->n;
  72862. }
  72863. #endif
  72864. /*
  72865. ** Return the number of columns in the result set for the statement pStmt.
  72866. */
  72867. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  72868. Vdbe *pVm = (Vdbe *)pStmt;
  72869. return pVm ? pVm->nResColumn : 0;
  72870. }
  72871. /*
  72872. ** Return the number of values available from the current row of the
  72873. ** currently executing statement pStmt.
  72874. */
  72875. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  72876. Vdbe *pVm = (Vdbe *)pStmt;
  72877. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  72878. return pVm->nResColumn;
  72879. }
  72880. /*
  72881. ** Return a pointer to static memory containing an SQL NULL value.
  72882. */
  72883. static const Mem *columnNullValue(void){
  72884. /* Even though the Mem structure contains an element
  72885. ** of type i64, on certain architectures (x86) with certain compiler
  72886. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  72887. ** instead of an 8-byte one. This all works fine, except that when
  72888. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  72889. ** that a Mem structure is located on an 8-byte boundary. To prevent
  72890. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  72891. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  72892. ** __attribute__((aligned(8))) macro. */
  72893. static const Mem nullMem
  72894. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  72895. __attribute__((aligned(8)))
  72896. #endif
  72897. = {
  72898. /* .u = */ {0},
  72899. /* .flags = */ (u16)MEM_Null,
  72900. /* .enc = */ (u8)0,
  72901. /* .eSubtype = */ (u8)0,
  72902. /* .n = */ (int)0,
  72903. /* .z = */ (char*)0,
  72904. /* .zMalloc = */ (char*)0,
  72905. /* .szMalloc = */ (int)0,
  72906. /* .uTemp = */ (u32)0,
  72907. /* .db = */ (sqlite3*)0,
  72908. /* .xDel = */ (void(*)(void*))0,
  72909. #ifdef SQLITE_DEBUG
  72910. /* .pScopyFrom = */ (Mem*)0,
  72911. /* .pFiller = */ (void*)0,
  72912. #endif
  72913. };
  72914. return &nullMem;
  72915. }
  72916. /*
  72917. ** Check to see if column iCol of the given statement is valid. If
  72918. ** it is, return a pointer to the Mem for the value of that column.
  72919. ** If iCol is not valid, return a pointer to a Mem which has a value
  72920. ** of NULL.
  72921. */
  72922. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  72923. Vdbe *pVm;
  72924. Mem *pOut;
  72925. pVm = (Vdbe *)pStmt;
  72926. if( pVm==0 ) return (Mem*)columnNullValue();
  72927. assert( pVm->db );
  72928. sqlite3_mutex_enter(pVm->db->mutex);
  72929. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  72930. pOut = &pVm->pResultSet[i];
  72931. }else{
  72932. sqlite3Error(pVm->db, SQLITE_RANGE);
  72933. pOut = (Mem*)columnNullValue();
  72934. }
  72935. return pOut;
  72936. }
  72937. /*
  72938. ** This function is called after invoking an sqlite3_value_XXX function on a
  72939. ** column value (i.e. a value returned by evaluating an SQL expression in the
  72940. ** select list of a SELECT statement) that may cause a malloc() failure. If
  72941. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  72942. ** code of statement pStmt set to SQLITE_NOMEM.
  72943. **
  72944. ** Specifically, this is called from within:
  72945. **
  72946. ** sqlite3_column_int()
  72947. ** sqlite3_column_int64()
  72948. ** sqlite3_column_text()
  72949. ** sqlite3_column_text16()
  72950. ** sqlite3_column_real()
  72951. ** sqlite3_column_bytes()
  72952. ** sqlite3_column_bytes16()
  72953. ** sqiite3_column_blob()
  72954. */
  72955. static void columnMallocFailure(sqlite3_stmt *pStmt)
  72956. {
  72957. /* If malloc() failed during an encoding conversion within an
  72958. ** sqlite3_column_XXX API, then set the return code of the statement to
  72959. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  72960. ** and _finalize() will return NOMEM.
  72961. */
  72962. Vdbe *p = (Vdbe *)pStmt;
  72963. if( p ){
  72964. assert( p->db!=0 );
  72965. assert( sqlite3_mutex_held(p->db->mutex) );
  72966. p->rc = sqlite3ApiExit(p->db, p->rc);
  72967. sqlite3_mutex_leave(p->db->mutex);
  72968. }
  72969. }
  72970. /**************************** sqlite3_column_ *******************************
  72971. ** The following routines are used to access elements of the current row
  72972. ** in the result set.
  72973. */
  72974. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  72975. const void *val;
  72976. val = sqlite3_value_blob( columnMem(pStmt,i) );
  72977. /* Even though there is no encoding conversion, value_blob() might
  72978. ** need to call malloc() to expand the result of a zeroblob()
  72979. ** expression.
  72980. */
  72981. columnMallocFailure(pStmt);
  72982. return val;
  72983. }
  72984. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  72985. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  72986. columnMallocFailure(pStmt);
  72987. return val;
  72988. }
  72989. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  72990. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  72991. columnMallocFailure(pStmt);
  72992. return val;
  72993. }
  72994. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  72995. double val = sqlite3_value_double( columnMem(pStmt,i) );
  72996. columnMallocFailure(pStmt);
  72997. return val;
  72998. }
  72999. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  73000. int val = sqlite3_value_int( columnMem(pStmt,i) );
  73001. columnMallocFailure(pStmt);
  73002. return val;
  73003. }
  73004. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  73005. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  73006. columnMallocFailure(pStmt);
  73007. return val;
  73008. }
  73009. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  73010. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  73011. columnMallocFailure(pStmt);
  73012. return val;
  73013. }
  73014. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  73015. Mem *pOut = columnMem(pStmt, i);
  73016. if( pOut->flags&MEM_Static ){
  73017. pOut->flags &= ~MEM_Static;
  73018. pOut->flags |= MEM_Ephem;
  73019. }
  73020. columnMallocFailure(pStmt);
  73021. return (sqlite3_value *)pOut;
  73022. }
  73023. #ifndef SQLITE_OMIT_UTF16
  73024. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  73025. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  73026. columnMallocFailure(pStmt);
  73027. return val;
  73028. }
  73029. #endif /* SQLITE_OMIT_UTF16 */
  73030. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  73031. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  73032. columnMallocFailure(pStmt);
  73033. return iType;
  73034. }
  73035. /*
  73036. ** Convert the N-th element of pStmt->pColName[] into a string using
  73037. ** xFunc() then return that string. If N is out of range, return 0.
  73038. **
  73039. ** There are up to 5 names for each column. useType determines which
  73040. ** name is returned. Here are the names:
  73041. **
  73042. ** 0 The column name as it should be displayed for output
  73043. ** 1 The datatype name for the column
  73044. ** 2 The name of the database that the column derives from
  73045. ** 3 The name of the table that the column derives from
  73046. ** 4 The name of the table column that the result column derives from
  73047. **
  73048. ** If the result is not a simple column reference (if it is an expression
  73049. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  73050. */
  73051. static const void *columnName(
  73052. sqlite3_stmt *pStmt,
  73053. int N,
  73054. const void *(*xFunc)(Mem*),
  73055. int useType
  73056. ){
  73057. const void *ret;
  73058. Vdbe *p;
  73059. int n;
  73060. sqlite3 *db;
  73061. #ifdef SQLITE_ENABLE_API_ARMOR
  73062. if( pStmt==0 ){
  73063. (void)SQLITE_MISUSE_BKPT;
  73064. return 0;
  73065. }
  73066. #endif
  73067. ret = 0;
  73068. p = (Vdbe *)pStmt;
  73069. db = p->db;
  73070. assert( db!=0 );
  73071. n = sqlite3_column_count(pStmt);
  73072. if( N<n && N>=0 ){
  73073. N += useType*n;
  73074. sqlite3_mutex_enter(db->mutex);
  73075. assert( db->mallocFailed==0 );
  73076. ret = xFunc(&p->aColName[N]);
  73077. /* A malloc may have failed inside of the xFunc() call. If this
  73078. ** is the case, clear the mallocFailed flag and return NULL.
  73079. */
  73080. if( db->mallocFailed ){
  73081. sqlite3OomClear(db);
  73082. ret = 0;
  73083. }
  73084. sqlite3_mutex_leave(db->mutex);
  73085. }
  73086. return ret;
  73087. }
  73088. /*
  73089. ** Return the name of the Nth column of the result set returned by SQL
  73090. ** statement pStmt.
  73091. */
  73092. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  73093. return columnName(
  73094. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  73095. }
  73096. #ifndef SQLITE_OMIT_UTF16
  73097. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  73098. return columnName(
  73099. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  73100. }
  73101. #endif
  73102. /*
  73103. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  73104. ** not define OMIT_DECLTYPE.
  73105. */
  73106. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  73107. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  73108. and SQLITE_ENABLE_COLUMN_METADATA"
  73109. #endif
  73110. #ifndef SQLITE_OMIT_DECLTYPE
  73111. /*
  73112. ** Return the column declaration type (if applicable) of the 'i'th column
  73113. ** of the result set of SQL statement pStmt.
  73114. */
  73115. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  73116. return columnName(
  73117. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  73118. }
  73119. #ifndef SQLITE_OMIT_UTF16
  73120. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  73121. return columnName(
  73122. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  73123. }
  73124. #endif /* SQLITE_OMIT_UTF16 */
  73125. #endif /* SQLITE_OMIT_DECLTYPE */
  73126. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  73127. /*
  73128. ** Return the name of the database from which a result column derives.
  73129. ** NULL is returned if the result column is an expression or constant or
  73130. ** anything else which is not an unambiguous reference to a database column.
  73131. */
  73132. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  73133. return columnName(
  73134. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  73135. }
  73136. #ifndef SQLITE_OMIT_UTF16
  73137. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  73138. return columnName(
  73139. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  73140. }
  73141. #endif /* SQLITE_OMIT_UTF16 */
  73142. /*
  73143. ** Return the name of the table from which a result column derives.
  73144. ** NULL is returned if the result column is an expression or constant or
  73145. ** anything else which is not an unambiguous reference to a database column.
  73146. */
  73147. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  73148. return columnName(
  73149. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  73150. }
  73151. #ifndef SQLITE_OMIT_UTF16
  73152. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  73153. return columnName(
  73154. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  73155. }
  73156. #endif /* SQLITE_OMIT_UTF16 */
  73157. /*
  73158. ** Return the name of the table column from which a result column derives.
  73159. ** NULL is returned if the result column is an expression or constant or
  73160. ** anything else which is not an unambiguous reference to a database column.
  73161. */
  73162. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  73163. return columnName(
  73164. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  73165. }
  73166. #ifndef SQLITE_OMIT_UTF16
  73167. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  73168. return columnName(
  73169. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  73170. }
  73171. #endif /* SQLITE_OMIT_UTF16 */
  73172. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  73173. /******************************* sqlite3_bind_ ***************************
  73174. **
  73175. ** Routines used to attach values to wildcards in a compiled SQL statement.
  73176. */
  73177. /*
  73178. ** Unbind the value bound to variable i in virtual machine p. This is the
  73179. ** the same as binding a NULL value to the column. If the "i" parameter is
  73180. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  73181. **
  73182. ** A successful evaluation of this routine acquires the mutex on p.
  73183. ** the mutex is released if any kind of error occurs.
  73184. **
  73185. ** The error code stored in database p->db is overwritten with the return
  73186. ** value in any case.
  73187. */
  73188. static int vdbeUnbind(Vdbe *p, int i){
  73189. Mem *pVar;
  73190. if( vdbeSafetyNotNull(p) ){
  73191. return SQLITE_MISUSE_BKPT;
  73192. }
  73193. sqlite3_mutex_enter(p->db->mutex);
  73194. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  73195. sqlite3Error(p->db, SQLITE_MISUSE);
  73196. sqlite3_mutex_leave(p->db->mutex);
  73197. sqlite3_log(SQLITE_MISUSE,
  73198. "bind on a busy prepared statement: [%s]", p->zSql);
  73199. return SQLITE_MISUSE_BKPT;
  73200. }
  73201. if( i<1 || i>p->nVar ){
  73202. sqlite3Error(p->db, SQLITE_RANGE);
  73203. sqlite3_mutex_leave(p->db->mutex);
  73204. return SQLITE_RANGE;
  73205. }
  73206. i--;
  73207. pVar = &p->aVar[i];
  73208. sqlite3VdbeMemRelease(pVar);
  73209. pVar->flags = MEM_Null;
  73210. sqlite3Error(p->db, SQLITE_OK);
  73211. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  73212. ** binding a new value to this variable invalidates the current query plan.
  73213. **
  73214. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  73215. ** parameter in the WHERE clause might influence the choice of query plan
  73216. ** for a statement, then the statement will be automatically recompiled,
  73217. ** as if there had been a schema change, on the first sqlite3_step() call
  73218. ** following any change to the bindings of that parameter.
  73219. */
  73220. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  73221. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  73222. p->expired = 1;
  73223. }
  73224. return SQLITE_OK;
  73225. }
  73226. /*
  73227. ** Bind a text or BLOB value.
  73228. */
  73229. static int bindText(
  73230. sqlite3_stmt *pStmt, /* The statement to bind against */
  73231. int i, /* Index of the parameter to bind */
  73232. const void *zData, /* Pointer to the data to be bound */
  73233. int nData, /* Number of bytes of data to be bound */
  73234. void (*xDel)(void*), /* Destructor for the data */
  73235. u8 encoding /* Encoding for the data */
  73236. ){
  73237. Vdbe *p = (Vdbe *)pStmt;
  73238. Mem *pVar;
  73239. int rc;
  73240. rc = vdbeUnbind(p, i);
  73241. if( rc==SQLITE_OK ){
  73242. if( zData!=0 ){
  73243. pVar = &p->aVar[i-1];
  73244. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  73245. if( rc==SQLITE_OK && encoding!=0 ){
  73246. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  73247. }
  73248. if( rc ){
  73249. sqlite3Error(p->db, rc);
  73250. rc = sqlite3ApiExit(p->db, rc);
  73251. }
  73252. }
  73253. sqlite3_mutex_leave(p->db->mutex);
  73254. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  73255. xDel((void*)zData);
  73256. }
  73257. return rc;
  73258. }
  73259. /*
  73260. ** Bind a blob value to an SQL statement variable.
  73261. */
  73262. SQLITE_API int sqlite3_bind_blob(
  73263. sqlite3_stmt *pStmt,
  73264. int i,
  73265. const void *zData,
  73266. int nData,
  73267. void (*xDel)(void*)
  73268. ){
  73269. #ifdef SQLITE_ENABLE_API_ARMOR
  73270. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  73271. #endif
  73272. return bindText(pStmt, i, zData, nData, xDel, 0);
  73273. }
  73274. SQLITE_API int sqlite3_bind_blob64(
  73275. sqlite3_stmt *pStmt,
  73276. int i,
  73277. const void *zData,
  73278. sqlite3_uint64 nData,
  73279. void (*xDel)(void*)
  73280. ){
  73281. assert( xDel!=SQLITE_DYNAMIC );
  73282. if( nData>0x7fffffff ){
  73283. return invokeValueDestructor(zData, xDel, 0);
  73284. }else{
  73285. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  73286. }
  73287. }
  73288. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  73289. int rc;
  73290. Vdbe *p = (Vdbe *)pStmt;
  73291. rc = vdbeUnbind(p, i);
  73292. if( rc==SQLITE_OK ){
  73293. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  73294. sqlite3_mutex_leave(p->db->mutex);
  73295. }
  73296. return rc;
  73297. }
  73298. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  73299. return sqlite3_bind_int64(p, i, (i64)iValue);
  73300. }
  73301. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  73302. int rc;
  73303. Vdbe *p = (Vdbe *)pStmt;
  73304. rc = vdbeUnbind(p, i);
  73305. if( rc==SQLITE_OK ){
  73306. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  73307. sqlite3_mutex_leave(p->db->mutex);
  73308. }
  73309. return rc;
  73310. }
  73311. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  73312. int rc;
  73313. Vdbe *p = (Vdbe*)pStmt;
  73314. rc = vdbeUnbind(p, i);
  73315. if( rc==SQLITE_OK ){
  73316. sqlite3_mutex_leave(p->db->mutex);
  73317. }
  73318. return rc;
  73319. }
  73320. SQLITE_API int sqlite3_bind_pointer(
  73321. sqlite3_stmt *pStmt,
  73322. int i,
  73323. void *pPtr,
  73324. const char *zPTtype,
  73325. void (*xDestructor)(void*)
  73326. ){
  73327. int rc;
  73328. Vdbe *p = (Vdbe*)pStmt;
  73329. rc = vdbeUnbind(p, i);
  73330. if( rc==SQLITE_OK ){
  73331. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  73332. sqlite3_mutex_leave(p->db->mutex);
  73333. }else if( xDestructor ){
  73334. xDestructor(pPtr);
  73335. }
  73336. return rc;
  73337. }
  73338. SQLITE_API int sqlite3_bind_text(
  73339. sqlite3_stmt *pStmt,
  73340. int i,
  73341. const char *zData,
  73342. int nData,
  73343. void (*xDel)(void*)
  73344. ){
  73345. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  73346. }
  73347. SQLITE_API int sqlite3_bind_text64(
  73348. sqlite3_stmt *pStmt,
  73349. int i,
  73350. const char *zData,
  73351. sqlite3_uint64 nData,
  73352. void (*xDel)(void*),
  73353. unsigned char enc
  73354. ){
  73355. assert( xDel!=SQLITE_DYNAMIC );
  73356. if( nData>0x7fffffff ){
  73357. return invokeValueDestructor(zData, xDel, 0);
  73358. }else{
  73359. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  73360. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  73361. }
  73362. }
  73363. #ifndef SQLITE_OMIT_UTF16
  73364. SQLITE_API int sqlite3_bind_text16(
  73365. sqlite3_stmt *pStmt,
  73366. int i,
  73367. const void *zData,
  73368. int nData,
  73369. void (*xDel)(void*)
  73370. ){
  73371. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  73372. }
  73373. #endif /* SQLITE_OMIT_UTF16 */
  73374. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  73375. int rc;
  73376. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  73377. case SQLITE_INTEGER: {
  73378. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  73379. break;
  73380. }
  73381. case SQLITE_FLOAT: {
  73382. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  73383. break;
  73384. }
  73385. case SQLITE_BLOB: {
  73386. if( pValue->flags & MEM_Zero ){
  73387. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  73388. }else{
  73389. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  73390. }
  73391. break;
  73392. }
  73393. case SQLITE_TEXT: {
  73394. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  73395. pValue->enc);
  73396. break;
  73397. }
  73398. default: {
  73399. rc = sqlite3_bind_null(pStmt, i);
  73400. break;
  73401. }
  73402. }
  73403. return rc;
  73404. }
  73405. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  73406. int rc;
  73407. Vdbe *p = (Vdbe *)pStmt;
  73408. rc = vdbeUnbind(p, i);
  73409. if( rc==SQLITE_OK ){
  73410. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  73411. sqlite3_mutex_leave(p->db->mutex);
  73412. }
  73413. return rc;
  73414. }
  73415. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  73416. int rc;
  73417. Vdbe *p = (Vdbe *)pStmt;
  73418. sqlite3_mutex_enter(p->db->mutex);
  73419. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73420. rc = SQLITE_TOOBIG;
  73421. }else{
  73422. assert( (n & 0x7FFFFFFF)==n );
  73423. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  73424. }
  73425. rc = sqlite3ApiExit(p->db, rc);
  73426. sqlite3_mutex_leave(p->db->mutex);
  73427. return rc;
  73428. }
  73429. /*
  73430. ** Return the number of wildcards that can be potentially bound to.
  73431. ** This routine is added to support DBD::SQLite.
  73432. */
  73433. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  73434. Vdbe *p = (Vdbe*)pStmt;
  73435. return p ? p->nVar : 0;
  73436. }
  73437. /*
  73438. ** Return the name of a wildcard parameter. Return NULL if the index
  73439. ** is out of range or if the wildcard is unnamed.
  73440. **
  73441. ** The result is always UTF-8.
  73442. */
  73443. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  73444. Vdbe *p = (Vdbe*)pStmt;
  73445. if( p==0 ) return 0;
  73446. return sqlite3VListNumToName(p->pVList, i);
  73447. }
  73448. /*
  73449. ** Given a wildcard parameter name, return the index of the variable
  73450. ** with that name. If there is no variable with the given name,
  73451. ** return 0.
  73452. */
  73453. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  73454. if( p==0 || zName==0 ) return 0;
  73455. return sqlite3VListNameToNum(p->pVList, zName, nName);
  73456. }
  73457. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  73458. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  73459. }
  73460. /*
  73461. ** Transfer all bindings from the first statement over to the second.
  73462. */
  73463. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  73464. Vdbe *pFrom = (Vdbe*)pFromStmt;
  73465. Vdbe *pTo = (Vdbe*)pToStmt;
  73466. int i;
  73467. assert( pTo->db==pFrom->db );
  73468. assert( pTo->nVar==pFrom->nVar );
  73469. sqlite3_mutex_enter(pTo->db->mutex);
  73470. for(i=0; i<pFrom->nVar; i++){
  73471. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  73472. }
  73473. sqlite3_mutex_leave(pTo->db->mutex);
  73474. return SQLITE_OK;
  73475. }
  73476. #ifndef SQLITE_OMIT_DEPRECATED
  73477. /*
  73478. ** Deprecated external interface. Internal/core SQLite code
  73479. ** should call sqlite3TransferBindings.
  73480. **
  73481. ** It is misuse to call this routine with statements from different
  73482. ** database connections. But as this is a deprecated interface, we
  73483. ** will not bother to check for that condition.
  73484. **
  73485. ** If the two statements contain a different number of bindings, then
  73486. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  73487. ** SQLITE_OK is returned.
  73488. */
  73489. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  73490. Vdbe *pFrom = (Vdbe*)pFromStmt;
  73491. Vdbe *pTo = (Vdbe*)pToStmt;
  73492. if( pFrom->nVar!=pTo->nVar ){
  73493. return SQLITE_ERROR;
  73494. }
  73495. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  73496. if( pTo->expmask ){
  73497. pTo->expired = 1;
  73498. }
  73499. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  73500. if( pFrom->expmask ){
  73501. pFrom->expired = 1;
  73502. }
  73503. return sqlite3TransferBindings(pFromStmt, pToStmt);
  73504. }
  73505. #endif
  73506. /*
  73507. ** Return the sqlite3* database handle to which the prepared statement given
  73508. ** in the argument belongs. This is the same database handle that was
  73509. ** the first argument to the sqlite3_prepare() that was used to create
  73510. ** the statement in the first place.
  73511. */
  73512. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  73513. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  73514. }
  73515. /*
  73516. ** Return true if the prepared statement is guaranteed to not modify the
  73517. ** database.
  73518. */
  73519. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  73520. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  73521. }
  73522. /*
  73523. ** Return true if the prepared statement is in need of being reset.
  73524. */
  73525. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  73526. Vdbe *v = (Vdbe*)pStmt;
  73527. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  73528. }
  73529. /*
  73530. ** Return a pointer to the next prepared statement after pStmt associated
  73531. ** with database connection pDb. If pStmt is NULL, return the first
  73532. ** prepared statement for the database connection. Return NULL if there
  73533. ** are no more.
  73534. */
  73535. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  73536. sqlite3_stmt *pNext;
  73537. #ifdef SQLITE_ENABLE_API_ARMOR
  73538. if( !sqlite3SafetyCheckOk(pDb) ){
  73539. (void)SQLITE_MISUSE_BKPT;
  73540. return 0;
  73541. }
  73542. #endif
  73543. sqlite3_mutex_enter(pDb->mutex);
  73544. if( pStmt==0 ){
  73545. pNext = (sqlite3_stmt*)pDb->pVdbe;
  73546. }else{
  73547. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  73548. }
  73549. sqlite3_mutex_leave(pDb->mutex);
  73550. return pNext;
  73551. }
  73552. /*
  73553. ** Return the value of a status counter for a prepared statement
  73554. */
  73555. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  73556. Vdbe *pVdbe = (Vdbe*)pStmt;
  73557. u32 v;
  73558. #ifdef SQLITE_ENABLE_API_ARMOR
  73559. if( !pStmt ){
  73560. (void)SQLITE_MISUSE_BKPT;
  73561. return 0;
  73562. }
  73563. #endif
  73564. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  73565. sqlite3 *db = pVdbe->db;
  73566. sqlite3_mutex_enter(db->mutex);
  73567. v = 0;
  73568. db->pnBytesFreed = (int*)&v;
  73569. sqlite3VdbeClearObject(db, pVdbe);
  73570. sqlite3DbFree(db, pVdbe);
  73571. db->pnBytesFreed = 0;
  73572. sqlite3_mutex_leave(db->mutex);
  73573. }else{
  73574. v = pVdbe->aCounter[op];
  73575. if( resetFlag ) pVdbe->aCounter[op] = 0;
  73576. }
  73577. return (int)v;
  73578. }
  73579. /*
  73580. ** Return the SQL associated with a prepared statement
  73581. */
  73582. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  73583. Vdbe *p = (Vdbe *)pStmt;
  73584. return p ? p->zSql : 0;
  73585. }
  73586. /*
  73587. ** Return the SQL associated with a prepared statement with
  73588. ** bound parameters expanded. Space to hold the returned string is
  73589. ** obtained from sqlite3_malloc(). The caller is responsible for
  73590. ** freeing the returned string by passing it to sqlite3_free().
  73591. **
  73592. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  73593. ** expanded bound parameters.
  73594. */
  73595. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  73596. #ifdef SQLITE_OMIT_TRACE
  73597. return 0;
  73598. #else
  73599. char *z = 0;
  73600. const char *zSql = sqlite3_sql(pStmt);
  73601. if( zSql ){
  73602. Vdbe *p = (Vdbe *)pStmt;
  73603. sqlite3_mutex_enter(p->db->mutex);
  73604. z = sqlite3VdbeExpandSql(p, zSql);
  73605. sqlite3_mutex_leave(p->db->mutex);
  73606. }
  73607. return z;
  73608. #endif
  73609. }
  73610. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73611. /*
  73612. ** Allocate and populate an UnpackedRecord structure based on the serialized
  73613. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  73614. ** if successful, or a NULL pointer if an OOM error is encountered.
  73615. */
  73616. static UnpackedRecord *vdbeUnpackRecord(
  73617. KeyInfo *pKeyInfo,
  73618. int nKey,
  73619. const void *pKey
  73620. ){
  73621. UnpackedRecord *pRet; /* Return value */
  73622. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  73623. if( pRet ){
  73624. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  73625. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  73626. }
  73627. return pRet;
  73628. }
  73629. /*
  73630. ** This function is called from within a pre-update callback to retrieve
  73631. ** a field of the row currently being updated or deleted.
  73632. */
  73633. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  73634. PreUpdate *p = db->pPreUpdate;
  73635. Mem *pMem;
  73636. int rc = SQLITE_OK;
  73637. /* Test that this call is being made from within an SQLITE_DELETE or
  73638. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  73639. if( !p || p->op==SQLITE_INSERT ){
  73640. rc = SQLITE_MISUSE_BKPT;
  73641. goto preupdate_old_out;
  73642. }
  73643. if( p->pPk ){
  73644. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  73645. }
  73646. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  73647. rc = SQLITE_RANGE;
  73648. goto preupdate_old_out;
  73649. }
  73650. /* If the old.* record has not yet been loaded into memory, do so now. */
  73651. if( p->pUnpacked==0 ){
  73652. u32 nRec;
  73653. u8 *aRec;
  73654. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  73655. aRec = sqlite3DbMallocRaw(db, nRec);
  73656. if( !aRec ) goto preupdate_old_out;
  73657. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  73658. if( rc==SQLITE_OK ){
  73659. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  73660. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  73661. }
  73662. if( rc!=SQLITE_OK ){
  73663. sqlite3DbFree(db, aRec);
  73664. goto preupdate_old_out;
  73665. }
  73666. p->aRecord = aRec;
  73667. }
  73668. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  73669. if( iIdx==p->pTab->iPKey ){
  73670. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  73671. }else if( iIdx>=p->pUnpacked->nField ){
  73672. *ppValue = (sqlite3_value *)columnNullValue();
  73673. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  73674. if( pMem->flags & MEM_Int ){
  73675. sqlite3VdbeMemRealify(pMem);
  73676. }
  73677. }
  73678. preupdate_old_out:
  73679. sqlite3Error(db, rc);
  73680. return sqlite3ApiExit(db, rc);
  73681. }
  73682. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73683. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73684. /*
  73685. ** This function is called from within a pre-update callback to retrieve
  73686. ** the number of columns in the row being updated, deleted or inserted.
  73687. */
  73688. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  73689. PreUpdate *p = db->pPreUpdate;
  73690. return (p ? p->keyinfo.nKeyField : 0);
  73691. }
  73692. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73693. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73694. /*
  73695. ** This function is designed to be called from within a pre-update callback
  73696. ** only. It returns zero if the change that caused the callback was made
  73697. ** immediately by a user SQL statement. Or, if the change was made by a
  73698. ** trigger program, it returns the number of trigger programs currently
  73699. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  73700. ** top-level trigger etc.).
  73701. **
  73702. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  73703. ** or SET DEFAULT action is considered a trigger.
  73704. */
  73705. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  73706. PreUpdate *p = db->pPreUpdate;
  73707. return (p ? p->v->nFrame : 0);
  73708. }
  73709. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73710. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73711. /*
  73712. ** This function is called from within a pre-update callback to retrieve
  73713. ** a field of the row currently being updated or inserted.
  73714. */
  73715. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  73716. PreUpdate *p = db->pPreUpdate;
  73717. int rc = SQLITE_OK;
  73718. Mem *pMem;
  73719. if( !p || p->op==SQLITE_DELETE ){
  73720. rc = SQLITE_MISUSE_BKPT;
  73721. goto preupdate_new_out;
  73722. }
  73723. if( p->pPk && p->op!=SQLITE_UPDATE ){
  73724. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  73725. }
  73726. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  73727. rc = SQLITE_RANGE;
  73728. goto preupdate_new_out;
  73729. }
  73730. if( p->op==SQLITE_INSERT ){
  73731. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  73732. ** that is being inserted. Deserialize it. */
  73733. UnpackedRecord *pUnpack = p->pNewUnpacked;
  73734. if( !pUnpack ){
  73735. Mem *pData = &p->v->aMem[p->iNewReg];
  73736. rc = ExpandBlob(pData);
  73737. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  73738. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  73739. if( !pUnpack ){
  73740. rc = SQLITE_NOMEM;
  73741. goto preupdate_new_out;
  73742. }
  73743. p->pNewUnpacked = pUnpack;
  73744. }
  73745. pMem = &pUnpack->aMem[iIdx];
  73746. if( iIdx==p->pTab->iPKey ){
  73747. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  73748. }else if( iIdx>=pUnpack->nField ){
  73749. pMem = (sqlite3_value *)columnNullValue();
  73750. }
  73751. }else{
  73752. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  73753. ** value. Make a copy of the cell contents and return a pointer to it.
  73754. ** It is not safe to return a pointer to the memory cell itself as the
  73755. ** caller may modify the value text encoding.
  73756. */
  73757. assert( p->op==SQLITE_UPDATE );
  73758. if( !p->aNew ){
  73759. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  73760. if( !p->aNew ){
  73761. rc = SQLITE_NOMEM;
  73762. goto preupdate_new_out;
  73763. }
  73764. }
  73765. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  73766. pMem = &p->aNew[iIdx];
  73767. if( pMem->flags==0 ){
  73768. if( iIdx==p->pTab->iPKey ){
  73769. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  73770. }else{
  73771. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  73772. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  73773. }
  73774. }
  73775. }
  73776. *ppValue = pMem;
  73777. preupdate_new_out:
  73778. sqlite3Error(db, rc);
  73779. return sqlite3ApiExit(db, rc);
  73780. }
  73781. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73782. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73783. /*
  73784. ** Return status data for a single loop within query pStmt.
  73785. */
  73786. SQLITE_API int sqlite3_stmt_scanstatus(
  73787. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  73788. int idx, /* Index of loop to report on */
  73789. int iScanStatusOp, /* Which metric to return */
  73790. void *pOut /* OUT: Write the answer here */
  73791. ){
  73792. Vdbe *p = (Vdbe*)pStmt;
  73793. ScanStatus *pScan;
  73794. if( idx<0 || idx>=p->nScan ) return 1;
  73795. pScan = &p->aScan[idx];
  73796. switch( iScanStatusOp ){
  73797. case SQLITE_SCANSTAT_NLOOP: {
  73798. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  73799. break;
  73800. }
  73801. case SQLITE_SCANSTAT_NVISIT: {
  73802. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  73803. break;
  73804. }
  73805. case SQLITE_SCANSTAT_EST: {
  73806. double r = 1.0;
  73807. LogEst x = pScan->nEst;
  73808. while( x<100 ){
  73809. x += 10;
  73810. r *= 0.5;
  73811. }
  73812. *(double*)pOut = r*sqlite3LogEstToInt(x);
  73813. break;
  73814. }
  73815. case SQLITE_SCANSTAT_NAME: {
  73816. *(const char**)pOut = pScan->zName;
  73817. break;
  73818. }
  73819. case SQLITE_SCANSTAT_EXPLAIN: {
  73820. if( pScan->addrExplain ){
  73821. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  73822. }else{
  73823. *(const char**)pOut = 0;
  73824. }
  73825. break;
  73826. }
  73827. case SQLITE_SCANSTAT_SELECTID: {
  73828. if( pScan->addrExplain ){
  73829. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  73830. }else{
  73831. *(int*)pOut = -1;
  73832. }
  73833. break;
  73834. }
  73835. default: {
  73836. return 1;
  73837. }
  73838. }
  73839. return 0;
  73840. }
  73841. /*
  73842. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  73843. */
  73844. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  73845. Vdbe *p = (Vdbe*)pStmt;
  73846. memset(p->anExec, 0, p->nOp * sizeof(i64));
  73847. }
  73848. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  73849. /************** End of vdbeapi.c *********************************************/
  73850. /************** Begin file vdbetrace.c ***************************************/
  73851. /*
  73852. ** 2009 November 25
  73853. **
  73854. ** The author disclaims copyright to this source code. In place of
  73855. ** a legal notice, here is a blessing:
  73856. **
  73857. ** May you do good and not evil.
  73858. ** May you find forgiveness for yourself and forgive others.
  73859. ** May you share freely, never taking more than you give.
  73860. **
  73861. *************************************************************************
  73862. **
  73863. ** This file contains code used to insert the values of host parameters
  73864. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  73865. **
  73866. ** The Vdbe parse-tree explainer is also found here.
  73867. */
  73868. /* #include "sqliteInt.h" */
  73869. /* #include "vdbeInt.h" */
  73870. #ifndef SQLITE_OMIT_TRACE
  73871. /*
  73872. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  73873. ** bytes in this text up to but excluding the first character in
  73874. ** a host parameter. If the text contains no host parameters, return
  73875. ** the total number of bytes in the text.
  73876. */
  73877. static int findNextHostParameter(const char *zSql, int *pnToken){
  73878. int tokenType;
  73879. int nTotal = 0;
  73880. int n;
  73881. *pnToken = 0;
  73882. while( zSql[0] ){
  73883. n = sqlite3GetToken((u8*)zSql, &tokenType);
  73884. assert( n>0 && tokenType!=TK_ILLEGAL );
  73885. if( tokenType==TK_VARIABLE ){
  73886. *pnToken = n;
  73887. break;
  73888. }
  73889. nTotal += n;
  73890. zSql += n;
  73891. }
  73892. return nTotal;
  73893. }
  73894. /*
  73895. ** This function returns a pointer to a nul-terminated string in memory
  73896. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  73897. ** string contains a copy of zRawSql but with host parameters expanded to
  73898. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  73899. ** then the returned string holds a copy of zRawSql with "-- " prepended
  73900. ** to each line of text.
  73901. **
  73902. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  73903. ** then long strings and blobs are truncated to that many bytes. This
  73904. ** can be used to prevent unreasonably large trace strings when dealing
  73905. ** with large (multi-megabyte) strings and blobs.
  73906. **
  73907. ** The calling function is responsible for making sure the memory returned
  73908. ** is eventually freed.
  73909. **
  73910. ** ALGORITHM: Scan the input string looking for host parameters in any of
  73911. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  73912. ** string literals, quoted identifier names, and comments. For text forms,
  73913. ** the host parameter index is found by scanning the prepared
  73914. ** statement for the corresponding OP_Variable opcode. Once the host
  73915. ** parameter index is known, locate the value in p->aVar[]. Then render
  73916. ** the value as a literal in place of the host parameter name.
  73917. */
  73918. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  73919. Vdbe *p, /* The prepared statement being evaluated */
  73920. const char *zRawSql /* Raw text of the SQL statement */
  73921. ){
  73922. sqlite3 *db; /* The database connection */
  73923. int idx = 0; /* Index of a host parameter */
  73924. int nextIndex = 1; /* Index of next ? host parameter */
  73925. int n; /* Length of a token prefix */
  73926. int nToken; /* Length of the parameter token */
  73927. int i; /* Loop counter */
  73928. Mem *pVar; /* Value of a host parameter */
  73929. StrAccum out; /* Accumulate the output here */
  73930. #ifndef SQLITE_OMIT_UTF16
  73931. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  73932. #endif
  73933. char zBase[100]; /* Initial working space */
  73934. db = p->db;
  73935. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  73936. db->aLimit[SQLITE_LIMIT_LENGTH]);
  73937. if( db->nVdbeExec>1 ){
  73938. while( *zRawSql ){
  73939. const char *zStart = zRawSql;
  73940. while( *(zRawSql++)!='\n' && *zRawSql );
  73941. sqlite3StrAccumAppend(&out, "-- ", 3);
  73942. assert( (zRawSql - zStart) > 0 );
  73943. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  73944. }
  73945. }else if( p->nVar==0 ){
  73946. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  73947. }else{
  73948. while( zRawSql[0] ){
  73949. n = findNextHostParameter(zRawSql, &nToken);
  73950. assert( n>0 );
  73951. sqlite3StrAccumAppend(&out, zRawSql, n);
  73952. zRawSql += n;
  73953. assert( zRawSql[0] || nToken==0 );
  73954. if( nToken==0 ) break;
  73955. if( zRawSql[0]=='?' ){
  73956. if( nToken>1 ){
  73957. assert( sqlite3Isdigit(zRawSql[1]) );
  73958. sqlite3GetInt32(&zRawSql[1], &idx);
  73959. }else{
  73960. idx = nextIndex;
  73961. }
  73962. }else{
  73963. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  73964. zRawSql[0]=='@' || zRawSql[0]=='#' );
  73965. testcase( zRawSql[0]==':' );
  73966. testcase( zRawSql[0]=='$' );
  73967. testcase( zRawSql[0]=='@' );
  73968. testcase( zRawSql[0]=='#' );
  73969. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  73970. assert( idx>0 );
  73971. }
  73972. zRawSql += nToken;
  73973. nextIndex = idx + 1;
  73974. assert( idx>0 && idx<=p->nVar );
  73975. pVar = &p->aVar[idx-1];
  73976. if( pVar->flags & MEM_Null ){
  73977. sqlite3StrAccumAppend(&out, "NULL", 4);
  73978. }else if( pVar->flags & MEM_Int ){
  73979. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  73980. }else if( pVar->flags & MEM_Real ){
  73981. sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
  73982. }else if( pVar->flags & MEM_Str ){
  73983. int nOut; /* Number of bytes of the string text to include in output */
  73984. #ifndef SQLITE_OMIT_UTF16
  73985. u8 enc = ENC(db);
  73986. if( enc!=SQLITE_UTF8 ){
  73987. memset(&utf8, 0, sizeof(utf8));
  73988. utf8.db = db;
  73989. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  73990. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  73991. out.accError = STRACCUM_NOMEM;
  73992. out.nAlloc = 0;
  73993. }
  73994. pVar = &utf8;
  73995. }
  73996. #endif
  73997. nOut = pVar->n;
  73998. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73999. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  74000. nOut = SQLITE_TRACE_SIZE_LIMIT;
  74001. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  74002. }
  74003. #endif
  74004. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  74005. #ifdef SQLITE_TRACE_SIZE_LIMIT
  74006. if( nOut<pVar->n ){
  74007. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  74008. }
  74009. #endif
  74010. #ifndef SQLITE_OMIT_UTF16
  74011. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  74012. #endif
  74013. }else if( pVar->flags & MEM_Zero ){
  74014. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  74015. }else{
  74016. int nOut; /* Number of bytes of the blob to include in output */
  74017. assert( pVar->flags & MEM_Blob );
  74018. sqlite3StrAccumAppend(&out, "x'", 2);
  74019. nOut = pVar->n;
  74020. #ifdef SQLITE_TRACE_SIZE_LIMIT
  74021. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  74022. #endif
  74023. for(i=0; i<nOut; i++){
  74024. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  74025. }
  74026. sqlite3StrAccumAppend(&out, "'", 1);
  74027. #ifdef SQLITE_TRACE_SIZE_LIMIT
  74028. if( nOut<pVar->n ){
  74029. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  74030. }
  74031. #endif
  74032. }
  74033. }
  74034. }
  74035. if( out.accError ) sqlite3StrAccumReset(&out);
  74036. return sqlite3StrAccumFinish(&out);
  74037. }
  74038. #endif /* #ifndef SQLITE_OMIT_TRACE */
  74039. /************** End of vdbetrace.c *******************************************/
  74040. /************** Begin file vdbe.c ********************************************/
  74041. /*
  74042. ** 2001 September 15
  74043. **
  74044. ** The author disclaims copyright to this source code. In place of
  74045. ** a legal notice, here is a blessing:
  74046. **
  74047. ** May you do good and not evil.
  74048. ** May you find forgiveness for yourself and forgive others.
  74049. ** May you share freely, never taking more than you give.
  74050. **
  74051. *************************************************************************
  74052. ** The code in this file implements the function that runs the
  74053. ** bytecode of a prepared statement.
  74054. **
  74055. ** Various scripts scan this source file in order to generate HTML
  74056. ** documentation, headers files, or other derived files. The formatting
  74057. ** of the code in this file is, therefore, important. See other comments
  74058. ** in this file for details. If in doubt, do not deviate from existing
  74059. ** commenting and indentation practices when changing or adding code.
  74060. */
  74061. /* #include "sqliteInt.h" */
  74062. /* #include "vdbeInt.h" */
  74063. /*
  74064. ** Invoke this macro on memory cells just prior to changing the
  74065. ** value of the cell. This macro verifies that shallow copies are
  74066. ** not misused. A shallow copy of a string or blob just copies a
  74067. ** pointer to the string or blob, not the content. If the original
  74068. ** is changed while the copy is still in use, the string or blob might
  74069. ** be changed out from under the copy. This macro verifies that nothing
  74070. ** like that ever happens.
  74071. */
  74072. #ifdef SQLITE_DEBUG
  74073. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  74074. #else
  74075. # define memAboutToChange(P,M)
  74076. #endif
  74077. /*
  74078. ** The following global variable is incremented every time a cursor
  74079. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  74080. ** procedures use this information to make sure that indices are
  74081. ** working correctly. This variable has no function other than to
  74082. ** help verify the correct operation of the library.
  74083. */
  74084. #ifdef SQLITE_TEST
  74085. SQLITE_API int sqlite3_search_count = 0;
  74086. #endif
  74087. /*
  74088. ** When this global variable is positive, it gets decremented once before
  74089. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  74090. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  74091. **
  74092. ** This facility is used for testing purposes only. It does not function
  74093. ** in an ordinary build.
  74094. */
  74095. #ifdef SQLITE_TEST
  74096. SQLITE_API int sqlite3_interrupt_count = 0;
  74097. #endif
  74098. /*
  74099. ** The next global variable is incremented each type the OP_Sort opcode
  74100. ** is executed. The test procedures use this information to make sure that
  74101. ** sorting is occurring or not occurring at appropriate times. This variable
  74102. ** has no function other than to help verify the correct operation of the
  74103. ** library.
  74104. */
  74105. #ifdef SQLITE_TEST
  74106. SQLITE_API int sqlite3_sort_count = 0;
  74107. #endif
  74108. /*
  74109. ** The next global variable records the size of the largest MEM_Blob
  74110. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  74111. ** use this information to make sure that the zero-blob functionality
  74112. ** is working correctly. This variable has no function other than to
  74113. ** help verify the correct operation of the library.
  74114. */
  74115. #ifdef SQLITE_TEST
  74116. SQLITE_API int sqlite3_max_blobsize = 0;
  74117. static void updateMaxBlobsize(Mem *p){
  74118. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  74119. sqlite3_max_blobsize = p->n;
  74120. }
  74121. }
  74122. #endif
  74123. /*
  74124. ** This macro evaluates to true if either the update hook or the preupdate
  74125. ** hook are enabled for database connect DB.
  74126. */
  74127. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  74128. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  74129. #else
  74130. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  74131. #endif
  74132. /*
  74133. ** The next global variable is incremented each time the OP_Found opcode
  74134. ** is executed. This is used to test whether or not the foreign key
  74135. ** operation implemented using OP_FkIsZero is working. This variable
  74136. ** has no function other than to help verify the correct operation of the
  74137. ** library.
  74138. */
  74139. #ifdef SQLITE_TEST
  74140. SQLITE_API int sqlite3_found_count = 0;
  74141. #endif
  74142. /*
  74143. ** Test a register to see if it exceeds the current maximum blob size.
  74144. ** If it does, record the new maximum blob size.
  74145. */
  74146. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  74147. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  74148. #else
  74149. # define UPDATE_MAX_BLOBSIZE(P)
  74150. #endif
  74151. /*
  74152. ** Invoke the VDBE coverage callback, if that callback is defined. This
  74153. ** feature is used for test suite validation only and does not appear an
  74154. ** production builds.
  74155. **
  74156. ** M is an integer, 2 or 3, that indices how many different ways the
  74157. ** branch can go. It is usually 2. "I" is the direction the branch
  74158. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  74159. ** second alternative branch is taken.
  74160. **
  74161. ** iSrcLine is the source code line (from the __LINE__ macro) that
  74162. ** generated the VDBE instruction. This instrumentation assumes that all
  74163. ** source code is in a single file (the amalgamation). Special values 1
  74164. ** and 2 for the iSrcLine parameter mean that this particular branch is
  74165. ** always taken or never taken, respectively.
  74166. */
  74167. #if !defined(SQLITE_VDBE_COVERAGE)
  74168. # define VdbeBranchTaken(I,M)
  74169. #else
  74170. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  74171. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  74172. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  74173. M = iSrcLine;
  74174. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  74175. ** VdbeCoverageNeverTaken() */
  74176. assert( (M & I)==I );
  74177. }else{
  74178. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  74179. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  74180. iSrcLine,I,M);
  74181. }
  74182. }
  74183. #endif
  74184. /*
  74185. ** Convert the given register into a string if it isn't one
  74186. ** already. Return non-zero if a malloc() fails.
  74187. */
  74188. #define Stringify(P, enc) \
  74189. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  74190. { goto no_mem; }
  74191. /*
  74192. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  74193. ** a pointer to a dynamically allocated string where some other entity
  74194. ** is responsible for deallocating that string. Because the register
  74195. ** does not control the string, it might be deleted without the register
  74196. ** knowing it.
  74197. **
  74198. ** This routine converts an ephemeral string into a dynamically allocated
  74199. ** string that the register itself controls. In other words, it
  74200. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  74201. */
  74202. #define Deephemeralize(P) \
  74203. if( ((P)->flags&MEM_Ephem)!=0 \
  74204. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  74205. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  74206. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  74207. /*
  74208. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  74209. ** if we run out of memory.
  74210. */
  74211. static VdbeCursor *allocateCursor(
  74212. Vdbe *p, /* The virtual machine */
  74213. int iCur, /* Index of the new VdbeCursor */
  74214. int nField, /* Number of fields in the table or index */
  74215. int iDb, /* Database the cursor belongs to, or -1 */
  74216. u8 eCurType /* Type of the new cursor */
  74217. ){
  74218. /* Find the memory cell that will be used to store the blob of memory
  74219. ** required for this VdbeCursor structure. It is convenient to use a
  74220. ** vdbe memory cell to manage the memory allocation required for a
  74221. ** VdbeCursor structure for the following reasons:
  74222. **
  74223. ** * Sometimes cursor numbers are used for a couple of different
  74224. ** purposes in a vdbe program. The different uses might require
  74225. ** different sized allocations. Memory cells provide growable
  74226. ** allocations.
  74227. **
  74228. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  74229. ** be freed lazily via the sqlite3_release_memory() API. This
  74230. ** minimizes the number of malloc calls made by the system.
  74231. **
  74232. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  74233. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  74234. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  74235. */
  74236. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  74237. int nByte;
  74238. VdbeCursor *pCx = 0;
  74239. nByte =
  74240. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  74241. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  74242. assert( iCur>=0 && iCur<p->nCursor );
  74243. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  74244. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  74245. p->apCsr[iCur] = 0;
  74246. }
  74247. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  74248. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  74249. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  74250. pCx->eCurType = eCurType;
  74251. pCx->iDb = iDb;
  74252. pCx->nField = nField;
  74253. pCx->aOffset = &pCx->aType[nField];
  74254. if( eCurType==CURTYPE_BTREE ){
  74255. pCx->uc.pCursor = (BtCursor*)
  74256. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  74257. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  74258. }
  74259. }
  74260. return pCx;
  74261. }
  74262. /*
  74263. ** Try to convert a value into a numeric representation if we can
  74264. ** do so without loss of information. In other words, if the string
  74265. ** looks like a number, convert it into a number. If it does not
  74266. ** look like a number, leave it alone.
  74267. **
  74268. ** If the bTryForInt flag is true, then extra effort is made to give
  74269. ** an integer representation. Strings that look like floating point
  74270. ** values but which have no fractional component (example: '48.00')
  74271. ** will have a MEM_Int representation when bTryForInt is true.
  74272. **
  74273. ** If bTryForInt is false, then if the input string contains a decimal
  74274. ** point or exponential notation, the result is only MEM_Real, even
  74275. ** if there is an exact integer representation of the quantity.
  74276. */
  74277. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  74278. double rValue;
  74279. i64 iValue;
  74280. u8 enc = pRec->enc;
  74281. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  74282. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  74283. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  74284. pRec->u.i = iValue;
  74285. pRec->flags |= MEM_Int;
  74286. }else{
  74287. pRec->u.r = rValue;
  74288. pRec->flags |= MEM_Real;
  74289. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  74290. }
  74291. }
  74292. /*
  74293. ** Processing is determine by the affinity parameter:
  74294. **
  74295. ** SQLITE_AFF_INTEGER:
  74296. ** SQLITE_AFF_REAL:
  74297. ** SQLITE_AFF_NUMERIC:
  74298. ** Try to convert pRec to an integer representation or a
  74299. ** floating-point representation if an integer representation
  74300. ** is not possible. Note that the integer representation is
  74301. ** always preferred, even if the affinity is REAL, because
  74302. ** an integer representation is more space efficient on disk.
  74303. **
  74304. ** SQLITE_AFF_TEXT:
  74305. ** Convert pRec to a text representation.
  74306. **
  74307. ** SQLITE_AFF_BLOB:
  74308. ** No-op. pRec is unchanged.
  74309. */
  74310. static void applyAffinity(
  74311. Mem *pRec, /* The value to apply affinity to */
  74312. char affinity, /* The affinity to be applied */
  74313. u8 enc /* Use this text encoding */
  74314. ){
  74315. if( affinity>=SQLITE_AFF_NUMERIC ){
  74316. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  74317. || affinity==SQLITE_AFF_NUMERIC );
  74318. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  74319. if( (pRec->flags & MEM_Real)==0 ){
  74320. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  74321. }else{
  74322. sqlite3VdbeIntegerAffinity(pRec);
  74323. }
  74324. }
  74325. }else if( affinity==SQLITE_AFF_TEXT ){
  74326. /* Only attempt the conversion to TEXT if there is an integer or real
  74327. ** representation (blob and NULL do not get converted) but no string
  74328. ** representation. It would be harmless to repeat the conversion if
  74329. ** there is already a string rep, but it is pointless to waste those
  74330. ** CPU cycles. */
  74331. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  74332. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  74333. sqlite3VdbeMemStringify(pRec, enc, 1);
  74334. }
  74335. }
  74336. pRec->flags &= ~(MEM_Real|MEM_Int);
  74337. }
  74338. }
  74339. /*
  74340. ** Try to convert the type of a function argument or a result column
  74341. ** into a numeric representation. Use either INTEGER or REAL whichever
  74342. ** is appropriate. But only do the conversion if it is possible without
  74343. ** loss of information and return the revised type of the argument.
  74344. */
  74345. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  74346. int eType = sqlite3_value_type(pVal);
  74347. if( eType==SQLITE_TEXT ){
  74348. Mem *pMem = (Mem*)pVal;
  74349. applyNumericAffinity(pMem, 0);
  74350. eType = sqlite3_value_type(pVal);
  74351. }
  74352. return eType;
  74353. }
  74354. /*
  74355. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  74356. ** not the internal Mem* type.
  74357. */
  74358. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  74359. sqlite3_value *pVal,
  74360. u8 affinity,
  74361. u8 enc
  74362. ){
  74363. applyAffinity((Mem *)pVal, affinity, enc);
  74364. }
  74365. /*
  74366. ** pMem currently only holds a string type (or maybe a BLOB that we can
  74367. ** interpret as a string if we want to). Compute its corresponding
  74368. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  74369. ** accordingly.
  74370. */
  74371. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  74372. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  74373. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  74374. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  74375. return 0;
  74376. }
  74377. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
  74378. return MEM_Int;
  74379. }
  74380. return MEM_Real;
  74381. }
  74382. /*
  74383. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  74384. ** none.
  74385. **
  74386. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  74387. ** But it does set pMem->u.r and pMem->u.i appropriately.
  74388. */
  74389. static u16 numericType(Mem *pMem){
  74390. if( pMem->flags & (MEM_Int|MEM_Real) ){
  74391. return pMem->flags & (MEM_Int|MEM_Real);
  74392. }
  74393. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  74394. return computeNumericType(pMem);
  74395. }
  74396. return 0;
  74397. }
  74398. #ifdef SQLITE_DEBUG
  74399. /*
  74400. ** Write a nice string representation of the contents of cell pMem
  74401. ** into buffer zBuf, length nBuf.
  74402. */
  74403. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  74404. char *zCsr = zBuf;
  74405. int f = pMem->flags;
  74406. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  74407. if( f&MEM_Blob ){
  74408. int i;
  74409. char c;
  74410. if( f & MEM_Dyn ){
  74411. c = 'z';
  74412. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  74413. }else if( f & MEM_Static ){
  74414. c = 't';
  74415. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  74416. }else if( f & MEM_Ephem ){
  74417. c = 'e';
  74418. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  74419. }else{
  74420. c = 's';
  74421. }
  74422. *(zCsr++) = c;
  74423. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  74424. zCsr += sqlite3Strlen30(zCsr);
  74425. for(i=0; i<16 && i<pMem->n; i++){
  74426. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  74427. zCsr += sqlite3Strlen30(zCsr);
  74428. }
  74429. for(i=0; i<16 && i<pMem->n; i++){
  74430. char z = pMem->z[i];
  74431. if( z<32 || z>126 ) *zCsr++ = '.';
  74432. else *zCsr++ = z;
  74433. }
  74434. *(zCsr++) = ']';
  74435. if( f & MEM_Zero ){
  74436. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  74437. zCsr += sqlite3Strlen30(zCsr);
  74438. }
  74439. *zCsr = '\0';
  74440. }else if( f & MEM_Str ){
  74441. int j, k;
  74442. zBuf[0] = ' ';
  74443. if( f & MEM_Dyn ){
  74444. zBuf[1] = 'z';
  74445. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  74446. }else if( f & MEM_Static ){
  74447. zBuf[1] = 't';
  74448. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  74449. }else if( f & MEM_Ephem ){
  74450. zBuf[1] = 'e';
  74451. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  74452. }else{
  74453. zBuf[1] = 's';
  74454. }
  74455. k = 2;
  74456. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  74457. k += sqlite3Strlen30(&zBuf[k]);
  74458. zBuf[k++] = '[';
  74459. for(j=0; j<15 && j<pMem->n; j++){
  74460. u8 c = pMem->z[j];
  74461. if( c>=0x20 && c<0x7f ){
  74462. zBuf[k++] = c;
  74463. }else{
  74464. zBuf[k++] = '.';
  74465. }
  74466. }
  74467. zBuf[k++] = ']';
  74468. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  74469. k += sqlite3Strlen30(&zBuf[k]);
  74470. zBuf[k++] = 0;
  74471. }
  74472. }
  74473. #endif
  74474. #ifdef SQLITE_DEBUG
  74475. /*
  74476. ** Print the value of a register for tracing purposes:
  74477. */
  74478. static void memTracePrint(Mem *p){
  74479. if( p->flags & MEM_Undefined ){
  74480. printf(" undefined");
  74481. }else if( p->flags & MEM_Null ){
  74482. printf(" NULL");
  74483. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  74484. printf(" si:%lld", p->u.i);
  74485. }else if( p->flags & MEM_Int ){
  74486. printf(" i:%lld", p->u.i);
  74487. #ifndef SQLITE_OMIT_FLOATING_POINT
  74488. }else if( p->flags & MEM_Real ){
  74489. printf(" r:%g", p->u.r);
  74490. #endif
  74491. }else if( p->flags & MEM_RowSet ){
  74492. printf(" (rowset)");
  74493. }else{
  74494. char zBuf[200];
  74495. sqlite3VdbeMemPrettyPrint(p, zBuf);
  74496. printf(" %s", zBuf);
  74497. }
  74498. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  74499. }
  74500. static void registerTrace(int iReg, Mem *p){
  74501. printf("REG[%d] = ", iReg);
  74502. memTracePrint(p);
  74503. printf("\n");
  74504. sqlite3VdbeCheckMemInvariants(p);
  74505. }
  74506. #endif
  74507. #ifdef SQLITE_DEBUG
  74508. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  74509. #else
  74510. # define REGISTER_TRACE(R,M)
  74511. #endif
  74512. #ifdef VDBE_PROFILE
  74513. /*
  74514. ** hwtime.h contains inline assembler code for implementing
  74515. ** high-performance timing routines.
  74516. */
  74517. /************** Include hwtime.h in the middle of vdbe.c *********************/
  74518. /************** Begin file hwtime.h ******************************************/
  74519. /*
  74520. ** 2008 May 27
  74521. **
  74522. ** The author disclaims copyright to this source code. In place of
  74523. ** a legal notice, here is a blessing:
  74524. **
  74525. ** May you do good and not evil.
  74526. ** May you find forgiveness for yourself and forgive others.
  74527. ** May you share freely, never taking more than you give.
  74528. **
  74529. ******************************************************************************
  74530. **
  74531. ** This file contains inline asm code for retrieving "high-performance"
  74532. ** counters for x86 class CPUs.
  74533. */
  74534. #ifndef SQLITE_HWTIME_H
  74535. #define SQLITE_HWTIME_H
  74536. /*
  74537. ** The following routine only works on pentium-class (or newer) processors.
  74538. ** It uses the RDTSC opcode to read the cycle count value out of the
  74539. ** processor and returns that value. This can be used for high-res
  74540. ** profiling.
  74541. */
  74542. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  74543. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  74544. #if defined(__GNUC__)
  74545. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  74546. unsigned int lo, hi;
  74547. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  74548. return (sqlite_uint64)hi << 32 | lo;
  74549. }
  74550. #elif defined(_MSC_VER)
  74551. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  74552. __asm {
  74553. rdtsc
  74554. ret ; return value at EDX:EAX
  74555. }
  74556. }
  74557. #endif
  74558. #elif (defined(__GNUC__) && defined(__x86_64__))
  74559. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  74560. unsigned long val;
  74561. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  74562. return val;
  74563. }
  74564. #elif (defined(__GNUC__) && defined(__ppc__))
  74565. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  74566. unsigned long long retval;
  74567. unsigned long junk;
  74568. __asm__ __volatile__ ("\n\
  74569. 1: mftbu %1\n\
  74570. mftb %L0\n\
  74571. mftbu %0\n\
  74572. cmpw %0,%1\n\
  74573. bne 1b"
  74574. : "=r" (retval), "=r" (junk));
  74575. return retval;
  74576. }
  74577. #else
  74578. #error Need implementation of sqlite3Hwtime() for your platform.
  74579. /*
  74580. ** To compile without implementing sqlite3Hwtime() for your platform,
  74581. ** you can remove the above #error and use the following
  74582. ** stub function. You will lose timing support for many
  74583. ** of the debugging and testing utilities, but it should at
  74584. ** least compile and run.
  74585. */
  74586. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  74587. #endif
  74588. #endif /* !defined(SQLITE_HWTIME_H) */
  74589. /************** End of hwtime.h **********************************************/
  74590. /************** Continuing where we left off in vdbe.c ***********************/
  74591. #endif
  74592. #ifndef NDEBUG
  74593. /*
  74594. ** This function is only called from within an assert() expression. It
  74595. ** checks that the sqlite3.nTransaction variable is correctly set to
  74596. ** the number of non-transaction savepoints currently in the
  74597. ** linked list starting at sqlite3.pSavepoint.
  74598. **
  74599. ** Usage:
  74600. **
  74601. ** assert( checkSavepointCount(db) );
  74602. */
  74603. static int checkSavepointCount(sqlite3 *db){
  74604. int n = 0;
  74605. Savepoint *p;
  74606. for(p=db->pSavepoint; p; p=p->pNext) n++;
  74607. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  74608. return 1;
  74609. }
  74610. #endif
  74611. /*
  74612. ** Return the register of pOp->p2 after first preparing it to be
  74613. ** overwritten with an integer value.
  74614. */
  74615. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  74616. sqlite3VdbeMemSetNull(pOut);
  74617. pOut->flags = MEM_Int;
  74618. return pOut;
  74619. }
  74620. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  74621. Mem *pOut;
  74622. assert( pOp->p2>0 );
  74623. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  74624. pOut = &p->aMem[pOp->p2];
  74625. memAboutToChange(p, pOut);
  74626. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  74627. return out2PrereleaseWithClear(pOut);
  74628. }else{
  74629. pOut->flags = MEM_Int;
  74630. return pOut;
  74631. }
  74632. }
  74633. /*
  74634. ** Execute as much of a VDBE program as we can.
  74635. ** This is the core of sqlite3_step().
  74636. */
  74637. SQLITE_PRIVATE int sqlite3VdbeExec(
  74638. Vdbe *p /* The VDBE */
  74639. ){
  74640. Op *aOp = p->aOp; /* Copy of p->aOp */
  74641. Op *pOp = aOp; /* Current operation */
  74642. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  74643. Op *pOrigOp; /* Value of pOp at the top of the loop */
  74644. #endif
  74645. #ifdef SQLITE_DEBUG
  74646. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  74647. #endif
  74648. int rc = SQLITE_OK; /* Value to return */
  74649. sqlite3 *db = p->db; /* The database */
  74650. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  74651. u8 encoding = ENC(db); /* The database encoding */
  74652. int iCompare = 0; /* Result of last comparison */
  74653. unsigned nVmStep = 0; /* Number of virtual machine steps */
  74654. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74655. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  74656. #endif
  74657. Mem *aMem = p->aMem; /* Copy of p->aMem */
  74658. Mem *pIn1 = 0; /* 1st input operand */
  74659. Mem *pIn2 = 0; /* 2nd input operand */
  74660. Mem *pIn3 = 0; /* 3rd input operand */
  74661. Mem *pOut = 0; /* Output operand */
  74662. #ifdef VDBE_PROFILE
  74663. u64 start; /* CPU clock count at start of opcode */
  74664. #endif
  74665. /*** INSERT STACK UNION HERE ***/
  74666. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  74667. sqlite3VdbeEnter(p);
  74668. if( p->rc==SQLITE_NOMEM ){
  74669. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  74670. ** sqlite3_column_text16() failed. */
  74671. goto no_mem;
  74672. }
  74673. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  74674. assert( p->bIsReader || p->readOnly!=0 );
  74675. p->iCurrentTime = 0;
  74676. assert( p->explain==0 );
  74677. p->pResultSet = 0;
  74678. db->busyHandler.nBusy = 0;
  74679. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  74680. sqlite3VdbeIOTraceSql(p);
  74681. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74682. if( db->xProgress ){
  74683. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  74684. assert( 0 < db->nProgressOps );
  74685. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  74686. }else{
  74687. nProgressLimit = 0xffffffff;
  74688. }
  74689. #endif
  74690. #ifdef SQLITE_DEBUG
  74691. sqlite3BeginBenignMalloc();
  74692. if( p->pc==0
  74693. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  74694. ){
  74695. int i;
  74696. int once = 1;
  74697. sqlite3VdbePrintSql(p);
  74698. if( p->db->flags & SQLITE_VdbeListing ){
  74699. printf("VDBE Program Listing:\n");
  74700. for(i=0; i<p->nOp; i++){
  74701. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  74702. }
  74703. }
  74704. if( p->db->flags & SQLITE_VdbeEQP ){
  74705. for(i=0; i<p->nOp; i++){
  74706. if( aOp[i].opcode==OP_Explain ){
  74707. if( once ) printf("VDBE Query Plan:\n");
  74708. printf("%s\n", aOp[i].p4.z);
  74709. once = 0;
  74710. }
  74711. }
  74712. }
  74713. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  74714. }
  74715. sqlite3EndBenignMalloc();
  74716. #endif
  74717. for(pOp=&aOp[p->pc]; 1; pOp++){
  74718. /* Errors are detected by individual opcodes, with an immediate
  74719. ** jumps to abort_due_to_error. */
  74720. assert( rc==SQLITE_OK );
  74721. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  74722. #ifdef VDBE_PROFILE
  74723. start = sqlite3Hwtime();
  74724. #endif
  74725. nVmStep++;
  74726. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74727. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  74728. #endif
  74729. /* Only allow tracing if SQLITE_DEBUG is defined.
  74730. */
  74731. #ifdef SQLITE_DEBUG
  74732. if( db->flags & SQLITE_VdbeTrace ){
  74733. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  74734. }
  74735. #endif
  74736. /* Check to see if we need to simulate an interrupt. This only happens
  74737. ** if we have a special test build.
  74738. */
  74739. #ifdef SQLITE_TEST
  74740. if( sqlite3_interrupt_count>0 ){
  74741. sqlite3_interrupt_count--;
  74742. if( sqlite3_interrupt_count==0 ){
  74743. sqlite3_interrupt(db);
  74744. }
  74745. }
  74746. #endif
  74747. /* Sanity checking on other operands */
  74748. #ifdef SQLITE_DEBUG
  74749. {
  74750. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  74751. if( (opProperty & OPFLG_IN1)!=0 ){
  74752. assert( pOp->p1>0 );
  74753. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  74754. assert( memIsValid(&aMem[pOp->p1]) );
  74755. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  74756. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  74757. }
  74758. if( (opProperty & OPFLG_IN2)!=0 ){
  74759. assert( pOp->p2>0 );
  74760. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  74761. assert( memIsValid(&aMem[pOp->p2]) );
  74762. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  74763. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  74764. }
  74765. if( (opProperty & OPFLG_IN3)!=0 ){
  74766. assert( pOp->p3>0 );
  74767. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74768. assert( memIsValid(&aMem[pOp->p3]) );
  74769. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  74770. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  74771. }
  74772. if( (opProperty & OPFLG_OUT2)!=0 ){
  74773. assert( pOp->p2>0 );
  74774. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  74775. memAboutToChange(p, &aMem[pOp->p2]);
  74776. }
  74777. if( (opProperty & OPFLG_OUT3)!=0 ){
  74778. assert( pOp->p3>0 );
  74779. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74780. memAboutToChange(p, &aMem[pOp->p3]);
  74781. }
  74782. }
  74783. #endif
  74784. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  74785. pOrigOp = pOp;
  74786. #endif
  74787. switch( pOp->opcode ){
  74788. /*****************************************************************************
  74789. ** What follows is a massive switch statement where each case implements a
  74790. ** separate instruction in the virtual machine. If we follow the usual
  74791. ** indentation conventions, each case should be indented by 6 spaces. But
  74792. ** that is a lot of wasted space on the left margin. So the code within
  74793. ** the switch statement will break with convention and be flush-left. Another
  74794. ** big comment (similar to this one) will mark the point in the code where
  74795. ** we transition back to normal indentation.
  74796. **
  74797. ** The formatting of each case is important. The makefile for SQLite
  74798. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  74799. ** file looking for lines that begin with "case OP_". The opcodes.h files
  74800. ** will be filled with #defines that give unique integer values to each
  74801. ** opcode and the opcodes.c file is filled with an array of strings where
  74802. ** each string is the symbolic name for the corresponding opcode. If the
  74803. ** case statement is followed by a comment of the form "/# same as ... #/"
  74804. ** that comment is used to determine the particular value of the opcode.
  74805. **
  74806. ** Other keywords in the comment that follows each case are used to
  74807. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  74808. ** Keywords include: in1, in2, in3, out2, out3. See
  74809. ** the mkopcodeh.awk script for additional information.
  74810. **
  74811. ** Documentation about VDBE opcodes is generated by scanning this file
  74812. ** for lines of that contain "Opcode:". That line and all subsequent
  74813. ** comment lines are used in the generation of the opcode.html documentation
  74814. ** file.
  74815. **
  74816. ** SUMMARY:
  74817. **
  74818. ** Formatting is important to scripts that scan this file.
  74819. ** Do not deviate from the formatting style currently in use.
  74820. **
  74821. *****************************************************************************/
  74822. /* Opcode: Goto * P2 * * *
  74823. **
  74824. ** An unconditional jump to address P2.
  74825. ** The next instruction executed will be
  74826. ** the one at index P2 from the beginning of
  74827. ** the program.
  74828. **
  74829. ** The P1 parameter is not actually used by this opcode. However, it
  74830. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  74831. ** that this Goto is the bottom of a loop and that the lines from P2 down
  74832. ** to the current line should be indented for EXPLAIN output.
  74833. */
  74834. case OP_Goto: { /* jump */
  74835. jump_to_p2_and_check_for_interrupt:
  74836. pOp = &aOp[pOp->p2 - 1];
  74837. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  74838. ** OP_VNext, or OP_SorterNext) all jump here upon
  74839. ** completion. Check to see if sqlite3_interrupt() has been called
  74840. ** or if the progress callback needs to be invoked.
  74841. **
  74842. ** This code uses unstructured "goto" statements and does not look clean.
  74843. ** But that is not due to sloppy coding habits. The code is written this
  74844. ** way for performance, to avoid having to run the interrupt and progress
  74845. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  74846. ** faster according to "valgrind --tool=cachegrind" */
  74847. check_for_interrupt:
  74848. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  74849. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74850. /* Call the progress callback if it is configured and the required number
  74851. ** of VDBE ops have been executed (either since this invocation of
  74852. ** sqlite3VdbeExec() or since last time the progress callback was called).
  74853. ** If the progress callback returns non-zero, exit the virtual machine with
  74854. ** a return code SQLITE_ABORT.
  74855. */
  74856. if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  74857. assert( db->nProgressOps!=0 );
  74858. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  74859. if( db->xProgress(db->pProgressArg) ){
  74860. rc = SQLITE_INTERRUPT;
  74861. goto abort_due_to_error;
  74862. }
  74863. }
  74864. #endif
  74865. break;
  74866. }
  74867. /* Opcode: Gosub P1 P2 * * *
  74868. **
  74869. ** Write the current address onto register P1
  74870. ** and then jump to address P2.
  74871. */
  74872. case OP_Gosub: { /* jump */
  74873. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74874. pIn1 = &aMem[pOp->p1];
  74875. assert( VdbeMemDynamic(pIn1)==0 );
  74876. memAboutToChange(p, pIn1);
  74877. pIn1->flags = MEM_Int;
  74878. pIn1->u.i = (int)(pOp-aOp);
  74879. REGISTER_TRACE(pOp->p1, pIn1);
  74880. /* Most jump operations do a goto to this spot in order to update
  74881. ** the pOp pointer. */
  74882. jump_to_p2:
  74883. pOp = &aOp[pOp->p2 - 1];
  74884. break;
  74885. }
  74886. /* Opcode: Return P1 * * * *
  74887. **
  74888. ** Jump to the next instruction after the address in register P1. After
  74889. ** the jump, register P1 becomes undefined.
  74890. */
  74891. case OP_Return: { /* in1 */
  74892. pIn1 = &aMem[pOp->p1];
  74893. assert( pIn1->flags==MEM_Int );
  74894. pOp = &aOp[pIn1->u.i];
  74895. pIn1->flags = MEM_Undefined;
  74896. break;
  74897. }
  74898. /* Opcode: InitCoroutine P1 P2 P3 * *
  74899. **
  74900. ** Set up register P1 so that it will Yield to the coroutine
  74901. ** located at address P3.
  74902. **
  74903. ** If P2!=0 then the coroutine implementation immediately follows
  74904. ** this opcode. So jump over the coroutine implementation to
  74905. ** address P2.
  74906. **
  74907. ** See also: EndCoroutine
  74908. */
  74909. case OP_InitCoroutine: { /* jump */
  74910. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74911. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  74912. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  74913. pOut = &aMem[pOp->p1];
  74914. assert( !VdbeMemDynamic(pOut) );
  74915. pOut->u.i = pOp->p3 - 1;
  74916. pOut->flags = MEM_Int;
  74917. if( pOp->p2 ) goto jump_to_p2;
  74918. break;
  74919. }
  74920. /* Opcode: EndCoroutine P1 * * * *
  74921. **
  74922. ** The instruction at the address in register P1 is a Yield.
  74923. ** Jump to the P2 parameter of that Yield.
  74924. ** After the jump, register P1 becomes undefined.
  74925. **
  74926. ** See also: InitCoroutine
  74927. */
  74928. case OP_EndCoroutine: { /* in1 */
  74929. VdbeOp *pCaller;
  74930. pIn1 = &aMem[pOp->p1];
  74931. assert( pIn1->flags==MEM_Int );
  74932. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  74933. pCaller = &aOp[pIn1->u.i];
  74934. assert( pCaller->opcode==OP_Yield );
  74935. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  74936. pOp = &aOp[pCaller->p2 - 1];
  74937. pIn1->flags = MEM_Undefined;
  74938. break;
  74939. }
  74940. /* Opcode: Yield P1 P2 * * *
  74941. **
  74942. ** Swap the program counter with the value in register P1. This
  74943. ** has the effect of yielding to a coroutine.
  74944. **
  74945. ** If the coroutine that is launched by this instruction ends with
  74946. ** Yield or Return then continue to the next instruction. But if
  74947. ** the coroutine launched by this instruction ends with
  74948. ** EndCoroutine, then jump to P2 rather than continuing with the
  74949. ** next instruction.
  74950. **
  74951. ** See also: InitCoroutine
  74952. */
  74953. case OP_Yield: { /* in1, jump */
  74954. int pcDest;
  74955. pIn1 = &aMem[pOp->p1];
  74956. assert( VdbeMemDynamic(pIn1)==0 );
  74957. pIn1->flags = MEM_Int;
  74958. pcDest = (int)pIn1->u.i;
  74959. pIn1->u.i = (int)(pOp - aOp);
  74960. REGISTER_TRACE(pOp->p1, pIn1);
  74961. pOp = &aOp[pcDest];
  74962. break;
  74963. }
  74964. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  74965. ** Synopsis: if r[P3]=null halt
  74966. **
  74967. ** Check the value in register P3. If it is NULL then Halt using
  74968. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  74969. ** value in register P3 is not NULL, then this routine is a no-op.
  74970. ** The P5 parameter should be 1.
  74971. */
  74972. case OP_HaltIfNull: { /* in3 */
  74973. pIn3 = &aMem[pOp->p3];
  74974. if( (pIn3->flags & MEM_Null)==0 ) break;
  74975. /* Fall through into OP_Halt */
  74976. }
  74977. /* Opcode: Halt P1 P2 * P4 P5
  74978. **
  74979. ** Exit immediately. All open cursors, etc are closed
  74980. ** automatically.
  74981. **
  74982. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  74983. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  74984. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  74985. ** whether or not to rollback the current transaction. Do not rollback
  74986. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  74987. ** then back out all changes that have occurred during this execution of the
  74988. ** VDBE, but do not rollback the transaction.
  74989. **
  74990. ** If P4 is not null then it is an error message string.
  74991. **
  74992. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  74993. **
  74994. ** 0: (no change)
  74995. ** 1: NOT NULL contraint failed: P4
  74996. ** 2: UNIQUE constraint failed: P4
  74997. ** 3: CHECK constraint failed: P4
  74998. ** 4: FOREIGN KEY constraint failed: P4
  74999. **
  75000. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  75001. ** omitted.
  75002. **
  75003. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  75004. ** every program. So a jump past the last instruction of the program
  75005. ** is the same as executing Halt.
  75006. */
  75007. case OP_Halt: {
  75008. VdbeFrame *pFrame;
  75009. int pcx;
  75010. pcx = (int)(pOp - aOp);
  75011. if( pOp->p1==SQLITE_OK && p->pFrame ){
  75012. /* Halt the sub-program. Return control to the parent frame. */
  75013. pFrame = p->pFrame;
  75014. p->pFrame = pFrame->pParent;
  75015. p->nFrame--;
  75016. sqlite3VdbeSetChanges(db, p->nChange);
  75017. pcx = sqlite3VdbeFrameRestore(pFrame);
  75018. if( pOp->p2==OE_Ignore ){
  75019. /* Instruction pcx is the OP_Program that invoked the sub-program
  75020. ** currently being halted. If the p2 instruction of this OP_Halt
  75021. ** instruction is set to OE_Ignore, then the sub-program is throwing
  75022. ** an IGNORE exception. In this case jump to the address specified
  75023. ** as the p2 of the calling OP_Program. */
  75024. pcx = p->aOp[pcx].p2-1;
  75025. }
  75026. aOp = p->aOp;
  75027. aMem = p->aMem;
  75028. pOp = &aOp[pcx];
  75029. break;
  75030. }
  75031. p->rc = pOp->p1;
  75032. p->errorAction = (u8)pOp->p2;
  75033. p->pc = pcx;
  75034. assert( pOp->p5<=4 );
  75035. if( p->rc ){
  75036. if( pOp->p5 ){
  75037. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  75038. "FOREIGN KEY" };
  75039. testcase( pOp->p5==1 );
  75040. testcase( pOp->p5==2 );
  75041. testcase( pOp->p5==3 );
  75042. testcase( pOp->p5==4 );
  75043. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  75044. if( pOp->p4.z ){
  75045. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  75046. }
  75047. }else{
  75048. sqlite3VdbeError(p, "%s", pOp->p4.z);
  75049. }
  75050. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  75051. }
  75052. rc = sqlite3VdbeHalt(p);
  75053. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  75054. if( rc==SQLITE_BUSY ){
  75055. p->rc = SQLITE_BUSY;
  75056. }else{
  75057. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  75058. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  75059. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  75060. }
  75061. goto vdbe_return;
  75062. }
  75063. /* Opcode: Integer P1 P2 * * *
  75064. ** Synopsis: r[P2]=P1
  75065. **
  75066. ** The 32-bit integer value P1 is written into register P2.
  75067. */
  75068. case OP_Integer: { /* out2 */
  75069. pOut = out2Prerelease(p, pOp);
  75070. pOut->u.i = pOp->p1;
  75071. break;
  75072. }
  75073. /* Opcode: Int64 * P2 * P4 *
  75074. ** Synopsis: r[P2]=P4
  75075. **
  75076. ** P4 is a pointer to a 64-bit integer value.
  75077. ** Write that value into register P2.
  75078. */
  75079. case OP_Int64: { /* out2 */
  75080. pOut = out2Prerelease(p, pOp);
  75081. assert( pOp->p4.pI64!=0 );
  75082. pOut->u.i = *pOp->p4.pI64;
  75083. break;
  75084. }
  75085. #ifndef SQLITE_OMIT_FLOATING_POINT
  75086. /* Opcode: Real * P2 * P4 *
  75087. ** Synopsis: r[P2]=P4
  75088. **
  75089. ** P4 is a pointer to a 64-bit floating point value.
  75090. ** Write that value into register P2.
  75091. */
  75092. case OP_Real: { /* same as TK_FLOAT, out2 */
  75093. pOut = out2Prerelease(p, pOp);
  75094. pOut->flags = MEM_Real;
  75095. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  75096. pOut->u.r = *pOp->p4.pReal;
  75097. break;
  75098. }
  75099. #endif
  75100. /* Opcode: String8 * P2 * P4 *
  75101. ** Synopsis: r[P2]='P4'
  75102. **
  75103. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  75104. ** into a String opcode before it is executed for the first time. During
  75105. ** this transformation, the length of string P4 is computed and stored
  75106. ** as the P1 parameter.
  75107. */
  75108. case OP_String8: { /* same as TK_STRING, out2 */
  75109. assert( pOp->p4.z!=0 );
  75110. pOut = out2Prerelease(p, pOp);
  75111. pOp->opcode = OP_String;
  75112. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  75113. #ifndef SQLITE_OMIT_UTF16
  75114. if( encoding!=SQLITE_UTF8 ){
  75115. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  75116. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  75117. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  75118. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  75119. assert( VdbeMemDynamic(pOut)==0 );
  75120. pOut->szMalloc = 0;
  75121. pOut->flags |= MEM_Static;
  75122. if( pOp->p4type==P4_DYNAMIC ){
  75123. sqlite3DbFree(db, pOp->p4.z);
  75124. }
  75125. pOp->p4type = P4_DYNAMIC;
  75126. pOp->p4.z = pOut->z;
  75127. pOp->p1 = pOut->n;
  75128. }
  75129. testcase( rc==SQLITE_TOOBIG );
  75130. #endif
  75131. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75132. goto too_big;
  75133. }
  75134. assert( rc==SQLITE_OK );
  75135. /* Fall through to the next case, OP_String */
  75136. }
  75137. /* Opcode: String P1 P2 P3 P4 P5
  75138. ** Synopsis: r[P2]='P4' (len=P1)
  75139. **
  75140. ** The string value P4 of length P1 (bytes) is stored in register P2.
  75141. **
  75142. ** If P3 is not zero and the content of register P3 is equal to P5, then
  75143. ** the datatype of the register P2 is converted to BLOB. The content is
  75144. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  75145. ** of a string, as if it had been CAST. In other words:
  75146. **
  75147. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  75148. */
  75149. case OP_String: { /* out2 */
  75150. assert( pOp->p4.z!=0 );
  75151. pOut = out2Prerelease(p, pOp);
  75152. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  75153. pOut->z = pOp->p4.z;
  75154. pOut->n = pOp->p1;
  75155. pOut->enc = encoding;
  75156. UPDATE_MAX_BLOBSIZE(pOut);
  75157. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  75158. if( pOp->p3>0 ){
  75159. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  75160. pIn3 = &aMem[pOp->p3];
  75161. assert( pIn3->flags & MEM_Int );
  75162. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  75163. }
  75164. #endif
  75165. break;
  75166. }
  75167. /* Opcode: Null P1 P2 P3 * *
  75168. ** Synopsis: r[P2..P3]=NULL
  75169. **
  75170. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  75171. ** NULL into register P3 and every register in between P2 and P3. If P3
  75172. ** is less than P2 (typically P3 is zero) then only register P2 is
  75173. ** set to NULL.
  75174. **
  75175. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  75176. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  75177. ** OP_Ne or OP_Eq.
  75178. */
  75179. case OP_Null: { /* out2 */
  75180. int cnt;
  75181. u16 nullFlag;
  75182. pOut = out2Prerelease(p, pOp);
  75183. cnt = pOp->p3-pOp->p2;
  75184. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  75185. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  75186. pOut->n = 0;
  75187. while( cnt>0 ){
  75188. pOut++;
  75189. memAboutToChange(p, pOut);
  75190. sqlite3VdbeMemSetNull(pOut);
  75191. pOut->flags = nullFlag;
  75192. pOut->n = 0;
  75193. cnt--;
  75194. }
  75195. break;
  75196. }
  75197. /* Opcode: SoftNull P1 * * * *
  75198. ** Synopsis: r[P1]=NULL
  75199. **
  75200. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  75201. ** instruction, but do not free any string or blob memory associated with
  75202. ** the register, so that if the value was a string or blob that was
  75203. ** previously copied using OP_SCopy, the copies will continue to be valid.
  75204. */
  75205. case OP_SoftNull: {
  75206. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  75207. pOut = &aMem[pOp->p1];
  75208. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  75209. break;
  75210. }
  75211. /* Opcode: Blob P1 P2 * P4 *
  75212. ** Synopsis: r[P2]=P4 (len=P1)
  75213. **
  75214. ** P4 points to a blob of data P1 bytes long. Store this
  75215. ** blob in register P2.
  75216. */
  75217. case OP_Blob: { /* out2 */
  75218. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  75219. pOut = out2Prerelease(p, pOp);
  75220. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  75221. pOut->enc = encoding;
  75222. UPDATE_MAX_BLOBSIZE(pOut);
  75223. break;
  75224. }
  75225. /* Opcode: Variable P1 P2 * P4 *
  75226. ** Synopsis: r[P2]=parameter(P1,P4)
  75227. **
  75228. ** Transfer the values of bound parameter P1 into register P2
  75229. **
  75230. ** If the parameter is named, then its name appears in P4.
  75231. ** The P4 value is used by sqlite3_bind_parameter_name().
  75232. */
  75233. case OP_Variable: { /* out2 */
  75234. Mem *pVar; /* Value being transferred */
  75235. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  75236. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  75237. pVar = &p->aVar[pOp->p1 - 1];
  75238. if( sqlite3VdbeMemTooBig(pVar) ){
  75239. goto too_big;
  75240. }
  75241. pOut = &aMem[pOp->p2];
  75242. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  75243. UPDATE_MAX_BLOBSIZE(pOut);
  75244. break;
  75245. }
  75246. /* Opcode: Move P1 P2 P3 * *
  75247. ** Synopsis: r[P2@P3]=r[P1@P3]
  75248. **
  75249. ** Move the P3 values in register P1..P1+P3-1 over into
  75250. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  75251. ** left holding a NULL. It is an error for register ranges
  75252. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  75253. ** for P3 to be less than 1.
  75254. */
  75255. case OP_Move: {
  75256. int n; /* Number of registers left to copy */
  75257. int p1; /* Register to copy from */
  75258. int p2; /* Register to copy to */
  75259. n = pOp->p3;
  75260. p1 = pOp->p1;
  75261. p2 = pOp->p2;
  75262. assert( n>0 && p1>0 && p2>0 );
  75263. assert( p1+n<=p2 || p2+n<=p1 );
  75264. pIn1 = &aMem[p1];
  75265. pOut = &aMem[p2];
  75266. do{
  75267. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  75268. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  75269. assert( memIsValid(pIn1) );
  75270. memAboutToChange(p, pOut);
  75271. sqlite3VdbeMemMove(pOut, pIn1);
  75272. #ifdef SQLITE_DEBUG
  75273. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  75274. pOut->pScopyFrom += pOp->p2 - p1;
  75275. }
  75276. #endif
  75277. Deephemeralize(pOut);
  75278. REGISTER_TRACE(p2++, pOut);
  75279. pIn1++;
  75280. pOut++;
  75281. }while( --n );
  75282. break;
  75283. }
  75284. /* Opcode: Copy P1 P2 P3 * *
  75285. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  75286. **
  75287. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  75288. **
  75289. ** This instruction makes a deep copy of the value. A duplicate
  75290. ** is made of any string or blob constant. See also OP_SCopy.
  75291. */
  75292. case OP_Copy: {
  75293. int n;
  75294. n = pOp->p3;
  75295. pIn1 = &aMem[pOp->p1];
  75296. pOut = &aMem[pOp->p2];
  75297. assert( pOut!=pIn1 );
  75298. while( 1 ){
  75299. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  75300. Deephemeralize(pOut);
  75301. #ifdef SQLITE_DEBUG
  75302. pOut->pScopyFrom = 0;
  75303. #endif
  75304. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  75305. if( (n--)==0 ) break;
  75306. pOut++;
  75307. pIn1++;
  75308. }
  75309. break;
  75310. }
  75311. /* Opcode: SCopy P1 P2 * * *
  75312. ** Synopsis: r[P2]=r[P1]
  75313. **
  75314. ** Make a shallow copy of register P1 into register P2.
  75315. **
  75316. ** This instruction makes a shallow copy of the value. If the value
  75317. ** is a string or blob, then the copy is only a pointer to the
  75318. ** original and hence if the original changes so will the copy.
  75319. ** Worse, if the original is deallocated, the copy becomes invalid.
  75320. ** Thus the program must guarantee that the original will not change
  75321. ** during the lifetime of the copy. Use OP_Copy to make a complete
  75322. ** copy.
  75323. */
  75324. case OP_SCopy: { /* out2 */
  75325. pIn1 = &aMem[pOp->p1];
  75326. pOut = &aMem[pOp->p2];
  75327. assert( pOut!=pIn1 );
  75328. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  75329. #ifdef SQLITE_DEBUG
  75330. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  75331. #endif
  75332. break;
  75333. }
  75334. /* Opcode: IntCopy P1 P2 * * *
  75335. ** Synopsis: r[P2]=r[P1]
  75336. **
  75337. ** Transfer the integer value held in register P1 into register P2.
  75338. **
  75339. ** This is an optimized version of SCopy that works only for integer
  75340. ** values.
  75341. */
  75342. case OP_IntCopy: { /* out2 */
  75343. pIn1 = &aMem[pOp->p1];
  75344. assert( (pIn1->flags & MEM_Int)!=0 );
  75345. pOut = &aMem[pOp->p2];
  75346. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  75347. break;
  75348. }
  75349. /* Opcode: ResultRow P1 P2 * * *
  75350. ** Synopsis: output=r[P1@P2]
  75351. **
  75352. ** The registers P1 through P1+P2-1 contain a single row of
  75353. ** results. This opcode causes the sqlite3_step() call to terminate
  75354. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  75355. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  75356. ** the result row.
  75357. */
  75358. case OP_ResultRow: {
  75359. Mem *pMem;
  75360. int i;
  75361. assert( p->nResColumn==pOp->p2 );
  75362. assert( pOp->p1>0 );
  75363. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  75364. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  75365. /* Run the progress counter just before returning.
  75366. */
  75367. if( db->xProgress!=0
  75368. && nVmStep>=nProgressLimit
  75369. && db->xProgress(db->pProgressArg)!=0
  75370. ){
  75371. rc = SQLITE_INTERRUPT;
  75372. goto abort_due_to_error;
  75373. }
  75374. #endif
  75375. /* If this statement has violated immediate foreign key constraints, do
  75376. ** not return the number of rows modified. And do not RELEASE the statement
  75377. ** transaction. It needs to be rolled back. */
  75378. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  75379. assert( db->flags&SQLITE_CountRows );
  75380. assert( p->usesStmtJournal );
  75381. goto abort_due_to_error;
  75382. }
  75383. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  75384. ** DML statements invoke this opcode to return the number of rows
  75385. ** modified to the user. This is the only way that a VM that
  75386. ** opens a statement transaction may invoke this opcode.
  75387. **
  75388. ** In case this is such a statement, close any statement transaction
  75389. ** opened by this VM before returning control to the user. This is to
  75390. ** ensure that statement-transactions are always nested, not overlapping.
  75391. ** If the open statement-transaction is not closed here, then the user
  75392. ** may step another VM that opens its own statement transaction. This
  75393. ** may lead to overlapping statement transactions.
  75394. **
  75395. ** The statement transaction is never a top-level transaction. Hence
  75396. ** the RELEASE call below can never fail.
  75397. */
  75398. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  75399. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  75400. assert( rc==SQLITE_OK );
  75401. /* Invalidate all ephemeral cursor row caches */
  75402. p->cacheCtr = (p->cacheCtr + 2)|1;
  75403. /* Make sure the results of the current row are \000 terminated
  75404. ** and have an assigned type. The results are de-ephemeralized as
  75405. ** a side effect.
  75406. */
  75407. pMem = p->pResultSet = &aMem[pOp->p1];
  75408. for(i=0; i<pOp->p2; i++){
  75409. assert( memIsValid(&pMem[i]) );
  75410. Deephemeralize(&pMem[i]);
  75411. assert( (pMem[i].flags & MEM_Ephem)==0
  75412. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  75413. sqlite3VdbeMemNulTerminate(&pMem[i]);
  75414. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  75415. }
  75416. if( db->mallocFailed ) goto no_mem;
  75417. if( db->mTrace & SQLITE_TRACE_ROW ){
  75418. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  75419. }
  75420. /* Return SQLITE_ROW
  75421. */
  75422. p->pc = (int)(pOp - aOp) + 1;
  75423. rc = SQLITE_ROW;
  75424. goto vdbe_return;
  75425. }
  75426. /* Opcode: Concat P1 P2 P3 * *
  75427. ** Synopsis: r[P3]=r[P2]+r[P1]
  75428. **
  75429. ** Add the text in register P1 onto the end of the text in
  75430. ** register P2 and store the result in register P3.
  75431. ** If either the P1 or P2 text are NULL then store NULL in P3.
  75432. **
  75433. ** P3 = P2 || P1
  75434. **
  75435. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  75436. ** if P3 is the same register as P2, the implementation is able
  75437. ** to avoid a memcpy().
  75438. */
  75439. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  75440. i64 nByte;
  75441. pIn1 = &aMem[pOp->p1];
  75442. pIn2 = &aMem[pOp->p2];
  75443. pOut = &aMem[pOp->p3];
  75444. assert( pIn1!=pOut );
  75445. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  75446. sqlite3VdbeMemSetNull(pOut);
  75447. break;
  75448. }
  75449. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  75450. Stringify(pIn1, encoding);
  75451. Stringify(pIn2, encoding);
  75452. nByte = pIn1->n + pIn2->n;
  75453. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75454. goto too_big;
  75455. }
  75456. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  75457. goto no_mem;
  75458. }
  75459. MemSetTypeFlag(pOut, MEM_Str);
  75460. if( pOut!=pIn2 ){
  75461. memcpy(pOut->z, pIn2->z, pIn2->n);
  75462. }
  75463. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  75464. pOut->z[nByte]=0;
  75465. pOut->z[nByte+1] = 0;
  75466. pOut->flags |= MEM_Term;
  75467. pOut->n = (int)nByte;
  75468. pOut->enc = encoding;
  75469. UPDATE_MAX_BLOBSIZE(pOut);
  75470. break;
  75471. }
  75472. /* Opcode: Add P1 P2 P3 * *
  75473. ** Synopsis: r[P3]=r[P1]+r[P2]
  75474. **
  75475. ** Add the value in register P1 to the value in register P2
  75476. ** and store the result in register P3.
  75477. ** If either input is NULL, the result is NULL.
  75478. */
  75479. /* Opcode: Multiply P1 P2 P3 * *
  75480. ** Synopsis: r[P3]=r[P1]*r[P2]
  75481. **
  75482. **
  75483. ** Multiply the value in register P1 by the value in register P2
  75484. ** and store the result in register P3.
  75485. ** If either input is NULL, the result is NULL.
  75486. */
  75487. /* Opcode: Subtract P1 P2 P3 * *
  75488. ** Synopsis: r[P3]=r[P2]-r[P1]
  75489. **
  75490. ** Subtract the value in register P1 from the value in register P2
  75491. ** and store the result in register P3.
  75492. ** If either input is NULL, the result is NULL.
  75493. */
  75494. /* Opcode: Divide P1 P2 P3 * *
  75495. ** Synopsis: r[P3]=r[P2]/r[P1]
  75496. **
  75497. ** Divide the value in register P1 by the value in register P2
  75498. ** and store the result in register P3 (P3=P2/P1). If the value in
  75499. ** register P1 is zero, then the result is NULL. If either input is
  75500. ** NULL, the result is NULL.
  75501. */
  75502. /* Opcode: Remainder P1 P2 P3 * *
  75503. ** Synopsis: r[P3]=r[P2]%r[P1]
  75504. **
  75505. ** Compute the remainder after integer register P2 is divided by
  75506. ** register P1 and store the result in register P3.
  75507. ** If the value in register P1 is zero the result is NULL.
  75508. ** If either operand is NULL, the result is NULL.
  75509. */
  75510. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  75511. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  75512. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  75513. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  75514. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  75515. char bIntint; /* Started out as two integer operands */
  75516. u16 flags; /* Combined MEM_* flags from both inputs */
  75517. u16 type1; /* Numeric type of left operand */
  75518. u16 type2; /* Numeric type of right operand */
  75519. i64 iA; /* Integer value of left operand */
  75520. i64 iB; /* Integer value of right operand */
  75521. double rA; /* Real value of left operand */
  75522. double rB; /* Real value of right operand */
  75523. pIn1 = &aMem[pOp->p1];
  75524. type1 = numericType(pIn1);
  75525. pIn2 = &aMem[pOp->p2];
  75526. type2 = numericType(pIn2);
  75527. pOut = &aMem[pOp->p3];
  75528. flags = pIn1->flags | pIn2->flags;
  75529. if( (type1 & type2 & MEM_Int)!=0 ){
  75530. iA = pIn1->u.i;
  75531. iB = pIn2->u.i;
  75532. bIntint = 1;
  75533. switch( pOp->opcode ){
  75534. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  75535. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  75536. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  75537. case OP_Divide: {
  75538. if( iA==0 ) goto arithmetic_result_is_null;
  75539. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  75540. iB /= iA;
  75541. break;
  75542. }
  75543. default: {
  75544. if( iA==0 ) goto arithmetic_result_is_null;
  75545. if( iA==-1 ) iA = 1;
  75546. iB %= iA;
  75547. break;
  75548. }
  75549. }
  75550. pOut->u.i = iB;
  75551. MemSetTypeFlag(pOut, MEM_Int);
  75552. }else if( (flags & MEM_Null)!=0 ){
  75553. goto arithmetic_result_is_null;
  75554. }else{
  75555. bIntint = 0;
  75556. fp_math:
  75557. rA = sqlite3VdbeRealValue(pIn1);
  75558. rB = sqlite3VdbeRealValue(pIn2);
  75559. switch( pOp->opcode ){
  75560. case OP_Add: rB += rA; break;
  75561. case OP_Subtract: rB -= rA; break;
  75562. case OP_Multiply: rB *= rA; break;
  75563. case OP_Divide: {
  75564. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  75565. if( rA==(double)0 ) goto arithmetic_result_is_null;
  75566. rB /= rA;
  75567. break;
  75568. }
  75569. default: {
  75570. iA = (i64)rA;
  75571. iB = (i64)rB;
  75572. if( iA==0 ) goto arithmetic_result_is_null;
  75573. if( iA==-1 ) iA = 1;
  75574. rB = (double)(iB % iA);
  75575. break;
  75576. }
  75577. }
  75578. #ifdef SQLITE_OMIT_FLOATING_POINT
  75579. pOut->u.i = rB;
  75580. MemSetTypeFlag(pOut, MEM_Int);
  75581. #else
  75582. if( sqlite3IsNaN(rB) ){
  75583. goto arithmetic_result_is_null;
  75584. }
  75585. pOut->u.r = rB;
  75586. MemSetTypeFlag(pOut, MEM_Real);
  75587. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  75588. sqlite3VdbeIntegerAffinity(pOut);
  75589. }
  75590. #endif
  75591. }
  75592. break;
  75593. arithmetic_result_is_null:
  75594. sqlite3VdbeMemSetNull(pOut);
  75595. break;
  75596. }
  75597. /* Opcode: CollSeq P1 * * P4
  75598. **
  75599. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  75600. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  75601. ** be returned. This is used by the built-in min(), max() and nullif()
  75602. ** functions.
  75603. **
  75604. ** If P1 is not zero, then it is a register that a subsequent min() or
  75605. ** max() aggregate will set to 1 if the current row is not the minimum or
  75606. ** maximum. The P1 register is initialized to 0 by this instruction.
  75607. **
  75608. ** The interface used by the implementation of the aforementioned functions
  75609. ** to retrieve the collation sequence set by this opcode is not available
  75610. ** publicly. Only built-in functions have access to this feature.
  75611. */
  75612. case OP_CollSeq: {
  75613. assert( pOp->p4type==P4_COLLSEQ );
  75614. if( pOp->p1 ){
  75615. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  75616. }
  75617. break;
  75618. }
  75619. /* Opcode: BitAnd P1 P2 P3 * *
  75620. ** Synopsis: r[P3]=r[P1]&r[P2]
  75621. **
  75622. ** Take the bit-wise AND of the values in register P1 and P2 and
  75623. ** store the result in register P3.
  75624. ** If either input is NULL, the result is NULL.
  75625. */
  75626. /* Opcode: BitOr P1 P2 P3 * *
  75627. ** Synopsis: r[P3]=r[P1]|r[P2]
  75628. **
  75629. ** Take the bit-wise OR of the values in register P1 and P2 and
  75630. ** store the result in register P3.
  75631. ** If either input is NULL, the result is NULL.
  75632. */
  75633. /* Opcode: ShiftLeft P1 P2 P3 * *
  75634. ** Synopsis: r[P3]=r[P2]<<r[P1]
  75635. **
  75636. ** Shift the integer value in register P2 to the left by the
  75637. ** number of bits specified by the integer in register P1.
  75638. ** Store the result in register P3.
  75639. ** If either input is NULL, the result is NULL.
  75640. */
  75641. /* Opcode: ShiftRight P1 P2 P3 * *
  75642. ** Synopsis: r[P3]=r[P2]>>r[P1]
  75643. **
  75644. ** Shift the integer value in register P2 to the right by the
  75645. ** number of bits specified by the integer in register P1.
  75646. ** Store the result in register P3.
  75647. ** If either input is NULL, the result is NULL.
  75648. */
  75649. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  75650. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  75651. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  75652. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  75653. i64 iA;
  75654. u64 uA;
  75655. i64 iB;
  75656. u8 op;
  75657. pIn1 = &aMem[pOp->p1];
  75658. pIn2 = &aMem[pOp->p2];
  75659. pOut = &aMem[pOp->p3];
  75660. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  75661. sqlite3VdbeMemSetNull(pOut);
  75662. break;
  75663. }
  75664. iA = sqlite3VdbeIntValue(pIn2);
  75665. iB = sqlite3VdbeIntValue(pIn1);
  75666. op = pOp->opcode;
  75667. if( op==OP_BitAnd ){
  75668. iA &= iB;
  75669. }else if( op==OP_BitOr ){
  75670. iA |= iB;
  75671. }else if( iB!=0 ){
  75672. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  75673. /* If shifting by a negative amount, shift in the other direction */
  75674. if( iB<0 ){
  75675. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  75676. op = 2*OP_ShiftLeft + 1 - op;
  75677. iB = iB>(-64) ? -iB : 64;
  75678. }
  75679. if( iB>=64 ){
  75680. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  75681. }else{
  75682. memcpy(&uA, &iA, sizeof(uA));
  75683. if( op==OP_ShiftLeft ){
  75684. uA <<= iB;
  75685. }else{
  75686. uA >>= iB;
  75687. /* Sign-extend on a right shift of a negative number */
  75688. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  75689. }
  75690. memcpy(&iA, &uA, sizeof(iA));
  75691. }
  75692. }
  75693. pOut->u.i = iA;
  75694. MemSetTypeFlag(pOut, MEM_Int);
  75695. break;
  75696. }
  75697. /* Opcode: AddImm P1 P2 * * *
  75698. ** Synopsis: r[P1]=r[P1]+P2
  75699. **
  75700. ** Add the constant P2 to the value in register P1.
  75701. ** The result is always an integer.
  75702. **
  75703. ** To force any register to be an integer, just add 0.
  75704. */
  75705. case OP_AddImm: { /* in1 */
  75706. pIn1 = &aMem[pOp->p1];
  75707. memAboutToChange(p, pIn1);
  75708. sqlite3VdbeMemIntegerify(pIn1);
  75709. pIn1->u.i += pOp->p2;
  75710. break;
  75711. }
  75712. /* Opcode: MustBeInt P1 P2 * * *
  75713. **
  75714. ** Force the value in register P1 to be an integer. If the value
  75715. ** in P1 is not an integer and cannot be converted into an integer
  75716. ** without data loss, then jump immediately to P2, or if P2==0
  75717. ** raise an SQLITE_MISMATCH exception.
  75718. */
  75719. case OP_MustBeInt: { /* jump, in1 */
  75720. pIn1 = &aMem[pOp->p1];
  75721. if( (pIn1->flags & MEM_Int)==0 ){
  75722. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  75723. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  75724. if( (pIn1->flags & MEM_Int)==0 ){
  75725. if( pOp->p2==0 ){
  75726. rc = SQLITE_MISMATCH;
  75727. goto abort_due_to_error;
  75728. }else{
  75729. goto jump_to_p2;
  75730. }
  75731. }
  75732. }
  75733. MemSetTypeFlag(pIn1, MEM_Int);
  75734. break;
  75735. }
  75736. #ifndef SQLITE_OMIT_FLOATING_POINT
  75737. /* Opcode: RealAffinity P1 * * * *
  75738. **
  75739. ** If register P1 holds an integer convert it to a real value.
  75740. **
  75741. ** This opcode is used when extracting information from a column that
  75742. ** has REAL affinity. Such column values may still be stored as
  75743. ** integers, for space efficiency, but after extraction we want them
  75744. ** to have only a real value.
  75745. */
  75746. case OP_RealAffinity: { /* in1 */
  75747. pIn1 = &aMem[pOp->p1];
  75748. if( pIn1->flags & MEM_Int ){
  75749. sqlite3VdbeMemRealify(pIn1);
  75750. }
  75751. break;
  75752. }
  75753. #endif
  75754. #ifndef SQLITE_OMIT_CAST
  75755. /* Opcode: Cast P1 P2 * * *
  75756. ** Synopsis: affinity(r[P1])
  75757. **
  75758. ** Force the value in register P1 to be the type defined by P2.
  75759. **
  75760. ** <ul>
  75761. ** <li> P2=='A' &rarr; BLOB
  75762. ** <li> P2=='B' &rarr; TEXT
  75763. ** <li> P2=='C' &rarr; NUMERIC
  75764. ** <li> P2=='D' &rarr; INTEGER
  75765. ** <li> P2=='E' &rarr; REAL
  75766. ** </ul>
  75767. **
  75768. ** A NULL value is not changed by this routine. It remains NULL.
  75769. */
  75770. case OP_Cast: { /* in1 */
  75771. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  75772. testcase( pOp->p2==SQLITE_AFF_TEXT );
  75773. testcase( pOp->p2==SQLITE_AFF_BLOB );
  75774. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  75775. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  75776. testcase( pOp->p2==SQLITE_AFF_REAL );
  75777. pIn1 = &aMem[pOp->p1];
  75778. memAboutToChange(p, pIn1);
  75779. rc = ExpandBlob(pIn1);
  75780. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  75781. UPDATE_MAX_BLOBSIZE(pIn1);
  75782. if( rc ) goto abort_due_to_error;
  75783. break;
  75784. }
  75785. #endif /* SQLITE_OMIT_CAST */
  75786. /* Opcode: Eq P1 P2 P3 P4 P5
  75787. ** Synopsis: IF r[P3]==r[P1]
  75788. **
  75789. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  75790. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  75791. ** store the result of comparison in register P2.
  75792. **
  75793. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75794. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75795. ** to coerce both inputs according to this affinity before the
  75796. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75797. ** affinity is used. Note that the affinity conversions are stored
  75798. ** back into the input registers P1 and P3. So this opcode can cause
  75799. ** persistent changes to registers P1 and P3.
  75800. **
  75801. ** Once any conversions have taken place, and neither value is NULL,
  75802. ** the values are compared. If both values are blobs then memcmp() is
  75803. ** used to determine the results of the comparison. If both values
  75804. ** are text, then the appropriate collating function specified in
  75805. ** P4 is used to do the comparison. If P4 is not specified then
  75806. ** memcmp() is used to compare text string. If both values are
  75807. ** numeric, then a numeric comparison is used. If the two values
  75808. ** are of different types, then numbers are considered less than
  75809. ** strings and strings are considered less than blobs.
  75810. **
  75811. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  75812. ** true or false and is never NULL. If both operands are NULL then the result
  75813. ** of comparison is true. If either operand is NULL then the result is false.
  75814. ** If neither operand is NULL the result is the same as it would be if
  75815. ** the SQLITE_NULLEQ flag were omitted from P5.
  75816. **
  75817. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75818. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  75819. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  75820. */
  75821. /* Opcode: Ne P1 P2 P3 P4 P5
  75822. ** Synopsis: IF r[P3]!=r[P1]
  75823. **
  75824. ** This works just like the Eq opcode except that the jump is taken if
  75825. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  75826. ** additional information.
  75827. **
  75828. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75829. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  75830. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  75831. */
  75832. /* Opcode: Lt P1 P2 P3 P4 P5
  75833. ** Synopsis: IF r[P3]<r[P1]
  75834. **
  75835. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  75836. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  75837. ** the result of comparison (0 or 1 or NULL) into register P2.
  75838. **
  75839. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  75840. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  75841. ** bit is clear then fall through if either operand is NULL.
  75842. **
  75843. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75844. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75845. ** to coerce both inputs according to this affinity before the
  75846. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75847. ** affinity is used. Note that the affinity conversions are stored
  75848. ** back into the input registers P1 and P3. So this opcode can cause
  75849. ** persistent changes to registers P1 and P3.
  75850. **
  75851. ** Once any conversions have taken place, and neither value is NULL,
  75852. ** the values are compared. If both values are blobs then memcmp() is
  75853. ** used to determine the results of the comparison. If both values
  75854. ** are text, then the appropriate collating function specified in
  75855. ** P4 is used to do the comparison. If P4 is not specified then
  75856. ** memcmp() is used to compare text string. If both values are
  75857. ** numeric, then a numeric comparison is used. If the two values
  75858. ** are of different types, then numbers are considered less than
  75859. ** strings and strings are considered less than blobs.
  75860. */
  75861. /* Opcode: Le P1 P2 P3 P4 P5
  75862. ** Synopsis: IF r[P3]<=r[P1]
  75863. **
  75864. ** This works just like the Lt opcode except that the jump is taken if
  75865. ** the content of register P3 is less than or equal to the content of
  75866. ** register P1. See the Lt opcode for additional information.
  75867. */
  75868. /* Opcode: Gt P1 P2 P3 P4 P5
  75869. ** Synopsis: IF r[P3]>r[P1]
  75870. **
  75871. ** This works just like the Lt opcode except that the jump is taken if
  75872. ** the content of register P3 is greater than the content of
  75873. ** register P1. See the Lt opcode for additional information.
  75874. */
  75875. /* Opcode: Ge P1 P2 P3 P4 P5
  75876. ** Synopsis: IF r[P3]>=r[P1]
  75877. **
  75878. ** This works just like the Lt opcode except that the jump is taken if
  75879. ** the content of register P3 is greater than or equal to the content of
  75880. ** register P1. See the Lt opcode for additional information.
  75881. */
  75882. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  75883. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  75884. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  75885. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  75886. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  75887. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  75888. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  75889. char affinity; /* Affinity to use for comparison */
  75890. u16 flags1; /* Copy of initial value of pIn1->flags */
  75891. u16 flags3; /* Copy of initial value of pIn3->flags */
  75892. pIn1 = &aMem[pOp->p1];
  75893. pIn3 = &aMem[pOp->p3];
  75894. flags1 = pIn1->flags;
  75895. flags3 = pIn3->flags;
  75896. if( (flags1 | flags3)&MEM_Null ){
  75897. /* One or both operands are NULL */
  75898. if( pOp->p5 & SQLITE_NULLEQ ){
  75899. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  75900. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  75901. ** or not both operands are null.
  75902. */
  75903. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  75904. assert( (flags1 & MEM_Cleared)==0 );
  75905. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  75906. if( (flags1&flags3&MEM_Null)!=0
  75907. && (flags3&MEM_Cleared)==0
  75908. ){
  75909. res = 0; /* Operands are equal */
  75910. }else{
  75911. res = 1; /* Operands are not equal */
  75912. }
  75913. }else{
  75914. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  75915. ** then the result is always NULL.
  75916. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  75917. */
  75918. if( pOp->p5 & SQLITE_STOREP2 ){
  75919. pOut = &aMem[pOp->p2];
  75920. iCompare = 1; /* Operands are not equal */
  75921. memAboutToChange(p, pOut);
  75922. MemSetTypeFlag(pOut, MEM_Null);
  75923. REGISTER_TRACE(pOp->p2, pOut);
  75924. }else{
  75925. VdbeBranchTaken(2,3);
  75926. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  75927. goto jump_to_p2;
  75928. }
  75929. }
  75930. break;
  75931. }
  75932. }else{
  75933. /* Neither operand is NULL. Do a comparison. */
  75934. affinity = pOp->p5 & SQLITE_AFF_MASK;
  75935. if( affinity>=SQLITE_AFF_NUMERIC ){
  75936. if( (flags1 | flags3)&MEM_Str ){
  75937. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75938. applyNumericAffinity(pIn1,0);
  75939. testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
  75940. flags3 = pIn3->flags;
  75941. }
  75942. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75943. applyNumericAffinity(pIn3,0);
  75944. }
  75945. }
  75946. /* Handle the common case of integer comparison here, as an
  75947. ** optimization, to avoid a call to sqlite3MemCompare() */
  75948. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  75949. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  75950. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  75951. res = 0;
  75952. goto compare_op;
  75953. }
  75954. }else if( affinity==SQLITE_AFF_TEXT ){
  75955. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  75956. testcase( pIn1->flags & MEM_Int );
  75957. testcase( pIn1->flags & MEM_Real );
  75958. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  75959. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  75960. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  75961. assert( pIn1!=pIn3 );
  75962. }
  75963. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  75964. testcase( pIn3->flags & MEM_Int );
  75965. testcase( pIn3->flags & MEM_Real );
  75966. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  75967. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  75968. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  75969. }
  75970. }
  75971. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  75972. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  75973. }
  75974. compare_op:
  75975. /* At this point, res is negative, zero, or positive if reg[P1] is
  75976. ** less than, equal to, or greater than reg[P3], respectively. Compute
  75977. ** the answer to this operator in res2, depending on what the comparison
  75978. ** operator actually is. The next block of code depends on the fact
  75979. ** that the 6 comparison operators are consecutive integers in this
  75980. ** order: NE, EQ, GT, LE, LT, GE */
  75981. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  75982. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  75983. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  75984. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  75985. res2 = aLTb[pOp->opcode - OP_Ne];
  75986. }else if( res==0 ){
  75987. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  75988. res2 = aEQb[pOp->opcode - OP_Ne];
  75989. }else{
  75990. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  75991. res2 = aGTb[pOp->opcode - OP_Ne];
  75992. }
  75993. /* Undo any changes made by applyAffinity() to the input registers. */
  75994. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  75995. pIn1->flags = flags1;
  75996. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  75997. pIn3->flags = flags3;
  75998. if( pOp->p5 & SQLITE_STOREP2 ){
  75999. pOut = &aMem[pOp->p2];
  76000. iCompare = res;
  76001. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  76002. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  76003. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  76004. ** is only used in contexts where either:
  76005. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  76006. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  76007. ** Therefore it is not necessary to check the content of r[P2] for
  76008. ** NULL. */
  76009. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  76010. assert( res2==0 || res2==1 );
  76011. testcase( res2==0 && pOp->opcode==OP_Eq );
  76012. testcase( res2==1 && pOp->opcode==OP_Eq );
  76013. testcase( res2==0 && pOp->opcode==OP_Ne );
  76014. testcase( res2==1 && pOp->opcode==OP_Ne );
  76015. if( (pOp->opcode==OP_Eq)==res2 ) break;
  76016. }
  76017. memAboutToChange(p, pOut);
  76018. MemSetTypeFlag(pOut, MEM_Int);
  76019. pOut->u.i = res2;
  76020. REGISTER_TRACE(pOp->p2, pOut);
  76021. }else{
  76022. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  76023. if( res2 ){
  76024. goto jump_to_p2;
  76025. }
  76026. }
  76027. break;
  76028. }
  76029. /* Opcode: ElseNotEq * P2 * * *
  76030. **
  76031. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  76032. ** If result of an OP_Eq comparison on the same two operands
  76033. ** would have be NULL or false (0), then then jump to P2.
  76034. ** If the result of an OP_Eq comparison on the two previous operands
  76035. ** would have been true (1), then fall through.
  76036. */
  76037. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  76038. assert( pOp>aOp );
  76039. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  76040. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  76041. VdbeBranchTaken(iCompare!=0, 2);
  76042. if( iCompare!=0 ) goto jump_to_p2;
  76043. break;
  76044. }
  76045. /* Opcode: Permutation * * * P4 *
  76046. **
  76047. ** Set the permutation used by the OP_Compare operator in the next
  76048. ** instruction. The permutation is stored in the P4 operand.
  76049. **
  76050. ** The permutation is only valid until the next OP_Compare that has
  76051. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  76052. ** occur immediately prior to the OP_Compare.
  76053. **
  76054. ** The first integer in the P4 integer array is the length of the array
  76055. ** and does not become part of the permutation.
  76056. */
  76057. case OP_Permutation: {
  76058. assert( pOp->p4type==P4_INTARRAY );
  76059. assert( pOp->p4.ai );
  76060. assert( pOp[1].opcode==OP_Compare );
  76061. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  76062. break;
  76063. }
  76064. /* Opcode: Compare P1 P2 P3 P4 P5
  76065. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  76066. **
  76067. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  76068. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  76069. ** the comparison for use by the next OP_Jump instruct.
  76070. **
  76071. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  76072. ** determined by the most recent OP_Permutation operator. If the
  76073. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  76074. ** order.
  76075. **
  76076. ** P4 is a KeyInfo structure that defines collating sequences and sort
  76077. ** orders for the comparison. The permutation applies to registers
  76078. ** only. The KeyInfo elements are used sequentially.
  76079. **
  76080. ** The comparison is a sort comparison, so NULLs compare equal,
  76081. ** NULLs are less than numbers, numbers are less than strings,
  76082. ** and strings are less than blobs.
  76083. */
  76084. case OP_Compare: {
  76085. int n;
  76086. int i;
  76087. int p1;
  76088. int p2;
  76089. const KeyInfo *pKeyInfo;
  76090. int idx;
  76091. CollSeq *pColl; /* Collating sequence to use on this term */
  76092. int bRev; /* True for DESCENDING sort order */
  76093. int *aPermute; /* The permutation */
  76094. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  76095. aPermute = 0;
  76096. }else{
  76097. assert( pOp>aOp );
  76098. assert( pOp[-1].opcode==OP_Permutation );
  76099. assert( pOp[-1].p4type==P4_INTARRAY );
  76100. aPermute = pOp[-1].p4.ai + 1;
  76101. assert( aPermute!=0 );
  76102. }
  76103. n = pOp->p3;
  76104. pKeyInfo = pOp->p4.pKeyInfo;
  76105. assert( n>0 );
  76106. assert( pKeyInfo!=0 );
  76107. p1 = pOp->p1;
  76108. p2 = pOp->p2;
  76109. #ifdef SQLITE_DEBUG
  76110. if( aPermute ){
  76111. int k, mx = 0;
  76112. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  76113. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  76114. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  76115. }else{
  76116. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  76117. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  76118. }
  76119. #endif /* SQLITE_DEBUG */
  76120. for(i=0; i<n; i++){
  76121. idx = aPermute ? aPermute[i] : i;
  76122. assert( memIsValid(&aMem[p1+idx]) );
  76123. assert( memIsValid(&aMem[p2+idx]) );
  76124. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  76125. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  76126. assert( i<pKeyInfo->nKeyField );
  76127. pColl = pKeyInfo->aColl[i];
  76128. bRev = pKeyInfo->aSortOrder[i];
  76129. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  76130. if( iCompare ){
  76131. if( bRev ) iCompare = -iCompare;
  76132. break;
  76133. }
  76134. }
  76135. break;
  76136. }
  76137. /* Opcode: Jump P1 P2 P3 * *
  76138. **
  76139. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  76140. ** in the most recent OP_Compare instruction the P1 vector was less than
  76141. ** equal to, or greater than the P2 vector, respectively.
  76142. */
  76143. case OP_Jump: { /* jump */
  76144. if( iCompare<0 ){
  76145. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  76146. }else if( iCompare==0 ){
  76147. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  76148. }else{
  76149. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  76150. }
  76151. break;
  76152. }
  76153. /* Opcode: And P1 P2 P3 * *
  76154. ** Synopsis: r[P3]=(r[P1] && r[P2])
  76155. **
  76156. ** Take the logical AND of the values in registers P1 and P2 and
  76157. ** write the result into register P3.
  76158. **
  76159. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  76160. ** the other input is NULL. A NULL and true or two NULLs give
  76161. ** a NULL output.
  76162. */
  76163. /* Opcode: Or P1 P2 P3 * *
  76164. ** Synopsis: r[P3]=(r[P1] || r[P2])
  76165. **
  76166. ** Take the logical OR of the values in register P1 and P2 and
  76167. ** store the answer in register P3.
  76168. **
  76169. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  76170. ** even if the other input is NULL. A NULL and false or two NULLs
  76171. ** give a NULL output.
  76172. */
  76173. case OP_And: /* same as TK_AND, in1, in2, out3 */
  76174. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  76175. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  76176. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  76177. pIn1 = &aMem[pOp->p1];
  76178. if( pIn1->flags & MEM_Null ){
  76179. v1 = 2;
  76180. }else{
  76181. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  76182. }
  76183. pIn2 = &aMem[pOp->p2];
  76184. if( pIn2->flags & MEM_Null ){
  76185. v2 = 2;
  76186. }else{
  76187. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  76188. }
  76189. if( pOp->opcode==OP_And ){
  76190. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  76191. v1 = and_logic[v1*3+v2];
  76192. }else{
  76193. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  76194. v1 = or_logic[v1*3+v2];
  76195. }
  76196. pOut = &aMem[pOp->p3];
  76197. if( v1==2 ){
  76198. MemSetTypeFlag(pOut, MEM_Null);
  76199. }else{
  76200. pOut->u.i = v1;
  76201. MemSetTypeFlag(pOut, MEM_Int);
  76202. }
  76203. break;
  76204. }
  76205. /* Opcode: Not P1 P2 * * *
  76206. ** Synopsis: r[P2]= !r[P1]
  76207. **
  76208. ** Interpret the value in register P1 as a boolean value. Store the
  76209. ** boolean complement in register P2. If the value in register P1 is
  76210. ** NULL, then a NULL is stored in P2.
  76211. */
  76212. case OP_Not: { /* same as TK_NOT, in1, out2 */
  76213. pIn1 = &aMem[pOp->p1];
  76214. pOut = &aMem[pOp->p2];
  76215. sqlite3VdbeMemSetNull(pOut);
  76216. if( (pIn1->flags & MEM_Null)==0 ){
  76217. pOut->flags = MEM_Int;
  76218. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  76219. }
  76220. break;
  76221. }
  76222. /* Opcode: BitNot P1 P2 * * *
  76223. ** Synopsis: r[P1]= ~r[P1]
  76224. **
  76225. ** Interpret the content of register P1 as an integer. Store the
  76226. ** ones-complement of the P1 value into register P2. If P1 holds
  76227. ** a NULL then store a NULL in P2.
  76228. */
  76229. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  76230. pIn1 = &aMem[pOp->p1];
  76231. pOut = &aMem[pOp->p2];
  76232. sqlite3VdbeMemSetNull(pOut);
  76233. if( (pIn1->flags & MEM_Null)==0 ){
  76234. pOut->flags = MEM_Int;
  76235. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  76236. }
  76237. break;
  76238. }
  76239. /* Opcode: Once P1 P2 * * *
  76240. **
  76241. ** Fall through to the next instruction the first time this opcode is
  76242. ** encountered on each invocation of the byte-code program. Jump to P2
  76243. ** on the second and all subsequent encounters during the same invocation.
  76244. **
  76245. ** Top-level programs determine first invocation by comparing the P1
  76246. ** operand against the P1 operand on the OP_Init opcode at the beginning
  76247. ** of the program. If the P1 values differ, then fall through and make
  76248. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  76249. ** the same then take the jump.
  76250. **
  76251. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  76252. ** whether or not the jump should be taken. The bitmask is necessary
  76253. ** because the self-altering code trick does not work for recursive
  76254. ** triggers.
  76255. */
  76256. case OP_Once: { /* jump */
  76257. u32 iAddr; /* Address of this instruction */
  76258. assert( p->aOp[0].opcode==OP_Init );
  76259. if( p->pFrame ){
  76260. iAddr = (int)(pOp - p->aOp);
  76261. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  76262. VdbeBranchTaken(1, 2);
  76263. goto jump_to_p2;
  76264. }
  76265. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  76266. }else{
  76267. if( p->aOp[0].p1==pOp->p1 ){
  76268. VdbeBranchTaken(1, 2);
  76269. goto jump_to_p2;
  76270. }
  76271. }
  76272. VdbeBranchTaken(0, 2);
  76273. pOp->p1 = p->aOp[0].p1;
  76274. break;
  76275. }
  76276. /* Opcode: If P1 P2 P3 * *
  76277. **
  76278. ** Jump to P2 if the value in register P1 is true. The value
  76279. ** is considered true if it is numeric and non-zero. If the value
  76280. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  76281. */
  76282. /* Opcode: IfNot P1 P2 P3 * *
  76283. **
  76284. ** Jump to P2 if the value in register P1 is False. The value
  76285. ** is considered false if it has a numeric value of zero. If the value
  76286. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  76287. */
  76288. case OP_If: /* jump, in1 */
  76289. case OP_IfNot: { /* jump, in1 */
  76290. int c;
  76291. pIn1 = &aMem[pOp->p1];
  76292. if( pIn1->flags & MEM_Null ){
  76293. c = pOp->p3;
  76294. }else{
  76295. #ifdef SQLITE_OMIT_FLOATING_POINT
  76296. c = sqlite3VdbeIntValue(pIn1)!=0;
  76297. #else
  76298. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  76299. #endif
  76300. if( pOp->opcode==OP_IfNot ) c = !c;
  76301. }
  76302. VdbeBranchTaken(c!=0, 2);
  76303. if( c ){
  76304. goto jump_to_p2;
  76305. }
  76306. break;
  76307. }
  76308. /* Opcode: IsNull P1 P2 * * *
  76309. ** Synopsis: if r[P1]==NULL goto P2
  76310. **
  76311. ** Jump to P2 if the value in register P1 is NULL.
  76312. */
  76313. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  76314. pIn1 = &aMem[pOp->p1];
  76315. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  76316. if( (pIn1->flags & MEM_Null)!=0 ){
  76317. goto jump_to_p2;
  76318. }
  76319. break;
  76320. }
  76321. /* Opcode: NotNull P1 P2 * * *
  76322. ** Synopsis: if r[P1]!=NULL goto P2
  76323. **
  76324. ** Jump to P2 if the value in register P1 is not NULL.
  76325. */
  76326. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  76327. pIn1 = &aMem[pOp->p1];
  76328. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  76329. if( (pIn1->flags & MEM_Null)==0 ){
  76330. goto jump_to_p2;
  76331. }
  76332. break;
  76333. }
  76334. /* Opcode: IfNullRow P1 P2 P3 * *
  76335. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  76336. **
  76337. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  76338. ** If it is, then set register P3 to NULL and jump immediately to P2.
  76339. ** If P1 is not on a NULL row, then fall through without making any
  76340. ** changes.
  76341. */
  76342. case OP_IfNullRow: { /* jump */
  76343. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76344. assert( p->apCsr[pOp->p1]!=0 );
  76345. if( p->apCsr[pOp->p1]->nullRow ){
  76346. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  76347. goto jump_to_p2;
  76348. }
  76349. break;
  76350. }
  76351. /* Opcode: Column P1 P2 P3 P4 P5
  76352. ** Synopsis: r[P3]=PX
  76353. **
  76354. ** Interpret the data that cursor P1 points to as a structure built using
  76355. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  76356. ** information about the format of the data.) Extract the P2-th column
  76357. ** from this record. If there are less that (P2+1)
  76358. ** values in the record, extract a NULL.
  76359. **
  76360. ** The value extracted is stored in register P3.
  76361. **
  76362. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  76363. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  76364. ** the result.
  76365. **
  76366. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  76367. ** then the cache of the cursor is reset prior to extracting the column.
  76368. ** The first OP_Column against a pseudo-table after the value of the content
  76369. ** register has changed should have this bit set.
  76370. **
  76371. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  76372. ** the result is guaranteed to only be used as the argument of a length()
  76373. ** or typeof() function, respectively. The loading of large blobs can be
  76374. ** skipped for length() and all content loading can be skipped for typeof().
  76375. */
  76376. case OP_Column: {
  76377. int p2; /* column number to retrieve */
  76378. VdbeCursor *pC; /* The VDBE cursor */
  76379. BtCursor *pCrsr; /* The BTree cursor */
  76380. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  76381. int len; /* The length of the serialized data for the column */
  76382. int i; /* Loop counter */
  76383. Mem *pDest; /* Where to write the extracted value */
  76384. Mem sMem; /* For storing the record being decoded */
  76385. const u8 *zData; /* Part of the record being decoded */
  76386. const u8 *zHdr; /* Next unparsed byte of the header */
  76387. const u8 *zEndHdr; /* Pointer to first byte after the header */
  76388. u64 offset64; /* 64-bit offset */
  76389. u32 t; /* A type code from the record header */
  76390. Mem *pReg; /* PseudoTable input register */
  76391. pC = p->apCsr[pOp->p1];
  76392. p2 = pOp->p2;
  76393. /* If the cursor cache is stale (meaning it is not currently point at
  76394. ** the correct row) then bring it up-to-date by doing the necessary
  76395. ** B-Tree seek. */
  76396. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  76397. if( rc ) goto abort_due_to_error;
  76398. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  76399. pDest = &aMem[pOp->p3];
  76400. memAboutToChange(p, pDest);
  76401. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76402. assert( pC!=0 );
  76403. assert( p2<pC->nField );
  76404. aOffset = pC->aOffset;
  76405. assert( pC->eCurType!=CURTYPE_VTAB );
  76406. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  76407. assert( pC->eCurType!=CURTYPE_SORTER );
  76408. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  76409. if( pC->nullRow ){
  76410. if( pC->eCurType==CURTYPE_PSEUDO ){
  76411. /* For the special case of as pseudo-cursor, the seekResult field
  76412. ** identifies the register that holds the record */
  76413. assert( pC->seekResult>0 );
  76414. pReg = &aMem[pC->seekResult];
  76415. assert( pReg->flags & MEM_Blob );
  76416. assert( memIsValid(pReg) );
  76417. pC->payloadSize = pC->szRow = pReg->n;
  76418. pC->aRow = (u8*)pReg->z;
  76419. }else{
  76420. sqlite3VdbeMemSetNull(pDest);
  76421. goto op_column_out;
  76422. }
  76423. }else{
  76424. pCrsr = pC->uc.pCursor;
  76425. assert( pC->eCurType==CURTYPE_BTREE );
  76426. assert( pCrsr );
  76427. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  76428. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  76429. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  76430. assert( pC->szRow<=pC->payloadSize );
  76431. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  76432. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76433. goto too_big;
  76434. }
  76435. }
  76436. pC->cacheStatus = p->cacheCtr;
  76437. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  76438. pC->nHdrParsed = 0;
  76439. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  76440. /* pC->aRow does not have to hold the entire row, but it does at least
  76441. ** need to cover the header of the record. If pC->aRow does not contain
  76442. ** the complete header, then set it to zero, forcing the header to be
  76443. ** dynamically allocated. */
  76444. pC->aRow = 0;
  76445. pC->szRow = 0;
  76446. /* Make sure a corrupt database has not given us an oversize header.
  76447. ** Do this now to avoid an oversize memory allocation.
  76448. **
  76449. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  76450. ** types use so much data space that there can only be 4096 and 32 of
  76451. ** them, respectively. So the maximum header length results from a
  76452. ** 3-byte type for each of the maximum of 32768 columns plus three
  76453. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  76454. */
  76455. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  76456. goto op_column_corrupt;
  76457. }
  76458. }else{
  76459. /* This is an optimization. By skipping over the first few tests
  76460. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  76461. ** measurable performance gain.
  76462. **
  76463. ** This branch is taken even if aOffset[0]==0. Such a record is never
  76464. ** generated by SQLite, and could be considered corruption, but we
  76465. ** accept it for historical reasons. When aOffset[0]==0, the code this
  76466. ** branch jumps to reads past the end of the record, but never more
  76467. ** than a few bytes. Even if the record occurs at the end of the page
  76468. ** content area, the "page header" comes after the page content and so
  76469. ** this overread is harmless. Similar overreads can occur for a corrupt
  76470. ** database file.
  76471. */
  76472. zData = pC->aRow;
  76473. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  76474. testcase( aOffset[0]==0 );
  76475. goto op_column_read_header;
  76476. }
  76477. }
  76478. /* Make sure at least the first p2+1 entries of the header have been
  76479. ** parsed and valid information is in aOffset[] and pC->aType[].
  76480. */
  76481. if( pC->nHdrParsed<=p2 ){
  76482. /* If there is more header available for parsing in the record, try
  76483. ** to extract additional fields up through the p2+1-th field
  76484. */
  76485. if( pC->iHdrOffset<aOffset[0] ){
  76486. /* Make sure zData points to enough of the record to cover the header. */
  76487. if( pC->aRow==0 ){
  76488. memset(&sMem, 0, sizeof(sMem));
  76489. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  76490. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76491. zData = (u8*)sMem.z;
  76492. }else{
  76493. zData = pC->aRow;
  76494. }
  76495. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  76496. op_column_read_header:
  76497. i = pC->nHdrParsed;
  76498. offset64 = aOffset[i];
  76499. zHdr = zData + pC->iHdrOffset;
  76500. zEndHdr = zData + aOffset[0];
  76501. testcase( zHdr>=zEndHdr );
  76502. do{
  76503. if( (t = zHdr[0])<0x80 ){
  76504. zHdr++;
  76505. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  76506. }else{
  76507. zHdr += sqlite3GetVarint32(zHdr, &t);
  76508. offset64 += sqlite3VdbeSerialTypeLen(t);
  76509. }
  76510. pC->aType[i++] = t;
  76511. aOffset[i] = (u32)(offset64 & 0xffffffff);
  76512. }while( i<=p2 && zHdr<zEndHdr );
  76513. /* The record is corrupt if any of the following are true:
  76514. ** (1) the bytes of the header extend past the declared header size
  76515. ** (2) the entire header was used but not all data was used
  76516. ** (3) the end of the data extends beyond the end of the record.
  76517. */
  76518. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  76519. || (offset64 > pC->payloadSize)
  76520. ){
  76521. if( aOffset[0]==0 ){
  76522. i = 0;
  76523. zHdr = zEndHdr;
  76524. }else{
  76525. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  76526. goto op_column_corrupt;
  76527. }
  76528. }
  76529. pC->nHdrParsed = i;
  76530. pC->iHdrOffset = (u32)(zHdr - zData);
  76531. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  76532. }else{
  76533. t = 0;
  76534. }
  76535. /* If after trying to extract new entries from the header, nHdrParsed is
  76536. ** still not up to p2, that means that the record has fewer than p2
  76537. ** columns. So the result will be either the default value or a NULL.
  76538. */
  76539. if( pC->nHdrParsed<=p2 ){
  76540. if( pOp->p4type==P4_MEM ){
  76541. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  76542. }else{
  76543. sqlite3VdbeMemSetNull(pDest);
  76544. }
  76545. goto op_column_out;
  76546. }
  76547. }else{
  76548. t = pC->aType[p2];
  76549. }
  76550. /* Extract the content for the p2+1-th column. Control can only
  76551. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  76552. ** all valid.
  76553. */
  76554. assert( p2<pC->nHdrParsed );
  76555. assert( rc==SQLITE_OK );
  76556. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  76557. if( VdbeMemDynamic(pDest) ){
  76558. sqlite3VdbeMemSetNull(pDest);
  76559. }
  76560. assert( t==pC->aType[p2] );
  76561. if( pC->szRow>=aOffset[p2+1] ){
  76562. /* This is the common case where the desired content fits on the original
  76563. ** page - where the content is not on an overflow page */
  76564. zData = pC->aRow + aOffset[p2];
  76565. if( t<12 ){
  76566. sqlite3VdbeSerialGet(zData, t, pDest);
  76567. }else{
  76568. /* If the column value is a string, we need a persistent value, not
  76569. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  76570. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  76571. */
  76572. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  76573. pDest->n = len = (t-12)/2;
  76574. pDest->enc = encoding;
  76575. if( pDest->szMalloc < len+2 ){
  76576. pDest->flags = MEM_Null;
  76577. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  76578. }else{
  76579. pDest->z = pDest->zMalloc;
  76580. }
  76581. memcpy(pDest->z, zData, len);
  76582. pDest->z[len] = 0;
  76583. pDest->z[len+1] = 0;
  76584. pDest->flags = aFlag[t&1];
  76585. }
  76586. }else{
  76587. pDest->enc = encoding;
  76588. /* This branch happens only when content is on overflow pages */
  76589. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  76590. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  76591. || (len = sqlite3VdbeSerialTypeLen(t))==0
  76592. ){
  76593. /* Content is irrelevant for
  76594. ** 1. the typeof() function,
  76595. ** 2. the length(X) function if X is a blob, and
  76596. ** 3. if the content length is zero.
  76597. ** So we might as well use bogus content rather than reading
  76598. ** content from disk.
  76599. **
  76600. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  76601. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  76602. ** read up to 16. So 16 bytes of bogus content is supplied.
  76603. */
  76604. static u8 aZero[16]; /* This is the bogus content */
  76605. sqlite3VdbeSerialGet(aZero, t, pDest);
  76606. }else{
  76607. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  76608. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76609. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  76610. pDest->flags &= ~MEM_Ephem;
  76611. }
  76612. }
  76613. op_column_out:
  76614. UPDATE_MAX_BLOBSIZE(pDest);
  76615. REGISTER_TRACE(pOp->p3, pDest);
  76616. break;
  76617. op_column_corrupt:
  76618. if( aOp[0].p3>0 ){
  76619. pOp = &aOp[aOp[0].p3-1];
  76620. break;
  76621. }else{
  76622. rc = SQLITE_CORRUPT_BKPT;
  76623. goto abort_due_to_error;
  76624. }
  76625. }
  76626. /* Opcode: Affinity P1 P2 * P4 *
  76627. ** Synopsis: affinity(r[P1@P2])
  76628. **
  76629. ** Apply affinities to a range of P2 registers starting with P1.
  76630. **
  76631. ** P4 is a string that is P2 characters long. The N-th character of the
  76632. ** string indicates the column affinity that should be used for the N-th
  76633. ** memory cell in the range.
  76634. */
  76635. case OP_Affinity: {
  76636. const char *zAffinity; /* The affinity to be applied */
  76637. zAffinity = pOp->p4.z;
  76638. assert( zAffinity!=0 );
  76639. assert( pOp->p2>0 );
  76640. assert( zAffinity[pOp->p2]==0 );
  76641. pIn1 = &aMem[pOp->p1];
  76642. do{
  76643. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  76644. assert( memIsValid(pIn1) );
  76645. applyAffinity(pIn1, *(zAffinity++), encoding);
  76646. pIn1++;
  76647. }while( zAffinity[0] );
  76648. break;
  76649. }
  76650. /* Opcode: MakeRecord P1 P2 P3 P4 *
  76651. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  76652. **
  76653. ** Convert P2 registers beginning with P1 into the [record format]
  76654. ** use as a data record in a database table or as a key
  76655. ** in an index. The OP_Column opcode can decode the record later.
  76656. **
  76657. ** P4 may be a string that is P2 characters long. The N-th character of the
  76658. ** string indicates the column affinity that should be used for the N-th
  76659. ** field of the index key.
  76660. **
  76661. ** The mapping from character to affinity is given by the SQLITE_AFF_
  76662. ** macros defined in sqliteInt.h.
  76663. **
  76664. ** If P4 is NULL then all index fields have the affinity BLOB.
  76665. */
  76666. case OP_MakeRecord: {
  76667. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  76668. Mem *pRec; /* The new record */
  76669. u64 nData; /* Number of bytes of data space */
  76670. int nHdr; /* Number of bytes of header space */
  76671. i64 nByte; /* Data space required for this record */
  76672. i64 nZero; /* Number of zero bytes at the end of the record */
  76673. int nVarint; /* Number of bytes in a varint */
  76674. u32 serial_type; /* Type field */
  76675. Mem *pData0; /* First field to be combined into the record */
  76676. Mem *pLast; /* Last field of the record */
  76677. int nField; /* Number of fields in the record */
  76678. char *zAffinity; /* The affinity string for the record */
  76679. int file_format; /* File format to use for encoding */
  76680. int i; /* Space used in zNewRecord[] header */
  76681. int j; /* Space used in zNewRecord[] content */
  76682. u32 len; /* Length of a field */
  76683. /* Assuming the record contains N fields, the record format looks
  76684. ** like this:
  76685. **
  76686. ** ------------------------------------------------------------------------
  76687. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  76688. ** ------------------------------------------------------------------------
  76689. **
  76690. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  76691. ** and so forth.
  76692. **
  76693. ** Each type field is a varint representing the serial type of the
  76694. ** corresponding data element (see sqlite3VdbeSerialType()). The
  76695. ** hdr-size field is also a varint which is the offset from the beginning
  76696. ** of the record to data0.
  76697. */
  76698. nData = 0; /* Number of bytes of data space */
  76699. nHdr = 0; /* Number of bytes of header space */
  76700. nZero = 0; /* Number of zero bytes at the end of the record */
  76701. nField = pOp->p1;
  76702. zAffinity = pOp->p4.z;
  76703. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  76704. pData0 = &aMem[nField];
  76705. nField = pOp->p2;
  76706. pLast = &pData0[nField-1];
  76707. file_format = p->minWriteFileFormat;
  76708. /* Identify the output register */
  76709. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  76710. pOut = &aMem[pOp->p3];
  76711. memAboutToChange(p, pOut);
  76712. /* Apply the requested affinity to all inputs
  76713. */
  76714. assert( pData0<=pLast );
  76715. if( zAffinity ){
  76716. pRec = pData0;
  76717. do{
  76718. applyAffinity(pRec++, *(zAffinity++), encoding);
  76719. assert( zAffinity[0]==0 || pRec<=pLast );
  76720. }while( zAffinity[0] );
  76721. }
  76722. #ifdef SQLITE_ENABLE_NULL_TRIM
  76723. /* NULLs can be safely trimmed from the end of the record, as long as
  76724. ** as the schema format is 2 or more and none of the omitted columns
  76725. ** have a non-NULL default value. Also, the record must be left with
  76726. ** at least one field. If P5>0 then it will be one more than the
  76727. ** index of the right-most column with a non-NULL default value */
  76728. if( pOp->p5 ){
  76729. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  76730. pLast--;
  76731. nField--;
  76732. }
  76733. }
  76734. #endif
  76735. /* Loop through the elements that will make up the record to figure
  76736. ** out how much space is required for the new record.
  76737. */
  76738. pRec = pLast;
  76739. do{
  76740. assert( memIsValid(pRec) );
  76741. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  76742. if( pRec->flags & MEM_Zero ){
  76743. if( nData ){
  76744. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  76745. }else{
  76746. nZero += pRec->u.nZero;
  76747. len -= pRec->u.nZero;
  76748. }
  76749. }
  76750. nData += len;
  76751. testcase( serial_type==127 );
  76752. testcase( serial_type==128 );
  76753. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  76754. if( pRec==pData0 ) break;
  76755. pRec--;
  76756. }while(1);
  76757. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  76758. ** which determines the total number of bytes in the header. The varint
  76759. ** value is the size of the header in bytes including the size varint
  76760. ** itself. */
  76761. testcase( nHdr==126 );
  76762. testcase( nHdr==127 );
  76763. if( nHdr<=126 ){
  76764. /* The common case */
  76765. nHdr += 1;
  76766. }else{
  76767. /* Rare case of a really large header */
  76768. nVarint = sqlite3VarintLen(nHdr);
  76769. nHdr += nVarint;
  76770. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  76771. }
  76772. nByte = nHdr+nData;
  76773. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76774. goto too_big;
  76775. }
  76776. /* Make sure the output register has a buffer large enough to store
  76777. ** the new record. The output register (pOp->p3) is not allowed to
  76778. ** be one of the input registers (because the following call to
  76779. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  76780. */
  76781. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  76782. goto no_mem;
  76783. }
  76784. zNewRecord = (u8 *)pOut->z;
  76785. /* Write the record */
  76786. i = putVarint32(zNewRecord, nHdr);
  76787. j = nHdr;
  76788. assert( pData0<=pLast );
  76789. pRec = pData0;
  76790. do{
  76791. serial_type = pRec->uTemp;
  76792. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  76793. ** additional varints, one per column. */
  76794. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  76795. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  76796. ** immediately follow the header. */
  76797. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  76798. }while( (++pRec)<=pLast );
  76799. assert( i==nHdr );
  76800. assert( j==nByte );
  76801. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  76802. pOut->n = (int)nByte;
  76803. pOut->flags = MEM_Blob;
  76804. if( nZero ){
  76805. pOut->u.nZero = nZero;
  76806. pOut->flags |= MEM_Zero;
  76807. }
  76808. REGISTER_TRACE(pOp->p3, pOut);
  76809. UPDATE_MAX_BLOBSIZE(pOut);
  76810. break;
  76811. }
  76812. /* Opcode: Count P1 P2 * * *
  76813. ** Synopsis: r[P2]=count()
  76814. **
  76815. ** Store the number of entries (an integer value) in the table or index
  76816. ** opened by cursor P1 in register P2
  76817. */
  76818. #ifndef SQLITE_OMIT_BTREECOUNT
  76819. case OP_Count: { /* out2 */
  76820. i64 nEntry;
  76821. BtCursor *pCrsr;
  76822. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  76823. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  76824. assert( pCrsr );
  76825. nEntry = 0; /* Not needed. Only used to silence a warning. */
  76826. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  76827. if( rc ) goto abort_due_to_error;
  76828. pOut = out2Prerelease(p, pOp);
  76829. pOut->u.i = nEntry;
  76830. break;
  76831. }
  76832. #endif
  76833. /* Opcode: Savepoint P1 * * P4 *
  76834. **
  76835. ** Open, release or rollback the savepoint named by parameter P4, depending
  76836. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  76837. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  76838. */
  76839. case OP_Savepoint: {
  76840. int p1; /* Value of P1 operand */
  76841. char *zName; /* Name of savepoint */
  76842. int nName;
  76843. Savepoint *pNew;
  76844. Savepoint *pSavepoint;
  76845. Savepoint *pTmp;
  76846. int iSavepoint;
  76847. int ii;
  76848. p1 = pOp->p1;
  76849. zName = pOp->p4.z;
  76850. /* Assert that the p1 parameter is valid. Also that if there is no open
  76851. ** transaction, then there cannot be any savepoints.
  76852. */
  76853. assert( db->pSavepoint==0 || db->autoCommit==0 );
  76854. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  76855. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  76856. assert( checkSavepointCount(db) );
  76857. assert( p->bIsReader );
  76858. if( p1==SAVEPOINT_BEGIN ){
  76859. if( db->nVdbeWrite>0 ){
  76860. /* A new savepoint cannot be created if there are active write
  76861. ** statements (i.e. open read/write incremental blob handles).
  76862. */
  76863. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  76864. rc = SQLITE_BUSY;
  76865. }else{
  76866. nName = sqlite3Strlen30(zName);
  76867. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76868. /* This call is Ok even if this savepoint is actually a transaction
  76869. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  76870. ** If this is a transaction savepoint being opened, it is guaranteed
  76871. ** that the db->aVTrans[] array is empty. */
  76872. assert( db->autoCommit==0 || db->nVTrans==0 );
  76873. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  76874. db->nStatement+db->nSavepoint);
  76875. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76876. #endif
  76877. /* Create a new savepoint structure. */
  76878. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  76879. if( pNew ){
  76880. pNew->zName = (char *)&pNew[1];
  76881. memcpy(pNew->zName, zName, nName+1);
  76882. /* If there is no open transaction, then mark this as a special
  76883. ** "transaction savepoint". */
  76884. if( db->autoCommit ){
  76885. db->autoCommit = 0;
  76886. db->isTransactionSavepoint = 1;
  76887. }else{
  76888. db->nSavepoint++;
  76889. }
  76890. /* Link the new savepoint into the database handle's list. */
  76891. pNew->pNext = db->pSavepoint;
  76892. db->pSavepoint = pNew;
  76893. pNew->nDeferredCons = db->nDeferredCons;
  76894. pNew->nDeferredImmCons = db->nDeferredImmCons;
  76895. }
  76896. }
  76897. }else{
  76898. iSavepoint = 0;
  76899. /* Find the named savepoint. If there is no such savepoint, then an
  76900. ** an error is returned to the user. */
  76901. for(
  76902. pSavepoint = db->pSavepoint;
  76903. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  76904. pSavepoint = pSavepoint->pNext
  76905. ){
  76906. iSavepoint++;
  76907. }
  76908. if( !pSavepoint ){
  76909. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  76910. rc = SQLITE_ERROR;
  76911. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  76912. /* It is not possible to release (commit) a savepoint if there are
  76913. ** active write statements.
  76914. */
  76915. sqlite3VdbeError(p, "cannot release savepoint - "
  76916. "SQL statements in progress");
  76917. rc = SQLITE_BUSY;
  76918. }else{
  76919. /* Determine whether or not this is a transaction savepoint. If so,
  76920. ** and this is a RELEASE command, then the current transaction
  76921. ** is committed.
  76922. */
  76923. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  76924. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  76925. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  76926. goto vdbe_return;
  76927. }
  76928. db->autoCommit = 1;
  76929. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  76930. p->pc = (int)(pOp - aOp);
  76931. db->autoCommit = 0;
  76932. p->rc = rc = SQLITE_BUSY;
  76933. goto vdbe_return;
  76934. }
  76935. db->isTransactionSavepoint = 0;
  76936. rc = p->rc;
  76937. }else{
  76938. int isSchemaChange;
  76939. iSavepoint = db->nSavepoint - iSavepoint - 1;
  76940. if( p1==SAVEPOINT_ROLLBACK ){
  76941. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  76942. for(ii=0; ii<db->nDb; ii++){
  76943. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  76944. SQLITE_ABORT_ROLLBACK,
  76945. isSchemaChange==0);
  76946. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76947. }
  76948. }else{
  76949. isSchemaChange = 0;
  76950. }
  76951. for(ii=0; ii<db->nDb; ii++){
  76952. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  76953. if( rc!=SQLITE_OK ){
  76954. goto abort_due_to_error;
  76955. }
  76956. }
  76957. if( isSchemaChange ){
  76958. sqlite3ExpirePreparedStatements(db);
  76959. sqlite3ResetAllSchemasOfConnection(db);
  76960. db->mDbFlags |= DBFLAG_SchemaChange;
  76961. }
  76962. }
  76963. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  76964. ** savepoints nested inside of the savepoint being operated on. */
  76965. while( db->pSavepoint!=pSavepoint ){
  76966. pTmp = db->pSavepoint;
  76967. db->pSavepoint = pTmp->pNext;
  76968. sqlite3DbFree(db, pTmp);
  76969. db->nSavepoint--;
  76970. }
  76971. /* If it is a RELEASE, then destroy the savepoint being operated on
  76972. ** too. If it is a ROLLBACK TO, then set the number of deferred
  76973. ** constraint violations present in the database to the value stored
  76974. ** when the savepoint was created. */
  76975. if( p1==SAVEPOINT_RELEASE ){
  76976. assert( pSavepoint==db->pSavepoint );
  76977. db->pSavepoint = pSavepoint->pNext;
  76978. sqlite3DbFree(db, pSavepoint);
  76979. if( !isTransaction ){
  76980. db->nSavepoint--;
  76981. }
  76982. }else{
  76983. db->nDeferredCons = pSavepoint->nDeferredCons;
  76984. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  76985. }
  76986. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  76987. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  76988. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76989. }
  76990. }
  76991. }
  76992. if( rc ) goto abort_due_to_error;
  76993. break;
  76994. }
  76995. /* Opcode: AutoCommit P1 P2 * * *
  76996. **
  76997. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  76998. ** back any currently active btree transactions. If there are any active
  76999. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  77000. ** there are active writing VMs or active VMs that use shared cache.
  77001. **
  77002. ** This instruction causes the VM to halt.
  77003. */
  77004. case OP_AutoCommit: {
  77005. int desiredAutoCommit;
  77006. int iRollback;
  77007. desiredAutoCommit = pOp->p1;
  77008. iRollback = pOp->p2;
  77009. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  77010. assert( desiredAutoCommit==1 || iRollback==0 );
  77011. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  77012. assert( p->bIsReader );
  77013. if( desiredAutoCommit!=db->autoCommit ){
  77014. if( iRollback ){
  77015. assert( desiredAutoCommit==1 );
  77016. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  77017. db->autoCommit = 1;
  77018. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  77019. /* If this instruction implements a COMMIT and other VMs are writing
  77020. ** return an error indicating that the other VMs must complete first.
  77021. */
  77022. sqlite3VdbeError(p, "cannot commit transaction - "
  77023. "SQL statements in progress");
  77024. rc = SQLITE_BUSY;
  77025. goto abort_due_to_error;
  77026. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  77027. goto vdbe_return;
  77028. }else{
  77029. db->autoCommit = (u8)desiredAutoCommit;
  77030. }
  77031. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  77032. p->pc = (int)(pOp - aOp);
  77033. db->autoCommit = (u8)(1-desiredAutoCommit);
  77034. p->rc = rc = SQLITE_BUSY;
  77035. goto vdbe_return;
  77036. }
  77037. assert( db->nStatement==0 );
  77038. sqlite3CloseSavepoints(db);
  77039. if( p->rc==SQLITE_OK ){
  77040. rc = SQLITE_DONE;
  77041. }else{
  77042. rc = SQLITE_ERROR;
  77043. }
  77044. goto vdbe_return;
  77045. }else{
  77046. sqlite3VdbeError(p,
  77047. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  77048. (iRollback)?"cannot rollback - no transaction is active":
  77049. "cannot commit - no transaction is active"));
  77050. rc = SQLITE_ERROR;
  77051. goto abort_due_to_error;
  77052. }
  77053. break;
  77054. }
  77055. /* Opcode: Transaction P1 P2 P3 P4 P5
  77056. **
  77057. ** Begin a transaction on database P1 if a transaction is not already
  77058. ** active.
  77059. ** If P2 is non-zero, then a write-transaction is started, or if a
  77060. ** read-transaction is already active, it is upgraded to a write-transaction.
  77061. ** If P2 is zero, then a read-transaction is started.
  77062. **
  77063. ** P1 is the index of the database file on which the transaction is
  77064. ** started. Index 0 is the main database file and index 1 is the
  77065. ** file used for temporary tables. Indices of 2 or more are used for
  77066. ** attached databases.
  77067. **
  77068. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  77069. ** true (this flag is set if the Vdbe may modify more than one row and may
  77070. ** throw an ABORT exception), a statement transaction may also be opened.
  77071. ** More specifically, a statement transaction is opened iff the database
  77072. ** connection is currently not in autocommit mode, or if there are other
  77073. ** active statements. A statement transaction allows the changes made by this
  77074. ** VDBE to be rolled back after an error without having to roll back the
  77075. ** entire transaction. If no error is encountered, the statement transaction
  77076. ** will automatically commit when the VDBE halts.
  77077. **
  77078. ** If P5!=0 then this opcode also checks the schema cookie against P3
  77079. ** and the schema generation counter against P4.
  77080. ** The cookie changes its value whenever the database schema changes.
  77081. ** This operation is used to detect when that the cookie has changed
  77082. ** and that the current process needs to reread the schema. If the schema
  77083. ** cookie in P3 differs from the schema cookie in the database header or
  77084. ** if the schema generation counter in P4 differs from the current
  77085. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  77086. ** halts. The sqlite3_step() wrapper function might then reprepare the
  77087. ** statement and rerun it from the beginning.
  77088. */
  77089. case OP_Transaction: {
  77090. Btree *pBt;
  77091. int iMeta;
  77092. int iGen;
  77093. assert( p->bIsReader );
  77094. assert( p->readOnly==0 || pOp->p2==0 );
  77095. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  77096. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  77097. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  77098. rc = SQLITE_READONLY;
  77099. goto abort_due_to_error;
  77100. }
  77101. pBt = db->aDb[pOp->p1].pBt;
  77102. if( pBt ){
  77103. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  77104. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  77105. testcase( rc==SQLITE_BUSY_RECOVERY );
  77106. if( rc!=SQLITE_OK ){
  77107. if( (rc&0xff)==SQLITE_BUSY ){
  77108. p->pc = (int)(pOp - aOp);
  77109. p->rc = rc;
  77110. goto vdbe_return;
  77111. }
  77112. goto abort_due_to_error;
  77113. }
  77114. if( pOp->p2 && p->usesStmtJournal
  77115. && (db->autoCommit==0 || db->nVdbeRead>1)
  77116. ){
  77117. assert( sqlite3BtreeIsInTrans(pBt) );
  77118. if( p->iStatement==0 ){
  77119. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  77120. db->nStatement++;
  77121. p->iStatement = db->nSavepoint + db->nStatement;
  77122. }
  77123. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  77124. if( rc==SQLITE_OK ){
  77125. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  77126. }
  77127. /* Store the current value of the database handles deferred constraint
  77128. ** counter. If the statement transaction needs to be rolled back,
  77129. ** the value of this counter needs to be restored too. */
  77130. p->nStmtDefCons = db->nDeferredCons;
  77131. p->nStmtDefImmCons = db->nDeferredImmCons;
  77132. }
  77133. /* Gather the schema version number for checking:
  77134. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  77135. ** version is checked to ensure that the schema has not changed since the
  77136. ** SQL statement was prepared.
  77137. */
  77138. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  77139. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  77140. }else{
  77141. iGen = iMeta = 0;
  77142. }
  77143. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  77144. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  77145. sqlite3DbFree(db, p->zErrMsg);
  77146. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  77147. /* If the schema-cookie from the database file matches the cookie
  77148. ** stored with the in-memory representation of the schema, do
  77149. ** not reload the schema from the database file.
  77150. **
  77151. ** If virtual-tables are in use, this is not just an optimization.
  77152. ** Often, v-tables store their data in other SQLite tables, which
  77153. ** are queried from within xNext() and other v-table methods using
  77154. ** prepared queries. If such a query is out-of-date, we do not want to
  77155. ** discard the database schema, as the user code implementing the
  77156. ** v-table would have to be ready for the sqlite3_vtab structure itself
  77157. ** to be invalidated whenever sqlite3_step() is called from within
  77158. ** a v-table method.
  77159. */
  77160. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  77161. sqlite3ResetOneSchema(db, pOp->p1);
  77162. }
  77163. p->expired = 1;
  77164. rc = SQLITE_SCHEMA;
  77165. }
  77166. if( rc ) goto abort_due_to_error;
  77167. break;
  77168. }
  77169. /* Opcode: ReadCookie P1 P2 P3 * *
  77170. **
  77171. ** Read cookie number P3 from database P1 and write it into register P2.
  77172. ** P3==1 is the schema version. P3==2 is the database format.
  77173. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  77174. ** the main database file and P1==1 is the database file used to store
  77175. ** temporary tables.
  77176. **
  77177. ** There must be a read-lock on the database (either a transaction
  77178. ** must be started or there must be an open cursor) before
  77179. ** executing this instruction.
  77180. */
  77181. case OP_ReadCookie: { /* out2 */
  77182. int iMeta;
  77183. int iDb;
  77184. int iCookie;
  77185. assert( p->bIsReader );
  77186. iDb = pOp->p1;
  77187. iCookie = pOp->p3;
  77188. assert( pOp->p3<SQLITE_N_BTREE_META );
  77189. assert( iDb>=0 && iDb<db->nDb );
  77190. assert( db->aDb[iDb].pBt!=0 );
  77191. assert( DbMaskTest(p->btreeMask, iDb) );
  77192. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  77193. pOut = out2Prerelease(p, pOp);
  77194. pOut->u.i = iMeta;
  77195. break;
  77196. }
  77197. /* Opcode: SetCookie P1 P2 P3 * *
  77198. **
  77199. ** Write the integer value P3 into cookie number P2 of database P1.
  77200. ** P2==1 is the schema version. P2==2 is the database format.
  77201. ** P2==3 is the recommended pager cache
  77202. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  77203. ** database file used to store temporary tables.
  77204. **
  77205. ** A transaction must be started before executing this opcode.
  77206. */
  77207. case OP_SetCookie: {
  77208. Db *pDb;
  77209. assert( pOp->p2<SQLITE_N_BTREE_META );
  77210. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  77211. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  77212. assert( p->readOnly==0 );
  77213. pDb = &db->aDb[pOp->p1];
  77214. assert( pDb->pBt!=0 );
  77215. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  77216. /* See note about index shifting on OP_ReadCookie */
  77217. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  77218. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  77219. /* When the schema cookie changes, record the new cookie internally */
  77220. pDb->pSchema->schema_cookie = pOp->p3;
  77221. db->mDbFlags |= DBFLAG_SchemaChange;
  77222. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  77223. /* Record changes in the file format */
  77224. pDb->pSchema->file_format = pOp->p3;
  77225. }
  77226. if( pOp->p1==1 ){
  77227. /* Invalidate all prepared statements whenever the TEMP database
  77228. ** schema is changed. Ticket #1644 */
  77229. sqlite3ExpirePreparedStatements(db);
  77230. p->expired = 0;
  77231. }
  77232. if( rc ) goto abort_due_to_error;
  77233. break;
  77234. }
  77235. /* Opcode: OpenRead P1 P2 P3 P4 P5
  77236. ** Synopsis: root=P2 iDb=P3
  77237. **
  77238. ** Open a read-only cursor for the database table whose root page is
  77239. ** P2 in a database file. The database file is determined by P3.
  77240. ** P3==0 means the main database, P3==1 means the database used for
  77241. ** temporary tables, and P3>1 means used the corresponding attached
  77242. ** database. Give the new cursor an identifier of P1. The P1
  77243. ** values need not be contiguous but all P1 values should be small integers.
  77244. ** It is an error for P1 to be negative.
  77245. **
  77246. ** If P5!=0 then use the content of register P2 as the root page, not
  77247. ** the value of P2 itself.
  77248. **
  77249. ** There will be a read lock on the database whenever there is an
  77250. ** open cursor. If the database was unlocked prior to this instruction
  77251. ** then a read lock is acquired as part of this instruction. A read
  77252. ** lock allows other processes to read the database but prohibits
  77253. ** any other process from modifying the database. The read lock is
  77254. ** released when all cursors are closed. If this instruction attempts
  77255. ** to get a read lock but fails, the script terminates with an
  77256. ** SQLITE_BUSY error code.
  77257. **
  77258. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  77259. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  77260. ** structure, then said structure defines the content and collating
  77261. ** sequence of the index being opened. Otherwise, if P4 is an integer
  77262. ** value, it is set to the number of columns in the table.
  77263. **
  77264. ** See also: OpenWrite, ReopenIdx
  77265. */
  77266. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  77267. ** Synopsis: root=P2 iDb=P3
  77268. **
  77269. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  77270. ** checks to see if the cursor on P1 is already open with a root page
  77271. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  77272. ** if the cursor is already open, do not reopen it.
  77273. **
  77274. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  77275. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  77276. ** every other ReopenIdx or OpenRead for the same cursor number.
  77277. **
  77278. ** See the OpenRead opcode documentation for additional information.
  77279. */
  77280. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  77281. ** Synopsis: root=P2 iDb=P3
  77282. **
  77283. ** Open a read/write cursor named P1 on the table or index whose root
  77284. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  77285. ** root page.
  77286. **
  77287. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  77288. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  77289. ** structure, then said structure defines the content and collating
  77290. ** sequence of the index being opened. Otherwise, if P4 is an integer
  77291. ** value, it is set to the number of columns in the table, or to the
  77292. ** largest index of any column of the table that is actually used.
  77293. **
  77294. ** This instruction works just like OpenRead except that it opens the cursor
  77295. ** in read/write mode. For a given table, there can be one or more read-only
  77296. ** cursors or a single read/write cursor but not both.
  77297. **
  77298. ** See also OpenRead.
  77299. */
  77300. case OP_ReopenIdx: {
  77301. int nField;
  77302. KeyInfo *pKeyInfo;
  77303. int p2;
  77304. int iDb;
  77305. int wrFlag;
  77306. Btree *pX;
  77307. VdbeCursor *pCur;
  77308. Db *pDb;
  77309. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  77310. assert( pOp->p4type==P4_KEYINFO );
  77311. pCur = p->apCsr[pOp->p1];
  77312. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  77313. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  77314. goto open_cursor_set_hints;
  77315. }
  77316. /* If the cursor is not currently open or is open on a different
  77317. ** index, then fall through into OP_OpenRead to force a reopen */
  77318. case OP_OpenRead:
  77319. case OP_OpenWrite:
  77320. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  77321. assert( p->bIsReader );
  77322. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  77323. || p->readOnly==0 );
  77324. if( p->expired ){
  77325. rc = SQLITE_ABORT_ROLLBACK;
  77326. goto abort_due_to_error;
  77327. }
  77328. nField = 0;
  77329. pKeyInfo = 0;
  77330. p2 = pOp->p2;
  77331. iDb = pOp->p3;
  77332. assert( iDb>=0 && iDb<db->nDb );
  77333. assert( DbMaskTest(p->btreeMask, iDb) );
  77334. pDb = &db->aDb[iDb];
  77335. pX = pDb->pBt;
  77336. assert( pX!=0 );
  77337. if( pOp->opcode==OP_OpenWrite ){
  77338. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  77339. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  77340. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77341. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  77342. p->minWriteFileFormat = pDb->pSchema->file_format;
  77343. }
  77344. }else{
  77345. wrFlag = 0;
  77346. }
  77347. if( pOp->p5 & OPFLAG_P2ISREG ){
  77348. assert( p2>0 );
  77349. assert( p2<=(p->nMem+1 - p->nCursor) );
  77350. pIn2 = &aMem[p2];
  77351. assert( memIsValid(pIn2) );
  77352. assert( (pIn2->flags & MEM_Int)!=0 );
  77353. sqlite3VdbeMemIntegerify(pIn2);
  77354. p2 = (int)pIn2->u.i;
  77355. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  77356. ** that opcode will always set the p2 value to 2 or more or else fail.
  77357. ** If there were a failure, the prepared statement would have halted
  77358. ** before reaching this instruction. */
  77359. assert( p2>=2 );
  77360. }
  77361. if( pOp->p4type==P4_KEYINFO ){
  77362. pKeyInfo = pOp->p4.pKeyInfo;
  77363. assert( pKeyInfo->enc==ENC(db) );
  77364. assert( pKeyInfo->db==db );
  77365. nField = pKeyInfo->nAllField;
  77366. }else if( pOp->p4type==P4_INT32 ){
  77367. nField = pOp->p4.i;
  77368. }
  77369. assert( pOp->p1>=0 );
  77370. assert( nField>=0 );
  77371. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  77372. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  77373. if( pCur==0 ) goto no_mem;
  77374. pCur->nullRow = 1;
  77375. pCur->isOrdered = 1;
  77376. pCur->pgnoRoot = p2;
  77377. #ifdef SQLITE_DEBUG
  77378. pCur->wrFlag = wrFlag;
  77379. #endif
  77380. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  77381. pCur->pKeyInfo = pKeyInfo;
  77382. /* Set the VdbeCursor.isTable variable. Previous versions of
  77383. ** SQLite used to check if the root-page flags were sane at this point
  77384. ** and report database corruption if they were not, but this check has
  77385. ** since moved into the btree layer. */
  77386. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  77387. open_cursor_set_hints:
  77388. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  77389. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  77390. testcase( pOp->p5 & OPFLAG_BULKCSR );
  77391. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  77392. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  77393. #endif
  77394. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  77395. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  77396. if( rc ) goto abort_due_to_error;
  77397. break;
  77398. }
  77399. /* Opcode: OpenDup P1 P2 * * *
  77400. **
  77401. ** Open a new cursor P1 that points to the same ephemeral table as
  77402. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  77403. ** opcode. Only ephemeral cursors may be duplicated.
  77404. **
  77405. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  77406. */
  77407. case OP_OpenDup: {
  77408. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  77409. VdbeCursor *pCx; /* The new cursor */
  77410. pOrig = p->apCsr[pOp->p2];
  77411. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  77412. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  77413. if( pCx==0 ) goto no_mem;
  77414. pCx->nullRow = 1;
  77415. pCx->isEphemeral = 1;
  77416. pCx->pKeyInfo = pOrig->pKeyInfo;
  77417. pCx->isTable = pOrig->isTable;
  77418. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  77419. pCx->pKeyInfo, pCx->uc.pCursor);
  77420. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  77421. ** opened for a database. Since there is already an open cursor when this
  77422. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  77423. assert( rc==SQLITE_OK );
  77424. break;
  77425. }
  77426. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  77427. ** Synopsis: nColumn=P2
  77428. **
  77429. ** Open a new cursor P1 to a transient table.
  77430. ** The cursor is always opened read/write even if
  77431. ** the main database is read-only. The ephemeral
  77432. ** table is deleted automatically when the cursor is closed.
  77433. **
  77434. ** P2 is the number of columns in the ephemeral table.
  77435. ** The cursor points to a BTree table if P4==0 and to a BTree index
  77436. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  77437. ** that defines the format of keys in the index.
  77438. **
  77439. ** The P5 parameter can be a mask of the BTREE_* flags defined
  77440. ** in btree.h. These flags control aspects of the operation of
  77441. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  77442. ** added automatically.
  77443. */
  77444. /* Opcode: OpenAutoindex P1 P2 * P4 *
  77445. ** Synopsis: nColumn=P2
  77446. **
  77447. ** This opcode works the same as OP_OpenEphemeral. It has a
  77448. ** different name to distinguish its use. Tables created using
  77449. ** by this opcode will be used for automatically created transient
  77450. ** indices in joins.
  77451. */
  77452. case OP_OpenAutoindex:
  77453. case OP_OpenEphemeral: {
  77454. VdbeCursor *pCx;
  77455. KeyInfo *pKeyInfo;
  77456. static const int vfsFlags =
  77457. SQLITE_OPEN_READWRITE |
  77458. SQLITE_OPEN_CREATE |
  77459. SQLITE_OPEN_EXCLUSIVE |
  77460. SQLITE_OPEN_DELETEONCLOSE |
  77461. SQLITE_OPEN_TRANSIENT_DB;
  77462. assert( pOp->p1>=0 );
  77463. assert( pOp->p2>=0 );
  77464. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  77465. if( pCx==0 ) goto no_mem;
  77466. pCx->nullRow = 1;
  77467. pCx->isEphemeral = 1;
  77468. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  77469. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  77470. if( rc==SQLITE_OK ){
  77471. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
  77472. }
  77473. if( rc==SQLITE_OK ){
  77474. /* If a transient index is required, create it by calling
  77475. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  77476. ** opening it. If a transient table is required, just use the
  77477. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  77478. */
  77479. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  77480. int pgno;
  77481. assert( pOp->p4type==P4_KEYINFO );
  77482. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  77483. if( rc==SQLITE_OK ){
  77484. assert( pgno==MASTER_ROOT+1 );
  77485. assert( pKeyInfo->db==db );
  77486. assert( pKeyInfo->enc==ENC(db) );
  77487. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  77488. pKeyInfo, pCx->uc.pCursor);
  77489. }
  77490. pCx->isTable = 0;
  77491. }else{
  77492. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  77493. 0, pCx->uc.pCursor);
  77494. pCx->isTable = 1;
  77495. }
  77496. }
  77497. if( rc ) goto abort_due_to_error;
  77498. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  77499. break;
  77500. }
  77501. /* Opcode: SorterOpen P1 P2 P3 P4 *
  77502. **
  77503. ** This opcode works like OP_OpenEphemeral except that it opens
  77504. ** a transient index that is specifically designed to sort large
  77505. ** tables using an external merge-sort algorithm.
  77506. **
  77507. ** If argument P3 is non-zero, then it indicates that the sorter may
  77508. ** assume that a stable sort considering the first P3 fields of each
  77509. ** key is sufficient to produce the required results.
  77510. */
  77511. case OP_SorterOpen: {
  77512. VdbeCursor *pCx;
  77513. assert( pOp->p1>=0 );
  77514. assert( pOp->p2>=0 );
  77515. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  77516. if( pCx==0 ) goto no_mem;
  77517. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  77518. assert( pCx->pKeyInfo->db==db );
  77519. assert( pCx->pKeyInfo->enc==ENC(db) );
  77520. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  77521. if( rc ) goto abort_due_to_error;
  77522. break;
  77523. }
  77524. /* Opcode: SequenceTest P1 P2 * * *
  77525. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  77526. **
  77527. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  77528. ** to P2. Regardless of whether or not the jump is taken, increment the
  77529. ** the sequence value.
  77530. */
  77531. case OP_SequenceTest: {
  77532. VdbeCursor *pC;
  77533. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77534. pC = p->apCsr[pOp->p1];
  77535. assert( isSorter(pC) );
  77536. if( (pC->seqCount++)==0 ){
  77537. goto jump_to_p2;
  77538. }
  77539. break;
  77540. }
  77541. /* Opcode: OpenPseudo P1 P2 P3 * *
  77542. ** Synopsis: P3 columns in r[P2]
  77543. **
  77544. ** Open a new cursor that points to a fake table that contains a single
  77545. ** row of data. The content of that one row is the content of memory
  77546. ** register P2. In other words, cursor P1 becomes an alias for the
  77547. ** MEM_Blob content contained in register P2.
  77548. **
  77549. ** A pseudo-table created by this opcode is used to hold a single
  77550. ** row output from the sorter so that the row can be decomposed into
  77551. ** individual columns using the OP_Column opcode. The OP_Column opcode
  77552. ** is the only cursor opcode that works with a pseudo-table.
  77553. **
  77554. ** P3 is the number of fields in the records that will be stored by
  77555. ** the pseudo-table.
  77556. */
  77557. case OP_OpenPseudo: {
  77558. VdbeCursor *pCx;
  77559. assert( pOp->p1>=0 );
  77560. assert( pOp->p3>=0 );
  77561. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  77562. if( pCx==0 ) goto no_mem;
  77563. pCx->nullRow = 1;
  77564. pCx->seekResult = pOp->p2;
  77565. pCx->isTable = 1;
  77566. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  77567. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  77568. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  77569. ** which is a performance optimization */
  77570. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  77571. assert( pOp->p5==0 );
  77572. break;
  77573. }
  77574. /* Opcode: Close P1 * * * *
  77575. **
  77576. ** Close a cursor previously opened as P1. If P1 is not
  77577. ** currently open, this instruction is a no-op.
  77578. */
  77579. case OP_Close: {
  77580. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77581. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  77582. p->apCsr[pOp->p1] = 0;
  77583. break;
  77584. }
  77585. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  77586. /* Opcode: ColumnsUsed P1 * * P4 *
  77587. **
  77588. ** This opcode (which only exists if SQLite was compiled with
  77589. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  77590. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  77591. ** (P4_INT64) in which the first 63 bits are one for each of the
  77592. ** first 63 columns of the table or index that are actually used
  77593. ** by the cursor. The high-order bit is set if any column after
  77594. ** the 64th is used.
  77595. */
  77596. case OP_ColumnsUsed: {
  77597. VdbeCursor *pC;
  77598. pC = p->apCsr[pOp->p1];
  77599. assert( pC->eCurType==CURTYPE_BTREE );
  77600. pC->maskUsed = *(u64*)pOp->p4.pI64;
  77601. break;
  77602. }
  77603. #endif
  77604. /* Opcode: SeekGE P1 P2 P3 P4 *
  77605. ** Synopsis: key=r[P3@P4]
  77606. **
  77607. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  77608. ** use the value in register P3 as the key. If cursor P1 refers
  77609. ** to an SQL index, then P3 is the first in an array of P4 registers
  77610. ** that are used as an unpacked index key.
  77611. **
  77612. ** Reposition cursor P1 so that it points to the smallest entry that
  77613. ** is greater than or equal to the key value. If there are no records
  77614. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  77615. **
  77616. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  77617. ** opcode will always land on a record that equally equals the key, or
  77618. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  77619. ** opcode must be followed by an IdxLE opcode with the same arguments.
  77620. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  77621. ** IdxLE opcode will be used on subsequent loop iterations.
  77622. **
  77623. ** This opcode leaves the cursor configured to move in forward order,
  77624. ** from the beginning toward the end. In other words, the cursor is
  77625. ** configured to use Next, not Prev.
  77626. **
  77627. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  77628. */
  77629. /* Opcode: SeekGT P1 P2 P3 P4 *
  77630. ** Synopsis: key=r[P3@P4]
  77631. **
  77632. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  77633. ** use the value in register P3 as a key. If cursor P1 refers
  77634. ** to an SQL index, then P3 is the first in an array of P4 registers
  77635. ** that are used as an unpacked index key.
  77636. **
  77637. ** Reposition cursor P1 so that it points to the smallest entry that
  77638. ** is greater than the key value. If there are no records greater than
  77639. ** the key and P2 is not zero, then jump to P2.
  77640. **
  77641. ** This opcode leaves the cursor configured to move in forward order,
  77642. ** from the beginning toward the end. In other words, the cursor is
  77643. ** configured to use Next, not Prev.
  77644. **
  77645. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  77646. */
  77647. /* Opcode: SeekLT P1 P2 P3 P4 *
  77648. ** Synopsis: key=r[P3@P4]
  77649. **
  77650. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  77651. ** use the value in register P3 as a key. If cursor P1 refers
  77652. ** to an SQL index, then P3 is the first in an array of P4 registers
  77653. ** that are used as an unpacked index key.
  77654. **
  77655. ** Reposition cursor P1 so that it points to the largest entry that
  77656. ** is less than the key value. If there are no records less than
  77657. ** the key and P2 is not zero, then jump to P2.
  77658. **
  77659. ** This opcode leaves the cursor configured to move in reverse order,
  77660. ** from the end toward the beginning. In other words, the cursor is
  77661. ** configured to use Prev, not Next.
  77662. **
  77663. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  77664. */
  77665. /* Opcode: SeekLE P1 P2 P3 P4 *
  77666. ** Synopsis: key=r[P3@P4]
  77667. **
  77668. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  77669. ** use the value in register P3 as a key. If cursor P1 refers
  77670. ** to an SQL index, then P3 is the first in an array of P4 registers
  77671. ** that are used as an unpacked index key.
  77672. **
  77673. ** Reposition cursor P1 so that it points to the largest entry that
  77674. ** is less than or equal to the key value. If there are no records
  77675. ** less than or equal to the key and P2 is not zero, then jump to P2.
  77676. **
  77677. ** This opcode leaves the cursor configured to move in reverse order,
  77678. ** from the end toward the beginning. In other words, the cursor is
  77679. ** configured to use Prev, not Next.
  77680. **
  77681. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  77682. ** opcode will always land on a record that equally equals the key, or
  77683. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  77684. ** opcode must be followed by an IdxGE opcode with the same arguments.
  77685. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  77686. ** IdxGE opcode will be used on subsequent loop iterations.
  77687. **
  77688. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  77689. */
  77690. case OP_SeekLT: /* jump, in3 */
  77691. case OP_SeekLE: /* jump, in3 */
  77692. case OP_SeekGE: /* jump, in3 */
  77693. case OP_SeekGT: { /* jump, in3 */
  77694. int res; /* Comparison result */
  77695. int oc; /* Opcode */
  77696. VdbeCursor *pC; /* The cursor to seek */
  77697. UnpackedRecord r; /* The key to seek for */
  77698. int nField; /* Number of columns or fields in the key */
  77699. i64 iKey; /* The rowid we are to seek to */
  77700. int eqOnly; /* Only interested in == results */
  77701. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77702. assert( pOp->p2!=0 );
  77703. pC = p->apCsr[pOp->p1];
  77704. assert( pC!=0 );
  77705. assert( pC->eCurType==CURTYPE_BTREE );
  77706. assert( OP_SeekLE == OP_SeekLT+1 );
  77707. assert( OP_SeekGE == OP_SeekLT+2 );
  77708. assert( OP_SeekGT == OP_SeekLT+3 );
  77709. assert( pC->isOrdered );
  77710. assert( pC->uc.pCursor!=0 );
  77711. oc = pOp->opcode;
  77712. eqOnly = 0;
  77713. pC->nullRow = 0;
  77714. #ifdef SQLITE_DEBUG
  77715. pC->seekOp = pOp->opcode;
  77716. #endif
  77717. if( pC->isTable ){
  77718. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  77719. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  77720. || CORRUPT_DB );
  77721. /* The input value in P3 might be of any type: integer, real, string,
  77722. ** blob, or NULL. But it needs to be an integer before we can do
  77723. ** the seek, so convert it. */
  77724. pIn3 = &aMem[pOp->p3];
  77725. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  77726. applyNumericAffinity(pIn3, 0);
  77727. }
  77728. iKey = sqlite3VdbeIntValue(pIn3);
  77729. /* If the P3 value could not be converted into an integer without
  77730. ** loss of information, then special processing is required... */
  77731. if( (pIn3->flags & MEM_Int)==0 ){
  77732. if( (pIn3->flags & MEM_Real)==0 ){
  77733. /* If the P3 value cannot be converted into any kind of a number,
  77734. ** then the seek is not possible, so jump to P2 */
  77735. VdbeBranchTaken(1,2); goto jump_to_p2;
  77736. break;
  77737. }
  77738. /* If the approximation iKey is larger than the actual real search
  77739. ** term, substitute >= for > and < for <=. e.g. if the search term
  77740. ** is 4.9 and the integer approximation 5:
  77741. **
  77742. ** (x > 4.9) -> (x >= 5)
  77743. ** (x <= 4.9) -> (x < 5)
  77744. */
  77745. if( pIn3->u.r<(double)iKey ){
  77746. assert( OP_SeekGE==(OP_SeekGT-1) );
  77747. assert( OP_SeekLT==(OP_SeekLE-1) );
  77748. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  77749. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  77750. }
  77751. /* If the approximation iKey is smaller than the actual real search
  77752. ** term, substitute <= for < and > for >=. */
  77753. else if( pIn3->u.r>(double)iKey ){
  77754. assert( OP_SeekLE==(OP_SeekLT+1) );
  77755. assert( OP_SeekGT==(OP_SeekGE+1) );
  77756. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  77757. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  77758. }
  77759. }
  77760. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  77761. pC->movetoTarget = iKey; /* Used by OP_Delete */
  77762. if( rc!=SQLITE_OK ){
  77763. goto abort_due_to_error;
  77764. }
  77765. }else{
  77766. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  77767. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  77768. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  77769. */
  77770. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  77771. eqOnly = 1;
  77772. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  77773. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  77774. assert( pOp[1].p1==pOp[0].p1 );
  77775. assert( pOp[1].p2==pOp[0].p2 );
  77776. assert( pOp[1].p3==pOp[0].p3 );
  77777. assert( pOp[1].p4.i==pOp[0].p4.i );
  77778. }
  77779. nField = pOp->p4.i;
  77780. assert( pOp->p4type==P4_INT32 );
  77781. assert( nField>0 );
  77782. r.pKeyInfo = pC->pKeyInfo;
  77783. r.nField = (u16)nField;
  77784. /* The next line of code computes as follows, only faster:
  77785. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  77786. ** r.default_rc = -1;
  77787. ** }else{
  77788. ** r.default_rc = +1;
  77789. ** }
  77790. */
  77791. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  77792. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  77793. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  77794. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  77795. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  77796. r.aMem = &aMem[pOp->p3];
  77797. #ifdef SQLITE_DEBUG
  77798. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  77799. #endif
  77800. r.eqSeen = 0;
  77801. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  77802. if( rc!=SQLITE_OK ){
  77803. goto abort_due_to_error;
  77804. }
  77805. if( eqOnly && r.eqSeen==0 ){
  77806. assert( res!=0 );
  77807. goto seek_not_found;
  77808. }
  77809. }
  77810. pC->deferredMoveto = 0;
  77811. pC->cacheStatus = CACHE_STALE;
  77812. #ifdef SQLITE_TEST
  77813. sqlite3_search_count++;
  77814. #endif
  77815. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  77816. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  77817. res = 0;
  77818. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  77819. if( rc!=SQLITE_OK ){
  77820. if( rc==SQLITE_DONE ){
  77821. rc = SQLITE_OK;
  77822. res = 1;
  77823. }else{
  77824. goto abort_due_to_error;
  77825. }
  77826. }
  77827. }else{
  77828. res = 0;
  77829. }
  77830. }else{
  77831. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  77832. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  77833. res = 0;
  77834. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  77835. if( rc!=SQLITE_OK ){
  77836. if( rc==SQLITE_DONE ){
  77837. rc = SQLITE_OK;
  77838. res = 1;
  77839. }else{
  77840. goto abort_due_to_error;
  77841. }
  77842. }
  77843. }else{
  77844. /* res might be negative because the table is empty. Check to
  77845. ** see if this is the case.
  77846. */
  77847. res = sqlite3BtreeEof(pC->uc.pCursor);
  77848. }
  77849. }
  77850. seek_not_found:
  77851. assert( pOp->p2>0 );
  77852. VdbeBranchTaken(res!=0,2);
  77853. if( res ){
  77854. goto jump_to_p2;
  77855. }else if( eqOnly ){
  77856. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  77857. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  77858. }
  77859. break;
  77860. }
  77861. /* Opcode: Found P1 P2 P3 P4 *
  77862. ** Synopsis: key=r[P3@P4]
  77863. **
  77864. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77865. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77866. ** record.
  77867. **
  77868. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77869. ** is a prefix of any entry in P1 then a jump is made to P2 and
  77870. ** P1 is left pointing at the matching entry.
  77871. **
  77872. ** This operation leaves the cursor in a state where it can be
  77873. ** advanced in the forward direction. The Next instruction will work,
  77874. ** but not the Prev instruction.
  77875. **
  77876. ** See also: NotFound, NoConflict, NotExists. SeekGe
  77877. */
  77878. /* Opcode: NotFound P1 P2 P3 P4 *
  77879. ** Synopsis: key=r[P3@P4]
  77880. **
  77881. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77882. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77883. ** record.
  77884. **
  77885. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77886. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  77887. ** does contain an entry whose prefix matches the P3/P4 record then control
  77888. ** falls through to the next instruction and P1 is left pointing at the
  77889. ** matching entry.
  77890. **
  77891. ** This operation leaves the cursor in a state where it cannot be
  77892. ** advanced in either direction. In other words, the Next and Prev
  77893. ** opcodes do not work after this operation.
  77894. **
  77895. ** See also: Found, NotExists, NoConflict
  77896. */
  77897. /* Opcode: NoConflict P1 P2 P3 P4 *
  77898. ** Synopsis: key=r[P3@P4]
  77899. **
  77900. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77901. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77902. ** record.
  77903. **
  77904. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77905. ** contains any NULL value, jump immediately to P2. If all terms of the
  77906. ** record are not-NULL then a check is done to determine if any row in the
  77907. ** P1 index btree has a matching key prefix. If there are no matches, jump
  77908. ** immediately to P2. If there is a match, fall through and leave the P1
  77909. ** cursor pointing to the matching row.
  77910. **
  77911. ** This opcode is similar to OP_NotFound with the exceptions that the
  77912. ** branch is always taken if any part of the search key input is NULL.
  77913. **
  77914. ** This operation leaves the cursor in a state where it cannot be
  77915. ** advanced in either direction. In other words, the Next and Prev
  77916. ** opcodes do not work after this operation.
  77917. **
  77918. ** See also: NotFound, Found, NotExists
  77919. */
  77920. case OP_NoConflict: /* jump, in3 */
  77921. case OP_NotFound: /* jump, in3 */
  77922. case OP_Found: { /* jump, in3 */
  77923. int alreadyExists;
  77924. int takeJump;
  77925. int ii;
  77926. VdbeCursor *pC;
  77927. int res;
  77928. UnpackedRecord *pFree;
  77929. UnpackedRecord *pIdxKey;
  77930. UnpackedRecord r;
  77931. #ifdef SQLITE_TEST
  77932. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  77933. #endif
  77934. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77935. assert( pOp->p4type==P4_INT32 );
  77936. pC = p->apCsr[pOp->p1];
  77937. assert( pC!=0 );
  77938. #ifdef SQLITE_DEBUG
  77939. pC->seekOp = pOp->opcode;
  77940. #endif
  77941. pIn3 = &aMem[pOp->p3];
  77942. assert( pC->eCurType==CURTYPE_BTREE );
  77943. assert( pC->uc.pCursor!=0 );
  77944. assert( pC->isTable==0 );
  77945. if( pOp->p4.i>0 ){
  77946. r.pKeyInfo = pC->pKeyInfo;
  77947. r.nField = (u16)pOp->p4.i;
  77948. r.aMem = pIn3;
  77949. #ifdef SQLITE_DEBUG
  77950. for(ii=0; ii<r.nField; ii++){
  77951. assert( memIsValid(&r.aMem[ii]) );
  77952. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  77953. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  77954. }
  77955. #endif
  77956. pIdxKey = &r;
  77957. pFree = 0;
  77958. }else{
  77959. assert( pIn3->flags & MEM_Blob );
  77960. rc = ExpandBlob(pIn3);
  77961. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  77962. if( rc ) goto no_mem;
  77963. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  77964. if( pIdxKey==0 ) goto no_mem;
  77965. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  77966. }
  77967. pIdxKey->default_rc = 0;
  77968. takeJump = 0;
  77969. if( pOp->opcode==OP_NoConflict ){
  77970. /* For the OP_NoConflict opcode, take the jump if any of the
  77971. ** input fields are NULL, since any key with a NULL will not
  77972. ** conflict */
  77973. for(ii=0; ii<pIdxKey->nField; ii++){
  77974. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  77975. takeJump = 1;
  77976. break;
  77977. }
  77978. }
  77979. }
  77980. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  77981. if( pFree ) sqlite3DbFreeNN(db, pFree);
  77982. if( rc!=SQLITE_OK ){
  77983. goto abort_due_to_error;
  77984. }
  77985. pC->seekResult = res;
  77986. alreadyExists = (res==0);
  77987. pC->nullRow = 1-alreadyExists;
  77988. pC->deferredMoveto = 0;
  77989. pC->cacheStatus = CACHE_STALE;
  77990. if( pOp->opcode==OP_Found ){
  77991. VdbeBranchTaken(alreadyExists!=0,2);
  77992. if( alreadyExists ) goto jump_to_p2;
  77993. }else{
  77994. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  77995. if( takeJump || !alreadyExists ) goto jump_to_p2;
  77996. }
  77997. break;
  77998. }
  77999. /* Opcode: SeekRowid P1 P2 P3 * *
  78000. ** Synopsis: intkey=r[P3]
  78001. **
  78002. ** P1 is the index of a cursor open on an SQL table btree (with integer
  78003. ** keys). If register P3 does not contain an integer or if P1 does not
  78004. ** contain a record with rowid P3 then jump immediately to P2.
  78005. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  78006. ** a record with rowid P3 then
  78007. ** leave the cursor pointing at that record and fall through to the next
  78008. ** instruction.
  78009. **
  78010. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  78011. ** the P3 register must be guaranteed to contain an integer value. With this
  78012. ** opcode, register P3 might not contain an integer.
  78013. **
  78014. ** The OP_NotFound opcode performs the same operation on index btrees
  78015. ** (with arbitrary multi-value keys).
  78016. **
  78017. ** This opcode leaves the cursor in a state where it cannot be advanced
  78018. ** in either direction. In other words, the Next and Prev opcodes will
  78019. ** not work following this opcode.
  78020. **
  78021. ** See also: Found, NotFound, NoConflict, SeekRowid
  78022. */
  78023. /* Opcode: NotExists P1 P2 P3 * *
  78024. ** Synopsis: intkey=r[P3]
  78025. **
  78026. ** P1 is the index of a cursor open on an SQL table btree (with integer
  78027. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  78028. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  78029. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  78030. ** leave the cursor pointing at that record and fall through to the next
  78031. ** instruction.
  78032. **
  78033. ** The OP_SeekRowid opcode performs the same operation but also allows the
  78034. ** P3 register to contain a non-integer value, in which case the jump is
  78035. ** always taken. This opcode requires that P3 always contain an integer.
  78036. **
  78037. ** The OP_NotFound opcode performs the same operation on index btrees
  78038. ** (with arbitrary multi-value keys).
  78039. **
  78040. ** This opcode leaves the cursor in a state where it cannot be advanced
  78041. ** in either direction. In other words, the Next and Prev opcodes will
  78042. ** not work following this opcode.
  78043. **
  78044. ** See also: Found, NotFound, NoConflict, SeekRowid
  78045. */
  78046. case OP_SeekRowid: { /* jump, in3 */
  78047. VdbeCursor *pC;
  78048. BtCursor *pCrsr;
  78049. int res;
  78050. u64 iKey;
  78051. pIn3 = &aMem[pOp->p3];
  78052. if( (pIn3->flags & MEM_Int)==0 ){
  78053. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  78054. if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
  78055. }
  78056. /* Fall through into OP_NotExists */
  78057. case OP_NotExists: /* jump, in3 */
  78058. pIn3 = &aMem[pOp->p3];
  78059. assert( pIn3->flags & MEM_Int );
  78060. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78061. pC = p->apCsr[pOp->p1];
  78062. assert( pC!=0 );
  78063. #ifdef SQLITE_DEBUG
  78064. pC->seekOp = 0;
  78065. #endif
  78066. assert( pC->isTable );
  78067. assert( pC->eCurType==CURTYPE_BTREE );
  78068. pCrsr = pC->uc.pCursor;
  78069. assert( pCrsr!=0 );
  78070. res = 0;
  78071. iKey = pIn3->u.i;
  78072. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  78073. assert( rc==SQLITE_OK || res==0 );
  78074. pC->movetoTarget = iKey; /* Used by OP_Delete */
  78075. pC->nullRow = 0;
  78076. pC->cacheStatus = CACHE_STALE;
  78077. pC->deferredMoveto = 0;
  78078. VdbeBranchTaken(res!=0,2);
  78079. pC->seekResult = res;
  78080. if( res!=0 ){
  78081. assert( rc==SQLITE_OK );
  78082. if( pOp->p2==0 ){
  78083. rc = SQLITE_CORRUPT_BKPT;
  78084. }else{
  78085. goto jump_to_p2;
  78086. }
  78087. }
  78088. if( rc ) goto abort_due_to_error;
  78089. break;
  78090. }
  78091. /* Opcode: Sequence P1 P2 * * *
  78092. ** Synopsis: r[P2]=cursor[P1].ctr++
  78093. **
  78094. ** Find the next available sequence number for cursor P1.
  78095. ** Write the sequence number into register P2.
  78096. ** The sequence number on the cursor is incremented after this
  78097. ** instruction.
  78098. */
  78099. case OP_Sequence: { /* out2 */
  78100. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78101. assert( p->apCsr[pOp->p1]!=0 );
  78102. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  78103. pOut = out2Prerelease(p, pOp);
  78104. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  78105. break;
  78106. }
  78107. /* Opcode: NewRowid P1 P2 P3 * *
  78108. ** Synopsis: r[P2]=rowid
  78109. **
  78110. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  78111. ** The record number is not previously used as a key in the database
  78112. ** table that cursor P1 points to. The new record number is written
  78113. ** written to register P2.
  78114. **
  78115. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  78116. ** the largest previously generated record number. No new record numbers are
  78117. ** allowed to be less than this value. When this value reaches its maximum,
  78118. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  78119. ** generated record number. This P3 mechanism is used to help implement the
  78120. ** AUTOINCREMENT feature.
  78121. */
  78122. case OP_NewRowid: { /* out2 */
  78123. i64 v; /* The new rowid */
  78124. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  78125. int res; /* Result of an sqlite3BtreeLast() */
  78126. int cnt; /* Counter to limit the number of searches */
  78127. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  78128. VdbeFrame *pFrame; /* Root frame of VDBE */
  78129. v = 0;
  78130. res = 0;
  78131. pOut = out2Prerelease(p, pOp);
  78132. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78133. pC = p->apCsr[pOp->p1];
  78134. assert( pC!=0 );
  78135. assert( pC->eCurType==CURTYPE_BTREE );
  78136. assert( pC->uc.pCursor!=0 );
  78137. {
  78138. /* The next rowid or record number (different terms for the same
  78139. ** thing) is obtained in a two-step algorithm.
  78140. **
  78141. ** First we attempt to find the largest existing rowid and add one
  78142. ** to that. But if the largest existing rowid is already the maximum
  78143. ** positive integer, we have to fall through to the second
  78144. ** probabilistic algorithm
  78145. **
  78146. ** The second algorithm is to select a rowid at random and see if
  78147. ** it already exists in the table. If it does not exist, we have
  78148. ** succeeded. If the random rowid does exist, we select a new one
  78149. ** and try again, up to 100 times.
  78150. */
  78151. assert( pC->isTable );
  78152. #ifdef SQLITE_32BIT_ROWID
  78153. # define MAX_ROWID 0x7fffffff
  78154. #else
  78155. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  78156. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  78157. ** to provide the constant while making all compilers happy.
  78158. */
  78159. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  78160. #endif
  78161. if( !pC->useRandomRowid ){
  78162. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  78163. if( rc!=SQLITE_OK ){
  78164. goto abort_due_to_error;
  78165. }
  78166. if( res ){
  78167. v = 1; /* IMP: R-61914-48074 */
  78168. }else{
  78169. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  78170. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  78171. if( v>=MAX_ROWID ){
  78172. pC->useRandomRowid = 1;
  78173. }else{
  78174. v++; /* IMP: R-29538-34987 */
  78175. }
  78176. }
  78177. }
  78178. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78179. if( pOp->p3 ){
  78180. /* Assert that P3 is a valid memory cell. */
  78181. assert( pOp->p3>0 );
  78182. if( p->pFrame ){
  78183. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  78184. /* Assert that P3 is a valid memory cell. */
  78185. assert( pOp->p3<=pFrame->nMem );
  78186. pMem = &pFrame->aMem[pOp->p3];
  78187. }else{
  78188. /* Assert that P3 is a valid memory cell. */
  78189. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  78190. pMem = &aMem[pOp->p3];
  78191. memAboutToChange(p, pMem);
  78192. }
  78193. assert( memIsValid(pMem) );
  78194. REGISTER_TRACE(pOp->p3, pMem);
  78195. sqlite3VdbeMemIntegerify(pMem);
  78196. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  78197. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  78198. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  78199. goto abort_due_to_error;
  78200. }
  78201. if( v<pMem->u.i+1 ){
  78202. v = pMem->u.i + 1;
  78203. }
  78204. pMem->u.i = v;
  78205. }
  78206. #endif
  78207. if( pC->useRandomRowid ){
  78208. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  78209. ** largest possible integer (9223372036854775807) then the database
  78210. ** engine starts picking positive candidate ROWIDs at random until
  78211. ** it finds one that is not previously used. */
  78212. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  78213. ** an AUTOINCREMENT table. */
  78214. cnt = 0;
  78215. do{
  78216. sqlite3_randomness(sizeof(v), &v);
  78217. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  78218. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  78219. 0, &res))==SQLITE_OK)
  78220. && (res==0)
  78221. && (++cnt<100));
  78222. if( rc ) goto abort_due_to_error;
  78223. if( res==0 ){
  78224. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  78225. goto abort_due_to_error;
  78226. }
  78227. assert( v>0 ); /* EV: R-40812-03570 */
  78228. }
  78229. pC->deferredMoveto = 0;
  78230. pC->cacheStatus = CACHE_STALE;
  78231. }
  78232. pOut->u.i = v;
  78233. break;
  78234. }
  78235. /* Opcode: Insert P1 P2 P3 P4 P5
  78236. ** Synopsis: intkey=r[P3] data=r[P2]
  78237. **
  78238. ** Write an entry into the table of cursor P1. A new entry is
  78239. ** created if it doesn't already exist or the data for an existing
  78240. ** entry is overwritten. The data is the value MEM_Blob stored in register
  78241. ** number P2. The key is stored in register P3. The key must
  78242. ** be a MEM_Int.
  78243. **
  78244. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  78245. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  78246. ** then rowid is stored for subsequent return by the
  78247. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  78248. **
  78249. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  78250. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  78251. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  78252. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  78253. **
  78254. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  78255. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  78256. ** is part of an INSERT operation. The difference is only important to
  78257. ** the update hook.
  78258. **
  78259. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  78260. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  78261. ** following a successful insert.
  78262. **
  78263. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  78264. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  78265. ** and register P2 becomes ephemeral. If the cursor is changed, the
  78266. ** value of register P2 will then change. Make sure this does not
  78267. ** cause any problems.)
  78268. **
  78269. ** This instruction only works on tables. The equivalent instruction
  78270. ** for indices is OP_IdxInsert.
  78271. */
  78272. /* Opcode: InsertInt P1 P2 P3 P4 P5
  78273. ** Synopsis: intkey=P3 data=r[P2]
  78274. **
  78275. ** This works exactly like OP_Insert except that the key is the
  78276. ** integer value P3, not the value of the integer stored in register P3.
  78277. */
  78278. case OP_Insert:
  78279. case OP_InsertInt: {
  78280. Mem *pData; /* MEM cell holding data for the record to be inserted */
  78281. Mem *pKey; /* MEM cell holding key for the record */
  78282. VdbeCursor *pC; /* Cursor to table into which insert is written */
  78283. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  78284. const char *zDb; /* database name - used by the update hook */
  78285. Table *pTab; /* Table structure - used by update and pre-update hooks */
  78286. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  78287. BtreePayload x; /* Payload to be inserted */
  78288. op = 0;
  78289. pData = &aMem[pOp->p2];
  78290. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78291. assert( memIsValid(pData) );
  78292. pC = p->apCsr[pOp->p1];
  78293. assert( pC!=0 );
  78294. assert( pC->eCurType==CURTYPE_BTREE );
  78295. assert( pC->uc.pCursor!=0 );
  78296. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  78297. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  78298. REGISTER_TRACE(pOp->p2, pData);
  78299. if( pOp->opcode==OP_Insert ){
  78300. pKey = &aMem[pOp->p3];
  78301. assert( pKey->flags & MEM_Int );
  78302. assert( memIsValid(pKey) );
  78303. REGISTER_TRACE(pOp->p3, pKey);
  78304. x.nKey = pKey->u.i;
  78305. }else{
  78306. assert( pOp->opcode==OP_InsertInt );
  78307. x.nKey = pOp->p3;
  78308. }
  78309. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  78310. assert( pC->iDb>=0 );
  78311. zDb = db->aDb[pC->iDb].zDbSName;
  78312. pTab = pOp->p4.pTab;
  78313. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  78314. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  78315. }else{
  78316. pTab = 0; /* Not needed. Silence a compiler warning. */
  78317. zDb = 0; /* Not needed. Silence a compiler warning. */
  78318. }
  78319. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78320. /* Invoke the pre-update hook, if any */
  78321. if( db->xPreUpdateCallback
  78322. && pOp->p4type==P4_TABLE
  78323. && !(pOp->p5 & OPFLAG_ISUPDATE)
  78324. ){
  78325. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
  78326. }
  78327. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  78328. #endif
  78329. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  78330. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  78331. assert( pData->flags & (MEM_Blob|MEM_Str) );
  78332. x.pData = pData->z;
  78333. x.nData = pData->n;
  78334. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  78335. if( pData->flags & MEM_Zero ){
  78336. x.nZero = pData->u.nZero;
  78337. }else{
  78338. x.nZero = 0;
  78339. }
  78340. x.pKey = 0;
  78341. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  78342. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  78343. );
  78344. pC->deferredMoveto = 0;
  78345. pC->cacheStatus = CACHE_STALE;
  78346. /* Invoke the update-hook if required. */
  78347. if( rc ) goto abort_due_to_error;
  78348. if( db->xUpdateCallback && op ){
  78349. db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
  78350. }
  78351. break;
  78352. }
  78353. /* Opcode: Delete P1 P2 P3 P4 P5
  78354. **
  78355. ** Delete the record at which the P1 cursor is currently pointing.
  78356. **
  78357. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  78358. ** the cursor will be left pointing at either the next or the previous
  78359. ** record in the table. If it is left pointing at the next record, then
  78360. ** the next Next instruction will be a no-op. As a result, in this case
  78361. ** it is ok to delete a record from within a Next loop. If
  78362. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  78363. ** left in an undefined state.
  78364. **
  78365. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  78366. ** delete one of several associated with deleting a table row and all its
  78367. ** associated index entries. Exactly one of those deletes is the "primary"
  78368. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  78369. ** marked with the AUXDELETE flag.
  78370. **
  78371. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  78372. ** change count is incremented (otherwise not).
  78373. **
  78374. ** P1 must not be pseudo-table. It has to be a real table with
  78375. ** multiple rows.
  78376. **
  78377. ** If P4 is not NULL then it points to a Table object. In this case either
  78378. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  78379. ** have been positioned using OP_NotFound prior to invoking this opcode in
  78380. ** this case. Specifically, if one is configured, the pre-update hook is
  78381. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  78382. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  78383. **
  78384. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  78385. ** of the memory cell that contains the value that the rowid of the row will
  78386. ** be set to by the update.
  78387. */
  78388. case OP_Delete: {
  78389. VdbeCursor *pC;
  78390. const char *zDb;
  78391. Table *pTab;
  78392. int opflags;
  78393. opflags = pOp->p2;
  78394. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78395. pC = p->apCsr[pOp->p1];
  78396. assert( pC!=0 );
  78397. assert( pC->eCurType==CURTYPE_BTREE );
  78398. assert( pC->uc.pCursor!=0 );
  78399. assert( pC->deferredMoveto==0 );
  78400. #ifdef SQLITE_DEBUG
  78401. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  78402. /* If p5 is zero, the seek operation that positioned the cursor prior to
  78403. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  78404. ** the row that is being deleted */
  78405. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  78406. assert( pC->movetoTarget==iKey );
  78407. }
  78408. #endif
  78409. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  78410. ** the name of the db to pass as to it. Also set local pTab to a copy
  78411. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  78412. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  78413. ** VdbeCursor.movetoTarget to the current rowid. */
  78414. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  78415. assert( pC->iDb>=0 );
  78416. assert( pOp->p4.pTab!=0 );
  78417. zDb = db->aDb[pC->iDb].zDbSName;
  78418. pTab = pOp->p4.pTab;
  78419. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  78420. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  78421. }
  78422. }else{
  78423. zDb = 0; /* Not needed. Silence a compiler warning. */
  78424. pTab = 0; /* Not needed. Silence a compiler warning. */
  78425. }
  78426. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78427. /* Invoke the pre-update-hook if required. */
  78428. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  78429. assert( !(opflags & OPFLAG_ISUPDATE)
  78430. || HasRowid(pTab)==0
  78431. || (aMem[pOp->p3].flags & MEM_Int)
  78432. );
  78433. sqlite3VdbePreUpdateHook(p, pC,
  78434. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  78435. zDb, pTab, pC->movetoTarget,
  78436. pOp->p3
  78437. );
  78438. }
  78439. if( opflags & OPFLAG_ISNOOP ) break;
  78440. #endif
  78441. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  78442. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  78443. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  78444. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  78445. #ifdef SQLITE_DEBUG
  78446. if( p->pFrame==0 ){
  78447. if( pC->isEphemeral==0
  78448. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  78449. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  78450. ){
  78451. nExtraDelete++;
  78452. }
  78453. if( pOp->p2 & OPFLAG_NCHANGE ){
  78454. nExtraDelete--;
  78455. }
  78456. }
  78457. #endif
  78458. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  78459. pC->cacheStatus = CACHE_STALE;
  78460. pC->seekResult = 0;
  78461. if( rc ) goto abort_due_to_error;
  78462. /* Invoke the update-hook if required. */
  78463. if( opflags & OPFLAG_NCHANGE ){
  78464. p->nChange++;
  78465. if( db->xUpdateCallback && HasRowid(pTab) ){
  78466. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  78467. pC->movetoTarget);
  78468. assert( pC->iDb>=0 );
  78469. }
  78470. }
  78471. break;
  78472. }
  78473. /* Opcode: ResetCount * * * * *
  78474. **
  78475. ** The value of the change counter is copied to the database handle
  78476. ** change counter (returned by subsequent calls to sqlite3_changes()).
  78477. ** Then the VMs internal change counter resets to 0.
  78478. ** This is used by trigger programs.
  78479. */
  78480. case OP_ResetCount: {
  78481. sqlite3VdbeSetChanges(db, p->nChange);
  78482. p->nChange = 0;
  78483. break;
  78484. }
  78485. /* Opcode: SorterCompare P1 P2 P3 P4
  78486. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  78487. **
  78488. ** P1 is a sorter cursor. This instruction compares a prefix of the
  78489. ** record blob in register P3 against a prefix of the entry that
  78490. ** the sorter cursor currently points to. Only the first P4 fields
  78491. ** of r[P3] and the sorter record are compared.
  78492. **
  78493. ** If either P3 or the sorter contains a NULL in one of their significant
  78494. ** fields (not counting the P4 fields at the end which are ignored) then
  78495. ** the comparison is assumed to be equal.
  78496. **
  78497. ** Fall through to next instruction if the two records compare equal to
  78498. ** each other. Jump to P2 if they are different.
  78499. */
  78500. case OP_SorterCompare: {
  78501. VdbeCursor *pC;
  78502. int res;
  78503. int nKeyCol;
  78504. pC = p->apCsr[pOp->p1];
  78505. assert( isSorter(pC) );
  78506. assert( pOp->p4type==P4_INT32 );
  78507. pIn3 = &aMem[pOp->p3];
  78508. nKeyCol = pOp->p4.i;
  78509. res = 0;
  78510. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  78511. VdbeBranchTaken(res!=0,2);
  78512. if( rc ) goto abort_due_to_error;
  78513. if( res ) goto jump_to_p2;
  78514. break;
  78515. };
  78516. /* Opcode: SorterData P1 P2 P3 * *
  78517. ** Synopsis: r[P2]=data
  78518. **
  78519. ** Write into register P2 the current sorter data for sorter cursor P1.
  78520. ** Then clear the column header cache on cursor P3.
  78521. **
  78522. ** This opcode is normally use to move a record out of the sorter and into
  78523. ** a register that is the source for a pseudo-table cursor created using
  78524. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  78525. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  78526. ** us from having to issue a separate NullRow instruction to clear that cache.
  78527. */
  78528. case OP_SorterData: {
  78529. VdbeCursor *pC;
  78530. pOut = &aMem[pOp->p2];
  78531. pC = p->apCsr[pOp->p1];
  78532. assert( isSorter(pC) );
  78533. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  78534. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  78535. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78536. if( rc ) goto abort_due_to_error;
  78537. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  78538. break;
  78539. }
  78540. /* Opcode: RowData P1 P2 P3 * *
  78541. ** Synopsis: r[P2]=data
  78542. **
  78543. ** Write into register P2 the complete row content for the row at
  78544. ** which cursor P1 is currently pointing.
  78545. ** There is no interpretation of the data.
  78546. ** It is just copied onto the P2 register exactly as
  78547. ** it is found in the database file.
  78548. **
  78549. ** If cursor P1 is an index, then the content is the key of the row.
  78550. ** If cursor P2 is a table, then the content extracted is the data.
  78551. **
  78552. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  78553. ** of a real table, not a pseudo-table.
  78554. **
  78555. ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
  78556. ** into the database page. That means that the content of the output
  78557. ** register will be invalidated as soon as the cursor moves - including
  78558. ** moves caused by other cursors that "save" the the current cursors
  78559. ** position in order that they can write to the same table. If P3==0
  78560. ** then a copy of the data is made into memory. P3!=0 is faster, but
  78561. ** P3==0 is safer.
  78562. **
  78563. ** If P3!=0 then the content of the P2 register is unsuitable for use
  78564. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  78565. ** The P2 register content is invalidated by opcodes like OP_Function or
  78566. ** by any use of another cursor pointing to the same table.
  78567. */
  78568. case OP_RowData: {
  78569. VdbeCursor *pC;
  78570. BtCursor *pCrsr;
  78571. u32 n;
  78572. pOut = out2Prerelease(p, pOp);
  78573. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78574. pC = p->apCsr[pOp->p1];
  78575. assert( pC!=0 );
  78576. assert( pC->eCurType==CURTYPE_BTREE );
  78577. assert( isSorter(pC)==0 );
  78578. assert( pC->nullRow==0 );
  78579. assert( pC->uc.pCursor!=0 );
  78580. pCrsr = pC->uc.pCursor;
  78581. /* The OP_RowData opcodes always follow OP_NotExists or
  78582. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  78583. ** that might invalidate the cursor.
  78584. ** If this where not the case, on of the following assert()s
  78585. ** would fail. Should this ever change (because of changes in the code
  78586. ** generator) then the fix would be to insert a call to
  78587. ** sqlite3VdbeCursorMoveto().
  78588. */
  78589. assert( pC->deferredMoveto==0 );
  78590. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  78591. #if 0 /* Not required due to the previous to assert() statements */
  78592. rc = sqlite3VdbeCursorMoveto(pC);
  78593. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  78594. #endif
  78595. n = sqlite3BtreePayloadSize(pCrsr);
  78596. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78597. goto too_big;
  78598. }
  78599. testcase( n==0 );
  78600. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  78601. if( rc ) goto abort_due_to_error;
  78602. if( !pOp->p3 ) Deephemeralize(pOut);
  78603. UPDATE_MAX_BLOBSIZE(pOut);
  78604. REGISTER_TRACE(pOp->p2, pOut);
  78605. break;
  78606. }
  78607. /* Opcode: Rowid P1 P2 * * *
  78608. ** Synopsis: r[P2]=rowid
  78609. **
  78610. ** Store in register P2 an integer which is the key of the table entry that
  78611. ** P1 is currently point to.
  78612. **
  78613. ** P1 can be either an ordinary table or a virtual table. There used to
  78614. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  78615. ** one opcode now works for both table types.
  78616. */
  78617. case OP_Rowid: { /* out2 */
  78618. VdbeCursor *pC;
  78619. i64 v;
  78620. sqlite3_vtab *pVtab;
  78621. const sqlite3_module *pModule;
  78622. pOut = out2Prerelease(p, pOp);
  78623. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78624. pC = p->apCsr[pOp->p1];
  78625. assert( pC!=0 );
  78626. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  78627. if( pC->nullRow ){
  78628. pOut->flags = MEM_Null;
  78629. break;
  78630. }else if( pC->deferredMoveto ){
  78631. v = pC->movetoTarget;
  78632. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78633. }else if( pC->eCurType==CURTYPE_VTAB ){
  78634. assert( pC->uc.pVCur!=0 );
  78635. pVtab = pC->uc.pVCur->pVtab;
  78636. pModule = pVtab->pModule;
  78637. assert( pModule->xRowid );
  78638. rc = pModule->xRowid(pC->uc.pVCur, &v);
  78639. sqlite3VtabImportErrmsg(p, pVtab);
  78640. if( rc ) goto abort_due_to_error;
  78641. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  78642. }else{
  78643. assert( pC->eCurType==CURTYPE_BTREE );
  78644. assert( pC->uc.pCursor!=0 );
  78645. rc = sqlite3VdbeCursorRestore(pC);
  78646. if( rc ) goto abort_due_to_error;
  78647. if( pC->nullRow ){
  78648. pOut->flags = MEM_Null;
  78649. break;
  78650. }
  78651. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  78652. }
  78653. pOut->u.i = v;
  78654. break;
  78655. }
  78656. /* Opcode: NullRow P1 * * * *
  78657. **
  78658. ** Move the cursor P1 to a null row. Any OP_Column operations
  78659. ** that occur while the cursor is on the null row will always
  78660. ** write a NULL.
  78661. */
  78662. case OP_NullRow: {
  78663. VdbeCursor *pC;
  78664. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78665. pC = p->apCsr[pOp->p1];
  78666. assert( pC!=0 );
  78667. pC->nullRow = 1;
  78668. pC->cacheStatus = CACHE_STALE;
  78669. if( pC->eCurType==CURTYPE_BTREE ){
  78670. assert( pC->uc.pCursor!=0 );
  78671. sqlite3BtreeClearCursor(pC->uc.pCursor);
  78672. }
  78673. break;
  78674. }
  78675. /* Opcode: SeekEnd P1 * * * *
  78676. **
  78677. ** Position cursor P1 at the end of the btree for the purpose of
  78678. ** appending a new entry onto the btree.
  78679. **
  78680. ** It is assumed that the cursor is used only for appending and so
  78681. ** if the cursor is valid, then the cursor must already be pointing
  78682. ** at the end of the btree and so no changes are made to
  78683. ** the cursor.
  78684. */
  78685. /* Opcode: Last P1 P2 * * *
  78686. **
  78687. ** The next use of the Rowid or Column or Prev instruction for P1
  78688. ** will refer to the last entry in the database table or index.
  78689. ** If the table or index is empty and P2>0, then jump immediately to P2.
  78690. ** If P2 is 0 or if the table or index is not empty, fall through
  78691. ** to the following instruction.
  78692. **
  78693. ** This opcode leaves the cursor configured to move in reverse order,
  78694. ** from the end toward the beginning. In other words, the cursor is
  78695. ** configured to use Prev, not Next.
  78696. */
  78697. case OP_SeekEnd:
  78698. case OP_Last: { /* jump */
  78699. VdbeCursor *pC;
  78700. BtCursor *pCrsr;
  78701. int res;
  78702. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78703. pC = p->apCsr[pOp->p1];
  78704. assert( pC!=0 );
  78705. assert( pC->eCurType==CURTYPE_BTREE );
  78706. pCrsr = pC->uc.pCursor;
  78707. res = 0;
  78708. assert( pCrsr!=0 );
  78709. #ifdef SQLITE_DEBUG
  78710. pC->seekOp = pOp->opcode;
  78711. #endif
  78712. if( pOp->opcode==OP_SeekEnd ){
  78713. assert( pOp->p2==0 );
  78714. pC->seekResult = -1;
  78715. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  78716. break;
  78717. }
  78718. }
  78719. rc = sqlite3BtreeLast(pCrsr, &res);
  78720. pC->nullRow = (u8)res;
  78721. pC->deferredMoveto = 0;
  78722. pC->cacheStatus = CACHE_STALE;
  78723. if( rc ) goto abort_due_to_error;
  78724. if( pOp->p2>0 ){
  78725. VdbeBranchTaken(res!=0,2);
  78726. if( res ) goto jump_to_p2;
  78727. }
  78728. break;
  78729. }
  78730. /* Opcode: IfSmaller P1 P2 P3 * *
  78731. **
  78732. ** Estimate the number of rows in the table P1. Jump to P2 if that
  78733. ** estimate is less than approximately 2**(0.1*P3).
  78734. */
  78735. case OP_IfSmaller: { /* jump */
  78736. VdbeCursor *pC;
  78737. BtCursor *pCrsr;
  78738. int res;
  78739. i64 sz;
  78740. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78741. pC = p->apCsr[pOp->p1];
  78742. assert( pC!=0 );
  78743. pCrsr = pC->uc.pCursor;
  78744. assert( pCrsr );
  78745. rc = sqlite3BtreeFirst(pCrsr, &res);
  78746. if( rc ) goto abort_due_to_error;
  78747. if( res==0 ){
  78748. sz = sqlite3BtreeRowCountEst(pCrsr);
  78749. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  78750. }
  78751. VdbeBranchTaken(res!=0,2);
  78752. if( res ) goto jump_to_p2;
  78753. break;
  78754. }
  78755. /* Opcode: SorterSort P1 P2 * * *
  78756. **
  78757. ** After all records have been inserted into the Sorter object
  78758. ** identified by P1, invoke this opcode to actually do the sorting.
  78759. ** Jump to P2 if there are no records to be sorted.
  78760. **
  78761. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  78762. ** for Sorter objects.
  78763. */
  78764. /* Opcode: Sort P1 P2 * * *
  78765. **
  78766. ** This opcode does exactly the same thing as OP_Rewind except that
  78767. ** it increments an undocumented global variable used for testing.
  78768. **
  78769. ** Sorting is accomplished by writing records into a sorting index,
  78770. ** then rewinding that index and playing it back from beginning to
  78771. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  78772. ** rewinding so that the global variable will be incremented and
  78773. ** regression tests can determine whether or not the optimizer is
  78774. ** correctly optimizing out sorts.
  78775. */
  78776. case OP_SorterSort: /* jump */
  78777. case OP_Sort: { /* jump */
  78778. #ifdef SQLITE_TEST
  78779. sqlite3_sort_count++;
  78780. sqlite3_search_count--;
  78781. #endif
  78782. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  78783. /* Fall through into OP_Rewind */
  78784. }
  78785. /* Opcode: Rewind P1 P2 * * *
  78786. **
  78787. ** The next use of the Rowid or Column or Next instruction for P1
  78788. ** will refer to the first entry in the database table or index.
  78789. ** If the table or index is empty, jump immediately to P2.
  78790. ** If the table or index is not empty, fall through to the following
  78791. ** instruction.
  78792. **
  78793. ** This opcode leaves the cursor configured to move in forward order,
  78794. ** from the beginning toward the end. In other words, the cursor is
  78795. ** configured to use Next, not Prev.
  78796. */
  78797. case OP_Rewind: { /* jump */
  78798. VdbeCursor *pC;
  78799. BtCursor *pCrsr;
  78800. int res;
  78801. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78802. pC = p->apCsr[pOp->p1];
  78803. assert( pC!=0 );
  78804. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  78805. res = 1;
  78806. #ifdef SQLITE_DEBUG
  78807. pC->seekOp = OP_Rewind;
  78808. #endif
  78809. if( isSorter(pC) ){
  78810. rc = sqlite3VdbeSorterRewind(pC, &res);
  78811. }else{
  78812. assert( pC->eCurType==CURTYPE_BTREE );
  78813. pCrsr = pC->uc.pCursor;
  78814. assert( pCrsr );
  78815. rc = sqlite3BtreeFirst(pCrsr, &res);
  78816. pC->deferredMoveto = 0;
  78817. pC->cacheStatus = CACHE_STALE;
  78818. }
  78819. if( rc ) goto abort_due_to_error;
  78820. pC->nullRow = (u8)res;
  78821. assert( pOp->p2>0 && pOp->p2<p->nOp );
  78822. VdbeBranchTaken(res!=0,2);
  78823. if( res ) goto jump_to_p2;
  78824. break;
  78825. }
  78826. /* Opcode: Next P1 P2 P3 P4 P5
  78827. **
  78828. ** Advance cursor P1 so that it points to the next key/data pair in its
  78829. ** table or index. If there are no more key/value pairs then fall through
  78830. ** to the following instruction. But if the cursor advance was successful,
  78831. ** jump immediately to P2.
  78832. **
  78833. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  78834. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  78835. ** to follow SeekLT, SeekLE, or OP_Last.
  78836. **
  78837. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  78838. ** been opened prior to this opcode or the program will segfault.
  78839. **
  78840. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78841. ** means P1 is an SQL index and that this instruction could have been
  78842. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78843. ** always either 0 or 1.
  78844. **
  78845. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78846. ** sqlite3BtreeNext().
  78847. **
  78848. ** If P5 is positive and the jump is taken, then event counter
  78849. ** number P5-1 in the prepared statement is incremented.
  78850. **
  78851. ** See also: Prev, NextIfOpen
  78852. */
  78853. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  78854. **
  78855. ** This opcode works just like Next except that if cursor P1 is not
  78856. ** open it behaves a no-op.
  78857. */
  78858. /* Opcode: Prev P1 P2 P3 P4 P5
  78859. **
  78860. ** Back up cursor P1 so that it points to the previous key/data pair in its
  78861. ** table or index. If there is no previous key/value pairs then fall through
  78862. ** to the following instruction. But if the cursor backup was successful,
  78863. ** jump immediately to P2.
  78864. **
  78865. **
  78866. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  78867. ** OP_Last opcode used to position the cursor. Prev is not allowed
  78868. ** to follow SeekGT, SeekGE, or OP_Rewind.
  78869. **
  78870. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  78871. ** not open then the behavior is undefined.
  78872. **
  78873. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78874. ** means P1 is an SQL index and that this instruction could have been
  78875. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78876. ** always either 0 or 1.
  78877. **
  78878. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78879. ** sqlite3BtreePrevious().
  78880. **
  78881. ** If P5 is positive and the jump is taken, then event counter
  78882. ** number P5-1 in the prepared statement is incremented.
  78883. */
  78884. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  78885. **
  78886. ** This opcode works just like Prev except that if cursor P1 is not
  78887. ** open it behaves a no-op.
  78888. */
  78889. /* Opcode: SorterNext P1 P2 * * P5
  78890. **
  78891. ** This opcode works just like OP_Next except that P1 must be a
  78892. ** sorter object for which the OP_SorterSort opcode has been
  78893. ** invoked. This opcode advances the cursor to the next sorted
  78894. ** record, or jumps to P2 if there are no more sorted records.
  78895. */
  78896. case OP_SorterNext: { /* jump */
  78897. VdbeCursor *pC;
  78898. pC = p->apCsr[pOp->p1];
  78899. assert( isSorter(pC) );
  78900. rc = sqlite3VdbeSorterNext(db, pC);
  78901. goto next_tail;
  78902. case OP_PrevIfOpen: /* jump */
  78903. case OP_NextIfOpen: /* jump */
  78904. if( p->apCsr[pOp->p1]==0 ) break;
  78905. /* Fall through */
  78906. case OP_Prev: /* jump */
  78907. case OP_Next: /* jump */
  78908. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78909. assert( pOp->p5<ArraySize(p->aCounter) );
  78910. pC = p->apCsr[pOp->p1];
  78911. assert( pC!=0 );
  78912. assert( pC->deferredMoveto==0 );
  78913. assert( pC->eCurType==CURTYPE_BTREE );
  78914. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  78915. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  78916. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  78917. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  78918. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  78919. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  78920. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  78921. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  78922. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  78923. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  78924. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  78925. || pC->seekOp==OP_Last );
  78926. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  78927. next_tail:
  78928. pC->cacheStatus = CACHE_STALE;
  78929. VdbeBranchTaken(rc==SQLITE_OK,2);
  78930. if( rc==SQLITE_OK ){
  78931. pC->nullRow = 0;
  78932. p->aCounter[pOp->p5]++;
  78933. #ifdef SQLITE_TEST
  78934. sqlite3_search_count++;
  78935. #endif
  78936. goto jump_to_p2_and_check_for_interrupt;
  78937. }
  78938. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  78939. rc = SQLITE_OK;
  78940. pC->nullRow = 1;
  78941. goto check_for_interrupt;
  78942. }
  78943. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  78944. ** Synopsis: key=r[P2]
  78945. **
  78946. ** Register P2 holds an SQL index key made using the
  78947. ** MakeRecord instructions. This opcode writes that key
  78948. ** into the index P1. Data for the entry is nil.
  78949. **
  78950. ** If P4 is not zero, then it is the number of values in the unpacked
  78951. ** key of reg(P2). In that case, P3 is the index of the first register
  78952. ** for the unpacked key. The availability of the unpacked key can sometimes
  78953. ** be an optimization.
  78954. **
  78955. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  78956. ** that this insert is likely to be an append.
  78957. **
  78958. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  78959. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  78960. ** then the change counter is unchanged.
  78961. **
  78962. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  78963. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  78964. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  78965. ** seeks on the cursor or if the most recent seek used a key equivalent
  78966. ** to P2.
  78967. **
  78968. ** This instruction only works for indices. The equivalent instruction
  78969. ** for tables is OP_Insert.
  78970. */
  78971. /* Opcode: SorterInsert P1 P2 * * *
  78972. ** Synopsis: key=r[P2]
  78973. **
  78974. ** Register P2 holds an SQL index key made using the
  78975. ** MakeRecord instructions. This opcode writes that key
  78976. ** into the sorter P1. Data for the entry is nil.
  78977. */
  78978. case OP_SorterInsert: /* in2 */
  78979. case OP_IdxInsert: { /* in2 */
  78980. VdbeCursor *pC;
  78981. BtreePayload x;
  78982. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78983. pC = p->apCsr[pOp->p1];
  78984. assert( pC!=0 );
  78985. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  78986. pIn2 = &aMem[pOp->p2];
  78987. assert( pIn2->flags & MEM_Blob );
  78988. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  78989. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  78990. assert( pC->isTable==0 );
  78991. rc = ExpandBlob(pIn2);
  78992. if( rc ) goto abort_due_to_error;
  78993. if( pOp->opcode==OP_SorterInsert ){
  78994. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  78995. }else{
  78996. x.nKey = pIn2->n;
  78997. x.pKey = pIn2->z;
  78998. x.aMem = aMem + pOp->p3;
  78999. x.nMem = (u16)pOp->p4.i;
  79000. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  79001. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  79002. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  79003. );
  79004. assert( pC->deferredMoveto==0 );
  79005. pC->cacheStatus = CACHE_STALE;
  79006. }
  79007. if( rc) goto abort_due_to_error;
  79008. break;
  79009. }
  79010. /* Opcode: IdxDelete P1 P2 P3 * *
  79011. ** Synopsis: key=r[P2@P3]
  79012. **
  79013. ** The content of P3 registers starting at register P2 form
  79014. ** an unpacked index key. This opcode removes that entry from the
  79015. ** index opened by cursor P1.
  79016. */
  79017. case OP_IdxDelete: {
  79018. VdbeCursor *pC;
  79019. BtCursor *pCrsr;
  79020. int res;
  79021. UnpackedRecord r;
  79022. assert( pOp->p3>0 );
  79023. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  79024. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79025. pC = p->apCsr[pOp->p1];
  79026. assert( pC!=0 );
  79027. assert( pC->eCurType==CURTYPE_BTREE );
  79028. pCrsr = pC->uc.pCursor;
  79029. assert( pCrsr!=0 );
  79030. assert( pOp->p5==0 );
  79031. r.pKeyInfo = pC->pKeyInfo;
  79032. r.nField = (u16)pOp->p3;
  79033. r.default_rc = 0;
  79034. r.aMem = &aMem[pOp->p2];
  79035. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  79036. if( rc ) goto abort_due_to_error;
  79037. if( res==0 ){
  79038. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  79039. if( rc ) goto abort_due_to_error;
  79040. }
  79041. assert( pC->deferredMoveto==0 );
  79042. pC->cacheStatus = CACHE_STALE;
  79043. pC->seekResult = 0;
  79044. break;
  79045. }
  79046. /* Opcode: DeferredSeek P1 * P3 P4 *
  79047. ** Synopsis: Move P3 to P1.rowid if needed
  79048. **
  79049. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  79050. ** table. This opcode does a deferred seek of the P3 table cursor
  79051. ** to the row that corresponds to the current row of P1.
  79052. **
  79053. ** This is a deferred seek. Nothing actually happens until
  79054. ** the cursor is used to read a record. That way, if no reads
  79055. ** occur, no unnecessary I/O happens.
  79056. **
  79057. ** P4 may be an array of integers (type P4_INTARRAY) containing
  79058. ** one entry for each column in the P3 table. If array entry a(i)
  79059. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  79060. ** equivalent to performing the deferred seek and then reading column i
  79061. ** from P1. This information is stored in P3 and used to redirect
  79062. ** reads against P3 over to P1, thus possibly avoiding the need to
  79063. ** seek and read cursor P3.
  79064. */
  79065. /* Opcode: IdxRowid P1 P2 * * *
  79066. ** Synopsis: r[P2]=rowid
  79067. **
  79068. ** Write into register P2 an integer which is the last entry in the record at
  79069. ** the end of the index key pointed to by cursor P1. This integer should be
  79070. ** the rowid of the table entry to which this index entry points.
  79071. **
  79072. ** See also: Rowid, MakeRecord.
  79073. */
  79074. case OP_DeferredSeek:
  79075. case OP_IdxRowid: { /* out2 */
  79076. VdbeCursor *pC; /* The P1 index cursor */
  79077. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  79078. i64 rowid; /* Rowid that P1 current points to */
  79079. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79080. pC = p->apCsr[pOp->p1];
  79081. assert( pC!=0 );
  79082. assert( pC->eCurType==CURTYPE_BTREE );
  79083. assert( pC->uc.pCursor!=0 );
  79084. assert( pC->isTable==0 );
  79085. assert( pC->deferredMoveto==0 );
  79086. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  79087. /* The IdxRowid and Seek opcodes are combined because of the commonality
  79088. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  79089. rc = sqlite3VdbeCursorRestore(pC);
  79090. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  79091. ** out from under the cursor. That will never happens for an IdxRowid
  79092. ** or Seek opcode */
  79093. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  79094. if( !pC->nullRow ){
  79095. rowid = 0; /* Not needed. Only used to silence a warning. */
  79096. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  79097. if( rc!=SQLITE_OK ){
  79098. goto abort_due_to_error;
  79099. }
  79100. if( pOp->opcode==OP_DeferredSeek ){
  79101. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  79102. pTabCur = p->apCsr[pOp->p3];
  79103. assert( pTabCur!=0 );
  79104. assert( pTabCur->eCurType==CURTYPE_BTREE );
  79105. assert( pTabCur->uc.pCursor!=0 );
  79106. assert( pTabCur->isTable );
  79107. pTabCur->nullRow = 0;
  79108. pTabCur->movetoTarget = rowid;
  79109. pTabCur->deferredMoveto = 1;
  79110. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  79111. pTabCur->aAltMap = pOp->p4.ai;
  79112. pTabCur->pAltCursor = pC;
  79113. }else{
  79114. pOut = out2Prerelease(p, pOp);
  79115. pOut->u.i = rowid;
  79116. }
  79117. }else{
  79118. assert( pOp->opcode==OP_IdxRowid );
  79119. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  79120. }
  79121. break;
  79122. }
  79123. /* Opcode: IdxGE P1 P2 P3 P4 P5
  79124. ** Synopsis: key=r[P3@P4]
  79125. **
  79126. ** The P4 register values beginning with P3 form an unpacked index
  79127. ** key that omits the PRIMARY KEY. Compare this key value against the index
  79128. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  79129. ** fields at the end.
  79130. **
  79131. ** If the P1 index entry is greater than or equal to the key value
  79132. ** then jump to P2. Otherwise fall through to the next instruction.
  79133. */
  79134. /* Opcode: IdxGT P1 P2 P3 P4 P5
  79135. ** Synopsis: key=r[P3@P4]
  79136. **
  79137. ** The P4 register values beginning with P3 form an unpacked index
  79138. ** key that omits the PRIMARY KEY. Compare this key value against the index
  79139. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  79140. ** fields at the end.
  79141. **
  79142. ** If the P1 index entry is greater than the key value
  79143. ** then jump to P2. Otherwise fall through to the next instruction.
  79144. */
  79145. /* Opcode: IdxLT P1 P2 P3 P4 P5
  79146. ** Synopsis: key=r[P3@P4]
  79147. **
  79148. ** The P4 register values beginning with P3 form an unpacked index
  79149. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  79150. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  79151. ** ROWID on the P1 index.
  79152. **
  79153. ** If the P1 index entry is less than the key value then jump to P2.
  79154. ** Otherwise fall through to the next instruction.
  79155. */
  79156. /* Opcode: IdxLE P1 P2 P3 P4 P5
  79157. ** Synopsis: key=r[P3@P4]
  79158. **
  79159. ** The P4 register values beginning with P3 form an unpacked index
  79160. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  79161. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  79162. ** ROWID on the P1 index.
  79163. **
  79164. ** If the P1 index entry is less than or equal to the key value then jump
  79165. ** to P2. Otherwise fall through to the next instruction.
  79166. */
  79167. case OP_IdxLE: /* jump */
  79168. case OP_IdxGT: /* jump */
  79169. case OP_IdxLT: /* jump */
  79170. case OP_IdxGE: { /* jump */
  79171. VdbeCursor *pC;
  79172. int res;
  79173. UnpackedRecord r;
  79174. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79175. pC = p->apCsr[pOp->p1];
  79176. assert( pC!=0 );
  79177. assert( pC->isOrdered );
  79178. assert( pC->eCurType==CURTYPE_BTREE );
  79179. assert( pC->uc.pCursor!=0);
  79180. assert( pC->deferredMoveto==0 );
  79181. assert( pOp->p5==0 || pOp->p5==1 );
  79182. assert( pOp->p4type==P4_INT32 );
  79183. r.pKeyInfo = pC->pKeyInfo;
  79184. r.nField = (u16)pOp->p4.i;
  79185. if( pOp->opcode<OP_IdxLT ){
  79186. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  79187. r.default_rc = -1;
  79188. }else{
  79189. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  79190. r.default_rc = 0;
  79191. }
  79192. r.aMem = &aMem[pOp->p3];
  79193. #ifdef SQLITE_DEBUG
  79194. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  79195. #endif
  79196. res = 0; /* Not needed. Only used to silence a warning. */
  79197. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  79198. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  79199. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  79200. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  79201. res = -res;
  79202. }else{
  79203. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  79204. res++;
  79205. }
  79206. VdbeBranchTaken(res>0,2);
  79207. if( rc ) goto abort_due_to_error;
  79208. if( res>0 ) goto jump_to_p2;
  79209. break;
  79210. }
  79211. /* Opcode: Destroy P1 P2 P3 * *
  79212. **
  79213. ** Delete an entire database table or index whose root page in the database
  79214. ** file is given by P1.
  79215. **
  79216. ** The table being destroyed is in the main database file if P3==0. If
  79217. ** P3==1 then the table to be clear is in the auxiliary database file
  79218. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  79219. **
  79220. ** If AUTOVACUUM is enabled then it is possible that another root page
  79221. ** might be moved into the newly deleted root page in order to keep all
  79222. ** root pages contiguous at the beginning of the database. The former
  79223. ** value of the root page that moved - its value before the move occurred -
  79224. ** is stored in register P2. If no page movement was required (because the
  79225. ** table being dropped was already the last one in the database) then a
  79226. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  79227. ** is stored in register P2.
  79228. **
  79229. ** This opcode throws an error if there are any active reader VMs when
  79230. ** it is invoked. This is done to avoid the difficulty associated with
  79231. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  79232. ** database. This error is thrown even if the database is not an AUTOVACUUM
  79233. ** db in order to avoid introducing an incompatibility between autovacuum
  79234. ** and non-autovacuum modes.
  79235. **
  79236. ** See also: Clear
  79237. */
  79238. case OP_Destroy: { /* out2 */
  79239. int iMoved;
  79240. int iDb;
  79241. assert( p->readOnly==0 );
  79242. assert( pOp->p1>1 );
  79243. pOut = out2Prerelease(p, pOp);
  79244. pOut->flags = MEM_Null;
  79245. if( db->nVdbeRead > db->nVDestroy+1 ){
  79246. rc = SQLITE_LOCKED;
  79247. p->errorAction = OE_Abort;
  79248. goto abort_due_to_error;
  79249. }else{
  79250. iDb = pOp->p3;
  79251. assert( DbMaskTest(p->btreeMask, iDb) );
  79252. iMoved = 0; /* Not needed. Only to silence a warning. */
  79253. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  79254. pOut->flags = MEM_Int;
  79255. pOut->u.i = iMoved;
  79256. if( rc ) goto abort_due_to_error;
  79257. #ifndef SQLITE_OMIT_AUTOVACUUM
  79258. if( iMoved!=0 ){
  79259. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  79260. /* All OP_Destroy operations occur on the same btree */
  79261. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  79262. resetSchemaOnFault = iDb+1;
  79263. }
  79264. #endif
  79265. }
  79266. break;
  79267. }
  79268. /* Opcode: Clear P1 P2 P3
  79269. **
  79270. ** Delete all contents of the database table or index whose root page
  79271. ** in the database file is given by P1. But, unlike Destroy, do not
  79272. ** remove the table or index from the database file.
  79273. **
  79274. ** The table being clear is in the main database file if P2==0. If
  79275. ** P2==1 then the table to be clear is in the auxiliary database file
  79276. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  79277. **
  79278. ** If the P3 value is non-zero, then the table referred to must be an
  79279. ** intkey table (an SQL table, not an index). In this case the row change
  79280. ** count is incremented by the number of rows in the table being cleared.
  79281. ** If P3 is greater than zero, then the value stored in register P3 is
  79282. ** also incremented by the number of rows in the table being cleared.
  79283. **
  79284. ** See also: Destroy
  79285. */
  79286. case OP_Clear: {
  79287. int nChange;
  79288. nChange = 0;
  79289. assert( p->readOnly==0 );
  79290. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  79291. rc = sqlite3BtreeClearTable(
  79292. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  79293. );
  79294. if( pOp->p3 ){
  79295. p->nChange += nChange;
  79296. if( pOp->p3>0 ){
  79297. assert( memIsValid(&aMem[pOp->p3]) );
  79298. memAboutToChange(p, &aMem[pOp->p3]);
  79299. aMem[pOp->p3].u.i += nChange;
  79300. }
  79301. }
  79302. if( rc ) goto abort_due_to_error;
  79303. break;
  79304. }
  79305. /* Opcode: ResetSorter P1 * * * *
  79306. **
  79307. ** Delete all contents from the ephemeral table or sorter
  79308. ** that is open on cursor P1.
  79309. **
  79310. ** This opcode only works for cursors used for sorting and
  79311. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  79312. */
  79313. case OP_ResetSorter: {
  79314. VdbeCursor *pC;
  79315. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79316. pC = p->apCsr[pOp->p1];
  79317. assert( pC!=0 );
  79318. if( isSorter(pC) ){
  79319. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  79320. }else{
  79321. assert( pC->eCurType==CURTYPE_BTREE );
  79322. assert( pC->isEphemeral );
  79323. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  79324. if( rc ) goto abort_due_to_error;
  79325. }
  79326. break;
  79327. }
  79328. /* Opcode: CreateBtree P1 P2 P3 * *
  79329. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  79330. **
  79331. ** Allocate a new b-tree in the main database file if P1==0 or in the
  79332. ** TEMP database file if P1==1 or in an attached database if
  79333. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  79334. ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
  79335. ** The root page number of the new b-tree is stored in register P2.
  79336. */
  79337. case OP_CreateBtree: { /* out2 */
  79338. int pgno;
  79339. Db *pDb;
  79340. pOut = out2Prerelease(p, pOp);
  79341. pgno = 0;
  79342. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  79343. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79344. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79345. assert( p->readOnly==0 );
  79346. pDb = &db->aDb[pOp->p1];
  79347. assert( pDb->pBt!=0 );
  79348. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  79349. if( rc ) goto abort_due_to_error;
  79350. pOut->u.i = pgno;
  79351. break;
  79352. }
  79353. /* Opcode: SqlExec * * * P4 *
  79354. **
  79355. ** Run the SQL statement or statements specified in the P4 string.
  79356. */
  79357. case OP_SqlExec: {
  79358. db->nSqlExec++;
  79359. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  79360. db->nSqlExec--;
  79361. if( rc ) goto abort_due_to_error;
  79362. break;
  79363. }
  79364. /* Opcode: ParseSchema P1 * * P4 *
  79365. **
  79366. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  79367. ** that match the WHERE clause P4.
  79368. **
  79369. ** This opcode invokes the parser to create a new virtual machine,
  79370. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  79371. */
  79372. case OP_ParseSchema: {
  79373. int iDb;
  79374. const char *zMaster;
  79375. char *zSql;
  79376. InitData initData;
  79377. /* Any prepared statement that invokes this opcode will hold mutexes
  79378. ** on every btree. This is a prerequisite for invoking
  79379. ** sqlite3InitCallback().
  79380. */
  79381. #ifdef SQLITE_DEBUG
  79382. for(iDb=0; iDb<db->nDb; iDb++){
  79383. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  79384. }
  79385. #endif
  79386. iDb = pOp->p1;
  79387. assert( iDb>=0 && iDb<db->nDb );
  79388. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  79389. /* Used to be a conditional */ {
  79390. zMaster = MASTER_NAME;
  79391. initData.db = db;
  79392. initData.iDb = pOp->p1;
  79393. initData.pzErrMsg = &p->zErrMsg;
  79394. zSql = sqlite3MPrintf(db,
  79395. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  79396. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  79397. if( zSql==0 ){
  79398. rc = SQLITE_NOMEM_BKPT;
  79399. }else{
  79400. assert( db->init.busy==0 );
  79401. db->init.busy = 1;
  79402. initData.rc = SQLITE_OK;
  79403. assert( !db->mallocFailed );
  79404. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  79405. if( rc==SQLITE_OK ) rc = initData.rc;
  79406. sqlite3DbFreeNN(db, zSql);
  79407. db->init.busy = 0;
  79408. }
  79409. }
  79410. if( rc ){
  79411. sqlite3ResetAllSchemasOfConnection(db);
  79412. if( rc==SQLITE_NOMEM ){
  79413. goto no_mem;
  79414. }
  79415. goto abort_due_to_error;
  79416. }
  79417. break;
  79418. }
  79419. #if !defined(SQLITE_OMIT_ANALYZE)
  79420. /* Opcode: LoadAnalysis P1 * * * *
  79421. **
  79422. ** Read the sqlite_stat1 table for database P1 and load the content
  79423. ** of that table into the internal index hash table. This will cause
  79424. ** the analysis to be used when preparing all subsequent queries.
  79425. */
  79426. case OP_LoadAnalysis: {
  79427. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79428. rc = sqlite3AnalysisLoad(db, pOp->p1);
  79429. if( rc ) goto abort_due_to_error;
  79430. break;
  79431. }
  79432. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  79433. /* Opcode: DropTable P1 * * P4 *
  79434. **
  79435. ** Remove the internal (in-memory) data structures that describe
  79436. ** the table named P4 in database P1. This is called after a table
  79437. ** is dropped from disk (using the Destroy opcode) in order to keep
  79438. ** the internal representation of the
  79439. ** schema consistent with what is on disk.
  79440. */
  79441. case OP_DropTable: {
  79442. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  79443. break;
  79444. }
  79445. /* Opcode: DropIndex P1 * * P4 *
  79446. **
  79447. ** Remove the internal (in-memory) data structures that describe
  79448. ** the index named P4 in database P1. This is called after an index
  79449. ** is dropped from disk (using the Destroy opcode)
  79450. ** in order to keep the internal representation of the
  79451. ** schema consistent with what is on disk.
  79452. */
  79453. case OP_DropIndex: {
  79454. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  79455. break;
  79456. }
  79457. /* Opcode: DropTrigger P1 * * P4 *
  79458. **
  79459. ** Remove the internal (in-memory) data structures that describe
  79460. ** the trigger named P4 in database P1. This is called after a trigger
  79461. ** is dropped from disk (using the Destroy opcode) in order to keep
  79462. ** the internal representation of the
  79463. ** schema consistent with what is on disk.
  79464. */
  79465. case OP_DropTrigger: {
  79466. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  79467. break;
  79468. }
  79469. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  79470. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  79471. **
  79472. ** Do an analysis of the currently open database. Store in
  79473. ** register P1 the text of an error message describing any problems.
  79474. ** If no problems are found, store a NULL in register P1.
  79475. **
  79476. ** The register P3 contains one less than the maximum number of allowed errors.
  79477. ** At most reg(P3) errors will be reported.
  79478. ** In other words, the analysis stops as soon as reg(P1) errors are
  79479. ** seen. Reg(P1) is updated with the number of errors remaining.
  79480. **
  79481. ** The root page numbers of all tables in the database are integers
  79482. ** stored in P4_INTARRAY argument.
  79483. **
  79484. ** If P5 is not zero, the check is done on the auxiliary database
  79485. ** file, not the main database file.
  79486. **
  79487. ** This opcode is used to implement the integrity_check pragma.
  79488. */
  79489. case OP_IntegrityCk: {
  79490. int nRoot; /* Number of tables to check. (Number of root pages.) */
  79491. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  79492. int nErr; /* Number of errors reported */
  79493. char *z; /* Text of the error report */
  79494. Mem *pnErr; /* Register keeping track of errors remaining */
  79495. assert( p->bIsReader );
  79496. nRoot = pOp->p2;
  79497. aRoot = pOp->p4.ai;
  79498. assert( nRoot>0 );
  79499. assert( aRoot[0]==nRoot );
  79500. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79501. pnErr = &aMem[pOp->p3];
  79502. assert( (pnErr->flags & MEM_Int)!=0 );
  79503. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  79504. pIn1 = &aMem[pOp->p1];
  79505. assert( pOp->p5<db->nDb );
  79506. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  79507. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  79508. (int)pnErr->u.i+1, &nErr);
  79509. sqlite3VdbeMemSetNull(pIn1);
  79510. if( nErr==0 ){
  79511. assert( z==0 );
  79512. }else if( z==0 ){
  79513. goto no_mem;
  79514. }else{
  79515. pnErr->u.i -= nErr-1;
  79516. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  79517. }
  79518. UPDATE_MAX_BLOBSIZE(pIn1);
  79519. sqlite3VdbeChangeEncoding(pIn1, encoding);
  79520. break;
  79521. }
  79522. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  79523. /* Opcode: RowSetAdd P1 P2 * * *
  79524. ** Synopsis: rowset(P1)=r[P2]
  79525. **
  79526. ** Insert the integer value held by register P2 into a RowSet object
  79527. ** held in register P1.
  79528. **
  79529. ** An assertion fails if P2 is not an integer.
  79530. */
  79531. case OP_RowSetAdd: { /* in1, in2 */
  79532. pIn1 = &aMem[pOp->p1];
  79533. pIn2 = &aMem[pOp->p2];
  79534. assert( (pIn2->flags & MEM_Int)!=0 );
  79535. if( (pIn1->flags & MEM_RowSet)==0 ){
  79536. sqlite3VdbeMemSetRowSet(pIn1);
  79537. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  79538. }
  79539. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  79540. break;
  79541. }
  79542. /* Opcode: RowSetRead P1 P2 P3 * *
  79543. ** Synopsis: r[P3]=rowset(P1)
  79544. **
  79545. ** Extract the smallest value from the RowSet object in P1
  79546. ** and put that value into register P3.
  79547. ** Or, if RowSet object P1 is initially empty, leave P3
  79548. ** unchanged and jump to instruction P2.
  79549. */
  79550. case OP_RowSetRead: { /* jump, in1, out3 */
  79551. i64 val;
  79552. pIn1 = &aMem[pOp->p1];
  79553. if( (pIn1->flags & MEM_RowSet)==0
  79554. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  79555. ){
  79556. /* The boolean index is empty */
  79557. sqlite3VdbeMemSetNull(pIn1);
  79558. VdbeBranchTaken(1,2);
  79559. goto jump_to_p2_and_check_for_interrupt;
  79560. }else{
  79561. /* A value was pulled from the index */
  79562. VdbeBranchTaken(0,2);
  79563. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  79564. }
  79565. goto check_for_interrupt;
  79566. }
  79567. /* Opcode: RowSetTest P1 P2 P3 P4
  79568. ** Synopsis: if r[P3] in rowset(P1) goto P2
  79569. **
  79570. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  79571. ** contains a RowSet object and that RowSet object contains
  79572. ** the value held in P3, jump to register P2. Otherwise, insert the
  79573. ** integer in P3 into the RowSet and continue on to the
  79574. ** next opcode.
  79575. **
  79576. ** The RowSet object is optimized for the case where sets of integers
  79577. ** are inserted in distinct phases, which each set contains no duplicates.
  79578. ** Each set is identified by a unique P4 value. The first set
  79579. ** must have P4==0, the final set must have P4==-1, and for all other sets
  79580. ** must have P4>0.
  79581. **
  79582. ** This allows optimizations: (a) when P4==0 there is no need to test
  79583. ** the RowSet object for P3, as it is guaranteed not to contain it,
  79584. ** (b) when P4==-1 there is no need to insert the value, as it will
  79585. ** never be tested for, and (c) when a value that is part of set X is
  79586. ** inserted, there is no need to search to see if the same value was
  79587. ** previously inserted as part of set X (only if it was previously
  79588. ** inserted as part of some other set).
  79589. */
  79590. case OP_RowSetTest: { /* jump, in1, in3 */
  79591. int iSet;
  79592. int exists;
  79593. pIn1 = &aMem[pOp->p1];
  79594. pIn3 = &aMem[pOp->p3];
  79595. iSet = pOp->p4.i;
  79596. assert( pIn3->flags&MEM_Int );
  79597. /* If there is anything other than a rowset object in memory cell P1,
  79598. ** delete it now and initialize P1 with an empty rowset
  79599. */
  79600. if( (pIn1->flags & MEM_RowSet)==0 ){
  79601. sqlite3VdbeMemSetRowSet(pIn1);
  79602. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  79603. }
  79604. assert( pOp->p4type==P4_INT32 );
  79605. assert( iSet==-1 || iSet>=0 );
  79606. if( iSet ){
  79607. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  79608. VdbeBranchTaken(exists!=0,2);
  79609. if( exists ) goto jump_to_p2;
  79610. }
  79611. if( iSet>=0 ){
  79612. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  79613. }
  79614. break;
  79615. }
  79616. #ifndef SQLITE_OMIT_TRIGGER
  79617. /* Opcode: Program P1 P2 P3 P4 P5
  79618. **
  79619. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  79620. **
  79621. ** P1 contains the address of the memory cell that contains the first memory
  79622. ** cell in an array of values used as arguments to the sub-program. P2
  79623. ** contains the address to jump to if the sub-program throws an IGNORE
  79624. ** exception using the RAISE() function. Register P3 contains the address
  79625. ** of a memory cell in this (the parent) VM that is used to allocate the
  79626. ** memory required by the sub-vdbe at runtime.
  79627. **
  79628. ** P4 is a pointer to the VM containing the trigger program.
  79629. **
  79630. ** If P5 is non-zero, then recursive program invocation is enabled.
  79631. */
  79632. case OP_Program: { /* jump */
  79633. int nMem; /* Number of memory registers for sub-program */
  79634. int nByte; /* Bytes of runtime space required for sub-program */
  79635. Mem *pRt; /* Register to allocate runtime space */
  79636. Mem *pMem; /* Used to iterate through memory cells */
  79637. Mem *pEnd; /* Last memory cell in new array */
  79638. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  79639. SubProgram *pProgram; /* Sub-program to execute */
  79640. void *t; /* Token identifying trigger */
  79641. pProgram = pOp->p4.pProgram;
  79642. pRt = &aMem[pOp->p3];
  79643. assert( pProgram->nOp>0 );
  79644. /* If the p5 flag is clear, then recursive invocation of triggers is
  79645. ** disabled for backwards compatibility (p5 is set if this sub-program
  79646. ** is really a trigger, not a foreign key action, and the flag set
  79647. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  79648. **
  79649. ** It is recursive invocation of triggers, at the SQL level, that is
  79650. ** disabled. In some cases a single trigger may generate more than one
  79651. ** SubProgram (if the trigger may be executed with more than one different
  79652. ** ON CONFLICT algorithm). SubProgram structures associated with a
  79653. ** single trigger all have the same value for the SubProgram.token
  79654. ** variable. */
  79655. if( pOp->p5 ){
  79656. t = pProgram->token;
  79657. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  79658. if( pFrame ) break;
  79659. }
  79660. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  79661. rc = SQLITE_ERROR;
  79662. sqlite3VdbeError(p, "too many levels of trigger recursion");
  79663. goto abort_due_to_error;
  79664. }
  79665. /* Register pRt is used to store the memory required to save the state
  79666. ** of the current program, and the memory required at runtime to execute
  79667. ** the trigger program. If this trigger has been fired before, then pRt
  79668. ** is already allocated. Otherwise, it must be initialized. */
  79669. if( (pRt->flags&MEM_Frame)==0 ){
  79670. /* SubProgram.nMem is set to the number of memory cells used by the
  79671. ** program stored in SubProgram.aOp. As well as these, one memory
  79672. ** cell is required for each cursor used by the program. Set local
  79673. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  79674. */
  79675. nMem = pProgram->nMem + pProgram->nCsr;
  79676. assert( nMem>0 );
  79677. if( pProgram->nCsr==0 ) nMem++;
  79678. nByte = ROUND8(sizeof(VdbeFrame))
  79679. + nMem * sizeof(Mem)
  79680. + pProgram->nCsr * sizeof(VdbeCursor*)
  79681. + (pProgram->nOp + 7)/8;
  79682. pFrame = sqlite3DbMallocZero(db, nByte);
  79683. if( !pFrame ){
  79684. goto no_mem;
  79685. }
  79686. sqlite3VdbeMemRelease(pRt);
  79687. pRt->flags = MEM_Frame;
  79688. pRt->u.pFrame = pFrame;
  79689. pFrame->v = p;
  79690. pFrame->nChildMem = nMem;
  79691. pFrame->nChildCsr = pProgram->nCsr;
  79692. pFrame->pc = (int)(pOp - aOp);
  79693. pFrame->aMem = p->aMem;
  79694. pFrame->nMem = p->nMem;
  79695. pFrame->apCsr = p->apCsr;
  79696. pFrame->nCursor = p->nCursor;
  79697. pFrame->aOp = p->aOp;
  79698. pFrame->nOp = p->nOp;
  79699. pFrame->token = pProgram->token;
  79700. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  79701. pFrame->anExec = p->anExec;
  79702. #endif
  79703. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  79704. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  79705. pMem->flags = MEM_Undefined;
  79706. pMem->db = db;
  79707. }
  79708. }else{
  79709. pFrame = pRt->u.pFrame;
  79710. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  79711. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  79712. assert( pProgram->nCsr==pFrame->nChildCsr );
  79713. assert( (int)(pOp - aOp)==pFrame->pc );
  79714. }
  79715. p->nFrame++;
  79716. pFrame->pParent = p->pFrame;
  79717. pFrame->lastRowid = db->lastRowid;
  79718. pFrame->nChange = p->nChange;
  79719. pFrame->nDbChange = p->db->nChange;
  79720. assert( pFrame->pAuxData==0 );
  79721. pFrame->pAuxData = p->pAuxData;
  79722. p->pAuxData = 0;
  79723. p->nChange = 0;
  79724. p->pFrame = pFrame;
  79725. p->aMem = aMem = VdbeFrameMem(pFrame);
  79726. p->nMem = pFrame->nChildMem;
  79727. p->nCursor = (u16)pFrame->nChildCsr;
  79728. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  79729. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  79730. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  79731. p->aOp = aOp = pProgram->aOp;
  79732. p->nOp = pProgram->nOp;
  79733. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  79734. p->anExec = 0;
  79735. #endif
  79736. pOp = &aOp[-1];
  79737. break;
  79738. }
  79739. /* Opcode: Param P1 P2 * * *
  79740. **
  79741. ** This opcode is only ever present in sub-programs called via the
  79742. ** OP_Program instruction. Copy a value currently stored in a memory
  79743. ** cell of the calling (parent) frame to cell P2 in the current frames
  79744. ** address space. This is used by trigger programs to access the new.*
  79745. ** and old.* values.
  79746. **
  79747. ** The address of the cell in the parent frame is determined by adding
  79748. ** the value of the P1 argument to the value of the P1 argument to the
  79749. ** calling OP_Program instruction.
  79750. */
  79751. case OP_Param: { /* out2 */
  79752. VdbeFrame *pFrame;
  79753. Mem *pIn;
  79754. pOut = out2Prerelease(p, pOp);
  79755. pFrame = p->pFrame;
  79756. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  79757. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  79758. break;
  79759. }
  79760. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  79761. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79762. /* Opcode: FkCounter P1 P2 * * *
  79763. ** Synopsis: fkctr[P1]+=P2
  79764. **
  79765. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  79766. ** If P1 is non-zero, the database constraint counter is incremented
  79767. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  79768. ** statement counter is incremented (immediate foreign key constraints).
  79769. */
  79770. case OP_FkCounter: {
  79771. if( db->flags & SQLITE_DeferFKs ){
  79772. db->nDeferredImmCons += pOp->p2;
  79773. }else if( pOp->p1 ){
  79774. db->nDeferredCons += pOp->p2;
  79775. }else{
  79776. p->nFkConstraint += pOp->p2;
  79777. }
  79778. break;
  79779. }
  79780. /* Opcode: FkIfZero P1 P2 * * *
  79781. ** Synopsis: if fkctr[P1]==0 goto P2
  79782. **
  79783. ** This opcode tests if a foreign key constraint-counter is currently zero.
  79784. ** If so, jump to instruction P2. Otherwise, fall through to the next
  79785. ** instruction.
  79786. **
  79787. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  79788. ** is zero (the one that counts deferred constraint violations). If P1 is
  79789. ** zero, the jump is taken if the statement constraint-counter is zero
  79790. ** (immediate foreign key constraint violations).
  79791. */
  79792. case OP_FkIfZero: { /* jump */
  79793. if( pOp->p1 ){
  79794. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  79795. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79796. }else{
  79797. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  79798. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79799. }
  79800. break;
  79801. }
  79802. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  79803. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79804. /* Opcode: MemMax P1 P2 * * *
  79805. ** Synopsis: r[P1]=max(r[P1],r[P2])
  79806. **
  79807. ** P1 is a register in the root frame of this VM (the root frame is
  79808. ** different from the current frame if this instruction is being executed
  79809. ** within a sub-program). Set the value of register P1 to the maximum of
  79810. ** its current value and the value in register P2.
  79811. **
  79812. ** This instruction throws an error if the memory cell is not initially
  79813. ** an integer.
  79814. */
  79815. case OP_MemMax: { /* in2 */
  79816. VdbeFrame *pFrame;
  79817. if( p->pFrame ){
  79818. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  79819. pIn1 = &pFrame->aMem[pOp->p1];
  79820. }else{
  79821. pIn1 = &aMem[pOp->p1];
  79822. }
  79823. assert( memIsValid(pIn1) );
  79824. sqlite3VdbeMemIntegerify(pIn1);
  79825. pIn2 = &aMem[pOp->p2];
  79826. sqlite3VdbeMemIntegerify(pIn2);
  79827. if( pIn1->u.i<pIn2->u.i){
  79828. pIn1->u.i = pIn2->u.i;
  79829. }
  79830. break;
  79831. }
  79832. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  79833. /* Opcode: IfPos P1 P2 P3 * *
  79834. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  79835. **
  79836. ** Register P1 must contain an integer.
  79837. ** If the value of register P1 is 1 or greater, subtract P3 from the
  79838. ** value in P1 and jump to P2.
  79839. **
  79840. ** If the initial value of register P1 is less than 1, then the
  79841. ** value is unchanged and control passes through to the next instruction.
  79842. */
  79843. case OP_IfPos: { /* jump, in1 */
  79844. pIn1 = &aMem[pOp->p1];
  79845. assert( pIn1->flags&MEM_Int );
  79846. VdbeBranchTaken( pIn1->u.i>0, 2);
  79847. if( pIn1->u.i>0 ){
  79848. pIn1->u.i -= pOp->p3;
  79849. goto jump_to_p2;
  79850. }
  79851. break;
  79852. }
  79853. /* Opcode: OffsetLimit P1 P2 P3 * *
  79854. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  79855. **
  79856. ** This opcode performs a commonly used computation associated with
  79857. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  79858. ** holds the offset counter. The opcode computes the combined value
  79859. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  79860. ** value computed is the total number of rows that will need to be
  79861. ** visited in order to complete the query.
  79862. **
  79863. ** If r[P3] is zero or negative, that means there is no OFFSET
  79864. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  79865. **
  79866. ** if r[P1] is zero or negative, that means there is no LIMIT
  79867. ** and r[P2] is set to -1.
  79868. **
  79869. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  79870. */
  79871. case OP_OffsetLimit: { /* in1, out2, in3 */
  79872. i64 x;
  79873. pIn1 = &aMem[pOp->p1];
  79874. pIn3 = &aMem[pOp->p3];
  79875. pOut = out2Prerelease(p, pOp);
  79876. assert( pIn1->flags & MEM_Int );
  79877. assert( pIn3->flags & MEM_Int );
  79878. x = pIn1->u.i;
  79879. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  79880. /* If the LIMIT is less than or equal to zero, loop forever. This
  79881. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  79882. ** also loop forever. This is undocumented. In fact, one could argue
  79883. ** that the loop should terminate. But assuming 1 billion iterations
  79884. ** per second (far exceeding the capabilities of any current hardware)
  79885. ** it would take nearly 300 years to actually reach the limit. So
  79886. ** looping forever is a reasonable approximation. */
  79887. pOut->u.i = -1;
  79888. }else{
  79889. pOut->u.i = x;
  79890. }
  79891. break;
  79892. }
  79893. /* Opcode: IfNotZero P1 P2 * * *
  79894. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  79895. **
  79896. ** Register P1 must contain an integer. If the content of register P1 is
  79897. ** initially greater than zero, then decrement the value in register P1.
  79898. ** If it is non-zero (negative or positive) and then also jump to P2.
  79899. ** If register P1 is initially zero, leave it unchanged and fall through.
  79900. */
  79901. case OP_IfNotZero: { /* jump, in1 */
  79902. pIn1 = &aMem[pOp->p1];
  79903. assert( pIn1->flags&MEM_Int );
  79904. VdbeBranchTaken(pIn1->u.i<0, 2);
  79905. if( pIn1->u.i ){
  79906. if( pIn1->u.i>0 ) pIn1->u.i--;
  79907. goto jump_to_p2;
  79908. }
  79909. break;
  79910. }
  79911. /* Opcode: DecrJumpZero P1 P2 * * *
  79912. ** Synopsis: if (--r[P1])==0 goto P2
  79913. **
  79914. ** Register P1 must hold an integer. Decrement the value in P1
  79915. ** and jump to P2 if the new value is exactly zero.
  79916. */
  79917. case OP_DecrJumpZero: { /* jump, in1 */
  79918. pIn1 = &aMem[pOp->p1];
  79919. assert( pIn1->flags&MEM_Int );
  79920. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  79921. VdbeBranchTaken(pIn1->u.i==0, 2);
  79922. if( pIn1->u.i==0 ) goto jump_to_p2;
  79923. break;
  79924. }
  79925. /* Opcode: AggStep0 * P2 P3 P4 P5
  79926. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79927. **
  79928. ** Execute the step function for an aggregate. The
  79929. ** function has P5 arguments. P4 is a pointer to the FuncDef
  79930. ** structure that specifies the function. Register P3 is the
  79931. ** accumulator.
  79932. **
  79933. ** The P5 arguments are taken from register P2 and its
  79934. ** successors.
  79935. */
  79936. /* Opcode: AggStep * P2 P3 P4 P5
  79937. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79938. **
  79939. ** Execute the step function for an aggregate. The
  79940. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  79941. ** object that is used to run the function. Register P3 is
  79942. ** as the accumulator.
  79943. **
  79944. ** The P5 arguments are taken from register P2 and its
  79945. ** successors.
  79946. **
  79947. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  79948. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  79949. ** the opcode is changed. In this way, the initialization of the
  79950. ** sqlite3_context only happens once, instead of on each call to the
  79951. ** step function.
  79952. */
  79953. case OP_AggStep0: {
  79954. int n;
  79955. sqlite3_context *pCtx;
  79956. assert( pOp->p4type==P4_FUNCDEF );
  79957. n = pOp->p5;
  79958. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79959. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  79960. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  79961. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  79962. if( pCtx==0 ) goto no_mem;
  79963. pCtx->pMem = 0;
  79964. pCtx->pFunc = pOp->p4.pFunc;
  79965. pCtx->iOp = (int)(pOp - aOp);
  79966. pCtx->pVdbe = p;
  79967. pCtx->argc = n;
  79968. pOp->p4type = P4_FUNCCTX;
  79969. pOp->p4.pCtx = pCtx;
  79970. pOp->opcode = OP_AggStep;
  79971. /* Fall through into OP_AggStep */
  79972. }
  79973. case OP_AggStep: {
  79974. int i;
  79975. sqlite3_context *pCtx;
  79976. Mem *pMem;
  79977. Mem t;
  79978. assert( pOp->p4type==P4_FUNCCTX );
  79979. pCtx = pOp->p4.pCtx;
  79980. pMem = &aMem[pOp->p3];
  79981. /* If this function is inside of a trigger, the register array in aMem[]
  79982. ** might change from one evaluation to the next. The next block of code
  79983. ** checks to see if the register array has changed, and if so it
  79984. ** reinitializes the relavant parts of the sqlite3_context object */
  79985. if( pCtx->pMem != pMem ){
  79986. pCtx->pMem = pMem;
  79987. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  79988. }
  79989. #ifdef SQLITE_DEBUG
  79990. for(i=0; i<pCtx->argc; i++){
  79991. assert( memIsValid(pCtx->argv[i]) );
  79992. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  79993. }
  79994. #endif
  79995. pMem->n++;
  79996. sqlite3VdbeMemInit(&t, db, MEM_Null);
  79997. pCtx->pOut = &t;
  79998. pCtx->fErrorOrAux = 0;
  79999. pCtx->skipFlag = 0;
  80000. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  80001. if( pCtx->fErrorOrAux ){
  80002. if( pCtx->isError ){
  80003. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  80004. rc = pCtx->isError;
  80005. }
  80006. sqlite3VdbeMemRelease(&t);
  80007. if( rc ) goto abort_due_to_error;
  80008. }else{
  80009. assert( t.flags==MEM_Null );
  80010. }
  80011. if( pCtx->skipFlag ){
  80012. assert( pOp[-1].opcode==OP_CollSeq );
  80013. i = pOp[-1].p1;
  80014. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  80015. }
  80016. break;
  80017. }
  80018. /* Opcode: AggFinal P1 P2 * P4 *
  80019. ** Synopsis: accum=r[P1] N=P2
  80020. **
  80021. ** Execute the finalizer function for an aggregate. P1 is
  80022. ** the memory location that is the accumulator for the aggregate.
  80023. **
  80024. ** P2 is the number of arguments that the step function takes and
  80025. ** P4 is a pointer to the FuncDef for this function. The P2
  80026. ** argument is not used by this opcode. It is only there to disambiguate
  80027. ** functions that can take varying numbers of arguments. The
  80028. ** P4 argument is only needed for the degenerate case where
  80029. ** the step function was not previously called.
  80030. */
  80031. case OP_AggFinal: {
  80032. Mem *pMem;
  80033. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  80034. pMem = &aMem[pOp->p1];
  80035. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  80036. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  80037. if( rc ){
  80038. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  80039. goto abort_due_to_error;
  80040. }
  80041. sqlite3VdbeChangeEncoding(pMem, encoding);
  80042. UPDATE_MAX_BLOBSIZE(pMem);
  80043. if( sqlite3VdbeMemTooBig(pMem) ){
  80044. goto too_big;
  80045. }
  80046. break;
  80047. }
  80048. #ifndef SQLITE_OMIT_WAL
  80049. /* Opcode: Checkpoint P1 P2 P3 * *
  80050. **
  80051. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  80052. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  80053. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  80054. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  80055. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  80056. ** in the WAL that have been checkpointed after the checkpoint
  80057. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  80058. ** mem[P3+2] are initialized to -1.
  80059. */
  80060. case OP_Checkpoint: {
  80061. int i; /* Loop counter */
  80062. int aRes[3]; /* Results */
  80063. Mem *pMem; /* Write results here */
  80064. assert( p->readOnly==0 );
  80065. aRes[0] = 0;
  80066. aRes[1] = aRes[2] = -1;
  80067. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  80068. || pOp->p2==SQLITE_CHECKPOINT_FULL
  80069. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  80070. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  80071. );
  80072. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  80073. if( rc ){
  80074. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  80075. rc = SQLITE_OK;
  80076. aRes[0] = 1;
  80077. }
  80078. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  80079. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  80080. }
  80081. break;
  80082. };
  80083. #endif
  80084. #ifndef SQLITE_OMIT_PRAGMA
  80085. /* Opcode: JournalMode P1 P2 P3 * *
  80086. **
  80087. ** Change the journal mode of database P1 to P3. P3 must be one of the
  80088. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  80089. ** modes (delete, truncate, persist, off and memory), this is a simple
  80090. ** operation. No IO is required.
  80091. **
  80092. ** If changing into or out of WAL mode the procedure is more complicated.
  80093. **
  80094. ** Write a string containing the final journal-mode to register P2.
  80095. */
  80096. case OP_JournalMode: { /* out2 */
  80097. Btree *pBt; /* Btree to change journal mode of */
  80098. Pager *pPager; /* Pager associated with pBt */
  80099. int eNew; /* New journal mode */
  80100. int eOld; /* The old journal mode */
  80101. #ifndef SQLITE_OMIT_WAL
  80102. const char *zFilename; /* Name of database file for pPager */
  80103. #endif
  80104. pOut = out2Prerelease(p, pOp);
  80105. eNew = pOp->p3;
  80106. assert( eNew==PAGER_JOURNALMODE_DELETE
  80107. || eNew==PAGER_JOURNALMODE_TRUNCATE
  80108. || eNew==PAGER_JOURNALMODE_PERSIST
  80109. || eNew==PAGER_JOURNALMODE_OFF
  80110. || eNew==PAGER_JOURNALMODE_MEMORY
  80111. || eNew==PAGER_JOURNALMODE_WAL
  80112. || eNew==PAGER_JOURNALMODE_QUERY
  80113. );
  80114. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  80115. assert( p->readOnly==0 );
  80116. pBt = db->aDb[pOp->p1].pBt;
  80117. pPager = sqlite3BtreePager(pBt);
  80118. eOld = sqlite3PagerGetJournalMode(pPager);
  80119. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  80120. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  80121. #ifndef SQLITE_OMIT_WAL
  80122. zFilename = sqlite3PagerFilename(pPager, 1);
  80123. /* Do not allow a transition to journal_mode=WAL for a database
  80124. ** in temporary storage or if the VFS does not support shared memory
  80125. */
  80126. if( eNew==PAGER_JOURNALMODE_WAL
  80127. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  80128. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  80129. ){
  80130. eNew = eOld;
  80131. }
  80132. if( (eNew!=eOld)
  80133. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  80134. ){
  80135. if( !db->autoCommit || db->nVdbeRead>1 ){
  80136. rc = SQLITE_ERROR;
  80137. sqlite3VdbeError(p,
  80138. "cannot change %s wal mode from within a transaction",
  80139. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  80140. );
  80141. goto abort_due_to_error;
  80142. }else{
  80143. if( eOld==PAGER_JOURNALMODE_WAL ){
  80144. /* If leaving WAL mode, close the log file. If successful, the call
  80145. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  80146. ** file. An EXCLUSIVE lock may still be held on the database file
  80147. ** after a successful return.
  80148. */
  80149. rc = sqlite3PagerCloseWal(pPager, db);
  80150. if( rc==SQLITE_OK ){
  80151. sqlite3PagerSetJournalMode(pPager, eNew);
  80152. }
  80153. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  80154. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  80155. ** as an intermediate */
  80156. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  80157. }
  80158. /* Open a transaction on the database file. Regardless of the journal
  80159. ** mode, this transaction always uses a rollback journal.
  80160. */
  80161. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  80162. if( rc==SQLITE_OK ){
  80163. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  80164. }
  80165. }
  80166. }
  80167. #endif /* ifndef SQLITE_OMIT_WAL */
  80168. if( rc ) eNew = eOld;
  80169. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  80170. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  80171. pOut->z = (char *)sqlite3JournalModename(eNew);
  80172. pOut->n = sqlite3Strlen30(pOut->z);
  80173. pOut->enc = SQLITE_UTF8;
  80174. sqlite3VdbeChangeEncoding(pOut, encoding);
  80175. if( rc ) goto abort_due_to_error;
  80176. break;
  80177. };
  80178. #endif /* SQLITE_OMIT_PRAGMA */
  80179. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  80180. /* Opcode: Vacuum P1 * * * *
  80181. **
  80182. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  80183. ** for an attached database. The "temp" database may not be vacuumed.
  80184. */
  80185. case OP_Vacuum: {
  80186. assert( p->readOnly==0 );
  80187. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  80188. if( rc ) goto abort_due_to_error;
  80189. break;
  80190. }
  80191. #endif
  80192. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  80193. /* Opcode: IncrVacuum P1 P2 * * *
  80194. **
  80195. ** Perform a single step of the incremental vacuum procedure on
  80196. ** the P1 database. If the vacuum has finished, jump to instruction
  80197. ** P2. Otherwise, fall through to the next instruction.
  80198. */
  80199. case OP_IncrVacuum: { /* jump */
  80200. Btree *pBt;
  80201. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  80202. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  80203. assert( p->readOnly==0 );
  80204. pBt = db->aDb[pOp->p1].pBt;
  80205. rc = sqlite3BtreeIncrVacuum(pBt);
  80206. VdbeBranchTaken(rc==SQLITE_DONE,2);
  80207. if( rc ){
  80208. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  80209. rc = SQLITE_OK;
  80210. goto jump_to_p2;
  80211. }
  80212. break;
  80213. }
  80214. #endif
  80215. /* Opcode: Expire P1 * * * *
  80216. **
  80217. ** Cause precompiled statements to expire. When an expired statement
  80218. ** is executed using sqlite3_step() it will either automatically
  80219. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  80220. ** or it will fail with SQLITE_SCHEMA.
  80221. **
  80222. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  80223. ** then only the currently executing statement is expired.
  80224. */
  80225. case OP_Expire: {
  80226. if( !pOp->p1 ){
  80227. sqlite3ExpirePreparedStatements(db);
  80228. }else{
  80229. p->expired = 1;
  80230. }
  80231. break;
  80232. }
  80233. #ifndef SQLITE_OMIT_SHARED_CACHE
  80234. /* Opcode: TableLock P1 P2 P3 P4 *
  80235. ** Synopsis: iDb=P1 root=P2 write=P3
  80236. **
  80237. ** Obtain a lock on a particular table. This instruction is only used when
  80238. ** the shared-cache feature is enabled.
  80239. **
  80240. ** P1 is the index of the database in sqlite3.aDb[] of the database
  80241. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  80242. ** a write lock if P3==1.
  80243. **
  80244. ** P2 contains the root-page of the table to lock.
  80245. **
  80246. ** P4 contains a pointer to the name of the table being locked. This is only
  80247. ** used to generate an error message if the lock cannot be obtained.
  80248. */
  80249. case OP_TableLock: {
  80250. u8 isWriteLock = (u8)pOp->p3;
  80251. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  80252. int p1 = pOp->p1;
  80253. assert( p1>=0 && p1<db->nDb );
  80254. assert( DbMaskTest(p->btreeMask, p1) );
  80255. assert( isWriteLock==0 || isWriteLock==1 );
  80256. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  80257. if( rc ){
  80258. if( (rc&0xFF)==SQLITE_LOCKED ){
  80259. const char *z = pOp->p4.z;
  80260. sqlite3VdbeError(p, "database table is locked: %s", z);
  80261. }
  80262. goto abort_due_to_error;
  80263. }
  80264. }
  80265. break;
  80266. }
  80267. #endif /* SQLITE_OMIT_SHARED_CACHE */
  80268. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80269. /* Opcode: VBegin * * * P4 *
  80270. **
  80271. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  80272. ** xBegin method for that table.
  80273. **
  80274. ** Also, whether or not P4 is set, check that this is not being called from
  80275. ** within a callback to a virtual table xSync() method. If it is, the error
  80276. ** code will be set to SQLITE_LOCKED.
  80277. */
  80278. case OP_VBegin: {
  80279. VTable *pVTab;
  80280. pVTab = pOp->p4.pVtab;
  80281. rc = sqlite3VtabBegin(db, pVTab);
  80282. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  80283. if( rc ) goto abort_due_to_error;
  80284. break;
  80285. }
  80286. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80287. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80288. /* Opcode: VCreate P1 P2 * * *
  80289. **
  80290. ** P2 is a register that holds the name of a virtual table in database
  80291. ** P1. Call the xCreate method for that table.
  80292. */
  80293. case OP_VCreate: {
  80294. Mem sMem; /* For storing the record being decoded */
  80295. const char *zTab; /* Name of the virtual table */
  80296. memset(&sMem, 0, sizeof(sMem));
  80297. sMem.db = db;
  80298. /* Because P2 is always a static string, it is impossible for the
  80299. ** sqlite3VdbeMemCopy() to fail */
  80300. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  80301. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  80302. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  80303. assert( rc==SQLITE_OK );
  80304. zTab = (const char*)sqlite3_value_text(&sMem);
  80305. assert( zTab || db->mallocFailed );
  80306. if( zTab ){
  80307. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  80308. }
  80309. sqlite3VdbeMemRelease(&sMem);
  80310. if( rc ) goto abort_due_to_error;
  80311. break;
  80312. }
  80313. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80314. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80315. /* Opcode: VDestroy P1 * * P4 *
  80316. **
  80317. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  80318. ** of that table.
  80319. */
  80320. case OP_VDestroy: {
  80321. db->nVDestroy++;
  80322. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  80323. db->nVDestroy--;
  80324. if( rc ) goto abort_due_to_error;
  80325. break;
  80326. }
  80327. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80328. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80329. /* Opcode: VOpen P1 * * P4 *
  80330. **
  80331. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  80332. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  80333. ** table and stores that cursor in P1.
  80334. */
  80335. case OP_VOpen: {
  80336. VdbeCursor *pCur;
  80337. sqlite3_vtab_cursor *pVCur;
  80338. sqlite3_vtab *pVtab;
  80339. const sqlite3_module *pModule;
  80340. assert( p->bIsReader );
  80341. pCur = 0;
  80342. pVCur = 0;
  80343. pVtab = pOp->p4.pVtab->pVtab;
  80344. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  80345. rc = SQLITE_LOCKED;
  80346. goto abort_due_to_error;
  80347. }
  80348. pModule = pVtab->pModule;
  80349. rc = pModule->xOpen(pVtab, &pVCur);
  80350. sqlite3VtabImportErrmsg(p, pVtab);
  80351. if( rc ) goto abort_due_to_error;
  80352. /* Initialize sqlite3_vtab_cursor base class */
  80353. pVCur->pVtab = pVtab;
  80354. /* Initialize vdbe cursor object */
  80355. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  80356. if( pCur ){
  80357. pCur->uc.pVCur = pVCur;
  80358. pVtab->nRef++;
  80359. }else{
  80360. assert( db->mallocFailed );
  80361. pModule->xClose(pVCur);
  80362. goto no_mem;
  80363. }
  80364. break;
  80365. }
  80366. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80368. /* Opcode: VFilter P1 P2 P3 P4 *
  80369. ** Synopsis: iplan=r[P3] zplan='P4'
  80370. **
  80371. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  80372. ** the filtered result set is empty.
  80373. **
  80374. ** P4 is either NULL or a string that was generated by the xBestIndex
  80375. ** method of the module. The interpretation of the P4 string is left
  80376. ** to the module implementation.
  80377. **
  80378. ** This opcode invokes the xFilter method on the virtual table specified
  80379. ** by P1. The integer query plan parameter to xFilter is stored in register
  80380. ** P3. Register P3+1 stores the argc parameter to be passed to the
  80381. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  80382. ** additional parameters which are passed to
  80383. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  80384. **
  80385. ** A jump is made to P2 if the result set after filtering would be empty.
  80386. */
  80387. case OP_VFilter: { /* jump */
  80388. int nArg;
  80389. int iQuery;
  80390. const sqlite3_module *pModule;
  80391. Mem *pQuery;
  80392. Mem *pArgc;
  80393. sqlite3_vtab_cursor *pVCur;
  80394. sqlite3_vtab *pVtab;
  80395. VdbeCursor *pCur;
  80396. int res;
  80397. int i;
  80398. Mem **apArg;
  80399. pQuery = &aMem[pOp->p3];
  80400. pArgc = &pQuery[1];
  80401. pCur = p->apCsr[pOp->p1];
  80402. assert( memIsValid(pQuery) );
  80403. REGISTER_TRACE(pOp->p3, pQuery);
  80404. assert( pCur->eCurType==CURTYPE_VTAB );
  80405. pVCur = pCur->uc.pVCur;
  80406. pVtab = pVCur->pVtab;
  80407. pModule = pVtab->pModule;
  80408. /* Grab the index number and argc parameters */
  80409. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  80410. nArg = (int)pArgc->u.i;
  80411. iQuery = (int)pQuery->u.i;
  80412. /* Invoke the xFilter method */
  80413. res = 0;
  80414. apArg = p->apArg;
  80415. for(i = 0; i<nArg; i++){
  80416. apArg[i] = &pArgc[i+1];
  80417. }
  80418. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  80419. sqlite3VtabImportErrmsg(p, pVtab);
  80420. if( rc ) goto abort_due_to_error;
  80421. res = pModule->xEof(pVCur);
  80422. pCur->nullRow = 0;
  80423. VdbeBranchTaken(res!=0,2);
  80424. if( res ) goto jump_to_p2;
  80425. break;
  80426. }
  80427. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80428. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80429. /* Opcode: VColumn P1 P2 P3 * *
  80430. ** Synopsis: r[P3]=vcolumn(P2)
  80431. **
  80432. ** Store the value of the P2-th column of
  80433. ** the row of the virtual-table that the
  80434. ** P1 cursor is pointing to into register P3.
  80435. */
  80436. case OP_VColumn: {
  80437. sqlite3_vtab *pVtab;
  80438. const sqlite3_module *pModule;
  80439. Mem *pDest;
  80440. sqlite3_context sContext;
  80441. VdbeCursor *pCur = p->apCsr[pOp->p1];
  80442. assert( pCur->eCurType==CURTYPE_VTAB );
  80443. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  80444. pDest = &aMem[pOp->p3];
  80445. memAboutToChange(p, pDest);
  80446. if( pCur->nullRow ){
  80447. sqlite3VdbeMemSetNull(pDest);
  80448. break;
  80449. }
  80450. pVtab = pCur->uc.pVCur->pVtab;
  80451. pModule = pVtab->pModule;
  80452. assert( pModule->xColumn );
  80453. memset(&sContext, 0, sizeof(sContext));
  80454. sContext.pOut = pDest;
  80455. MemSetTypeFlag(pDest, MEM_Null);
  80456. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  80457. sqlite3VtabImportErrmsg(p, pVtab);
  80458. if( sContext.isError ){
  80459. rc = sContext.isError;
  80460. }
  80461. sqlite3VdbeChangeEncoding(pDest, encoding);
  80462. REGISTER_TRACE(pOp->p3, pDest);
  80463. UPDATE_MAX_BLOBSIZE(pDest);
  80464. if( sqlite3VdbeMemTooBig(pDest) ){
  80465. goto too_big;
  80466. }
  80467. if( rc ) goto abort_due_to_error;
  80468. break;
  80469. }
  80470. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80471. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80472. /* Opcode: VNext P1 P2 * * *
  80473. **
  80474. ** Advance virtual table P1 to the next row in its result set and
  80475. ** jump to instruction P2. Or, if the virtual table has reached
  80476. ** the end of its result set, then fall through to the next instruction.
  80477. */
  80478. case OP_VNext: { /* jump */
  80479. sqlite3_vtab *pVtab;
  80480. const sqlite3_module *pModule;
  80481. int res;
  80482. VdbeCursor *pCur;
  80483. res = 0;
  80484. pCur = p->apCsr[pOp->p1];
  80485. assert( pCur->eCurType==CURTYPE_VTAB );
  80486. if( pCur->nullRow ){
  80487. break;
  80488. }
  80489. pVtab = pCur->uc.pVCur->pVtab;
  80490. pModule = pVtab->pModule;
  80491. assert( pModule->xNext );
  80492. /* Invoke the xNext() method of the module. There is no way for the
  80493. ** underlying implementation to return an error if one occurs during
  80494. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  80495. ** data is available) and the error code returned when xColumn or
  80496. ** some other method is next invoked on the save virtual table cursor.
  80497. */
  80498. rc = pModule->xNext(pCur->uc.pVCur);
  80499. sqlite3VtabImportErrmsg(p, pVtab);
  80500. if( rc ) goto abort_due_to_error;
  80501. res = pModule->xEof(pCur->uc.pVCur);
  80502. VdbeBranchTaken(!res,2);
  80503. if( !res ){
  80504. /* If there is data, jump to P2 */
  80505. goto jump_to_p2_and_check_for_interrupt;
  80506. }
  80507. goto check_for_interrupt;
  80508. }
  80509. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80510. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80511. /* Opcode: VRename P1 * * P4 *
  80512. **
  80513. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  80514. ** This opcode invokes the corresponding xRename method. The value
  80515. ** in register P1 is passed as the zName argument to the xRename method.
  80516. */
  80517. case OP_VRename: {
  80518. sqlite3_vtab *pVtab;
  80519. Mem *pName;
  80520. pVtab = pOp->p4.pVtab->pVtab;
  80521. pName = &aMem[pOp->p1];
  80522. assert( pVtab->pModule->xRename );
  80523. assert( memIsValid(pName) );
  80524. assert( p->readOnly==0 );
  80525. REGISTER_TRACE(pOp->p1, pName);
  80526. assert( pName->flags & MEM_Str );
  80527. testcase( pName->enc==SQLITE_UTF8 );
  80528. testcase( pName->enc==SQLITE_UTF16BE );
  80529. testcase( pName->enc==SQLITE_UTF16LE );
  80530. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  80531. if( rc ) goto abort_due_to_error;
  80532. rc = pVtab->pModule->xRename(pVtab, pName->z);
  80533. sqlite3VtabImportErrmsg(p, pVtab);
  80534. p->expired = 0;
  80535. if( rc ) goto abort_due_to_error;
  80536. break;
  80537. }
  80538. #endif
  80539. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80540. /* Opcode: VUpdate P1 P2 P3 P4 P5
  80541. ** Synopsis: data=r[P3@P2]
  80542. **
  80543. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  80544. ** This opcode invokes the corresponding xUpdate method. P2 values
  80545. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  80546. ** invocation. The value in register (P3+P2-1) corresponds to the
  80547. ** p2th element of the argv array passed to xUpdate.
  80548. **
  80549. ** The xUpdate method will do a DELETE or an INSERT or both.
  80550. ** The argv[0] element (which corresponds to memory cell P3)
  80551. ** is the rowid of a row to delete. If argv[0] is NULL then no
  80552. ** deletion occurs. The argv[1] element is the rowid of the new
  80553. ** row. This can be NULL to have the virtual table select the new
  80554. ** rowid for itself. The subsequent elements in the array are
  80555. ** the values of columns in the new row.
  80556. **
  80557. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  80558. ** a row to delete.
  80559. **
  80560. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  80561. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  80562. ** is set to the value of the rowid for the row just inserted.
  80563. **
  80564. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  80565. ** apply in the case of a constraint failure on an insert or update.
  80566. */
  80567. case OP_VUpdate: {
  80568. sqlite3_vtab *pVtab;
  80569. const sqlite3_module *pModule;
  80570. int nArg;
  80571. int i;
  80572. sqlite_int64 rowid;
  80573. Mem **apArg;
  80574. Mem *pX;
  80575. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  80576. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  80577. );
  80578. assert( p->readOnly==0 );
  80579. pVtab = pOp->p4.pVtab->pVtab;
  80580. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  80581. rc = SQLITE_LOCKED;
  80582. goto abort_due_to_error;
  80583. }
  80584. pModule = pVtab->pModule;
  80585. nArg = pOp->p2;
  80586. assert( pOp->p4type==P4_VTAB );
  80587. if( ALWAYS(pModule->xUpdate) ){
  80588. u8 vtabOnConflict = db->vtabOnConflict;
  80589. apArg = p->apArg;
  80590. pX = &aMem[pOp->p3];
  80591. for(i=0; i<nArg; i++){
  80592. assert( memIsValid(pX) );
  80593. memAboutToChange(p, pX);
  80594. apArg[i] = pX;
  80595. pX++;
  80596. }
  80597. db->vtabOnConflict = pOp->p5;
  80598. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  80599. db->vtabOnConflict = vtabOnConflict;
  80600. sqlite3VtabImportErrmsg(p, pVtab);
  80601. if( rc==SQLITE_OK && pOp->p1 ){
  80602. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  80603. db->lastRowid = rowid;
  80604. }
  80605. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  80606. if( pOp->p5==OE_Ignore ){
  80607. rc = SQLITE_OK;
  80608. }else{
  80609. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  80610. }
  80611. }else{
  80612. p->nChange++;
  80613. }
  80614. if( rc ) goto abort_due_to_error;
  80615. }
  80616. break;
  80617. }
  80618. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80619. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80620. /* Opcode: Pagecount P1 P2 * * *
  80621. **
  80622. ** Write the current number of pages in database P1 to memory cell P2.
  80623. */
  80624. case OP_Pagecount: { /* out2 */
  80625. pOut = out2Prerelease(p, pOp);
  80626. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  80627. break;
  80628. }
  80629. #endif
  80630. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80631. /* Opcode: MaxPgcnt P1 P2 P3 * *
  80632. **
  80633. ** Try to set the maximum page count for database P1 to the value in P3.
  80634. ** Do not let the maximum page count fall below the current page count and
  80635. ** do not change the maximum page count value if P3==0.
  80636. **
  80637. ** Store the maximum page count after the change in register P2.
  80638. */
  80639. case OP_MaxPgcnt: { /* out2 */
  80640. unsigned int newMax;
  80641. Btree *pBt;
  80642. pOut = out2Prerelease(p, pOp);
  80643. pBt = db->aDb[pOp->p1].pBt;
  80644. newMax = 0;
  80645. if( pOp->p3 ){
  80646. newMax = sqlite3BtreeLastPage(pBt);
  80647. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  80648. }
  80649. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  80650. break;
  80651. }
  80652. #endif
  80653. /* Opcode: Function0 P1 P2 P3 P4 P5
  80654. ** Synopsis: r[P3]=func(r[P2@P5])
  80655. **
  80656. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  80657. ** defines the function) with P5 arguments taken from register P2 and
  80658. ** successors. The result of the function is stored in register P3.
  80659. ** Register P3 must not be one of the function inputs.
  80660. **
  80661. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  80662. ** function was determined to be constant at compile time. If the first
  80663. ** argument was constant then bit 0 of P1 is set. This is used to determine
  80664. ** whether meta data associated with a user function argument using the
  80665. ** sqlite3_set_auxdata() API may be safely retained until the next
  80666. ** invocation of this opcode.
  80667. **
  80668. ** See also: Function, AggStep, AggFinal
  80669. */
  80670. /* Opcode: Function P1 P2 P3 P4 P5
  80671. ** Synopsis: r[P3]=func(r[P2@P5])
  80672. **
  80673. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  80674. ** contains a pointer to the function to be run) with P5 arguments taken
  80675. ** from register P2 and successors. The result of the function is stored
  80676. ** in register P3. Register P3 must not be one of the function inputs.
  80677. **
  80678. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  80679. ** function was determined to be constant at compile time. If the first
  80680. ** argument was constant then bit 0 of P1 is set. This is used to determine
  80681. ** whether meta data associated with a user function argument using the
  80682. ** sqlite3_set_auxdata() API may be safely retained until the next
  80683. ** invocation of this opcode.
  80684. **
  80685. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  80686. ** to a FuncDef object. But on first evaluation, the P4 operand is
  80687. ** automatically converted into an sqlite3_context object and the operation
  80688. ** changed to this OP_Function opcode. In this way, the initialization of
  80689. ** the sqlite3_context object occurs only once, rather than once for each
  80690. ** evaluation of the function.
  80691. **
  80692. ** See also: Function0, AggStep, AggFinal
  80693. */
  80694. case OP_PureFunc0:
  80695. case OP_Function0: {
  80696. int n;
  80697. sqlite3_context *pCtx;
  80698. assert( pOp->p4type==P4_FUNCDEF );
  80699. n = pOp->p5;
  80700. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  80701. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  80702. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  80703. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  80704. if( pCtx==0 ) goto no_mem;
  80705. pCtx->pOut = 0;
  80706. pCtx->pFunc = pOp->p4.pFunc;
  80707. pCtx->iOp = (int)(pOp - aOp);
  80708. pCtx->pVdbe = p;
  80709. pCtx->argc = n;
  80710. pOp->p4type = P4_FUNCCTX;
  80711. pOp->p4.pCtx = pCtx;
  80712. assert( OP_PureFunc == OP_PureFunc0+2 );
  80713. assert( OP_Function == OP_Function0+2 );
  80714. pOp->opcode += 2;
  80715. /* Fall through into OP_Function */
  80716. }
  80717. case OP_PureFunc:
  80718. case OP_Function: {
  80719. int i;
  80720. sqlite3_context *pCtx;
  80721. assert( pOp->p4type==P4_FUNCCTX );
  80722. pCtx = pOp->p4.pCtx;
  80723. /* If this function is inside of a trigger, the register array in aMem[]
  80724. ** might change from one evaluation to the next. The next block of code
  80725. ** checks to see if the register array has changed, and if so it
  80726. ** reinitializes the relavant parts of the sqlite3_context object */
  80727. pOut = &aMem[pOp->p3];
  80728. if( pCtx->pOut != pOut ){
  80729. pCtx->pOut = pOut;
  80730. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  80731. }
  80732. memAboutToChange(p, pOut);
  80733. #ifdef SQLITE_DEBUG
  80734. for(i=0; i<pCtx->argc; i++){
  80735. assert( memIsValid(pCtx->argv[i]) );
  80736. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  80737. }
  80738. #endif
  80739. MemSetTypeFlag(pOut, MEM_Null);
  80740. pCtx->fErrorOrAux = 0;
  80741. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  80742. /* If the function returned an error, throw an exception */
  80743. if( pCtx->fErrorOrAux ){
  80744. if( pCtx->isError ){
  80745. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  80746. rc = pCtx->isError;
  80747. }
  80748. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  80749. if( rc ) goto abort_due_to_error;
  80750. }
  80751. /* Copy the result of the function into register P3 */
  80752. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  80753. sqlite3VdbeChangeEncoding(pOut, encoding);
  80754. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  80755. }
  80756. REGISTER_TRACE(pOp->p3, pOut);
  80757. UPDATE_MAX_BLOBSIZE(pOut);
  80758. break;
  80759. }
  80760. /* Opcode: Init P1 P2 P3 P4 *
  80761. ** Synopsis: Start at P2
  80762. **
  80763. ** Programs contain a single instance of this opcode as the very first
  80764. ** opcode.
  80765. **
  80766. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  80767. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  80768. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  80769. **
  80770. ** If P2 is not zero, jump to instruction P2.
  80771. **
  80772. ** Increment the value of P1 so that OP_Once opcodes will jump the
  80773. ** first time they are evaluated for this run.
  80774. **
  80775. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  80776. ** error is encountered.
  80777. */
  80778. case OP_Init: { /* jump */
  80779. char *zTrace;
  80780. int i;
  80781. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  80782. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  80783. **
  80784. ** This assert() provides evidence for:
  80785. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  80786. ** would have been returned by the legacy sqlite3_trace() interface by
  80787. ** using the X argument when X begins with "--" and invoking
  80788. ** sqlite3_expanded_sql(P) otherwise.
  80789. */
  80790. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  80791. assert( pOp==p->aOp ); /* Always instruction 0 */
  80792. #ifndef SQLITE_OMIT_TRACE
  80793. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  80794. && !p->doingRerun
  80795. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  80796. ){
  80797. #ifndef SQLITE_OMIT_DEPRECATED
  80798. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  80799. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  80800. char *z = sqlite3VdbeExpandSql(p, zTrace);
  80801. x(db->pTraceArg, z);
  80802. sqlite3_free(z);
  80803. }else
  80804. #endif
  80805. if( db->nVdbeExec>1 ){
  80806. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  80807. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  80808. sqlite3DbFree(db, z);
  80809. }else{
  80810. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  80811. }
  80812. }
  80813. #ifdef SQLITE_USE_FCNTL_TRACE
  80814. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  80815. if( zTrace ){
  80816. int j;
  80817. for(j=0; j<db->nDb; j++){
  80818. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  80819. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  80820. }
  80821. }
  80822. #endif /* SQLITE_USE_FCNTL_TRACE */
  80823. #ifdef SQLITE_DEBUG
  80824. if( (db->flags & SQLITE_SqlTrace)!=0
  80825. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  80826. ){
  80827. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  80828. }
  80829. #endif /* SQLITE_DEBUG */
  80830. #endif /* SQLITE_OMIT_TRACE */
  80831. assert( pOp->p2>0 );
  80832. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  80833. for(i=1; i<p->nOp; i++){
  80834. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  80835. }
  80836. pOp->p1 = 0;
  80837. }
  80838. pOp->p1++;
  80839. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  80840. goto jump_to_p2;
  80841. }
  80842. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  80843. /* Opcode: CursorHint P1 * * P4 *
  80844. **
  80845. ** Provide a hint to cursor P1 that it only needs to return rows that
  80846. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  80847. ** to values currently held in registers. TK_COLUMN terms in the P4
  80848. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  80849. */
  80850. case OP_CursorHint: {
  80851. VdbeCursor *pC;
  80852. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80853. assert( pOp->p4type==P4_EXPR );
  80854. pC = p->apCsr[pOp->p1];
  80855. if( pC ){
  80856. assert( pC->eCurType==CURTYPE_BTREE );
  80857. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  80858. pOp->p4.pExpr, aMem);
  80859. }
  80860. break;
  80861. }
  80862. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  80863. /* Opcode: Noop * * * * *
  80864. **
  80865. ** Do nothing. This instruction is often useful as a jump
  80866. ** destination.
  80867. */
  80868. /*
  80869. ** The magic Explain opcode are only inserted when explain==2 (which
  80870. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  80871. ** This opcode records information from the optimizer. It is the
  80872. ** the same as a no-op. This opcodesnever appears in a real VM program.
  80873. */
  80874. default: { /* This is really OP_Noop and OP_Explain */
  80875. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  80876. break;
  80877. }
  80878. /*****************************************************************************
  80879. ** The cases of the switch statement above this line should all be indented
  80880. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  80881. ** readability. From this point on down, the normal indentation rules are
  80882. ** restored.
  80883. *****************************************************************************/
  80884. }
  80885. #ifdef VDBE_PROFILE
  80886. {
  80887. u64 endTime = sqlite3Hwtime();
  80888. if( endTime>start ) pOrigOp->cycles += endTime - start;
  80889. pOrigOp->cnt++;
  80890. }
  80891. #endif
  80892. /* The following code adds nothing to the actual functionality
  80893. ** of the program. It is only here for testing and debugging.
  80894. ** On the other hand, it does burn CPU cycles every time through
  80895. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  80896. */
  80897. #ifndef NDEBUG
  80898. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  80899. #ifdef SQLITE_DEBUG
  80900. if( db->flags & SQLITE_VdbeTrace ){
  80901. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  80902. if( rc!=0 ) printf("rc=%d\n",rc);
  80903. if( opProperty & (OPFLG_OUT2) ){
  80904. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  80905. }
  80906. if( opProperty & OPFLG_OUT3 ){
  80907. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  80908. }
  80909. }
  80910. #endif /* SQLITE_DEBUG */
  80911. #endif /* NDEBUG */
  80912. } /* The end of the for(;;) loop the loops through opcodes */
  80913. /* If we reach this point, it means that execution is finished with
  80914. ** an error of some kind.
  80915. */
  80916. abort_due_to_error:
  80917. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  80918. assert( rc );
  80919. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  80920. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80921. }
  80922. p->rc = rc;
  80923. sqlite3SystemError(db, rc);
  80924. testcase( sqlite3GlobalConfig.xLog!=0 );
  80925. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  80926. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  80927. sqlite3VdbeHalt(p);
  80928. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  80929. rc = SQLITE_ERROR;
  80930. if( resetSchemaOnFault>0 ){
  80931. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  80932. }
  80933. /* This is the only way out of this procedure. We have to
  80934. ** release the mutexes on btrees that were acquired at the
  80935. ** top. */
  80936. vdbe_return:
  80937. testcase( nVmStep>0 );
  80938. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  80939. sqlite3VdbeLeave(p);
  80940. assert( rc!=SQLITE_OK || nExtraDelete==0
  80941. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  80942. );
  80943. return rc;
  80944. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  80945. ** is encountered.
  80946. */
  80947. too_big:
  80948. sqlite3VdbeError(p, "string or blob too big");
  80949. rc = SQLITE_TOOBIG;
  80950. goto abort_due_to_error;
  80951. /* Jump to here if a malloc() fails.
  80952. */
  80953. no_mem:
  80954. sqlite3OomFault(db);
  80955. sqlite3VdbeError(p, "out of memory");
  80956. rc = SQLITE_NOMEM_BKPT;
  80957. goto abort_due_to_error;
  80958. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  80959. ** flag.
  80960. */
  80961. abort_due_to_interrupt:
  80962. assert( db->u1.isInterrupted );
  80963. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  80964. p->rc = rc;
  80965. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80966. goto abort_due_to_error;
  80967. }
  80968. /************** End of vdbe.c ************************************************/
  80969. /************** Begin file vdbeblob.c ****************************************/
  80970. /*
  80971. ** 2007 May 1
  80972. **
  80973. ** The author disclaims copyright to this source code. In place of
  80974. ** a legal notice, here is a blessing:
  80975. **
  80976. ** May you do good and not evil.
  80977. ** May you find forgiveness for yourself and forgive others.
  80978. ** May you share freely, never taking more than you give.
  80979. **
  80980. *************************************************************************
  80981. **
  80982. ** This file contains code used to implement incremental BLOB I/O.
  80983. */
  80984. /* #include "sqliteInt.h" */
  80985. /* #include "vdbeInt.h" */
  80986. #ifndef SQLITE_OMIT_INCRBLOB
  80987. /*
  80988. ** Valid sqlite3_blob* handles point to Incrblob structures.
  80989. */
  80990. typedef struct Incrblob Incrblob;
  80991. struct Incrblob {
  80992. int nByte; /* Size of open blob, in bytes */
  80993. int iOffset; /* Byte offset of blob in cursor data */
  80994. u16 iCol; /* Table column this handle is open on */
  80995. BtCursor *pCsr; /* Cursor pointing at blob row */
  80996. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  80997. sqlite3 *db; /* The associated database */
  80998. char *zDb; /* Database name */
  80999. Table *pTab; /* Table object */
  81000. };
  81001. /*
  81002. ** This function is used by both blob_open() and blob_reopen(). It seeks
  81003. ** the b-tree cursor associated with blob handle p to point to row iRow.
  81004. ** If successful, SQLITE_OK is returned and subsequent calls to
  81005. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  81006. **
  81007. ** If an error occurs, or if the specified row does not exist or does not
  81008. ** contain a value of type TEXT or BLOB in the column nominated when the
  81009. ** blob handle was opened, then an error code is returned and *pzErr may
  81010. ** be set to point to a buffer containing an error message. It is the
  81011. ** responsibility of the caller to free the error message buffer using
  81012. ** sqlite3DbFree().
  81013. **
  81014. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  81015. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  81016. ** immediately return SQLITE_ABORT.
  81017. */
  81018. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  81019. int rc; /* Error code */
  81020. char *zErr = 0; /* Error message */
  81021. Vdbe *v = (Vdbe *)p->pStmt;
  81022. /* Set the value of register r[1] in the SQL statement to integer iRow.
  81023. ** This is done directly as a performance optimization
  81024. */
  81025. v->aMem[1].flags = MEM_Int;
  81026. v->aMem[1].u.i = iRow;
  81027. /* If the statement has been run before (and is paused at the OP_ResultRow)
  81028. ** then back it up to the point where it does the OP_NotExists. This could
  81029. ** have been down with an extra OP_Goto, but simply setting the program
  81030. ** counter is faster. */
  81031. if( v->pc>4 ){
  81032. v->pc = 4;
  81033. assert( v->aOp[v->pc].opcode==OP_NotExists );
  81034. rc = sqlite3VdbeExec(v);
  81035. }else{
  81036. rc = sqlite3_step(p->pStmt);
  81037. }
  81038. if( rc==SQLITE_ROW ){
  81039. VdbeCursor *pC = v->apCsr[0];
  81040. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  81041. testcase( pC->nHdrParsed==p->iCol );
  81042. testcase( pC->nHdrParsed==p->iCol+1 );
  81043. if( type<12 ){
  81044. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  81045. type==0?"null": type==7?"real": "integer"
  81046. );
  81047. rc = SQLITE_ERROR;
  81048. sqlite3_finalize(p->pStmt);
  81049. p->pStmt = 0;
  81050. }else{
  81051. p->iOffset = pC->aType[p->iCol + pC->nField];
  81052. p->nByte = sqlite3VdbeSerialTypeLen(type);
  81053. p->pCsr = pC->uc.pCursor;
  81054. sqlite3BtreeIncrblobCursor(p->pCsr);
  81055. }
  81056. }
  81057. if( rc==SQLITE_ROW ){
  81058. rc = SQLITE_OK;
  81059. }else if( p->pStmt ){
  81060. rc = sqlite3_finalize(p->pStmt);
  81061. p->pStmt = 0;
  81062. if( rc==SQLITE_OK ){
  81063. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  81064. rc = SQLITE_ERROR;
  81065. }else{
  81066. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  81067. }
  81068. }
  81069. assert( rc!=SQLITE_OK || zErr==0 );
  81070. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  81071. *pzErr = zErr;
  81072. return rc;
  81073. }
  81074. /*
  81075. ** Open a blob handle.
  81076. */
  81077. SQLITE_API int sqlite3_blob_open(
  81078. sqlite3* db, /* The database connection */
  81079. const char *zDb, /* The attached database containing the blob */
  81080. const char *zTable, /* The table containing the blob */
  81081. const char *zColumn, /* The column containing the blob */
  81082. sqlite_int64 iRow, /* The row containing the glob */
  81083. int wrFlag, /* True -> read/write access, false -> read-only */
  81084. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  81085. ){
  81086. int nAttempt = 0;
  81087. int iCol; /* Index of zColumn in row-record */
  81088. int rc = SQLITE_OK;
  81089. char *zErr = 0;
  81090. Table *pTab;
  81091. Incrblob *pBlob = 0;
  81092. Parse sParse;
  81093. #ifdef SQLITE_ENABLE_API_ARMOR
  81094. if( ppBlob==0 ){
  81095. return SQLITE_MISUSE_BKPT;
  81096. }
  81097. #endif
  81098. *ppBlob = 0;
  81099. #ifdef SQLITE_ENABLE_API_ARMOR
  81100. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  81101. return SQLITE_MISUSE_BKPT;
  81102. }
  81103. #endif
  81104. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  81105. sqlite3_mutex_enter(db->mutex);
  81106. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  81107. do {
  81108. memset(&sParse, 0, sizeof(Parse));
  81109. if( !pBlob ) goto blob_open_out;
  81110. sParse.db = db;
  81111. sqlite3DbFree(db, zErr);
  81112. zErr = 0;
  81113. sqlite3BtreeEnterAll(db);
  81114. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  81115. if( pTab && IsVirtual(pTab) ){
  81116. pTab = 0;
  81117. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  81118. }
  81119. if( pTab && !HasRowid(pTab) ){
  81120. pTab = 0;
  81121. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  81122. }
  81123. #ifndef SQLITE_OMIT_VIEW
  81124. if( pTab && pTab->pSelect ){
  81125. pTab = 0;
  81126. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  81127. }
  81128. #endif
  81129. if( !pTab ){
  81130. if( sParse.zErrMsg ){
  81131. sqlite3DbFree(db, zErr);
  81132. zErr = sParse.zErrMsg;
  81133. sParse.zErrMsg = 0;
  81134. }
  81135. rc = SQLITE_ERROR;
  81136. sqlite3BtreeLeaveAll(db);
  81137. goto blob_open_out;
  81138. }
  81139. pBlob->pTab = pTab;
  81140. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  81141. /* Now search pTab for the exact column. */
  81142. for(iCol=0; iCol<pTab->nCol; iCol++) {
  81143. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  81144. break;
  81145. }
  81146. }
  81147. if( iCol==pTab->nCol ){
  81148. sqlite3DbFree(db, zErr);
  81149. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  81150. rc = SQLITE_ERROR;
  81151. sqlite3BtreeLeaveAll(db);
  81152. goto blob_open_out;
  81153. }
  81154. /* If the value is being opened for writing, check that the
  81155. ** column is not indexed, and that it is not part of a foreign key.
  81156. */
  81157. if( wrFlag ){
  81158. const char *zFault = 0;
  81159. Index *pIdx;
  81160. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81161. if( db->flags&SQLITE_ForeignKeys ){
  81162. /* Check that the column is not part of an FK child key definition. It
  81163. ** is not necessary to check if it is part of a parent key, as parent
  81164. ** key columns must be indexed. The check below will pick up this
  81165. ** case. */
  81166. FKey *pFKey;
  81167. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  81168. int j;
  81169. for(j=0; j<pFKey->nCol; j++){
  81170. if( pFKey->aCol[j].iFrom==iCol ){
  81171. zFault = "foreign key";
  81172. }
  81173. }
  81174. }
  81175. }
  81176. #endif
  81177. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81178. int j;
  81179. for(j=0; j<pIdx->nKeyCol; j++){
  81180. /* FIXME: Be smarter about indexes that use expressions */
  81181. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  81182. zFault = "indexed";
  81183. }
  81184. }
  81185. }
  81186. if( zFault ){
  81187. sqlite3DbFree(db, zErr);
  81188. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  81189. rc = SQLITE_ERROR;
  81190. sqlite3BtreeLeaveAll(db);
  81191. goto blob_open_out;
  81192. }
  81193. }
  81194. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  81195. assert( pBlob->pStmt || db->mallocFailed );
  81196. if( pBlob->pStmt ){
  81197. /* This VDBE program seeks a btree cursor to the identified
  81198. ** db/table/row entry. The reason for using a vdbe program instead
  81199. ** of writing code to use the b-tree layer directly is that the
  81200. ** vdbe program will take advantage of the various transaction,
  81201. ** locking and error handling infrastructure built into the vdbe.
  81202. **
  81203. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  81204. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  81205. ** uses it to implement the blob_read(), blob_write() and
  81206. ** blob_bytes() functions.
  81207. **
  81208. ** The sqlite3_blob_close() function finalizes the vdbe program,
  81209. ** which closes the b-tree cursor and (possibly) commits the
  81210. ** transaction.
  81211. */
  81212. static const int iLn = VDBE_OFFSET_LINENO(2);
  81213. static const VdbeOpList openBlob[] = {
  81214. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  81215. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  81216. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  81217. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  81218. {OP_Column, 0, 0, 1}, /* 3 */
  81219. {OP_ResultRow, 1, 0, 0}, /* 4 */
  81220. {OP_Halt, 0, 0, 0}, /* 5 */
  81221. };
  81222. Vdbe *v = (Vdbe *)pBlob->pStmt;
  81223. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81224. VdbeOp *aOp;
  81225. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  81226. pTab->pSchema->schema_cookie,
  81227. pTab->pSchema->iGeneration);
  81228. sqlite3VdbeChangeP5(v, 1);
  81229. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  81230. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  81231. /* Make sure a mutex is held on the table to be accessed */
  81232. sqlite3VdbeUsesBtree(v, iDb);
  81233. if( db->mallocFailed==0 ){
  81234. assert( aOp!=0 );
  81235. /* Configure the OP_TableLock instruction */
  81236. #ifdef SQLITE_OMIT_SHARED_CACHE
  81237. aOp[0].opcode = OP_Noop;
  81238. #else
  81239. aOp[0].p1 = iDb;
  81240. aOp[0].p2 = pTab->tnum;
  81241. aOp[0].p3 = wrFlag;
  81242. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  81243. }
  81244. if( db->mallocFailed==0 ){
  81245. #endif
  81246. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  81247. ** parameter of the other to pTab->tnum. */
  81248. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  81249. aOp[1].p2 = pTab->tnum;
  81250. aOp[1].p3 = iDb;
  81251. /* Configure the number of columns. Configure the cursor to
  81252. ** think that the table has one more column than it really
  81253. ** does. An OP_Column to retrieve this imaginary column will
  81254. ** always return an SQL NULL. This is useful because it means
  81255. ** we can invoke OP_Column to fill in the vdbe cursors type
  81256. ** and offset cache without causing any IO.
  81257. */
  81258. aOp[1].p4type = P4_INT32;
  81259. aOp[1].p4.i = pTab->nCol+1;
  81260. aOp[3].p2 = pTab->nCol;
  81261. sParse.nVar = 0;
  81262. sParse.nMem = 1;
  81263. sParse.nTab = 1;
  81264. sqlite3VdbeMakeReady(v, &sParse);
  81265. }
  81266. }
  81267. pBlob->iCol = iCol;
  81268. pBlob->db = db;
  81269. sqlite3BtreeLeaveAll(db);
  81270. if( db->mallocFailed ){
  81271. goto blob_open_out;
  81272. }
  81273. rc = blobSeekToRow(pBlob, iRow, &zErr);
  81274. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  81275. blob_open_out:
  81276. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  81277. *ppBlob = (sqlite3_blob *)pBlob;
  81278. }else{
  81279. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  81280. sqlite3DbFree(db, pBlob);
  81281. }
  81282. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  81283. sqlite3DbFree(db, zErr);
  81284. sqlite3ParserReset(&sParse);
  81285. rc = sqlite3ApiExit(db, rc);
  81286. sqlite3_mutex_leave(db->mutex);
  81287. return rc;
  81288. }
  81289. /*
  81290. ** Close a blob handle that was previously created using
  81291. ** sqlite3_blob_open().
  81292. */
  81293. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  81294. Incrblob *p = (Incrblob *)pBlob;
  81295. int rc;
  81296. sqlite3 *db;
  81297. if( p ){
  81298. db = p->db;
  81299. sqlite3_mutex_enter(db->mutex);
  81300. rc = sqlite3_finalize(p->pStmt);
  81301. sqlite3DbFree(db, p);
  81302. sqlite3_mutex_leave(db->mutex);
  81303. }else{
  81304. rc = SQLITE_OK;
  81305. }
  81306. return rc;
  81307. }
  81308. /*
  81309. ** Perform a read or write operation on a blob
  81310. */
  81311. static int blobReadWrite(
  81312. sqlite3_blob *pBlob,
  81313. void *z,
  81314. int n,
  81315. int iOffset,
  81316. int (*xCall)(BtCursor*, u32, u32, void*)
  81317. ){
  81318. int rc;
  81319. Incrblob *p = (Incrblob *)pBlob;
  81320. Vdbe *v;
  81321. sqlite3 *db;
  81322. if( p==0 ) return SQLITE_MISUSE_BKPT;
  81323. db = p->db;
  81324. sqlite3_mutex_enter(db->mutex);
  81325. v = (Vdbe*)p->pStmt;
  81326. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  81327. /* Request is out of range. Return a transient error. */
  81328. rc = SQLITE_ERROR;
  81329. }else if( v==0 ){
  81330. /* If there is no statement handle, then the blob-handle has
  81331. ** already been invalidated. Return SQLITE_ABORT in this case.
  81332. */
  81333. rc = SQLITE_ABORT;
  81334. }else{
  81335. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  81336. ** returned, clean-up the statement handle.
  81337. */
  81338. assert( db == v->db );
  81339. sqlite3BtreeEnterCursor(p->pCsr);
  81340. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  81341. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  81342. /* If a pre-update hook is registered and this is a write cursor,
  81343. ** invoke it here.
  81344. **
  81345. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  81346. ** operation should really be an SQLITE_UPDATE. This is probably
  81347. ** incorrect, but is convenient because at this point the new.* values
  81348. ** are not easily obtainable. And for the sessions module, an
  81349. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  81350. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  81351. ** slightly more efficient). Since you cannot write to a PK column
  81352. ** using the incremental-blob API, this works. For the sessions module
  81353. ** anyhow.
  81354. */
  81355. sqlite3_int64 iKey;
  81356. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  81357. sqlite3VdbePreUpdateHook(
  81358. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  81359. );
  81360. }
  81361. #endif
  81362. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  81363. sqlite3BtreeLeaveCursor(p->pCsr);
  81364. if( rc==SQLITE_ABORT ){
  81365. sqlite3VdbeFinalize(v);
  81366. p->pStmt = 0;
  81367. }else{
  81368. v->rc = rc;
  81369. }
  81370. }
  81371. sqlite3Error(db, rc);
  81372. rc = sqlite3ApiExit(db, rc);
  81373. sqlite3_mutex_leave(db->mutex);
  81374. return rc;
  81375. }
  81376. /*
  81377. ** Read data from a blob handle.
  81378. */
  81379. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  81380. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  81381. }
  81382. /*
  81383. ** Write data to a blob handle.
  81384. */
  81385. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  81386. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  81387. }
  81388. /*
  81389. ** Query a blob handle for the size of the data.
  81390. **
  81391. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  81392. ** so no mutex is required for access.
  81393. */
  81394. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  81395. Incrblob *p = (Incrblob *)pBlob;
  81396. return (p && p->pStmt) ? p->nByte : 0;
  81397. }
  81398. /*
  81399. ** Move an existing blob handle to point to a different row of the same
  81400. ** database table.
  81401. **
  81402. ** If an error occurs, or if the specified row does not exist or does not
  81403. ** contain a blob or text value, then an error code is returned and the
  81404. ** database handle error code and message set. If this happens, then all
  81405. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  81406. ** immediately return SQLITE_ABORT.
  81407. */
  81408. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  81409. int rc;
  81410. Incrblob *p = (Incrblob *)pBlob;
  81411. sqlite3 *db;
  81412. if( p==0 ) return SQLITE_MISUSE_BKPT;
  81413. db = p->db;
  81414. sqlite3_mutex_enter(db->mutex);
  81415. if( p->pStmt==0 ){
  81416. /* If there is no statement handle, then the blob-handle has
  81417. ** already been invalidated. Return SQLITE_ABORT in this case.
  81418. */
  81419. rc = SQLITE_ABORT;
  81420. }else{
  81421. char *zErr;
  81422. rc = blobSeekToRow(p, iRow, &zErr);
  81423. if( rc!=SQLITE_OK ){
  81424. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  81425. sqlite3DbFree(db, zErr);
  81426. }
  81427. assert( rc!=SQLITE_SCHEMA );
  81428. }
  81429. rc = sqlite3ApiExit(db, rc);
  81430. assert( rc==SQLITE_OK || p->pStmt==0 );
  81431. sqlite3_mutex_leave(db->mutex);
  81432. return rc;
  81433. }
  81434. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  81435. /************** End of vdbeblob.c ********************************************/
  81436. /************** Begin file vdbesort.c ****************************************/
  81437. /*
  81438. ** 2011-07-09
  81439. **
  81440. ** The author disclaims copyright to this source code. In place of
  81441. ** a legal notice, here is a blessing:
  81442. **
  81443. ** May you do good and not evil.
  81444. ** May you find forgiveness for yourself and forgive others.
  81445. ** May you share freely, never taking more than you give.
  81446. **
  81447. *************************************************************************
  81448. ** This file contains code for the VdbeSorter object, used in concert with
  81449. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  81450. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  81451. ** using indexes and without LIMIT clauses.
  81452. **
  81453. ** The VdbeSorter object implements a multi-threaded external merge sort
  81454. ** algorithm that is efficient even if the number of elements being sorted
  81455. ** exceeds the available memory.
  81456. **
  81457. ** Here is the (internal, non-API) interface between this module and the
  81458. ** rest of the SQLite system:
  81459. **
  81460. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  81461. **
  81462. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  81463. ** object. The row is a binary blob in the
  81464. ** OP_MakeRecord format that contains both
  81465. ** the ORDER BY key columns and result columns
  81466. ** in the case of a SELECT w/ ORDER BY, or
  81467. ** the complete record for an index entry
  81468. ** in the case of a CREATE INDEX.
  81469. **
  81470. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  81471. ** Position the read cursor on the
  81472. ** first sorted element.
  81473. **
  81474. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  81475. ** element.
  81476. **
  81477. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  81478. ** row currently under the read cursor.
  81479. **
  81480. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  81481. ** currently under the read cursor against
  81482. ** another binary blob X and report if
  81483. ** X is strictly less than the read cursor.
  81484. ** Used to enforce uniqueness in a
  81485. ** CREATE UNIQUE INDEX statement.
  81486. **
  81487. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  81488. ** all resources.
  81489. **
  81490. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  81491. ** is like Close() followed by Init() only
  81492. ** much faster.
  81493. **
  81494. ** The interfaces above must be called in a particular order. Write() can
  81495. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  81496. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  81497. **
  81498. ** Init()
  81499. ** for each record: Write()
  81500. ** Rewind()
  81501. ** Rowkey()/Compare()
  81502. ** Next()
  81503. ** Close()
  81504. **
  81505. ** Algorithm:
  81506. **
  81507. ** Records passed to the sorter via calls to Write() are initially held
  81508. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  81509. ** a threshold, when Rewind() is called the set of records is sorted using
  81510. ** an in-memory merge sort. In this case, no temporary files are required
  81511. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  81512. ** directly from main memory.
  81513. **
  81514. ** If the amount of space used to store records in main memory exceeds the
  81515. ** threshold, then the set of records currently in memory are sorted and
  81516. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  81517. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  81518. ** of PMAs may be created by merging existing PMAs together - for example
  81519. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  81520. **
  81521. ** The threshold for the amount of main memory to use before flushing
  81522. ** records to a PMA is roughly the same as the limit configured for the
  81523. ** page-cache of the main database. Specifically, the threshold is set to
  81524. ** the value returned by "PRAGMA main.page_size" multipled by
  81525. ** that returned by "PRAGMA main.cache_size", in bytes.
  81526. **
  81527. ** If the sorter is running in single-threaded mode, then all PMAs generated
  81528. ** are appended to a single temporary file. Or, if the sorter is running in
  81529. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  81530. ** N is the configured number of worker threads. In this case, instead of
  81531. ** sorting the records and writing the PMA to a temporary file itself, the
  81532. ** calling thread usually launches a worker thread to do so. Except, if
  81533. ** there are already N worker threads running, the main thread does the work
  81534. ** itself.
  81535. **
  81536. ** The sorter is running in multi-threaded mode if (a) the library was built
  81537. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  81538. ** than zero, and (b) worker threads have been enabled at runtime by calling
  81539. ** "PRAGMA threads=N" with some value of N greater than 0.
  81540. **
  81541. ** When Rewind() is called, any data remaining in memory is flushed to a
  81542. ** final PMA. So at this point the data is stored in some number of sorted
  81543. ** PMAs within temporary files on disk.
  81544. **
  81545. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  81546. ** sorter is running in single-threaded mode, then these PMAs are merged
  81547. ** incrementally as keys are retreived from the sorter by the VDBE. The
  81548. ** MergeEngine object, described in further detail below, performs this
  81549. ** merge.
  81550. **
  81551. ** Or, if running in multi-threaded mode, then a background thread is
  81552. ** launched to merge the existing PMAs. Once the background thread has
  81553. ** merged T bytes of data into a single sorted PMA, the main thread
  81554. ** begins reading keys from that PMA while the background thread proceeds
  81555. ** with merging the next T bytes of data. And so on.
  81556. **
  81557. ** Parameter T is set to half the value of the memory threshold used
  81558. ** by Write() above to determine when to create a new PMA.
  81559. **
  81560. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  81561. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  81562. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  81563. ** disk are merged together. Then T bytes of data from the second set, and
  81564. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  81565. ** PMAs at a time. This done is to improve locality.
  81566. **
  81567. ** If running in multi-threaded mode and there are more than
  81568. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  81569. ** than one background thread may be created. Specifically, there may be
  81570. ** one background thread for each temporary file on disk, and one background
  81571. ** thread to merge the output of each of the others to a single PMA for
  81572. ** the main thread to read from.
  81573. */
  81574. /* #include "sqliteInt.h" */
  81575. /* #include "vdbeInt.h" */
  81576. /*
  81577. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  81578. ** messages to stderr that may be helpful in understanding the performance
  81579. ** characteristics of the sorter in multi-threaded mode.
  81580. */
  81581. #if 0
  81582. # define SQLITE_DEBUG_SORTER_THREADS 1
  81583. #endif
  81584. /*
  81585. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  81586. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  81587. ** overflows. 512MiB.
  81588. */
  81589. #define SQLITE_MAX_PMASZ (1<<29)
  81590. /*
  81591. ** Private objects used by the sorter
  81592. */
  81593. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  81594. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  81595. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  81596. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  81597. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  81598. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  81599. typedef struct SorterList SorterList; /* In-memory list of records */
  81600. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  81601. /*
  81602. ** A container for a temp file handle and the current amount of data
  81603. ** stored in the file.
  81604. */
  81605. struct SorterFile {
  81606. sqlite3_file *pFd; /* File handle */
  81607. i64 iEof; /* Bytes of data stored in pFd */
  81608. };
  81609. /*
  81610. ** An in-memory list of objects to be sorted.
  81611. **
  81612. ** If aMemory==0 then each object is allocated separately and the objects
  81613. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  81614. ** are stored in the aMemory[] bulk memory, one right after the other, and
  81615. ** are connected using SorterRecord.u.iNext.
  81616. */
  81617. struct SorterList {
  81618. SorterRecord *pList; /* Linked list of records */
  81619. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  81620. int szPMA; /* Size of pList as PMA in bytes */
  81621. };
  81622. /*
  81623. ** The MergeEngine object is used to combine two or more smaller PMAs into
  81624. ** one big PMA using a merge operation. Separate PMAs all need to be
  81625. ** combined into one big PMA in order to be able to step through the sorted
  81626. ** records in order.
  81627. **
  81628. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  81629. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  81630. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  81631. ** For the purposes of the paragraphs below, we assume that the array is
  81632. ** actually N elements in size, where N is the smallest power of 2 greater
  81633. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  81634. ** are treated as if they are empty (always at EOF).
  81635. **
  81636. ** The aTree[] array is also N elements in size. The value of N is stored in
  81637. ** the MergeEngine.nTree variable.
  81638. **
  81639. ** The final (N/2) elements of aTree[] contain the results of comparing
  81640. ** pairs of PMA keys together. Element i contains the result of
  81641. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  81642. ** aTree element is set to the index of it.
  81643. **
  81644. ** For the purposes of this comparison, EOF is considered greater than any
  81645. ** other key value. If the keys are equal (only possible with two EOF
  81646. ** values), it doesn't matter which index is stored.
  81647. **
  81648. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  81649. ** above contains the index of the smallest of each block of 4 PmaReaders
  81650. ** And so on. So that aTree[1] contains the index of the PmaReader that
  81651. ** currently points to the smallest key value. aTree[0] is unused.
  81652. **
  81653. ** Example:
  81654. **
  81655. ** aReadr[0] -> Banana
  81656. ** aReadr[1] -> Feijoa
  81657. ** aReadr[2] -> Elderberry
  81658. ** aReadr[3] -> Currant
  81659. ** aReadr[4] -> Grapefruit
  81660. ** aReadr[5] -> Apple
  81661. ** aReadr[6] -> Durian
  81662. ** aReadr[7] -> EOF
  81663. **
  81664. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  81665. **
  81666. ** The current element is "Apple" (the value of the key indicated by
  81667. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  81668. ** be advanced to the next key in its segment. Say the next key is
  81669. ** "Eggplant":
  81670. **
  81671. ** aReadr[5] -> Eggplant
  81672. **
  81673. ** The contents of aTree[] are updated first by comparing the new PmaReader
  81674. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  81675. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  81676. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  81677. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  81678. ** so the value written into element 1 of the array is 0. As follows:
  81679. **
  81680. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  81681. **
  81682. ** In other words, each time we advance to the next sorter element, log2(N)
  81683. ** key comparison operations are required, where N is the number of segments
  81684. ** being merged (rounded up to the next power of 2).
  81685. */
  81686. struct MergeEngine {
  81687. int nTree; /* Used size of aTree/aReadr (power of 2) */
  81688. SortSubtask *pTask; /* Used by this thread only */
  81689. int *aTree; /* Current state of incremental merge */
  81690. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  81691. };
  81692. /*
  81693. ** This object represents a single thread of control in a sort operation.
  81694. ** Exactly VdbeSorter.nTask instances of this object are allocated
  81695. ** as part of each VdbeSorter object. Instances are never allocated any
  81696. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  81697. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  81698. ** single-threaded operation, there is exactly one instance of this object
  81699. ** and for multi-threaded operation there are two or more instances.
  81700. **
  81701. ** Essentially, this structure contains all those fields of the VdbeSorter
  81702. ** structure for which each thread requires a separate instance. For example,
  81703. ** each thread requries its own UnpackedRecord object to unpack records in
  81704. ** as part of comparison operations.
  81705. **
  81706. ** Before a background thread is launched, variable bDone is set to 0. Then,
  81707. ** right before it exits, the thread itself sets bDone to 1. This is used for
  81708. ** two purposes:
  81709. **
  81710. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  81711. ** attempt to select a SortSubtask for which there is not already an
  81712. ** active background thread (since doing so causes the main thread
  81713. ** to block until it finishes).
  81714. **
  81715. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  81716. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  81717. ** block provoke debugging output.
  81718. **
  81719. ** In both cases, the effects of the main thread seeing (bDone==0) even
  81720. ** after the thread has finished are not dire. So we don't worry about
  81721. ** memory barriers and such here.
  81722. */
  81723. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  81724. struct SortSubtask {
  81725. SQLiteThread *pThread; /* Background thread, if any */
  81726. int bDone; /* Set if thread is finished but not joined */
  81727. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  81728. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  81729. SorterList list; /* List for thread to write to a PMA */
  81730. int nPMA; /* Number of PMAs currently in file */
  81731. SorterCompare xCompare; /* Compare function to use */
  81732. SorterFile file; /* Temp file for level-0 PMAs */
  81733. SorterFile file2; /* Space for other PMAs */
  81734. };
  81735. /*
  81736. ** Main sorter structure. A single instance of this is allocated for each
  81737. ** sorter cursor created by the VDBE.
  81738. **
  81739. ** mxKeysize:
  81740. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  81741. ** this variable is updated so as to be set to the size on disk of the
  81742. ** largest record in the sorter.
  81743. */
  81744. struct VdbeSorter {
  81745. int mnPmaSize; /* Minimum PMA size, in bytes */
  81746. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  81747. int mxKeysize; /* Largest serialized key seen so far */
  81748. int pgsz; /* Main database page size */
  81749. PmaReader *pReader; /* Readr data from here after Rewind() */
  81750. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  81751. sqlite3 *db; /* Database connection */
  81752. KeyInfo *pKeyInfo; /* How to compare records */
  81753. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  81754. SorterList list; /* List of in-memory records */
  81755. int iMemory; /* Offset of free space in list.aMemory */
  81756. int nMemory; /* Size of list.aMemory allocation in bytes */
  81757. u8 bUsePMA; /* True if one or more PMAs created */
  81758. u8 bUseThreads; /* True to use background threads */
  81759. u8 iPrev; /* Previous thread used to flush PMA */
  81760. u8 nTask; /* Size of aTask[] array */
  81761. u8 typeMask;
  81762. SortSubtask aTask[1]; /* One or more subtasks */
  81763. };
  81764. #define SORTER_TYPE_INTEGER 0x01
  81765. #define SORTER_TYPE_TEXT 0x02
  81766. /*
  81767. ** An instance of the following object is used to read records out of a
  81768. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  81769. ** aKey might point into aMap or into aBuffer. If neither of those locations
  81770. ** contain a contiguous representation of the key, then aAlloc is allocated
  81771. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  81772. **
  81773. ** pFd==0 at EOF.
  81774. */
  81775. struct PmaReader {
  81776. i64 iReadOff; /* Current read offset */
  81777. i64 iEof; /* 1 byte past EOF for this PmaReader */
  81778. int nAlloc; /* Bytes of space at aAlloc */
  81779. int nKey; /* Number of bytes in key */
  81780. sqlite3_file *pFd; /* File handle we are reading from */
  81781. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  81782. u8 *aKey; /* Pointer to current key */
  81783. u8 *aBuffer; /* Current read buffer */
  81784. int nBuffer; /* Size of read buffer in bytes */
  81785. u8 *aMap; /* Pointer to mapping of entire file */
  81786. IncrMerger *pIncr; /* Incremental merger */
  81787. };
  81788. /*
  81789. ** Normally, a PmaReader object iterates through an existing PMA stored
  81790. ** within a temp file. However, if the PmaReader.pIncr variable points to
  81791. ** an object of the following type, it may be used to iterate/merge through
  81792. ** multiple PMAs simultaneously.
  81793. **
  81794. ** There are two types of IncrMerger object - single (bUseThread==0) and
  81795. ** multi-threaded (bUseThread==1).
  81796. **
  81797. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  81798. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  81799. ** size. When the IncrMerger is initialized, it reads enough data from
  81800. ** pMerger to populate aFile[0]. It then sets variables within the
  81801. ** corresponding PmaReader object to read from that file and kicks off
  81802. ** a background thread to populate aFile[1] with the next mxSz bytes of
  81803. ** sorted record data from pMerger.
  81804. **
  81805. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  81806. ** background thread has finished populating aFile[1]. It then exchanges
  81807. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  81808. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  81809. ** another background thread to populate the new aFile[1]. And so on, until
  81810. ** the contents of pMerger are exhausted.
  81811. **
  81812. ** A single-threaded IncrMerger does not open any temporary files of its
  81813. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  81814. ** at offset iStartOff of file pTask->file2. And instead of using a
  81815. ** background thread to prepare data for the PmaReader, with a single
  81816. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  81817. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  81818. ** of data.
  81819. */
  81820. struct IncrMerger {
  81821. SortSubtask *pTask; /* Task that owns this merger */
  81822. MergeEngine *pMerger; /* Merge engine thread reads data from */
  81823. i64 iStartOff; /* Offset to start writing file at */
  81824. int mxSz; /* Maximum bytes of data to store */
  81825. int bEof; /* Set to true when merge is finished */
  81826. int bUseThread; /* True to use a bg thread for this object */
  81827. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  81828. };
  81829. /*
  81830. ** An instance of this object is used for writing a PMA.
  81831. **
  81832. ** The PMA is written one record at a time. Each record is of an arbitrary
  81833. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  81834. ** each block is aligned on a page boundary. This object caches writes to
  81835. ** the PMA so that aligned, page-size blocks are written.
  81836. */
  81837. struct PmaWriter {
  81838. int eFWErr; /* Non-zero if in an error state */
  81839. u8 *aBuffer; /* Pointer to write buffer */
  81840. int nBuffer; /* Size of write buffer in bytes */
  81841. int iBufStart; /* First byte of buffer to write */
  81842. int iBufEnd; /* Last byte of buffer to write */
  81843. i64 iWriteOff; /* Offset of start of buffer in file */
  81844. sqlite3_file *pFd; /* File handle to write to */
  81845. };
  81846. /*
  81847. ** This object is the header on a single record while that record is being
  81848. ** held in memory and prior to being written out as part of a PMA.
  81849. **
  81850. ** How the linked list is connected depends on how memory is being managed
  81851. ** by this module. If using a separate allocation for each in-memory record
  81852. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  81853. ** SorterRecord.u.pNext pointers.
  81854. **
  81855. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  81856. ** then while records are being accumulated the list is linked using the
  81857. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  81858. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  81859. ** has finished passing records to the sorter, or when the in-memory buffer
  81860. ** is full, the list is sorted. As part of the sorting process, it is
  81861. ** converted to use the SorterRecord.u.pNext pointers. See function
  81862. ** vdbeSorterSort() for details.
  81863. */
  81864. struct SorterRecord {
  81865. int nVal; /* Size of the record in bytes */
  81866. union {
  81867. SorterRecord *pNext; /* Pointer to next record in list */
  81868. int iNext; /* Offset within aMemory of next record */
  81869. } u;
  81870. /* The data for the record immediately follows this header */
  81871. };
  81872. /* Return a pointer to the buffer containing the record data for SorterRecord
  81873. ** object p. Should be used as if:
  81874. **
  81875. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  81876. */
  81877. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  81878. /* Maximum number of PMAs that a single MergeEngine can merge */
  81879. #define SORTER_MAX_MERGE_COUNT 16
  81880. static int vdbeIncrSwap(IncrMerger*);
  81881. static void vdbeIncrFree(IncrMerger *);
  81882. /*
  81883. ** Free all memory belonging to the PmaReader object passed as the
  81884. ** argument. All structure fields are set to zero before returning.
  81885. */
  81886. static void vdbePmaReaderClear(PmaReader *pReadr){
  81887. sqlite3_free(pReadr->aAlloc);
  81888. sqlite3_free(pReadr->aBuffer);
  81889. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  81890. vdbeIncrFree(pReadr->pIncr);
  81891. memset(pReadr, 0, sizeof(PmaReader));
  81892. }
  81893. /*
  81894. ** Read the next nByte bytes of data from the PMA p.
  81895. ** If successful, set *ppOut to point to a buffer containing the data
  81896. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  81897. ** error code.
  81898. **
  81899. ** The buffer returned in *ppOut is only valid until the
  81900. ** next call to this function.
  81901. */
  81902. static int vdbePmaReadBlob(
  81903. PmaReader *p, /* PmaReader from which to take the blob */
  81904. int nByte, /* Bytes of data to read */
  81905. u8 **ppOut /* OUT: Pointer to buffer containing data */
  81906. ){
  81907. int iBuf; /* Offset within buffer to read from */
  81908. int nAvail; /* Bytes of data available in buffer */
  81909. if( p->aMap ){
  81910. *ppOut = &p->aMap[p->iReadOff];
  81911. p->iReadOff += nByte;
  81912. return SQLITE_OK;
  81913. }
  81914. assert( p->aBuffer );
  81915. /* If there is no more data to be read from the buffer, read the next
  81916. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  81917. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  81918. iBuf = p->iReadOff % p->nBuffer;
  81919. if( iBuf==0 ){
  81920. int nRead; /* Bytes to read from disk */
  81921. int rc; /* sqlite3OsRead() return code */
  81922. /* Determine how many bytes of data to read. */
  81923. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  81924. nRead = p->nBuffer;
  81925. }else{
  81926. nRead = (int)(p->iEof - p->iReadOff);
  81927. }
  81928. assert( nRead>0 );
  81929. /* Readr data from the file. Return early if an error occurs. */
  81930. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  81931. assert( rc!=SQLITE_IOERR_SHORT_READ );
  81932. if( rc!=SQLITE_OK ) return rc;
  81933. }
  81934. nAvail = p->nBuffer - iBuf;
  81935. if( nByte<=nAvail ){
  81936. /* The requested data is available in the in-memory buffer. In this
  81937. ** case there is no need to make a copy of the data, just return a
  81938. ** pointer into the buffer to the caller. */
  81939. *ppOut = &p->aBuffer[iBuf];
  81940. p->iReadOff += nByte;
  81941. }else{
  81942. /* The requested data is not all available in the in-memory buffer.
  81943. ** In this case, allocate space at p->aAlloc[] to copy the requested
  81944. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  81945. int nRem; /* Bytes remaining to copy */
  81946. /* Extend the p->aAlloc[] allocation if required. */
  81947. if( p->nAlloc<nByte ){
  81948. u8 *aNew;
  81949. int nNew = MAX(128, p->nAlloc*2);
  81950. while( nByte>nNew ) nNew = nNew*2;
  81951. aNew = sqlite3Realloc(p->aAlloc, nNew);
  81952. if( !aNew ) return SQLITE_NOMEM_BKPT;
  81953. p->nAlloc = nNew;
  81954. p->aAlloc = aNew;
  81955. }
  81956. /* Copy as much data as is available in the buffer into the start of
  81957. ** p->aAlloc[]. */
  81958. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  81959. p->iReadOff += nAvail;
  81960. nRem = nByte - nAvail;
  81961. /* The following loop copies up to p->nBuffer bytes per iteration into
  81962. ** the p->aAlloc[] buffer. */
  81963. while( nRem>0 ){
  81964. int rc; /* vdbePmaReadBlob() return code */
  81965. int nCopy; /* Number of bytes to copy */
  81966. u8 *aNext; /* Pointer to buffer to copy data from */
  81967. nCopy = nRem;
  81968. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  81969. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  81970. if( rc!=SQLITE_OK ) return rc;
  81971. assert( aNext!=p->aAlloc );
  81972. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  81973. nRem -= nCopy;
  81974. }
  81975. *ppOut = p->aAlloc;
  81976. }
  81977. return SQLITE_OK;
  81978. }
  81979. /*
  81980. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  81981. ** the value read.
  81982. */
  81983. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  81984. int iBuf;
  81985. if( p->aMap ){
  81986. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  81987. }else{
  81988. iBuf = p->iReadOff % p->nBuffer;
  81989. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  81990. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  81991. }else{
  81992. u8 aVarint[16], *a;
  81993. int i = 0, rc;
  81994. do{
  81995. rc = vdbePmaReadBlob(p, 1, &a);
  81996. if( rc ) return rc;
  81997. aVarint[(i++)&0xf] = a[0];
  81998. }while( (a[0]&0x80)!=0 );
  81999. sqlite3GetVarint(aVarint, pnOut);
  82000. }
  82001. }
  82002. return SQLITE_OK;
  82003. }
  82004. /*
  82005. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  82006. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  82007. ** (because the file is too large or the VFS layer is configured not to use
  82008. ** mmap), return SQLITE_OK and set *pp to NULL.
  82009. **
  82010. ** Or, if an error occurs, return an SQLite error code. The final value of
  82011. ** *pp is undefined in this case.
  82012. */
  82013. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  82014. int rc = SQLITE_OK;
  82015. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  82016. sqlite3_file *pFd = pFile->pFd;
  82017. if( pFd->pMethods->iVersion>=3 ){
  82018. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  82019. testcase( rc!=SQLITE_OK );
  82020. }
  82021. }
  82022. return rc;
  82023. }
  82024. /*
  82025. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  82026. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  82027. ** if successful, or an SQLite error code if an error occurs.
  82028. */
  82029. static int vdbePmaReaderSeek(
  82030. SortSubtask *pTask, /* Task context */
  82031. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  82032. SorterFile *pFile, /* Sorter file to read from */
  82033. i64 iOff /* Offset in pFile */
  82034. ){
  82035. int rc = SQLITE_OK;
  82036. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  82037. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  82038. if( pReadr->aMap ){
  82039. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  82040. pReadr->aMap = 0;
  82041. }
  82042. pReadr->iReadOff = iOff;
  82043. pReadr->iEof = pFile->iEof;
  82044. pReadr->pFd = pFile->pFd;
  82045. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  82046. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  82047. int pgsz = pTask->pSorter->pgsz;
  82048. int iBuf = pReadr->iReadOff % pgsz;
  82049. if( pReadr->aBuffer==0 ){
  82050. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  82051. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  82052. pReadr->nBuffer = pgsz;
  82053. }
  82054. if( rc==SQLITE_OK && iBuf ){
  82055. int nRead = pgsz - iBuf;
  82056. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  82057. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  82058. }
  82059. rc = sqlite3OsRead(
  82060. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  82061. );
  82062. testcase( rc!=SQLITE_OK );
  82063. }
  82064. }
  82065. return rc;
  82066. }
  82067. /*
  82068. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  82069. ** no error occurs, or an SQLite error code if one does.
  82070. */
  82071. static int vdbePmaReaderNext(PmaReader *pReadr){
  82072. int rc = SQLITE_OK; /* Return Code */
  82073. u64 nRec = 0; /* Size of record in bytes */
  82074. if( pReadr->iReadOff>=pReadr->iEof ){
  82075. IncrMerger *pIncr = pReadr->pIncr;
  82076. int bEof = 1;
  82077. if( pIncr ){
  82078. rc = vdbeIncrSwap(pIncr);
  82079. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  82080. rc = vdbePmaReaderSeek(
  82081. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  82082. );
  82083. bEof = 0;
  82084. }
  82085. }
  82086. if( bEof ){
  82087. /* This is an EOF condition */
  82088. vdbePmaReaderClear(pReadr);
  82089. testcase( rc!=SQLITE_OK );
  82090. return rc;
  82091. }
  82092. }
  82093. if( rc==SQLITE_OK ){
  82094. rc = vdbePmaReadVarint(pReadr, &nRec);
  82095. }
  82096. if( rc==SQLITE_OK ){
  82097. pReadr->nKey = (int)nRec;
  82098. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  82099. testcase( rc!=SQLITE_OK );
  82100. }
  82101. return rc;
  82102. }
  82103. /*
  82104. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  82105. ** starting at offset iStart and ending at offset iEof-1. This function
  82106. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  82107. ** PMA is empty).
  82108. **
  82109. ** If the pnByte parameter is NULL, then it is assumed that the file
  82110. ** contains a single PMA, and that that PMA omits the initial length varint.
  82111. */
  82112. static int vdbePmaReaderInit(
  82113. SortSubtask *pTask, /* Task context */
  82114. SorterFile *pFile, /* Sorter file to read from */
  82115. i64 iStart, /* Start offset in pFile */
  82116. PmaReader *pReadr, /* PmaReader to populate */
  82117. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  82118. ){
  82119. int rc;
  82120. assert( pFile->iEof>iStart );
  82121. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  82122. assert( pReadr->aBuffer==0 );
  82123. assert( pReadr->aMap==0 );
  82124. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  82125. if( rc==SQLITE_OK ){
  82126. u64 nByte = 0; /* Size of PMA in bytes */
  82127. rc = vdbePmaReadVarint(pReadr, &nByte);
  82128. pReadr->iEof = pReadr->iReadOff + nByte;
  82129. *pnByte += nByte;
  82130. }
  82131. if( rc==SQLITE_OK ){
  82132. rc = vdbePmaReaderNext(pReadr);
  82133. }
  82134. return rc;
  82135. }
  82136. /*
  82137. ** A version of vdbeSorterCompare() that assumes that it has already been
  82138. ** determined that the first field of key1 is equal to the first field of
  82139. ** key2.
  82140. */
  82141. static int vdbeSorterCompareTail(
  82142. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  82143. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  82144. const void *pKey1, int nKey1, /* Left side of comparison */
  82145. const void *pKey2, int nKey2 /* Right side of comparison */
  82146. ){
  82147. UnpackedRecord *r2 = pTask->pUnpacked;
  82148. if( *pbKey2Cached==0 ){
  82149. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  82150. *pbKey2Cached = 1;
  82151. }
  82152. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  82153. }
  82154. /*
  82155. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  82156. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  82157. ** used by the comparison. Return the result of the comparison.
  82158. **
  82159. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  82160. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  82161. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  82162. ** version of key2 and *pbKey2Cached set to true before returning.
  82163. **
  82164. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  82165. ** to SQLITE_NOMEM.
  82166. */
  82167. static int vdbeSorterCompare(
  82168. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  82169. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  82170. const void *pKey1, int nKey1, /* Left side of comparison */
  82171. const void *pKey2, int nKey2 /* Right side of comparison */
  82172. ){
  82173. UnpackedRecord *r2 = pTask->pUnpacked;
  82174. if( !*pbKey2Cached ){
  82175. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  82176. *pbKey2Cached = 1;
  82177. }
  82178. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  82179. }
  82180. /*
  82181. ** A specially optimized version of vdbeSorterCompare() that assumes that
  82182. ** the first field of each key is a TEXT value and that the collation
  82183. ** sequence to compare them with is BINARY.
  82184. */
  82185. static int vdbeSorterCompareText(
  82186. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  82187. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  82188. const void *pKey1, int nKey1, /* Left side of comparison */
  82189. const void *pKey2, int nKey2 /* Right side of comparison */
  82190. ){
  82191. const u8 * const p1 = (const u8 * const)pKey1;
  82192. const u8 * const p2 = (const u8 * const)pKey2;
  82193. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  82194. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  82195. int n1;
  82196. int n2;
  82197. int res;
  82198. getVarint32(&p1[1], n1);
  82199. getVarint32(&p2[1], n2);
  82200. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  82201. if( res==0 ){
  82202. res = n1 - n2;
  82203. }
  82204. if( res==0 ){
  82205. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  82206. res = vdbeSorterCompareTail(
  82207. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  82208. );
  82209. }
  82210. }else{
  82211. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  82212. res = res * -1;
  82213. }
  82214. }
  82215. return res;
  82216. }
  82217. /*
  82218. ** A specially optimized version of vdbeSorterCompare() that assumes that
  82219. ** the first field of each key is an INTEGER value.
  82220. */
  82221. static int vdbeSorterCompareInt(
  82222. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  82223. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  82224. const void *pKey1, int nKey1, /* Left side of comparison */
  82225. const void *pKey2, int nKey2 /* Right side of comparison */
  82226. ){
  82227. const u8 * const p1 = (const u8 * const)pKey1;
  82228. const u8 * const p2 = (const u8 * const)pKey2;
  82229. const int s1 = p1[1]; /* Left hand serial type */
  82230. const int s2 = p2[1]; /* Right hand serial type */
  82231. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  82232. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  82233. int res; /* Return value */
  82234. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  82235. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  82236. if( s1==s2 ){
  82237. /* The two values have the same sign. Compare using memcmp(). */
  82238. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  82239. const u8 n = aLen[s1];
  82240. int i;
  82241. res = 0;
  82242. for(i=0; i<n; i++){
  82243. if( (res = v1[i] - v2[i])!=0 ){
  82244. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  82245. res = v1[0] & 0x80 ? -1 : +1;
  82246. }
  82247. break;
  82248. }
  82249. }
  82250. }else if( s1>7 && s2>7 ){
  82251. res = s1 - s2;
  82252. }else{
  82253. if( s2>7 ){
  82254. res = +1;
  82255. }else if( s1>7 ){
  82256. res = -1;
  82257. }else{
  82258. res = s1 - s2;
  82259. }
  82260. assert( res!=0 );
  82261. if( res>0 ){
  82262. if( *v1 & 0x80 ) res = -1;
  82263. }else{
  82264. if( *v2 & 0x80 ) res = +1;
  82265. }
  82266. }
  82267. if( res==0 ){
  82268. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  82269. res = vdbeSorterCompareTail(
  82270. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  82271. );
  82272. }
  82273. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  82274. res = res * -1;
  82275. }
  82276. return res;
  82277. }
  82278. /*
  82279. ** Initialize the temporary index cursor just opened as a sorter cursor.
  82280. **
  82281. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  82282. ** to determine the number of fields that should be compared from the
  82283. ** records being sorted. However, if the value passed as argument nField
  82284. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  82285. ** is used instead. This is used when sorting records for a CREATE INDEX
  82286. ** statement. In this case, keys are always delivered to the sorter in
  82287. ** order of the primary key, which happens to be make up the final part
  82288. ** of the records being sorted. So if the sort is stable, there is never
  82289. ** any reason to compare PK fields and they can be ignored for a small
  82290. ** performance boost.
  82291. **
  82292. ** The sorter can guarantee a stable sort when running in single-threaded
  82293. ** mode, but not in multi-threaded mode.
  82294. **
  82295. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82296. */
  82297. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  82298. sqlite3 *db, /* Database connection (for malloc()) */
  82299. int nField, /* Number of key fields in each record */
  82300. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  82301. ){
  82302. int pgsz; /* Page size of main database */
  82303. int i; /* Used to iterate through aTask[] */
  82304. VdbeSorter *pSorter; /* The new sorter */
  82305. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  82306. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  82307. int sz; /* Size of pSorter in bytes */
  82308. int rc = SQLITE_OK;
  82309. #if SQLITE_MAX_WORKER_THREADS==0
  82310. # define nWorker 0
  82311. #else
  82312. int nWorker;
  82313. #endif
  82314. /* Initialize the upper limit on the number of worker threads */
  82315. #if SQLITE_MAX_WORKER_THREADS>0
  82316. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  82317. nWorker = 0;
  82318. }else{
  82319. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  82320. }
  82321. #endif
  82322. /* Do not allow the total number of threads (main thread + all workers)
  82323. ** to exceed the maximum merge count */
  82324. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  82325. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  82326. nWorker = SORTER_MAX_MERGE_COUNT-1;
  82327. }
  82328. #endif
  82329. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  82330. assert( pCsr->eCurType==CURTYPE_SORTER );
  82331. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  82332. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  82333. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  82334. pCsr->uc.pSorter = pSorter;
  82335. if( pSorter==0 ){
  82336. rc = SQLITE_NOMEM_BKPT;
  82337. }else{
  82338. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  82339. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  82340. pKeyInfo->db = 0;
  82341. if( nField && nWorker==0 ){
  82342. pKeyInfo->nKeyField = nField;
  82343. }
  82344. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  82345. pSorter->nTask = nWorker + 1;
  82346. pSorter->iPrev = (u8)(nWorker - 1);
  82347. pSorter->bUseThreads = (pSorter->nTask>1);
  82348. pSorter->db = db;
  82349. for(i=0; i<pSorter->nTask; i++){
  82350. SortSubtask *pTask = &pSorter->aTask[i];
  82351. pTask->pSorter = pSorter;
  82352. }
  82353. if( !sqlite3TempInMemory(db) ){
  82354. i64 mxCache; /* Cache size in bytes*/
  82355. u32 szPma = sqlite3GlobalConfig.szPma;
  82356. pSorter->mnPmaSize = szPma * pgsz;
  82357. mxCache = db->aDb[0].pSchema->cache_size;
  82358. if( mxCache<0 ){
  82359. /* A negative cache-size value C indicates that the cache is abs(C)
  82360. ** KiB in size. */
  82361. mxCache = mxCache * -1024;
  82362. }else{
  82363. mxCache = mxCache * pgsz;
  82364. }
  82365. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  82366. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  82367. /* Avoid large memory allocations if the application has requested
  82368. ** SQLITE_CONFIG_SMALL_MALLOC. */
  82369. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  82370. assert( pSorter->iMemory==0 );
  82371. pSorter->nMemory = pgsz;
  82372. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  82373. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  82374. }
  82375. }
  82376. if( pKeyInfo->nAllField<13
  82377. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  82378. ){
  82379. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  82380. }
  82381. }
  82382. return rc;
  82383. }
  82384. #undef nWorker /* Defined at the top of this function */
  82385. /*
  82386. ** Free the list of sorted records starting at pRecord.
  82387. */
  82388. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  82389. SorterRecord *p;
  82390. SorterRecord *pNext;
  82391. for(p=pRecord; p; p=pNext){
  82392. pNext = p->u.pNext;
  82393. sqlite3DbFree(db, p);
  82394. }
  82395. }
  82396. /*
  82397. ** Free all resources owned by the object indicated by argument pTask. All
  82398. ** fields of *pTask are zeroed before returning.
  82399. */
  82400. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  82401. sqlite3DbFree(db, pTask->pUnpacked);
  82402. #if SQLITE_MAX_WORKER_THREADS>0
  82403. /* pTask->list.aMemory can only be non-zero if it was handed memory
  82404. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  82405. if( pTask->list.aMemory ){
  82406. sqlite3_free(pTask->list.aMemory);
  82407. }else
  82408. #endif
  82409. {
  82410. assert( pTask->list.aMemory==0 );
  82411. vdbeSorterRecordFree(0, pTask->list.pList);
  82412. }
  82413. if( pTask->file.pFd ){
  82414. sqlite3OsCloseFree(pTask->file.pFd);
  82415. }
  82416. if( pTask->file2.pFd ){
  82417. sqlite3OsCloseFree(pTask->file2.pFd);
  82418. }
  82419. memset(pTask, 0, sizeof(SortSubtask));
  82420. }
  82421. #ifdef SQLITE_DEBUG_SORTER_THREADS
  82422. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  82423. i64 t;
  82424. int iTask = (pTask - pTask->pSorter->aTask);
  82425. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  82426. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  82427. }
  82428. static void vdbeSorterRewindDebug(const char *zEvent){
  82429. i64 t;
  82430. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  82431. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  82432. }
  82433. static void vdbeSorterPopulateDebug(
  82434. SortSubtask *pTask,
  82435. const char *zEvent
  82436. ){
  82437. i64 t;
  82438. int iTask = (pTask - pTask->pSorter->aTask);
  82439. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  82440. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  82441. }
  82442. static void vdbeSorterBlockDebug(
  82443. SortSubtask *pTask,
  82444. int bBlocked,
  82445. const char *zEvent
  82446. ){
  82447. if( bBlocked ){
  82448. i64 t;
  82449. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  82450. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  82451. }
  82452. }
  82453. #else
  82454. # define vdbeSorterWorkDebug(x,y)
  82455. # define vdbeSorterRewindDebug(y)
  82456. # define vdbeSorterPopulateDebug(x,y)
  82457. # define vdbeSorterBlockDebug(x,y,z)
  82458. #endif
  82459. #if SQLITE_MAX_WORKER_THREADS>0
  82460. /*
  82461. ** Join thread pTask->thread.
  82462. */
  82463. static int vdbeSorterJoinThread(SortSubtask *pTask){
  82464. int rc = SQLITE_OK;
  82465. if( pTask->pThread ){
  82466. #ifdef SQLITE_DEBUG_SORTER_THREADS
  82467. int bDone = pTask->bDone;
  82468. #endif
  82469. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  82470. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  82471. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  82472. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  82473. rc = SQLITE_PTR_TO_INT(pRet);
  82474. assert( pTask->bDone==1 );
  82475. pTask->bDone = 0;
  82476. pTask->pThread = 0;
  82477. }
  82478. return rc;
  82479. }
  82480. /*
  82481. ** Launch a background thread to run xTask(pIn).
  82482. */
  82483. static int vdbeSorterCreateThread(
  82484. SortSubtask *pTask, /* Thread will use this task object */
  82485. void *(*xTask)(void*), /* Routine to run in a separate thread */
  82486. void *pIn /* Argument passed into xTask() */
  82487. ){
  82488. assert( pTask->pThread==0 && pTask->bDone==0 );
  82489. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  82490. }
  82491. /*
  82492. ** Join all outstanding threads launched by SorterWrite() to create
  82493. ** level-0 PMAs.
  82494. */
  82495. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  82496. int rc = rcin;
  82497. int i;
  82498. /* This function is always called by the main user thread.
  82499. **
  82500. ** If this function is being called after SorterRewind() has been called,
  82501. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  82502. ** is currently attempt to join one of the other threads. To avoid a race
  82503. ** condition where this thread also attempts to join the same object, join
  82504. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  82505. for(i=pSorter->nTask-1; i>=0; i--){
  82506. SortSubtask *pTask = &pSorter->aTask[i];
  82507. int rc2 = vdbeSorterJoinThread(pTask);
  82508. if( rc==SQLITE_OK ) rc = rc2;
  82509. }
  82510. return rc;
  82511. }
  82512. #else
  82513. # define vdbeSorterJoinAll(x,rcin) (rcin)
  82514. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  82515. #endif
  82516. /*
  82517. ** Allocate a new MergeEngine object capable of handling up to
  82518. ** nReader PmaReader inputs.
  82519. **
  82520. ** nReader is automatically rounded up to the next power of two.
  82521. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  82522. */
  82523. static MergeEngine *vdbeMergeEngineNew(int nReader){
  82524. int N = 2; /* Smallest power of two >= nReader */
  82525. int nByte; /* Total bytes of space to allocate */
  82526. MergeEngine *pNew; /* Pointer to allocated object to return */
  82527. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  82528. while( N<nReader ) N += N;
  82529. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  82530. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  82531. if( pNew ){
  82532. pNew->nTree = N;
  82533. pNew->pTask = 0;
  82534. pNew->aReadr = (PmaReader*)&pNew[1];
  82535. pNew->aTree = (int*)&pNew->aReadr[N];
  82536. }
  82537. return pNew;
  82538. }
  82539. /*
  82540. ** Free the MergeEngine object passed as the only argument.
  82541. */
  82542. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  82543. int i;
  82544. if( pMerger ){
  82545. for(i=0; i<pMerger->nTree; i++){
  82546. vdbePmaReaderClear(&pMerger->aReadr[i]);
  82547. }
  82548. }
  82549. sqlite3_free(pMerger);
  82550. }
  82551. /*
  82552. ** Free all resources associated with the IncrMerger object indicated by
  82553. ** the first argument.
  82554. */
  82555. static void vdbeIncrFree(IncrMerger *pIncr){
  82556. if( pIncr ){
  82557. #if SQLITE_MAX_WORKER_THREADS>0
  82558. if( pIncr->bUseThread ){
  82559. vdbeSorterJoinThread(pIncr->pTask);
  82560. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  82561. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  82562. }
  82563. #endif
  82564. vdbeMergeEngineFree(pIncr->pMerger);
  82565. sqlite3_free(pIncr);
  82566. }
  82567. }
  82568. /*
  82569. ** Reset a sorting cursor back to its original empty state.
  82570. */
  82571. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  82572. int i;
  82573. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  82574. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  82575. #if SQLITE_MAX_WORKER_THREADS>0
  82576. if( pSorter->pReader ){
  82577. vdbePmaReaderClear(pSorter->pReader);
  82578. sqlite3DbFree(db, pSorter->pReader);
  82579. pSorter->pReader = 0;
  82580. }
  82581. #endif
  82582. vdbeMergeEngineFree(pSorter->pMerger);
  82583. pSorter->pMerger = 0;
  82584. for(i=0; i<pSorter->nTask; i++){
  82585. SortSubtask *pTask = &pSorter->aTask[i];
  82586. vdbeSortSubtaskCleanup(db, pTask);
  82587. pTask->pSorter = pSorter;
  82588. }
  82589. if( pSorter->list.aMemory==0 ){
  82590. vdbeSorterRecordFree(0, pSorter->list.pList);
  82591. }
  82592. pSorter->list.pList = 0;
  82593. pSorter->list.szPMA = 0;
  82594. pSorter->bUsePMA = 0;
  82595. pSorter->iMemory = 0;
  82596. pSorter->mxKeysize = 0;
  82597. sqlite3DbFree(db, pSorter->pUnpacked);
  82598. pSorter->pUnpacked = 0;
  82599. }
  82600. /*
  82601. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  82602. */
  82603. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  82604. VdbeSorter *pSorter;
  82605. assert( pCsr->eCurType==CURTYPE_SORTER );
  82606. pSorter = pCsr->uc.pSorter;
  82607. if( pSorter ){
  82608. sqlite3VdbeSorterReset(db, pSorter);
  82609. sqlite3_free(pSorter->list.aMemory);
  82610. sqlite3DbFree(db, pSorter);
  82611. pCsr->uc.pSorter = 0;
  82612. }
  82613. }
  82614. #if SQLITE_MAX_MMAP_SIZE>0
  82615. /*
  82616. ** The first argument is a file-handle open on a temporary file. The file
  82617. ** is guaranteed to be nByte bytes or smaller in size. This function
  82618. ** attempts to extend the file to nByte bytes in size and to ensure that
  82619. ** the VFS has memory mapped it.
  82620. **
  82621. ** Whether or not the file does end up memory mapped of course depends on
  82622. ** the specific VFS implementation.
  82623. */
  82624. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  82625. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  82626. void *p = 0;
  82627. int chunksize = 4*1024;
  82628. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  82629. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  82630. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  82631. sqlite3OsUnfetch(pFd, 0, p);
  82632. }
  82633. }
  82634. #else
  82635. # define vdbeSorterExtendFile(x,y,z)
  82636. #endif
  82637. /*
  82638. ** Allocate space for a file-handle and open a temporary file. If successful,
  82639. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  82640. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  82641. */
  82642. static int vdbeSorterOpenTempFile(
  82643. sqlite3 *db, /* Database handle doing sort */
  82644. i64 nExtend, /* Attempt to extend file to this size */
  82645. sqlite3_file **ppFd
  82646. ){
  82647. int rc;
  82648. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  82649. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  82650. SQLITE_OPEN_TEMP_JOURNAL |
  82651. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  82652. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  82653. );
  82654. if( rc==SQLITE_OK ){
  82655. i64 max = SQLITE_MAX_MMAP_SIZE;
  82656. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  82657. if( nExtend>0 ){
  82658. vdbeSorterExtendFile(db, *ppFd, nExtend);
  82659. }
  82660. }
  82661. return rc;
  82662. }
  82663. /*
  82664. ** If it has not already been allocated, allocate the UnpackedRecord
  82665. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  82666. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  82667. */
  82668. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  82669. if( pTask->pUnpacked==0 ){
  82670. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  82671. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  82672. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  82673. pTask->pUnpacked->errCode = 0;
  82674. }
  82675. return SQLITE_OK;
  82676. }
  82677. /*
  82678. ** Merge the two sorted lists p1 and p2 into a single list.
  82679. */
  82680. static SorterRecord *vdbeSorterMerge(
  82681. SortSubtask *pTask, /* Calling thread context */
  82682. SorterRecord *p1, /* First list to merge */
  82683. SorterRecord *p2 /* Second list to merge */
  82684. ){
  82685. SorterRecord *pFinal = 0;
  82686. SorterRecord **pp = &pFinal;
  82687. int bCached = 0;
  82688. assert( p1!=0 && p2!=0 );
  82689. for(;;){
  82690. int res;
  82691. res = pTask->xCompare(
  82692. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  82693. );
  82694. if( res<=0 ){
  82695. *pp = p1;
  82696. pp = &p1->u.pNext;
  82697. p1 = p1->u.pNext;
  82698. if( p1==0 ){
  82699. *pp = p2;
  82700. break;
  82701. }
  82702. }else{
  82703. *pp = p2;
  82704. pp = &p2->u.pNext;
  82705. p2 = p2->u.pNext;
  82706. bCached = 0;
  82707. if( p2==0 ){
  82708. *pp = p1;
  82709. break;
  82710. }
  82711. }
  82712. }
  82713. return pFinal;
  82714. }
  82715. /*
  82716. ** Return the SorterCompare function to compare values collected by the
  82717. ** sorter object passed as the only argument.
  82718. */
  82719. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  82720. if( p->typeMask==SORTER_TYPE_INTEGER ){
  82721. return vdbeSorterCompareInt;
  82722. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  82723. return vdbeSorterCompareText;
  82724. }
  82725. return vdbeSorterCompare;
  82726. }
  82727. /*
  82728. ** Sort the linked list of records headed at pTask->pList. Return
  82729. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  82730. ** an error occurs.
  82731. */
  82732. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  82733. int i;
  82734. SorterRecord **aSlot;
  82735. SorterRecord *p;
  82736. int rc;
  82737. rc = vdbeSortAllocUnpacked(pTask);
  82738. if( rc!=SQLITE_OK ) return rc;
  82739. p = pList->pList;
  82740. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  82741. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  82742. if( !aSlot ){
  82743. return SQLITE_NOMEM_BKPT;
  82744. }
  82745. while( p ){
  82746. SorterRecord *pNext;
  82747. if( pList->aMemory ){
  82748. if( (u8*)p==pList->aMemory ){
  82749. pNext = 0;
  82750. }else{
  82751. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  82752. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  82753. }
  82754. }else{
  82755. pNext = p->u.pNext;
  82756. }
  82757. p->u.pNext = 0;
  82758. for(i=0; aSlot[i]; i++){
  82759. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  82760. aSlot[i] = 0;
  82761. }
  82762. aSlot[i] = p;
  82763. p = pNext;
  82764. }
  82765. p = 0;
  82766. for(i=0; i<64; i++){
  82767. if( aSlot[i]==0 ) continue;
  82768. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  82769. }
  82770. pList->pList = p;
  82771. sqlite3_free(aSlot);
  82772. assert( pTask->pUnpacked->errCode==SQLITE_OK
  82773. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  82774. );
  82775. return pTask->pUnpacked->errCode;
  82776. }
  82777. /*
  82778. ** Initialize a PMA-writer object.
  82779. */
  82780. static void vdbePmaWriterInit(
  82781. sqlite3_file *pFd, /* File handle to write to */
  82782. PmaWriter *p, /* Object to populate */
  82783. int nBuf, /* Buffer size */
  82784. i64 iStart /* Offset of pFd to begin writing at */
  82785. ){
  82786. memset(p, 0, sizeof(PmaWriter));
  82787. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  82788. if( !p->aBuffer ){
  82789. p->eFWErr = SQLITE_NOMEM_BKPT;
  82790. }else{
  82791. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  82792. p->iWriteOff = iStart - p->iBufStart;
  82793. p->nBuffer = nBuf;
  82794. p->pFd = pFd;
  82795. }
  82796. }
  82797. /*
  82798. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  82799. ** if successful, or an SQLite error code if an error occurs.
  82800. */
  82801. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  82802. int nRem = nData;
  82803. while( nRem>0 && p->eFWErr==0 ){
  82804. int nCopy = nRem;
  82805. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  82806. nCopy = p->nBuffer - p->iBufEnd;
  82807. }
  82808. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  82809. p->iBufEnd += nCopy;
  82810. if( p->iBufEnd==p->nBuffer ){
  82811. p->eFWErr = sqlite3OsWrite(p->pFd,
  82812. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  82813. p->iWriteOff + p->iBufStart
  82814. );
  82815. p->iBufStart = p->iBufEnd = 0;
  82816. p->iWriteOff += p->nBuffer;
  82817. }
  82818. assert( p->iBufEnd<p->nBuffer );
  82819. nRem -= nCopy;
  82820. }
  82821. }
  82822. /*
  82823. ** Flush any buffered data to disk and clean up the PMA-writer object.
  82824. ** The results of using the PMA-writer after this call are undefined.
  82825. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  82826. ** required. Otherwise, return an SQLite error code.
  82827. **
  82828. ** Before returning, set *piEof to the offset immediately following the
  82829. ** last byte written to the file.
  82830. */
  82831. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  82832. int rc;
  82833. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  82834. p->eFWErr = sqlite3OsWrite(p->pFd,
  82835. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  82836. p->iWriteOff + p->iBufStart
  82837. );
  82838. }
  82839. *piEof = (p->iWriteOff + p->iBufEnd);
  82840. sqlite3_free(p->aBuffer);
  82841. rc = p->eFWErr;
  82842. memset(p, 0, sizeof(PmaWriter));
  82843. return rc;
  82844. }
  82845. /*
  82846. ** Write value iVal encoded as a varint to the PMA. Return
  82847. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  82848. */
  82849. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  82850. int nByte;
  82851. u8 aByte[10];
  82852. nByte = sqlite3PutVarint(aByte, iVal);
  82853. vdbePmaWriteBlob(p, aByte, nByte);
  82854. }
  82855. /*
  82856. ** Write the current contents of in-memory linked-list pList to a level-0
  82857. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  82858. ** successful, or an SQLite error code otherwise.
  82859. **
  82860. ** The format of a PMA is:
  82861. **
  82862. ** * A varint. This varint contains the total number of bytes of content
  82863. ** in the PMA (not including the varint itself).
  82864. **
  82865. ** * One or more records packed end-to-end in order of ascending keys.
  82866. ** Each record consists of a varint followed by a blob of data (the
  82867. ** key). The varint is the number of bytes in the blob of data.
  82868. */
  82869. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  82870. sqlite3 *db = pTask->pSorter->db;
  82871. int rc = SQLITE_OK; /* Return code */
  82872. PmaWriter writer; /* Object used to write to the file */
  82873. #ifdef SQLITE_DEBUG
  82874. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  82875. ** This is used by an assert() statement at the end of this function. */
  82876. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  82877. #endif
  82878. vdbeSorterWorkDebug(pTask, "enter");
  82879. memset(&writer, 0, sizeof(PmaWriter));
  82880. assert( pList->szPMA>0 );
  82881. /* If the first temporary PMA file has not been opened, open it now. */
  82882. if( pTask->file.pFd==0 ){
  82883. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  82884. assert( rc!=SQLITE_OK || pTask->file.pFd );
  82885. assert( pTask->file.iEof==0 );
  82886. assert( pTask->nPMA==0 );
  82887. }
  82888. /* Try to get the file to memory map */
  82889. if( rc==SQLITE_OK ){
  82890. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  82891. }
  82892. /* Sort the list */
  82893. if( rc==SQLITE_OK ){
  82894. rc = vdbeSorterSort(pTask, pList);
  82895. }
  82896. if( rc==SQLITE_OK ){
  82897. SorterRecord *p;
  82898. SorterRecord *pNext = 0;
  82899. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  82900. pTask->file.iEof);
  82901. pTask->nPMA++;
  82902. vdbePmaWriteVarint(&writer, pList->szPMA);
  82903. for(p=pList->pList; p; p=pNext){
  82904. pNext = p->u.pNext;
  82905. vdbePmaWriteVarint(&writer, p->nVal);
  82906. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  82907. if( pList->aMemory==0 ) sqlite3_free(p);
  82908. }
  82909. pList->pList = p;
  82910. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  82911. }
  82912. vdbeSorterWorkDebug(pTask, "exit");
  82913. assert( rc!=SQLITE_OK || pList->pList==0 );
  82914. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  82915. return rc;
  82916. }
  82917. /*
  82918. ** Advance the MergeEngine to its next entry.
  82919. ** Set *pbEof to true there is no next entry because
  82920. ** the MergeEngine has reached the end of all its inputs.
  82921. **
  82922. ** Return SQLITE_OK if successful or an error code if an error occurs.
  82923. */
  82924. static int vdbeMergeEngineStep(
  82925. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  82926. int *pbEof /* Set TRUE at EOF. Set false for more content */
  82927. ){
  82928. int rc;
  82929. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  82930. SortSubtask *pTask = pMerger->pTask;
  82931. /* Advance the current PmaReader */
  82932. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  82933. /* Update contents of aTree[] */
  82934. if( rc==SQLITE_OK ){
  82935. int i; /* Index of aTree[] to recalculate */
  82936. PmaReader *pReadr1; /* First PmaReader to compare */
  82937. PmaReader *pReadr2; /* Second PmaReader to compare */
  82938. int bCached = 0;
  82939. /* Find the first two PmaReaders to compare. The one that was just
  82940. ** advanced (iPrev) and the one next to it in the array. */
  82941. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  82942. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  82943. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  82944. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  82945. int iRes;
  82946. if( pReadr1->pFd==0 ){
  82947. iRes = +1;
  82948. }else if( pReadr2->pFd==0 ){
  82949. iRes = -1;
  82950. }else{
  82951. iRes = pTask->xCompare(pTask, &bCached,
  82952. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  82953. );
  82954. }
  82955. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  82956. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  82957. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  82958. ** pKey2 to point to the record belonging to pReadr2.
  82959. **
  82960. ** Alternatively, if pReadr2 contains the smaller of the two values,
  82961. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  82962. ** was actually called above, then pTask->pUnpacked now contains
  82963. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  82964. ** vdbeSorterCompare() from decoding pReadr2 again.
  82965. **
  82966. ** If the two values were equal, then the value from the oldest
  82967. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  82968. ** is sorted from oldest to newest, so pReadr1 contains older values
  82969. ** than pReadr2 iff (pReadr1<pReadr2). */
  82970. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  82971. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  82972. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82973. bCached = 0;
  82974. }else{
  82975. if( pReadr1->pFd ) bCached = 0;
  82976. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  82977. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82978. }
  82979. }
  82980. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  82981. }
  82982. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  82983. }
  82984. #if SQLITE_MAX_WORKER_THREADS>0
  82985. /*
  82986. ** The main routine for background threads that write level-0 PMAs.
  82987. */
  82988. static void *vdbeSorterFlushThread(void *pCtx){
  82989. SortSubtask *pTask = (SortSubtask*)pCtx;
  82990. int rc; /* Return code */
  82991. assert( pTask->bDone==0 );
  82992. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  82993. pTask->bDone = 1;
  82994. return SQLITE_INT_TO_PTR(rc);
  82995. }
  82996. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  82997. /*
  82998. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  82999. ** using a background thread.
  83000. */
  83001. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  83002. #if SQLITE_MAX_WORKER_THREADS==0
  83003. pSorter->bUsePMA = 1;
  83004. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  83005. #else
  83006. int rc = SQLITE_OK;
  83007. int i;
  83008. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  83009. int nWorker = (pSorter->nTask-1);
  83010. /* Set the flag to indicate that at least one PMA has been written.
  83011. ** Or will be, anyhow. */
  83012. pSorter->bUsePMA = 1;
  83013. /* Select a sub-task to sort and flush the current list of in-memory
  83014. ** records to disk. If the sorter is running in multi-threaded mode,
  83015. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  83016. ** the background thread from a sub-tasks previous turn is still running,
  83017. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  83018. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  83019. ** sub-tasks are prefered as they use background threads - the final
  83020. ** sub-task uses the main thread. */
  83021. for(i=0; i<nWorker; i++){
  83022. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  83023. pTask = &pSorter->aTask[iTest];
  83024. if( pTask->bDone ){
  83025. rc = vdbeSorterJoinThread(pTask);
  83026. }
  83027. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  83028. }
  83029. if( rc==SQLITE_OK ){
  83030. if( i==nWorker ){
  83031. /* Use the foreground thread for this operation */
  83032. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  83033. }else{
  83034. /* Launch a background thread for this operation */
  83035. u8 *aMem = pTask->list.aMemory;
  83036. void *pCtx = (void*)pTask;
  83037. assert( pTask->pThread==0 && pTask->bDone==0 );
  83038. assert( pTask->list.pList==0 );
  83039. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  83040. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  83041. pTask->list = pSorter->list;
  83042. pSorter->list.pList = 0;
  83043. pSorter->list.szPMA = 0;
  83044. if( aMem ){
  83045. pSorter->list.aMemory = aMem;
  83046. pSorter->nMemory = sqlite3MallocSize(aMem);
  83047. }else if( pSorter->list.aMemory ){
  83048. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  83049. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  83050. }
  83051. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  83052. }
  83053. }
  83054. return rc;
  83055. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  83056. }
  83057. /*
  83058. ** Add a record to the sorter.
  83059. */
  83060. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  83061. const VdbeCursor *pCsr, /* Sorter cursor */
  83062. Mem *pVal /* Memory cell containing record */
  83063. ){
  83064. VdbeSorter *pSorter;
  83065. int rc = SQLITE_OK; /* Return Code */
  83066. SorterRecord *pNew; /* New list element */
  83067. int bFlush; /* True to flush contents of memory to PMA */
  83068. int nReq; /* Bytes of memory required */
  83069. int nPMA; /* Bytes of PMA space required */
  83070. int t; /* serial type of first record field */
  83071. assert( pCsr->eCurType==CURTYPE_SORTER );
  83072. pSorter = pCsr->uc.pSorter;
  83073. getVarint32((const u8*)&pVal->z[1], t);
  83074. if( t>0 && t<10 && t!=7 ){
  83075. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  83076. }else if( t>10 && (t & 0x01) ){
  83077. pSorter->typeMask &= SORTER_TYPE_TEXT;
  83078. }else{
  83079. pSorter->typeMask = 0;
  83080. }
  83081. assert( pSorter );
  83082. /* Figure out whether or not the current contents of memory should be
  83083. ** flushed to a PMA before continuing. If so, do so.
  83084. **
  83085. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  83086. ** flush the contents of memory to a new PMA if (a) at least one value is
  83087. ** already in memory and (b) the new value will not fit in memory.
  83088. **
  83089. ** Or, if using separate allocations for each record, flush the contents
  83090. ** of memory to a PMA if either of the following are true:
  83091. **
  83092. ** * The total memory allocated for the in-memory list is greater
  83093. ** than (page-size * cache-size), or
  83094. **
  83095. ** * The total memory allocated for the in-memory list is greater
  83096. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  83097. */
  83098. nReq = pVal->n + sizeof(SorterRecord);
  83099. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  83100. if( pSorter->mxPmaSize ){
  83101. if( pSorter->list.aMemory ){
  83102. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  83103. }else{
  83104. bFlush = (
  83105. (pSorter->list.szPMA > pSorter->mxPmaSize)
  83106. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  83107. );
  83108. }
  83109. if( bFlush ){
  83110. rc = vdbeSorterFlushPMA(pSorter);
  83111. pSorter->list.szPMA = 0;
  83112. pSorter->iMemory = 0;
  83113. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  83114. }
  83115. }
  83116. pSorter->list.szPMA += nPMA;
  83117. if( nPMA>pSorter->mxKeysize ){
  83118. pSorter->mxKeysize = nPMA;
  83119. }
  83120. if( pSorter->list.aMemory ){
  83121. int nMin = pSorter->iMemory + nReq;
  83122. if( nMin>pSorter->nMemory ){
  83123. u8 *aNew;
  83124. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  83125. int nNew = pSorter->nMemory * 2;
  83126. while( nNew < nMin ) nNew = nNew*2;
  83127. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  83128. if( nNew < nMin ) nNew = nMin;
  83129. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  83130. if( !aNew ) return SQLITE_NOMEM_BKPT;
  83131. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  83132. pSorter->list.aMemory = aNew;
  83133. pSorter->nMemory = nNew;
  83134. }
  83135. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  83136. pSorter->iMemory += ROUND8(nReq);
  83137. if( pSorter->list.pList ){
  83138. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  83139. }
  83140. }else{
  83141. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  83142. if( pNew==0 ){
  83143. return SQLITE_NOMEM_BKPT;
  83144. }
  83145. pNew->u.pNext = pSorter->list.pList;
  83146. }
  83147. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  83148. pNew->nVal = pVal->n;
  83149. pSorter->list.pList = pNew;
  83150. return rc;
  83151. }
  83152. /*
  83153. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  83154. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  83155. ** except that the number-of-bytes varint is omitted from the start.
  83156. */
  83157. static int vdbeIncrPopulate(IncrMerger *pIncr){
  83158. int rc = SQLITE_OK;
  83159. int rc2;
  83160. i64 iStart = pIncr->iStartOff;
  83161. SorterFile *pOut = &pIncr->aFile[1];
  83162. SortSubtask *pTask = pIncr->pTask;
  83163. MergeEngine *pMerger = pIncr->pMerger;
  83164. PmaWriter writer;
  83165. assert( pIncr->bEof==0 );
  83166. vdbeSorterPopulateDebug(pTask, "enter");
  83167. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  83168. while( rc==SQLITE_OK ){
  83169. int dummy;
  83170. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  83171. int nKey = pReader->nKey;
  83172. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  83173. /* Check if the output file is full or if the input has been exhausted.
  83174. ** In either case exit the loop. */
  83175. if( pReader->pFd==0 ) break;
  83176. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  83177. /* Write the next key to the output. */
  83178. vdbePmaWriteVarint(&writer, nKey);
  83179. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  83180. assert( pIncr->pMerger->pTask==pTask );
  83181. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  83182. }
  83183. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  83184. if( rc==SQLITE_OK ) rc = rc2;
  83185. vdbeSorterPopulateDebug(pTask, "exit");
  83186. return rc;
  83187. }
  83188. #if SQLITE_MAX_WORKER_THREADS>0
  83189. /*
  83190. ** The main routine for background threads that populate aFile[1] of
  83191. ** multi-threaded IncrMerger objects.
  83192. */
  83193. static void *vdbeIncrPopulateThread(void *pCtx){
  83194. IncrMerger *pIncr = (IncrMerger*)pCtx;
  83195. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  83196. pIncr->pTask->bDone = 1;
  83197. return pRet;
  83198. }
  83199. /*
  83200. ** Launch a background thread to populate aFile[1] of pIncr.
  83201. */
  83202. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  83203. void *p = (void*)pIncr;
  83204. assert( pIncr->bUseThread );
  83205. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  83206. }
  83207. #endif
  83208. /*
  83209. ** This function is called when the PmaReader corresponding to pIncr has
  83210. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  83211. ** aFile[0] such that the PmaReader should start rereading it from the
  83212. ** beginning.
  83213. **
  83214. ** For single-threaded objects, this is accomplished by literally reading
  83215. ** keys from pIncr->pMerger and repopulating aFile[0].
  83216. **
  83217. ** For multi-threaded objects, all that is required is to wait until the
  83218. ** background thread is finished (if it is not already) and then swap
  83219. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  83220. ** been exhausted, this function also launches a new background thread
  83221. ** to populate the new aFile[1].
  83222. **
  83223. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  83224. */
  83225. static int vdbeIncrSwap(IncrMerger *pIncr){
  83226. int rc = SQLITE_OK;
  83227. #if SQLITE_MAX_WORKER_THREADS>0
  83228. if( pIncr->bUseThread ){
  83229. rc = vdbeSorterJoinThread(pIncr->pTask);
  83230. if( rc==SQLITE_OK ){
  83231. SorterFile f0 = pIncr->aFile[0];
  83232. pIncr->aFile[0] = pIncr->aFile[1];
  83233. pIncr->aFile[1] = f0;
  83234. }
  83235. if( rc==SQLITE_OK ){
  83236. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  83237. pIncr->bEof = 1;
  83238. }else{
  83239. rc = vdbeIncrBgPopulate(pIncr);
  83240. }
  83241. }
  83242. }else
  83243. #endif
  83244. {
  83245. rc = vdbeIncrPopulate(pIncr);
  83246. pIncr->aFile[0] = pIncr->aFile[1];
  83247. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  83248. pIncr->bEof = 1;
  83249. }
  83250. }
  83251. return rc;
  83252. }
  83253. /*
  83254. ** Allocate and return a new IncrMerger object to read data from pMerger.
  83255. **
  83256. ** If an OOM condition is encountered, return NULL. In this case free the
  83257. ** pMerger argument before returning.
  83258. */
  83259. static int vdbeIncrMergerNew(
  83260. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  83261. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  83262. IncrMerger **ppOut /* Write the new IncrMerger here */
  83263. ){
  83264. int rc = SQLITE_OK;
  83265. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  83266. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  83267. if( pIncr ){
  83268. pIncr->pMerger = pMerger;
  83269. pIncr->pTask = pTask;
  83270. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  83271. pTask->file2.iEof += pIncr->mxSz;
  83272. }else{
  83273. vdbeMergeEngineFree(pMerger);
  83274. rc = SQLITE_NOMEM_BKPT;
  83275. }
  83276. return rc;
  83277. }
  83278. #if SQLITE_MAX_WORKER_THREADS>0
  83279. /*
  83280. ** Set the "use-threads" flag on object pIncr.
  83281. */
  83282. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  83283. pIncr->bUseThread = 1;
  83284. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  83285. }
  83286. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  83287. /*
  83288. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  83289. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  83290. ** are advanced. This routine merely does the comparison.
  83291. */
  83292. static void vdbeMergeEngineCompare(
  83293. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  83294. int iOut /* Store the result in pMerger->aTree[iOut] */
  83295. ){
  83296. int i1;
  83297. int i2;
  83298. int iRes;
  83299. PmaReader *p1;
  83300. PmaReader *p2;
  83301. assert( iOut<pMerger->nTree && iOut>0 );
  83302. if( iOut>=(pMerger->nTree/2) ){
  83303. i1 = (iOut - pMerger->nTree/2) * 2;
  83304. i2 = i1 + 1;
  83305. }else{
  83306. i1 = pMerger->aTree[iOut*2];
  83307. i2 = pMerger->aTree[iOut*2+1];
  83308. }
  83309. p1 = &pMerger->aReadr[i1];
  83310. p2 = &pMerger->aReadr[i2];
  83311. if( p1->pFd==0 ){
  83312. iRes = i2;
  83313. }else if( p2->pFd==0 ){
  83314. iRes = i1;
  83315. }else{
  83316. SortSubtask *pTask = pMerger->pTask;
  83317. int bCached = 0;
  83318. int res;
  83319. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  83320. res = pTask->xCompare(
  83321. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  83322. );
  83323. if( res<=0 ){
  83324. iRes = i1;
  83325. }else{
  83326. iRes = i2;
  83327. }
  83328. }
  83329. pMerger->aTree[iOut] = iRes;
  83330. }
  83331. /*
  83332. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  83333. ** and vdbePmaReaderIncrMergeInit().
  83334. **
  83335. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  83336. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  83337. ** when there exists one or more separate worker threads.
  83338. */
  83339. #define INCRINIT_NORMAL 0
  83340. #define INCRINIT_TASK 1
  83341. #define INCRINIT_ROOT 2
  83342. /*
  83343. ** Forward reference required as the vdbeIncrMergeInit() and
  83344. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  83345. ** building a merge tree.
  83346. */
  83347. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  83348. /*
  83349. ** Initialize the MergeEngine object passed as the second argument. Once this
  83350. ** function returns, the first key of merged data may be read from the
  83351. ** MergeEngine object in the usual fashion.
  83352. **
  83353. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  83354. ** objects attached to the PmaReader objects that the merger reads from have
  83355. ** already been populated, but that they have not yet populated aFile[0] and
  83356. ** set the PmaReader objects up to read from it. In this case all that is
  83357. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  83358. ** its first key.
  83359. **
  83360. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  83361. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  83362. ** to pMerger.
  83363. **
  83364. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  83365. */
  83366. static int vdbeMergeEngineInit(
  83367. SortSubtask *pTask, /* Thread that will run pMerger */
  83368. MergeEngine *pMerger, /* MergeEngine to initialize */
  83369. int eMode /* One of the INCRINIT_XXX constants */
  83370. ){
  83371. int rc = SQLITE_OK; /* Return code */
  83372. int i; /* For looping over PmaReader objects */
  83373. int nTree = pMerger->nTree;
  83374. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  83375. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  83376. /* Verify that the MergeEngine is assigned to a single thread */
  83377. assert( pMerger->pTask==0 );
  83378. pMerger->pTask = pTask;
  83379. for(i=0; i<nTree; i++){
  83380. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  83381. /* PmaReaders should be normally initialized in order, as if they are
  83382. ** reading from the same temp file this makes for more linear file IO.
  83383. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  83384. ** in use it will block the vdbePmaReaderNext() call while it uses
  83385. ** the main thread to fill its buffer. So calling PmaReaderNext()
  83386. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  83387. ** better advantage of multi-processor hardware. */
  83388. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  83389. }else{
  83390. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  83391. }
  83392. if( rc!=SQLITE_OK ) return rc;
  83393. }
  83394. for(i=pMerger->nTree-1; i>0; i--){
  83395. vdbeMergeEngineCompare(pMerger, i);
  83396. }
  83397. return pTask->pUnpacked->errCode;
  83398. }
  83399. /*
  83400. ** The PmaReader passed as the first argument is guaranteed to be an
  83401. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  83402. ** and/or initialize the temp file related fields of the IncrMerge
  83403. ** object at (pReadr->pIncr).
  83404. **
  83405. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  83406. ** in the sub-tree headed by pReadr are also initialized. Data is then
  83407. ** loaded into the buffers belonging to pReadr and it is set to point to
  83408. ** the first key in its range.
  83409. **
  83410. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  83411. ** to be a multi-threaded PmaReader and this function is being called in a
  83412. ** background thread. In this case all PmaReaders in the sub-tree are
  83413. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  83414. ** pReadr is populated. However, pReadr itself is not set up to point
  83415. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  83416. ** that.
  83417. **
  83418. ** The reason this function does not call vdbePmaReaderNext() immediately
  83419. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  83420. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  83421. ** this entire function is being run by thread (pTask->thread), that will
  83422. ** lead to the current background thread attempting to join itself.
  83423. **
  83424. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  83425. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  83426. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  83427. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  83428. ** the current PmaReader set to point to the first key in its range.
  83429. **
  83430. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  83431. */
  83432. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  83433. int rc = SQLITE_OK;
  83434. IncrMerger *pIncr = pReadr->pIncr;
  83435. SortSubtask *pTask = pIncr->pTask;
  83436. sqlite3 *db = pTask->pSorter->db;
  83437. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  83438. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  83439. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  83440. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  83441. ** requires two temp files to itself, whereas a single-threaded object
  83442. ** only requires a region of pTask->file2. */
  83443. if( rc==SQLITE_OK ){
  83444. int mxSz = pIncr->mxSz;
  83445. #if SQLITE_MAX_WORKER_THREADS>0
  83446. if( pIncr->bUseThread ){
  83447. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  83448. if( rc==SQLITE_OK ){
  83449. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  83450. }
  83451. }else
  83452. #endif
  83453. /*if( !pIncr->bUseThread )*/{
  83454. if( pTask->file2.pFd==0 ){
  83455. assert( pTask->file2.iEof>0 );
  83456. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  83457. pTask->file2.iEof = 0;
  83458. }
  83459. if( rc==SQLITE_OK ){
  83460. pIncr->aFile[1].pFd = pTask->file2.pFd;
  83461. pIncr->iStartOff = pTask->file2.iEof;
  83462. pTask->file2.iEof += mxSz;
  83463. }
  83464. }
  83465. }
  83466. #if SQLITE_MAX_WORKER_THREADS>0
  83467. if( rc==SQLITE_OK && pIncr->bUseThread ){
  83468. /* Use the current thread to populate aFile[1], even though this
  83469. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  83470. ** then this function is already running in background thread
  83471. ** pIncr->pTask->thread.
  83472. **
  83473. ** If this is the INCRINIT_ROOT object, then it is running in the
  83474. ** main VDBE thread. But that is Ok, as that thread cannot return
  83475. ** control to the VDBE or proceed with anything useful until the
  83476. ** first results are ready from this merger object anyway.
  83477. */
  83478. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  83479. rc = vdbeIncrPopulate(pIncr);
  83480. }
  83481. #endif
  83482. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  83483. rc = vdbePmaReaderNext(pReadr);
  83484. }
  83485. return rc;
  83486. }
  83487. #if SQLITE_MAX_WORKER_THREADS>0
  83488. /*
  83489. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  83490. ** background threads.
  83491. */
  83492. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  83493. PmaReader *pReader = (PmaReader*)pCtx;
  83494. void *pRet = SQLITE_INT_TO_PTR(
  83495. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  83496. );
  83497. pReader->pIncr->pTask->bDone = 1;
  83498. return pRet;
  83499. }
  83500. #endif
  83501. /*
  83502. ** If the PmaReader passed as the first argument is not an incremental-reader
  83503. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  83504. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  83505. ** this routine to initialize the incremental merge.
  83506. **
  83507. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  83508. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  83509. ** Or, if the IncrMerger is single threaded, the same function is called
  83510. ** using the current thread.
  83511. */
  83512. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  83513. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  83514. int rc = SQLITE_OK; /* Return code */
  83515. if( pIncr ){
  83516. #if SQLITE_MAX_WORKER_THREADS>0
  83517. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  83518. if( pIncr->bUseThread ){
  83519. void *pCtx = (void*)pReadr;
  83520. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  83521. }else
  83522. #endif
  83523. {
  83524. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  83525. }
  83526. }
  83527. return rc;
  83528. }
  83529. /*
  83530. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  83531. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  83532. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  83533. ** to NULL and return an SQLite error code.
  83534. **
  83535. ** When this function is called, *piOffset is set to the offset of the
  83536. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  83537. ** set to the offset immediately following the last byte of the last
  83538. ** PMA before returning. If an error does occur, then the final value of
  83539. ** *piOffset is undefined.
  83540. */
  83541. static int vdbeMergeEngineLevel0(
  83542. SortSubtask *pTask, /* Sorter task to read from */
  83543. int nPMA, /* Number of PMAs to read */
  83544. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  83545. MergeEngine **ppOut /* OUT: New merge-engine */
  83546. ){
  83547. MergeEngine *pNew; /* Merge engine to return */
  83548. i64 iOff = *piOffset;
  83549. int i;
  83550. int rc = SQLITE_OK;
  83551. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  83552. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  83553. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  83554. i64 nDummy = 0;
  83555. PmaReader *pReadr = &pNew->aReadr[i];
  83556. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  83557. iOff = pReadr->iEof;
  83558. }
  83559. if( rc!=SQLITE_OK ){
  83560. vdbeMergeEngineFree(pNew);
  83561. *ppOut = 0;
  83562. }
  83563. *piOffset = iOff;
  83564. return rc;
  83565. }
  83566. /*
  83567. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  83568. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  83569. **
  83570. ** i.e.
  83571. **
  83572. ** nPMA<=16 -> TreeDepth() == 0
  83573. ** nPMA<=256 -> TreeDepth() == 1
  83574. ** nPMA<=65536 -> TreeDepth() == 2
  83575. */
  83576. static int vdbeSorterTreeDepth(int nPMA){
  83577. int nDepth = 0;
  83578. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  83579. while( nDiv < (i64)nPMA ){
  83580. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  83581. nDepth++;
  83582. }
  83583. return nDepth;
  83584. }
  83585. /*
  83586. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  83587. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  83588. ** tree, counting from zero. This function adds pLeaf to the tree.
  83589. **
  83590. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  83591. ** code is returned and pLeaf is freed.
  83592. */
  83593. static int vdbeSorterAddToTree(
  83594. SortSubtask *pTask, /* Task context */
  83595. int nDepth, /* Depth of tree according to TreeDepth() */
  83596. int iSeq, /* Sequence number of leaf within tree */
  83597. MergeEngine *pRoot, /* Root of tree */
  83598. MergeEngine *pLeaf /* Leaf to add to tree */
  83599. ){
  83600. int rc = SQLITE_OK;
  83601. int nDiv = 1;
  83602. int i;
  83603. MergeEngine *p = pRoot;
  83604. IncrMerger *pIncr;
  83605. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  83606. for(i=1; i<nDepth; i++){
  83607. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  83608. }
  83609. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  83610. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  83611. PmaReader *pReadr = &p->aReadr[iIter];
  83612. if( pReadr->pIncr==0 ){
  83613. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  83614. if( pNew==0 ){
  83615. rc = SQLITE_NOMEM_BKPT;
  83616. }else{
  83617. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  83618. }
  83619. }
  83620. if( rc==SQLITE_OK ){
  83621. p = pReadr->pIncr->pMerger;
  83622. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  83623. }
  83624. }
  83625. if( rc==SQLITE_OK ){
  83626. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  83627. }else{
  83628. vdbeIncrFree(pIncr);
  83629. }
  83630. return rc;
  83631. }
  83632. /*
  83633. ** This function is called as part of a SorterRewind() operation on a sorter
  83634. ** that has already written two or more level-0 PMAs to one or more temp
  83635. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  83636. ** can be used to incrementally merge all PMAs on disk.
  83637. **
  83638. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  83639. ** MergeEngine object at the root of the tree before returning. Or, if an
  83640. ** error occurs, an SQLite error code is returned and the final value
  83641. ** of *ppOut is undefined.
  83642. */
  83643. static int vdbeSorterMergeTreeBuild(
  83644. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  83645. MergeEngine **ppOut /* Write the MergeEngine here */
  83646. ){
  83647. MergeEngine *pMain = 0;
  83648. int rc = SQLITE_OK;
  83649. int iTask;
  83650. #if SQLITE_MAX_WORKER_THREADS>0
  83651. /* If the sorter uses more than one task, then create the top-level
  83652. ** MergeEngine here. This MergeEngine will read data from exactly
  83653. ** one PmaReader per sub-task. */
  83654. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  83655. if( pSorter->nTask>1 ){
  83656. pMain = vdbeMergeEngineNew(pSorter->nTask);
  83657. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  83658. }
  83659. #endif
  83660. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  83661. SortSubtask *pTask = &pSorter->aTask[iTask];
  83662. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  83663. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  83664. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  83665. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  83666. i64 iReadOff = 0;
  83667. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  83668. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  83669. }else{
  83670. int i;
  83671. int iSeq = 0;
  83672. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  83673. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  83674. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  83675. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  83676. int nReader; /* Number of level-0 PMAs to merge */
  83677. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  83678. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  83679. if( rc==SQLITE_OK ){
  83680. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  83681. }
  83682. }
  83683. }
  83684. if( rc==SQLITE_OK ){
  83685. #if SQLITE_MAX_WORKER_THREADS>0
  83686. if( pMain!=0 ){
  83687. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  83688. }else
  83689. #endif
  83690. {
  83691. assert( pMain==0 );
  83692. pMain = pRoot;
  83693. }
  83694. }else{
  83695. vdbeMergeEngineFree(pRoot);
  83696. }
  83697. }
  83698. }
  83699. if( rc!=SQLITE_OK ){
  83700. vdbeMergeEngineFree(pMain);
  83701. pMain = 0;
  83702. }
  83703. *ppOut = pMain;
  83704. return rc;
  83705. }
  83706. /*
  83707. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  83708. ** on a sorter that has written two or more PMAs to temporary files. It sets
  83709. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  83710. ** (for multi-threaded sorters) so that it can be used to iterate through
  83711. ** all records stored in the sorter.
  83712. **
  83713. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  83714. */
  83715. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  83716. int rc; /* Return code */
  83717. SortSubtask *pTask0 = &pSorter->aTask[0];
  83718. MergeEngine *pMain = 0;
  83719. #if SQLITE_MAX_WORKER_THREADS
  83720. sqlite3 *db = pTask0->pSorter->db;
  83721. int i;
  83722. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  83723. for(i=0; i<pSorter->nTask; i++){
  83724. pSorter->aTask[i].xCompare = xCompare;
  83725. }
  83726. #endif
  83727. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  83728. if( rc==SQLITE_OK ){
  83729. #if SQLITE_MAX_WORKER_THREADS
  83730. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  83731. if( pSorter->bUseThreads ){
  83732. int iTask;
  83733. PmaReader *pReadr = 0;
  83734. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  83735. rc = vdbeSortAllocUnpacked(pLast);
  83736. if( rc==SQLITE_OK ){
  83737. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  83738. pSorter->pReader = pReadr;
  83739. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  83740. }
  83741. if( rc==SQLITE_OK ){
  83742. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  83743. if( rc==SQLITE_OK ){
  83744. vdbeIncrMergerSetThreads(pReadr->pIncr);
  83745. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  83746. IncrMerger *pIncr;
  83747. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  83748. vdbeIncrMergerSetThreads(pIncr);
  83749. assert( pIncr->pTask!=pLast );
  83750. }
  83751. }
  83752. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  83753. /* Check that:
  83754. **
  83755. ** a) The incremental merge object is configured to use the
  83756. ** right task, and
  83757. ** b) If it is using task (nTask-1), it is configured to run
  83758. ** in single-threaded mode. This is important, as the
  83759. ** root merge (INCRINIT_ROOT) will be using the same task
  83760. ** object.
  83761. */
  83762. PmaReader *p = &pMain->aReadr[iTask];
  83763. assert( p->pIncr==0 || (
  83764. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  83765. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  83766. ));
  83767. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  83768. }
  83769. }
  83770. pMain = 0;
  83771. }
  83772. if( rc==SQLITE_OK ){
  83773. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  83774. }
  83775. }else
  83776. #endif
  83777. {
  83778. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  83779. pSorter->pMerger = pMain;
  83780. pMain = 0;
  83781. }
  83782. }
  83783. if( rc!=SQLITE_OK ){
  83784. vdbeMergeEngineFree(pMain);
  83785. }
  83786. return rc;
  83787. }
  83788. /*
  83789. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  83790. ** this function is called to prepare for iterating through the records
  83791. ** in sorted order.
  83792. */
  83793. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  83794. VdbeSorter *pSorter;
  83795. int rc = SQLITE_OK; /* Return code */
  83796. assert( pCsr->eCurType==CURTYPE_SORTER );
  83797. pSorter = pCsr->uc.pSorter;
  83798. assert( pSorter );
  83799. /* If no data has been written to disk, then do not do so now. Instead,
  83800. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  83801. ** from the in-memory list. */
  83802. if( pSorter->bUsePMA==0 ){
  83803. if( pSorter->list.pList ){
  83804. *pbEof = 0;
  83805. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  83806. }else{
  83807. *pbEof = 1;
  83808. }
  83809. return rc;
  83810. }
  83811. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  83812. ** function flushes the contents of memory to disk, it immediately always
  83813. ** creates a new list consisting of a single key immediately afterwards.
  83814. ** So the list is never empty at this point. */
  83815. assert( pSorter->list.pList );
  83816. rc = vdbeSorterFlushPMA(pSorter);
  83817. /* Join all threads */
  83818. rc = vdbeSorterJoinAll(pSorter, rc);
  83819. vdbeSorterRewindDebug("rewind");
  83820. /* Assuming no errors have occurred, set up a merger structure to
  83821. ** incrementally read and merge all remaining PMAs. */
  83822. assert( pSorter->pReader==0 );
  83823. if( rc==SQLITE_OK ){
  83824. rc = vdbeSorterSetupMerge(pSorter);
  83825. *pbEof = 0;
  83826. }
  83827. vdbeSorterRewindDebug("rewinddone");
  83828. return rc;
  83829. }
  83830. /*
  83831. ** Advance to the next element in the sorter. Return value:
  83832. **
  83833. ** SQLITE_OK success
  83834. ** SQLITE_DONE end of data
  83835. ** otherwise some kind of error.
  83836. */
  83837. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  83838. VdbeSorter *pSorter;
  83839. int rc; /* Return code */
  83840. assert( pCsr->eCurType==CURTYPE_SORTER );
  83841. pSorter = pCsr->uc.pSorter;
  83842. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  83843. if( pSorter->bUsePMA ){
  83844. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  83845. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  83846. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  83847. #if SQLITE_MAX_WORKER_THREADS>0
  83848. if( pSorter->bUseThreads ){
  83849. rc = vdbePmaReaderNext(pSorter->pReader);
  83850. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  83851. }else
  83852. #endif
  83853. /*if( !pSorter->bUseThreads )*/ {
  83854. int res = 0;
  83855. assert( pSorter->pMerger!=0 );
  83856. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  83857. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  83858. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  83859. }
  83860. }else{
  83861. SorterRecord *pFree = pSorter->list.pList;
  83862. pSorter->list.pList = pFree->u.pNext;
  83863. pFree->u.pNext = 0;
  83864. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  83865. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  83866. }
  83867. return rc;
  83868. }
  83869. /*
  83870. ** Return a pointer to a buffer owned by the sorter that contains the
  83871. ** current key.
  83872. */
  83873. static void *vdbeSorterRowkey(
  83874. const VdbeSorter *pSorter, /* Sorter object */
  83875. int *pnKey /* OUT: Size of current key in bytes */
  83876. ){
  83877. void *pKey;
  83878. if( pSorter->bUsePMA ){
  83879. PmaReader *pReader;
  83880. #if SQLITE_MAX_WORKER_THREADS>0
  83881. if( pSorter->bUseThreads ){
  83882. pReader = pSorter->pReader;
  83883. }else
  83884. #endif
  83885. /*if( !pSorter->bUseThreads )*/{
  83886. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  83887. }
  83888. *pnKey = pReader->nKey;
  83889. pKey = pReader->aKey;
  83890. }else{
  83891. *pnKey = pSorter->list.pList->nVal;
  83892. pKey = SRVAL(pSorter->list.pList);
  83893. }
  83894. return pKey;
  83895. }
  83896. /*
  83897. ** Copy the current sorter key into the memory cell pOut.
  83898. */
  83899. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  83900. VdbeSorter *pSorter;
  83901. void *pKey; int nKey; /* Sorter key to copy into pOut */
  83902. assert( pCsr->eCurType==CURTYPE_SORTER );
  83903. pSorter = pCsr->uc.pSorter;
  83904. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83905. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  83906. return SQLITE_NOMEM_BKPT;
  83907. }
  83908. pOut->n = nKey;
  83909. MemSetTypeFlag(pOut, MEM_Blob);
  83910. memcpy(pOut->z, pKey, nKey);
  83911. return SQLITE_OK;
  83912. }
  83913. /*
  83914. ** Compare the key in memory cell pVal with the key that the sorter cursor
  83915. ** passed as the first argument currently points to. For the purposes of
  83916. ** the comparison, ignore the rowid field at the end of each record.
  83917. **
  83918. ** If the sorter cursor key contains any NULL values, consider it to be
  83919. ** less than pVal. Even if pVal also contains NULL values.
  83920. **
  83921. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  83922. ** Otherwise, set *pRes to a negative, zero or positive value if the
  83923. ** key in pVal is smaller than, equal to or larger than the current sorter
  83924. ** key.
  83925. **
  83926. ** This routine forms the core of the OP_SorterCompare opcode, which in
  83927. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  83928. */
  83929. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  83930. const VdbeCursor *pCsr, /* Sorter cursor */
  83931. Mem *pVal, /* Value to compare to current sorter key */
  83932. int nKeyCol, /* Compare this many columns */
  83933. int *pRes /* OUT: Result of comparison */
  83934. ){
  83935. VdbeSorter *pSorter;
  83936. UnpackedRecord *r2;
  83937. KeyInfo *pKeyInfo;
  83938. int i;
  83939. void *pKey; int nKey; /* Sorter key to compare pVal with */
  83940. assert( pCsr->eCurType==CURTYPE_SORTER );
  83941. pSorter = pCsr->uc.pSorter;
  83942. r2 = pSorter->pUnpacked;
  83943. pKeyInfo = pCsr->pKeyInfo;
  83944. if( r2==0 ){
  83945. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  83946. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  83947. r2->nField = nKeyCol;
  83948. }
  83949. assert( r2->nField==nKeyCol );
  83950. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83951. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  83952. for(i=0; i<nKeyCol; i++){
  83953. if( r2->aMem[i].flags & MEM_Null ){
  83954. *pRes = -1;
  83955. return SQLITE_OK;
  83956. }
  83957. }
  83958. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  83959. return SQLITE_OK;
  83960. }
  83961. /************** End of vdbesort.c ********************************************/
  83962. /************** Begin file memjournal.c **************************************/
  83963. /*
  83964. ** 2008 October 7
  83965. **
  83966. ** The author disclaims copyright to this source code. In place of
  83967. ** a legal notice, here is a blessing:
  83968. **
  83969. ** May you do good and not evil.
  83970. ** May you find forgiveness for yourself and forgive others.
  83971. ** May you share freely, never taking more than you give.
  83972. **
  83973. *************************************************************************
  83974. **
  83975. ** This file contains code use to implement an in-memory rollback journal.
  83976. ** The in-memory rollback journal is used to journal transactions for
  83977. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  83978. **
  83979. ** Update: The in-memory journal is also used to temporarily cache
  83980. ** smaller journals that are not critical for power-loss recovery.
  83981. ** For example, statement journals that are not too big will be held
  83982. ** entirely in memory, thus reducing the number of file I/O calls, and
  83983. ** more importantly, reducing temporary file creation events. If these
  83984. ** journals become too large for memory, they are spilled to disk. But
  83985. ** in the common case, they are usually small and no file I/O needs to
  83986. ** occur.
  83987. */
  83988. /* #include "sqliteInt.h" */
  83989. /* Forward references to internal structures */
  83990. typedef struct MemJournal MemJournal;
  83991. typedef struct FilePoint FilePoint;
  83992. typedef struct FileChunk FileChunk;
  83993. /*
  83994. ** The rollback journal is composed of a linked list of these structures.
  83995. **
  83996. ** The zChunk array is always at least 8 bytes in size - usually much more.
  83997. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  83998. */
  83999. struct FileChunk {
  84000. FileChunk *pNext; /* Next chunk in the journal */
  84001. u8 zChunk[8]; /* Content of this chunk */
  84002. };
  84003. /*
  84004. ** By default, allocate this many bytes of memory for each FileChunk object.
  84005. */
  84006. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  84007. /*
  84008. ** For chunk size nChunkSize, return the number of bytes that should
  84009. ** be allocated for each FileChunk structure.
  84010. */
  84011. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  84012. /*
  84013. ** An instance of this object serves as a cursor into the rollback journal.
  84014. ** The cursor can be either for reading or writing.
  84015. */
  84016. struct FilePoint {
  84017. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  84018. FileChunk *pChunk; /* Specific chunk into which cursor points */
  84019. };
  84020. /*
  84021. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  84022. ** is an instance of this class.
  84023. */
  84024. struct MemJournal {
  84025. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  84026. int nChunkSize; /* In-memory chunk-size */
  84027. int nSpill; /* Bytes of data before flushing */
  84028. int nSize; /* Bytes of data currently in memory */
  84029. FileChunk *pFirst; /* Head of in-memory chunk-list */
  84030. FilePoint endpoint; /* Pointer to the end of the file */
  84031. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  84032. int flags; /* xOpen flags */
  84033. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  84034. const char *zJournal; /* Name of the journal file */
  84035. };
  84036. /*
  84037. ** Read data from the in-memory journal file. This is the implementation
  84038. ** of the sqlite3_vfs.xRead method.
  84039. */
  84040. static int memjrnlRead(
  84041. sqlite3_file *pJfd, /* The journal file from which to read */
  84042. void *zBuf, /* Put the results here */
  84043. int iAmt, /* Number of bytes to read */
  84044. sqlite_int64 iOfst /* Begin reading at this offset */
  84045. ){
  84046. MemJournal *p = (MemJournal *)pJfd;
  84047. u8 *zOut = zBuf;
  84048. int nRead = iAmt;
  84049. int iChunkOffset;
  84050. FileChunk *pChunk;
  84051. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  84052. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  84053. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  84054. return SQLITE_IOERR_SHORT_READ;
  84055. }
  84056. #endif
  84057. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  84058. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  84059. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  84060. sqlite3_int64 iOff = 0;
  84061. for(pChunk=p->pFirst;
  84062. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  84063. pChunk=pChunk->pNext
  84064. ){
  84065. iOff += p->nChunkSize;
  84066. }
  84067. }else{
  84068. pChunk = p->readpoint.pChunk;
  84069. assert( pChunk!=0 );
  84070. }
  84071. iChunkOffset = (int)(iOfst%p->nChunkSize);
  84072. do {
  84073. int iSpace = p->nChunkSize - iChunkOffset;
  84074. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  84075. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  84076. zOut += nCopy;
  84077. nRead -= iSpace;
  84078. iChunkOffset = 0;
  84079. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  84080. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  84081. p->readpoint.pChunk = pChunk;
  84082. return SQLITE_OK;
  84083. }
  84084. /*
  84085. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  84086. */
  84087. static void memjrnlFreeChunks(MemJournal *p){
  84088. FileChunk *pIter;
  84089. FileChunk *pNext;
  84090. for(pIter=p->pFirst; pIter; pIter=pNext){
  84091. pNext = pIter->pNext;
  84092. sqlite3_free(pIter);
  84093. }
  84094. p->pFirst = 0;
  84095. }
  84096. /*
  84097. ** Flush the contents of memory to a real file on disk.
  84098. */
  84099. static int memjrnlCreateFile(MemJournal *p){
  84100. int rc;
  84101. sqlite3_file *pReal = (sqlite3_file*)p;
  84102. MemJournal copy = *p;
  84103. memset(p, 0, sizeof(MemJournal));
  84104. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  84105. if( rc==SQLITE_OK ){
  84106. int nChunk = copy.nChunkSize;
  84107. i64 iOff = 0;
  84108. FileChunk *pIter;
  84109. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  84110. if( iOff + nChunk > copy.endpoint.iOffset ){
  84111. nChunk = copy.endpoint.iOffset - iOff;
  84112. }
  84113. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  84114. if( rc ) break;
  84115. iOff += nChunk;
  84116. }
  84117. if( rc==SQLITE_OK ){
  84118. /* No error has occurred. Free the in-memory buffers. */
  84119. memjrnlFreeChunks(&copy);
  84120. }
  84121. }
  84122. if( rc!=SQLITE_OK ){
  84123. /* If an error occurred while creating or writing to the file, restore
  84124. ** the original before returning. This way, SQLite uses the in-memory
  84125. ** journal data to roll back changes made to the internal page-cache
  84126. ** before this function was called. */
  84127. sqlite3OsClose(pReal);
  84128. *p = copy;
  84129. }
  84130. return rc;
  84131. }
  84132. /*
  84133. ** Write data to the file.
  84134. */
  84135. static int memjrnlWrite(
  84136. sqlite3_file *pJfd, /* The journal file into which to write */
  84137. const void *zBuf, /* Take data to be written from here */
  84138. int iAmt, /* Number of bytes to write */
  84139. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  84140. ){
  84141. MemJournal *p = (MemJournal *)pJfd;
  84142. int nWrite = iAmt;
  84143. u8 *zWrite = (u8 *)zBuf;
  84144. /* If the file should be created now, create it and write the new data
  84145. ** into the file on disk. */
  84146. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  84147. int rc = memjrnlCreateFile(p);
  84148. if( rc==SQLITE_OK ){
  84149. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  84150. }
  84151. return rc;
  84152. }
  84153. /* If the contents of this write should be stored in memory */
  84154. else{
  84155. /* An in-memory journal file should only ever be appended to. Random
  84156. ** access writes are not required. The only exception to this is when
  84157. ** the in-memory journal is being used by a connection using the
  84158. ** atomic-write optimization. In this case the first 28 bytes of the
  84159. ** journal file may be written as part of committing the transaction. */
  84160. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  84161. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  84162. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  84163. if( iOfst==0 && p->pFirst ){
  84164. assert( p->nChunkSize>iAmt );
  84165. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  84166. }else
  84167. #else
  84168. assert( iOfst>0 || p->pFirst==0 );
  84169. #endif
  84170. {
  84171. while( nWrite>0 ){
  84172. FileChunk *pChunk = p->endpoint.pChunk;
  84173. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  84174. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  84175. if( iChunkOffset==0 ){
  84176. /* New chunk is required to extend the file. */
  84177. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  84178. if( !pNew ){
  84179. return SQLITE_IOERR_NOMEM_BKPT;
  84180. }
  84181. pNew->pNext = 0;
  84182. if( pChunk ){
  84183. assert( p->pFirst );
  84184. pChunk->pNext = pNew;
  84185. }else{
  84186. assert( !p->pFirst );
  84187. p->pFirst = pNew;
  84188. }
  84189. p->endpoint.pChunk = pNew;
  84190. }
  84191. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  84192. zWrite += iSpace;
  84193. nWrite -= iSpace;
  84194. p->endpoint.iOffset += iSpace;
  84195. }
  84196. p->nSize = iAmt + iOfst;
  84197. }
  84198. }
  84199. return SQLITE_OK;
  84200. }
  84201. /*
  84202. ** Truncate the file.
  84203. **
  84204. ** If the journal file is already on disk, truncate it there. Or, if it
  84205. ** is still in main memory but is being truncated to zero bytes in size,
  84206. ** ignore
  84207. */
  84208. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  84209. MemJournal *p = (MemJournal *)pJfd;
  84210. if( ALWAYS(size==0) ){
  84211. memjrnlFreeChunks(p);
  84212. p->nSize = 0;
  84213. p->endpoint.pChunk = 0;
  84214. p->endpoint.iOffset = 0;
  84215. p->readpoint.pChunk = 0;
  84216. p->readpoint.iOffset = 0;
  84217. }
  84218. return SQLITE_OK;
  84219. }
  84220. /*
  84221. ** Close the file.
  84222. */
  84223. static int memjrnlClose(sqlite3_file *pJfd){
  84224. MemJournal *p = (MemJournal *)pJfd;
  84225. memjrnlFreeChunks(p);
  84226. return SQLITE_OK;
  84227. }
  84228. /*
  84229. ** Sync the file.
  84230. **
  84231. ** If the real file has been created, call its xSync method. Otherwise,
  84232. ** syncing an in-memory journal is a no-op.
  84233. */
  84234. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  84235. UNUSED_PARAMETER2(pJfd, flags);
  84236. return SQLITE_OK;
  84237. }
  84238. /*
  84239. ** Query the size of the file in bytes.
  84240. */
  84241. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  84242. MemJournal *p = (MemJournal *)pJfd;
  84243. *pSize = (sqlite_int64) p->endpoint.iOffset;
  84244. return SQLITE_OK;
  84245. }
  84246. /*
  84247. ** Table of methods for MemJournal sqlite3_file object.
  84248. */
  84249. static const struct sqlite3_io_methods MemJournalMethods = {
  84250. 1, /* iVersion */
  84251. memjrnlClose, /* xClose */
  84252. memjrnlRead, /* xRead */
  84253. memjrnlWrite, /* xWrite */
  84254. memjrnlTruncate, /* xTruncate */
  84255. memjrnlSync, /* xSync */
  84256. memjrnlFileSize, /* xFileSize */
  84257. 0, /* xLock */
  84258. 0, /* xUnlock */
  84259. 0, /* xCheckReservedLock */
  84260. 0, /* xFileControl */
  84261. 0, /* xSectorSize */
  84262. 0, /* xDeviceCharacteristics */
  84263. 0, /* xShmMap */
  84264. 0, /* xShmLock */
  84265. 0, /* xShmBarrier */
  84266. 0, /* xShmUnmap */
  84267. 0, /* xFetch */
  84268. 0 /* xUnfetch */
  84269. };
  84270. /*
  84271. ** Open a journal file.
  84272. **
  84273. ** The behaviour of the journal file depends on the value of parameter
  84274. ** nSpill. If nSpill is 0, then the journal file is always create and
  84275. ** accessed using the underlying VFS. If nSpill is less than zero, then
  84276. ** all content is always stored in main-memory. Finally, if nSpill is a
  84277. ** positive value, then the journal file is initially created in-memory
  84278. ** but may be flushed to disk later on. In this case the journal file is
  84279. ** flushed to disk either when it grows larger than nSpill bytes in size,
  84280. ** or when sqlite3JournalCreate() is called.
  84281. */
  84282. SQLITE_PRIVATE int sqlite3JournalOpen(
  84283. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  84284. const char *zName, /* Name of the journal file */
  84285. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  84286. int flags, /* Opening flags */
  84287. int nSpill /* Bytes buffered before opening the file */
  84288. ){
  84289. MemJournal *p = (MemJournal*)pJfd;
  84290. /* Zero the file-handle object. If nSpill was passed zero, initialize
  84291. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  84292. ** case none of the code in this module is executed as a result of calls
  84293. ** made on the journal file-handle. */
  84294. memset(p, 0, sizeof(MemJournal));
  84295. if( nSpill==0 ){
  84296. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  84297. }
  84298. if( nSpill>0 ){
  84299. p->nChunkSize = nSpill;
  84300. }else{
  84301. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  84302. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  84303. }
  84304. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  84305. p->nSpill = nSpill;
  84306. p->flags = flags;
  84307. p->zJournal = zName;
  84308. p->pVfs = pVfs;
  84309. return SQLITE_OK;
  84310. }
  84311. /*
  84312. ** Open an in-memory journal file.
  84313. */
  84314. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  84315. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  84316. }
  84317. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  84318. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  84319. /*
  84320. ** If the argument p points to a MemJournal structure that is not an
  84321. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  84322. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  84323. ** file has not yet been created, create it now.
  84324. */
  84325. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  84326. int rc = SQLITE_OK;
  84327. MemJournal *p = (MemJournal*)pJfd;
  84328. if( p->pMethod==&MemJournalMethods && (
  84329. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  84330. p->nSpill>0
  84331. #else
  84332. /* While this appears to not be possible without ATOMIC_WRITE, the
  84333. ** paths are complex, so it seems prudent to leave the test in as
  84334. ** a NEVER(), in case our analysis is subtly flawed. */
  84335. NEVER(p->nSpill>0)
  84336. #endif
  84337. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  84338. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  84339. #endif
  84340. )){
  84341. rc = memjrnlCreateFile(p);
  84342. }
  84343. return rc;
  84344. }
  84345. #endif
  84346. /*
  84347. ** The file-handle passed as the only argument is open on a journal file.
  84348. ** Return true if this "journal file" is currently stored in heap memory,
  84349. ** or false otherwise.
  84350. */
  84351. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  84352. return p->pMethods==&MemJournalMethods;
  84353. }
  84354. /*
  84355. ** Return the number of bytes required to store a JournalFile that uses vfs
  84356. ** pVfs to create the underlying on-disk files.
  84357. */
  84358. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  84359. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  84360. }
  84361. /************** End of memjournal.c ******************************************/
  84362. /************** Begin file walker.c ******************************************/
  84363. /*
  84364. ** 2008 August 16
  84365. **
  84366. ** The author disclaims copyright to this source code. In place of
  84367. ** a legal notice, here is a blessing:
  84368. **
  84369. ** May you do good and not evil.
  84370. ** May you find forgiveness for yourself and forgive others.
  84371. ** May you share freely, never taking more than you give.
  84372. **
  84373. *************************************************************************
  84374. ** This file contains routines used for walking the parser tree for
  84375. ** an SQL statement.
  84376. */
  84377. /* #include "sqliteInt.h" */
  84378. /* #include <stdlib.h> */
  84379. /* #include <string.h> */
  84380. /*
  84381. ** Walk an expression tree. Invoke the callback once for each node
  84382. ** of the expression, while descending. (In other words, the callback
  84383. ** is invoked before visiting children.)
  84384. **
  84385. ** The return value from the callback should be one of the WRC_*
  84386. ** constants to specify how to proceed with the walk.
  84387. **
  84388. ** WRC_Continue Continue descending down the tree.
  84389. **
  84390. ** WRC_Prune Do not descend into child nodes, but allow
  84391. ** the walk to continue with sibling nodes.
  84392. **
  84393. ** WRC_Abort Do no more callbacks. Unwind the stack and
  84394. ** return from the top-level walk call.
  84395. **
  84396. ** The return value from this routine is WRC_Abort to abandon the tree walk
  84397. ** and WRC_Continue to continue.
  84398. */
  84399. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  84400. int rc;
  84401. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  84402. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  84403. while(1){
  84404. rc = pWalker->xExprCallback(pWalker, pExpr);
  84405. if( rc ) return rc & WRC_Abort;
  84406. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  84407. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  84408. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  84409. if( pExpr->pRight ){
  84410. pExpr = pExpr->pRight;
  84411. continue;
  84412. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84413. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  84414. }else if( pExpr->x.pList ){
  84415. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  84416. }
  84417. }
  84418. break;
  84419. }
  84420. return WRC_Continue;
  84421. }
  84422. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  84423. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  84424. }
  84425. /*
  84426. ** Call sqlite3WalkExpr() for every expression in list p or until
  84427. ** an abort request is seen.
  84428. */
  84429. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  84430. int i;
  84431. struct ExprList_item *pItem;
  84432. if( p ){
  84433. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  84434. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  84435. }
  84436. }
  84437. return WRC_Continue;
  84438. }
  84439. /*
  84440. ** Walk all expressions associated with SELECT statement p. Do
  84441. ** not invoke the SELECT callback on p, but do (of course) invoke
  84442. ** any expr callbacks and SELECT callbacks that come from subqueries.
  84443. ** Return WRC_Abort or WRC_Continue.
  84444. */
  84445. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  84446. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  84447. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  84448. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  84449. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  84450. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  84451. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  84452. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  84453. return WRC_Continue;
  84454. }
  84455. /*
  84456. ** Walk the parse trees associated with all subqueries in the
  84457. ** FROM clause of SELECT statement p. Do not invoke the select
  84458. ** callback on p, but do invoke it on each FROM clause subquery
  84459. ** and on any subqueries further down in the tree. Return
  84460. ** WRC_Abort or WRC_Continue;
  84461. */
  84462. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  84463. SrcList *pSrc;
  84464. int i;
  84465. struct SrcList_item *pItem;
  84466. pSrc = p->pSrc;
  84467. if( ALWAYS(pSrc) ){
  84468. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  84469. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  84470. return WRC_Abort;
  84471. }
  84472. if( pItem->fg.isTabFunc
  84473. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  84474. ){
  84475. return WRC_Abort;
  84476. }
  84477. }
  84478. }
  84479. return WRC_Continue;
  84480. }
  84481. /*
  84482. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  84483. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  84484. ** on the compound select chain, p->pPrior.
  84485. **
  84486. ** If it is not NULL, the xSelectCallback() callback is invoked before
  84487. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  84488. ** method is invoked following the walk of the expressions and FROM clause,
  84489. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  84490. ** and if the expressions and FROM clause both return WRC_Continue;
  84491. **
  84492. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  84493. ** there is an abort request.
  84494. **
  84495. ** If the Walker does not have an xSelectCallback() then this routine
  84496. ** is a no-op returning WRC_Continue.
  84497. */
  84498. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  84499. int rc;
  84500. if( p==0 ) return WRC_Continue;
  84501. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  84502. do{
  84503. rc = pWalker->xSelectCallback(pWalker, p);
  84504. if( rc ) return rc & WRC_Abort;
  84505. if( sqlite3WalkSelectExpr(pWalker, p)
  84506. || sqlite3WalkSelectFrom(pWalker, p)
  84507. ){
  84508. return WRC_Abort;
  84509. }
  84510. if( pWalker->xSelectCallback2 ){
  84511. pWalker->xSelectCallback2(pWalker, p);
  84512. }
  84513. p = p->pPrior;
  84514. }while( p!=0 );
  84515. return WRC_Continue;
  84516. }
  84517. /************** End of walker.c **********************************************/
  84518. /************** Begin file resolve.c *****************************************/
  84519. /*
  84520. ** 2008 August 18
  84521. **
  84522. ** The author disclaims copyright to this source code. In place of
  84523. ** a legal notice, here is a blessing:
  84524. **
  84525. ** May you do good and not evil.
  84526. ** May you find forgiveness for yourself and forgive others.
  84527. ** May you share freely, never taking more than you give.
  84528. **
  84529. *************************************************************************
  84530. **
  84531. ** This file contains routines used for walking the parser tree and
  84532. ** resolve all identifiers by associating them with a particular
  84533. ** table and column.
  84534. */
  84535. /* #include "sqliteInt.h" */
  84536. /*
  84537. ** Walk the expression tree pExpr and increase the aggregate function
  84538. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  84539. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  84540. ** outer query into an inner subquery.
  84541. **
  84542. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  84543. ** is a helper function - a callback for the tree walker.
  84544. */
  84545. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  84546. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  84547. return WRC_Continue;
  84548. }
  84549. static void incrAggFunctionDepth(Expr *pExpr, int N){
  84550. if( N>0 ){
  84551. Walker w;
  84552. memset(&w, 0, sizeof(w));
  84553. w.xExprCallback = incrAggDepth;
  84554. w.u.n = N;
  84555. sqlite3WalkExpr(&w, pExpr);
  84556. }
  84557. }
  84558. /*
  84559. ** Turn the pExpr expression into an alias for the iCol-th column of the
  84560. ** result set in pEList.
  84561. **
  84562. ** If the reference is followed by a COLLATE operator, then make sure
  84563. ** the COLLATE operator is preserved. For example:
  84564. **
  84565. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  84566. **
  84567. ** Should be transformed into:
  84568. **
  84569. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  84570. **
  84571. ** The nSubquery parameter specifies how many levels of subquery the
  84572. ** alias is removed from the original expression. The usual value is
  84573. ** zero but it might be more if the alias is contained within a subquery
  84574. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  84575. ** structures must be increased by the nSubquery amount.
  84576. */
  84577. static void resolveAlias(
  84578. Parse *pParse, /* Parsing context */
  84579. ExprList *pEList, /* A result set */
  84580. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  84581. Expr *pExpr, /* Transform this into an alias to the result set */
  84582. const char *zType, /* "GROUP" or "ORDER" or "" */
  84583. int nSubquery /* Number of subqueries that the label is moving */
  84584. ){
  84585. Expr *pOrig; /* The iCol-th column of the result set */
  84586. Expr *pDup; /* Copy of pOrig */
  84587. sqlite3 *db; /* The database connection */
  84588. assert( iCol>=0 && iCol<pEList->nExpr );
  84589. pOrig = pEList->a[iCol].pExpr;
  84590. assert( pOrig!=0 );
  84591. db = pParse->db;
  84592. pDup = sqlite3ExprDup(db, pOrig, 0);
  84593. if( pDup==0 ) return;
  84594. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  84595. if( pExpr->op==TK_COLLATE ){
  84596. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  84597. }
  84598. ExprSetProperty(pDup, EP_Alias);
  84599. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  84600. ** prevents ExprDelete() from deleting the Expr structure itself,
  84601. ** allowing it to be repopulated by the memcpy() on the following line.
  84602. ** The pExpr->u.zToken might point into memory that will be freed by the
  84603. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  84604. ** make a copy of the token before doing the sqlite3DbFree().
  84605. */
  84606. ExprSetProperty(pExpr, EP_Static);
  84607. sqlite3ExprDelete(db, pExpr);
  84608. memcpy(pExpr, pDup, sizeof(*pExpr));
  84609. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  84610. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  84611. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  84612. pExpr->flags |= EP_MemToken;
  84613. }
  84614. sqlite3DbFree(db, pDup);
  84615. }
  84616. /*
  84617. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  84618. **
  84619. ** Return FALSE if the USING clause is NULL or if it does not contain
  84620. ** zCol.
  84621. */
  84622. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  84623. if( pUsing ){
  84624. int k;
  84625. for(k=0; k<pUsing->nId; k++){
  84626. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  84627. }
  84628. }
  84629. return 0;
  84630. }
  84631. /*
  84632. ** Subqueries stores the original database, table and column names for their
  84633. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  84634. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  84635. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  84636. ** match anything.
  84637. */
  84638. SQLITE_PRIVATE int sqlite3MatchSpanName(
  84639. const char *zSpan,
  84640. const char *zCol,
  84641. const char *zTab,
  84642. const char *zDb
  84643. ){
  84644. int n;
  84645. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  84646. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  84647. return 0;
  84648. }
  84649. zSpan += n+1;
  84650. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  84651. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  84652. return 0;
  84653. }
  84654. zSpan += n+1;
  84655. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  84656. return 0;
  84657. }
  84658. return 1;
  84659. }
  84660. /*
  84661. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  84662. ** that name in the set of source tables in pSrcList and make the pExpr
  84663. ** expression node refer back to that source column. The following changes
  84664. ** are made to pExpr:
  84665. **
  84666. ** pExpr->iDb Set the index in db->aDb[] of the database X
  84667. ** (even if X is implied).
  84668. ** pExpr->iTable Set to the cursor number for the table obtained
  84669. ** from pSrcList.
  84670. ** pExpr->pTab Points to the Table structure of X.Y (even if
  84671. ** X and/or Y are implied.)
  84672. ** pExpr->iColumn Set to the column number within the table.
  84673. ** pExpr->op Set to TK_COLUMN.
  84674. ** pExpr->pLeft Any expression this points to is deleted
  84675. ** pExpr->pRight Any expression this points to is deleted.
  84676. **
  84677. ** The zDb variable is the name of the database (the "X"). This value may be
  84678. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  84679. ** can be used. The zTable variable is the name of the table (the "Y"). This
  84680. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  84681. ** means that the form of the name is Z and that columns from any table
  84682. ** can be used.
  84683. **
  84684. ** If the name cannot be resolved unambiguously, leave an error message
  84685. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  84686. */
  84687. static int lookupName(
  84688. Parse *pParse, /* The parsing context */
  84689. const char *zDb, /* Name of the database containing table, or NULL */
  84690. const char *zTab, /* Name of table containing column, or NULL */
  84691. const char *zCol, /* Name of the column. */
  84692. NameContext *pNC, /* The name context used to resolve the name */
  84693. Expr *pExpr /* Make this EXPR node point to the selected column */
  84694. ){
  84695. int i, j; /* Loop counters */
  84696. int cnt = 0; /* Number of matching column names */
  84697. int cntTab = 0; /* Number of matching table names */
  84698. int nSubquery = 0; /* How many levels of subquery */
  84699. sqlite3 *db = pParse->db; /* The database connection */
  84700. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  84701. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  84702. NameContext *pTopNC = pNC; /* First namecontext in the list */
  84703. Schema *pSchema = 0; /* Schema of the expression */
  84704. int isTrigger = 0; /* True if resolved to a trigger column */
  84705. Table *pTab = 0; /* Table hold the row */
  84706. Column *pCol; /* A column of pTab */
  84707. assert( pNC ); /* the name context cannot be NULL. */
  84708. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  84709. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  84710. /* Initialize the node to no-match */
  84711. pExpr->iTable = -1;
  84712. pExpr->pTab = 0;
  84713. ExprSetVVAProperty(pExpr, EP_NoReduce);
  84714. /* Translate the schema name in zDb into a pointer to the corresponding
  84715. ** schema. If not found, pSchema will remain NULL and nothing will match
  84716. ** resulting in an appropriate error message toward the end of this routine
  84717. */
  84718. if( zDb ){
  84719. testcase( pNC->ncFlags & NC_PartIdx );
  84720. testcase( pNC->ncFlags & NC_IsCheck );
  84721. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  84722. /* Silently ignore database qualifiers inside CHECK constraints and
  84723. ** partial indices. Do not raise errors because that might break
  84724. ** legacy and because it does not hurt anything to just ignore the
  84725. ** database name. */
  84726. zDb = 0;
  84727. }else{
  84728. for(i=0; i<db->nDb; i++){
  84729. assert( db->aDb[i].zDbSName );
  84730. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  84731. pSchema = db->aDb[i].pSchema;
  84732. break;
  84733. }
  84734. }
  84735. }
  84736. }
  84737. /* Start at the inner-most context and move outward until a match is found */
  84738. assert( pNC && cnt==0 );
  84739. do{
  84740. ExprList *pEList;
  84741. SrcList *pSrcList = pNC->pSrcList;
  84742. if( pSrcList ){
  84743. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  84744. pTab = pItem->pTab;
  84745. assert( pTab!=0 && pTab->zName!=0 );
  84746. assert( pTab->nCol>0 );
  84747. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  84748. int hit = 0;
  84749. pEList = pItem->pSelect->pEList;
  84750. for(j=0; j<pEList->nExpr; j++){
  84751. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  84752. cnt++;
  84753. cntTab = 2;
  84754. pMatch = pItem;
  84755. pExpr->iColumn = j;
  84756. hit = 1;
  84757. }
  84758. }
  84759. if( hit || zTab==0 ) continue;
  84760. }
  84761. if( zDb && pTab->pSchema!=pSchema ){
  84762. continue;
  84763. }
  84764. if( zTab ){
  84765. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  84766. assert( zTabName!=0 );
  84767. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  84768. continue;
  84769. }
  84770. }
  84771. if( 0==(cntTab++) ){
  84772. pMatch = pItem;
  84773. }
  84774. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  84775. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  84776. /* If there has been exactly one prior match and this match
  84777. ** is for the right-hand table of a NATURAL JOIN or is in a
  84778. ** USING clause, then skip this match.
  84779. */
  84780. if( cnt==1 ){
  84781. if( pItem->fg.jointype & JT_NATURAL ) continue;
  84782. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  84783. }
  84784. cnt++;
  84785. pMatch = pItem;
  84786. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  84787. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  84788. break;
  84789. }
  84790. }
  84791. }
  84792. if( pMatch ){
  84793. pExpr->iTable = pMatch->iCursor;
  84794. pExpr->pTab = pMatch->pTab;
  84795. /* RIGHT JOIN not (yet) supported */
  84796. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  84797. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  84798. ExprSetProperty(pExpr, EP_CanBeNull);
  84799. }
  84800. pSchema = pExpr->pTab->pSchema;
  84801. }
  84802. } /* if( pSrcList ) */
  84803. #ifndef SQLITE_OMIT_TRIGGER
  84804. /* If we have not already resolved the name, then maybe
  84805. ** it is a new.* or old.* trigger argument reference
  84806. */
  84807. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  84808. int op = pParse->eTriggerOp;
  84809. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  84810. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  84811. pExpr->iTable = 1;
  84812. pTab = pParse->pTriggerTab;
  84813. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  84814. pExpr->iTable = 0;
  84815. pTab = pParse->pTriggerTab;
  84816. }else{
  84817. pTab = 0;
  84818. }
  84819. if( pTab ){
  84820. int iCol;
  84821. pSchema = pTab->pSchema;
  84822. cntTab++;
  84823. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  84824. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  84825. if( iCol==pTab->iPKey ){
  84826. iCol = -1;
  84827. }
  84828. break;
  84829. }
  84830. }
  84831. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  84832. /* IMP: R-51414-32910 */
  84833. iCol = -1;
  84834. }
  84835. if( iCol<pTab->nCol ){
  84836. cnt++;
  84837. if( iCol<0 ){
  84838. pExpr->affinity = SQLITE_AFF_INTEGER;
  84839. }else if( pExpr->iTable==0 ){
  84840. testcase( iCol==31 );
  84841. testcase( iCol==32 );
  84842. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  84843. }else{
  84844. testcase( iCol==31 );
  84845. testcase( iCol==32 );
  84846. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  84847. }
  84848. pExpr->iColumn = (i16)iCol;
  84849. pExpr->pTab = pTab;
  84850. isTrigger = 1;
  84851. }
  84852. }
  84853. }
  84854. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  84855. /*
  84856. ** Perhaps the name is a reference to the ROWID
  84857. */
  84858. if( cnt==0
  84859. && cntTab==1
  84860. && pMatch
  84861. && (pNC->ncFlags & NC_IdxExpr)==0
  84862. && sqlite3IsRowid(zCol)
  84863. && VisibleRowid(pMatch->pTab)
  84864. ){
  84865. cnt = 1;
  84866. pExpr->iColumn = -1;
  84867. pExpr->affinity = SQLITE_AFF_INTEGER;
  84868. }
  84869. /*
  84870. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  84871. ** might refer to an result-set alias. This happens, for example, when
  84872. ** we are resolving names in the WHERE clause of the following command:
  84873. **
  84874. ** SELECT a+b AS x FROM table WHERE x<10;
  84875. **
  84876. ** In cases like this, replace pExpr with a copy of the expression that
  84877. ** forms the result set entry ("a+b" in the example) and return immediately.
  84878. ** Note that the expression in the result set should have already been
  84879. ** resolved by the time the WHERE clause is resolved.
  84880. **
  84881. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  84882. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  84883. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  84884. ** is supported for backwards compatibility only. Hence, we issue a warning
  84885. ** on sqlite3_log() whenever the capability is used.
  84886. */
  84887. if( (pEList = pNC->pEList)!=0
  84888. && zTab==0
  84889. && cnt==0
  84890. ){
  84891. for(j=0; j<pEList->nExpr; j++){
  84892. char *zAs = pEList->a[j].zName;
  84893. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  84894. Expr *pOrig;
  84895. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  84896. assert( pExpr->x.pList==0 );
  84897. assert( pExpr->x.pSelect==0 );
  84898. pOrig = pEList->a[j].pExpr;
  84899. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  84900. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  84901. return WRC_Abort;
  84902. }
  84903. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  84904. sqlite3ErrorMsg(pParse, "row value misused");
  84905. return WRC_Abort;
  84906. }
  84907. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  84908. cnt = 1;
  84909. pMatch = 0;
  84910. assert( zTab==0 && zDb==0 );
  84911. goto lookupname_end;
  84912. }
  84913. }
  84914. }
  84915. /* Advance to the next name context. The loop will exit when either
  84916. ** we have a match (cnt>0) or when we run out of name contexts.
  84917. */
  84918. if( cnt ) break;
  84919. pNC = pNC->pNext;
  84920. nSubquery++;
  84921. }while( pNC );
  84922. /*
  84923. ** If X and Y are NULL (in other words if only the column name Z is
  84924. ** supplied) and the value of Z is enclosed in double-quotes, then
  84925. ** Z is a string literal if it doesn't match any column names. In that
  84926. ** case, we need to return right away and not make any changes to
  84927. ** pExpr.
  84928. **
  84929. ** Because no reference was made to outer contexts, the pNC->nRef
  84930. ** fields are not changed in any context.
  84931. */
  84932. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  84933. pExpr->op = TK_STRING;
  84934. pExpr->pTab = 0;
  84935. return WRC_Prune;
  84936. }
  84937. /*
  84938. ** cnt==0 means there was not match. cnt>1 means there were two or
  84939. ** more matches. Either way, we have an error.
  84940. */
  84941. if( cnt!=1 ){
  84942. const char *zErr;
  84943. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  84944. if( zDb ){
  84945. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  84946. }else if( zTab ){
  84947. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  84948. }else{
  84949. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  84950. }
  84951. pParse->checkSchema = 1;
  84952. pTopNC->nErr++;
  84953. }
  84954. /* If a column from a table in pSrcList is referenced, then record
  84955. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  84956. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  84957. ** column number is greater than the number of bits in the bitmask
  84958. ** then set the high-order bit of the bitmask.
  84959. */
  84960. if( pExpr->iColumn>=0 && pMatch!=0 ){
  84961. int n = pExpr->iColumn;
  84962. testcase( n==BMS-1 );
  84963. if( n>=BMS ){
  84964. n = BMS-1;
  84965. }
  84966. assert( pMatch->iCursor==pExpr->iTable );
  84967. pMatch->colUsed |= ((Bitmask)1)<<n;
  84968. }
  84969. /* Clean up and return
  84970. */
  84971. sqlite3ExprDelete(db, pExpr->pLeft);
  84972. pExpr->pLeft = 0;
  84973. sqlite3ExprDelete(db, pExpr->pRight);
  84974. pExpr->pRight = 0;
  84975. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  84976. ExprSetProperty(pExpr, EP_Leaf);
  84977. lookupname_end:
  84978. if( cnt==1 ){
  84979. assert( pNC!=0 );
  84980. if( !ExprHasProperty(pExpr, EP_Alias) ){
  84981. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  84982. }
  84983. /* Increment the nRef value on all name contexts from TopNC up to
  84984. ** the point where the name matched. */
  84985. for(;;){
  84986. assert( pTopNC!=0 );
  84987. pTopNC->nRef++;
  84988. if( pTopNC==pNC ) break;
  84989. pTopNC = pTopNC->pNext;
  84990. }
  84991. return WRC_Prune;
  84992. } else {
  84993. return WRC_Abort;
  84994. }
  84995. }
  84996. /*
  84997. ** Allocate and return a pointer to an expression to load the column iCol
  84998. ** from datasource iSrc in SrcList pSrc.
  84999. */
  85000. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  85001. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  85002. if( p ){
  85003. struct SrcList_item *pItem = &pSrc->a[iSrc];
  85004. p->pTab = pItem->pTab;
  85005. p->iTable = pItem->iCursor;
  85006. if( p->pTab->iPKey==iCol ){
  85007. p->iColumn = -1;
  85008. }else{
  85009. p->iColumn = (ynVar)iCol;
  85010. testcase( iCol==BMS );
  85011. testcase( iCol==BMS-1 );
  85012. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  85013. }
  85014. }
  85015. return p;
  85016. }
  85017. /*
  85018. ** Report an error that an expression is not valid for some set of
  85019. ** pNC->ncFlags values determined by validMask.
  85020. */
  85021. static void notValid(
  85022. Parse *pParse, /* Leave error message here */
  85023. NameContext *pNC, /* The name context */
  85024. const char *zMsg, /* Type of error */
  85025. int validMask /* Set of contexts for which prohibited */
  85026. ){
  85027. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  85028. if( (pNC->ncFlags & validMask)!=0 ){
  85029. const char *zIn = "partial index WHERE clauses";
  85030. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  85031. #ifndef SQLITE_OMIT_CHECK
  85032. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  85033. #endif
  85034. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  85035. }
  85036. }
  85037. /*
  85038. ** Expression p should encode a floating point value between 1.0 and 0.0.
  85039. ** Return 1024 times this value. Or return -1 if p is not a floating point
  85040. ** value between 1.0 and 0.0.
  85041. */
  85042. static int exprProbability(Expr *p){
  85043. double r = -1.0;
  85044. if( p->op!=TK_FLOAT ) return -1;
  85045. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  85046. assert( r>=0.0 );
  85047. if( r>1.0 ) return -1;
  85048. return (int)(r*134217728.0);
  85049. }
  85050. /*
  85051. ** This routine is callback for sqlite3WalkExpr().
  85052. **
  85053. ** Resolve symbolic names into TK_COLUMN operators for the current
  85054. ** node in the expression tree. Return 0 to continue the search down
  85055. ** the tree or 2 to abort the tree walk.
  85056. **
  85057. ** This routine also does error checking and name resolution for
  85058. ** function names. The operator for aggregate functions is changed
  85059. ** to TK_AGG_FUNCTION.
  85060. */
  85061. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  85062. NameContext *pNC;
  85063. Parse *pParse;
  85064. pNC = pWalker->u.pNC;
  85065. assert( pNC!=0 );
  85066. pParse = pNC->pParse;
  85067. assert( pParse==pWalker->pParse );
  85068. #ifndef NDEBUG
  85069. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  85070. SrcList *pSrcList = pNC->pSrcList;
  85071. int i;
  85072. for(i=0; i<pNC->pSrcList->nSrc; i++){
  85073. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  85074. }
  85075. }
  85076. #endif
  85077. switch( pExpr->op ){
  85078. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  85079. /* The special operator TK_ROW means use the rowid for the first
  85080. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  85081. ** clause processing on UPDATE and DELETE statements.
  85082. */
  85083. case TK_ROW: {
  85084. SrcList *pSrcList = pNC->pSrcList;
  85085. struct SrcList_item *pItem;
  85086. assert( pSrcList && pSrcList->nSrc==1 );
  85087. pItem = pSrcList->a;
  85088. pExpr->op = TK_COLUMN;
  85089. pExpr->pTab = pItem->pTab;
  85090. pExpr->iTable = pItem->iCursor;
  85091. pExpr->iColumn = -1;
  85092. pExpr->affinity = SQLITE_AFF_INTEGER;
  85093. break;
  85094. }
  85095. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  85096. && !defined(SQLITE_OMIT_SUBQUERY) */
  85097. /* A column name: ID
  85098. ** Or table name and column name: ID.ID
  85099. ** Or a database, table and column: ID.ID.ID
  85100. **
  85101. ** The TK_ID and TK_OUT cases are combined so that there will only
  85102. ** be one call to lookupName(). Then the compiler will in-line
  85103. ** lookupName() for a size reduction and performance increase.
  85104. */
  85105. case TK_ID:
  85106. case TK_DOT: {
  85107. const char *zColumn;
  85108. const char *zTable;
  85109. const char *zDb;
  85110. Expr *pRight;
  85111. if( pExpr->op==TK_ID ){
  85112. zDb = 0;
  85113. zTable = 0;
  85114. zColumn = pExpr->u.zToken;
  85115. }else{
  85116. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  85117. pRight = pExpr->pRight;
  85118. if( pRight->op==TK_ID ){
  85119. zDb = 0;
  85120. zTable = pExpr->pLeft->u.zToken;
  85121. zColumn = pRight->u.zToken;
  85122. }else{
  85123. assert( pRight->op==TK_DOT );
  85124. zDb = pExpr->pLeft->u.zToken;
  85125. zTable = pRight->pLeft->u.zToken;
  85126. zColumn = pRight->pRight->u.zToken;
  85127. }
  85128. }
  85129. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  85130. }
  85131. /* Resolve function names
  85132. */
  85133. case TK_FUNCTION: {
  85134. ExprList *pList = pExpr->x.pList; /* The argument list */
  85135. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  85136. int no_such_func = 0; /* True if no such function exists */
  85137. int wrong_num_args = 0; /* True if wrong number of arguments */
  85138. int is_agg = 0; /* True if is an aggregate function */
  85139. int nId; /* Number of characters in function name */
  85140. const char *zId; /* The function name. */
  85141. FuncDef *pDef; /* Information about the function */
  85142. u8 enc = ENC(pParse->db); /* The database encoding */
  85143. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  85144. zId = pExpr->u.zToken;
  85145. nId = sqlite3Strlen30(zId);
  85146. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  85147. if( pDef==0 ){
  85148. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  85149. if( pDef==0 ){
  85150. no_such_func = 1;
  85151. }else{
  85152. wrong_num_args = 1;
  85153. }
  85154. }else{
  85155. is_agg = pDef->xFinalize!=0;
  85156. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  85157. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  85158. if( n==2 ){
  85159. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  85160. if( pExpr->iTable<0 ){
  85161. sqlite3ErrorMsg(pParse,
  85162. "second argument to likelihood() must be a "
  85163. "constant between 0.0 and 1.0");
  85164. pNC->nErr++;
  85165. }
  85166. }else{
  85167. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  85168. ** equivalent to likelihood(X, 0.0625).
  85169. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  85170. ** short-hand for likelihood(X,0.0625).
  85171. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  85172. ** for likelihood(X,0.9375).
  85173. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  85174. ** to likelihood(X,0.9375). */
  85175. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  85176. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  85177. }
  85178. }
  85179. #ifndef SQLITE_OMIT_AUTHORIZATION
  85180. {
  85181. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  85182. if( auth!=SQLITE_OK ){
  85183. if( auth==SQLITE_DENY ){
  85184. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  85185. pDef->zName);
  85186. pNC->nErr++;
  85187. }
  85188. pExpr->op = TK_NULL;
  85189. return WRC_Prune;
  85190. }
  85191. }
  85192. #endif
  85193. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  85194. /* For the purposes of the EP_ConstFunc flag, date and time
  85195. ** functions and other functions that change slowly are considered
  85196. ** constant because they are constant for the duration of one query */
  85197. ExprSetProperty(pExpr,EP_ConstFunc);
  85198. }
  85199. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  85200. /* Date/time functions that use 'now', and other functions like
  85201. ** sqlite_version() that might change over time cannot be used
  85202. ** in an index. */
  85203. notValid(pParse, pNC, "non-deterministic functions",
  85204. NC_IdxExpr|NC_PartIdx);
  85205. }
  85206. }
  85207. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  85208. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  85209. pNC->nErr++;
  85210. is_agg = 0;
  85211. }else if( no_such_func && pParse->db->init.busy==0
  85212. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  85213. && pParse->explain==0
  85214. #endif
  85215. ){
  85216. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  85217. pNC->nErr++;
  85218. }else if( wrong_num_args ){
  85219. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  85220. nId, zId);
  85221. pNC->nErr++;
  85222. }
  85223. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  85224. sqlite3WalkExprList(pWalker, pList);
  85225. if( is_agg ){
  85226. NameContext *pNC2 = pNC;
  85227. pExpr->op = TK_AGG_FUNCTION;
  85228. pExpr->op2 = 0;
  85229. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  85230. pExpr->op2++;
  85231. pNC2 = pNC2->pNext;
  85232. }
  85233. assert( pDef!=0 );
  85234. if( pNC2 ){
  85235. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  85236. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  85237. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  85238. }
  85239. pNC->ncFlags |= NC_AllowAgg;
  85240. }
  85241. /* FIX ME: Compute pExpr->affinity based on the expected return
  85242. ** type of the function
  85243. */
  85244. return WRC_Prune;
  85245. }
  85246. #ifndef SQLITE_OMIT_SUBQUERY
  85247. case TK_SELECT:
  85248. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  85249. #endif
  85250. case TK_IN: {
  85251. testcase( pExpr->op==TK_IN );
  85252. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  85253. int nRef = pNC->nRef;
  85254. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  85255. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  85256. assert( pNC->nRef>=nRef );
  85257. if( nRef!=pNC->nRef ){
  85258. ExprSetProperty(pExpr, EP_VarSelect);
  85259. pNC->ncFlags |= NC_VarSelect;
  85260. }
  85261. }
  85262. break;
  85263. }
  85264. case TK_VARIABLE: {
  85265. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  85266. break;
  85267. }
  85268. case TK_BETWEEN:
  85269. case TK_EQ:
  85270. case TK_NE:
  85271. case TK_LT:
  85272. case TK_LE:
  85273. case TK_GT:
  85274. case TK_GE:
  85275. case TK_IS:
  85276. case TK_ISNOT: {
  85277. int nLeft, nRight;
  85278. if( pParse->db->mallocFailed ) break;
  85279. assert( pExpr->pLeft!=0 );
  85280. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  85281. if( pExpr->op==TK_BETWEEN ){
  85282. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  85283. if( nRight==nLeft ){
  85284. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  85285. }
  85286. }else{
  85287. assert( pExpr->pRight!=0 );
  85288. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  85289. }
  85290. if( nLeft!=nRight ){
  85291. testcase( pExpr->op==TK_EQ );
  85292. testcase( pExpr->op==TK_NE );
  85293. testcase( pExpr->op==TK_LT );
  85294. testcase( pExpr->op==TK_LE );
  85295. testcase( pExpr->op==TK_GT );
  85296. testcase( pExpr->op==TK_GE );
  85297. testcase( pExpr->op==TK_IS );
  85298. testcase( pExpr->op==TK_ISNOT );
  85299. testcase( pExpr->op==TK_BETWEEN );
  85300. sqlite3ErrorMsg(pParse, "row value misused");
  85301. }
  85302. break;
  85303. }
  85304. }
  85305. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  85306. }
  85307. /*
  85308. ** pEList is a list of expressions which are really the result set of the
  85309. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  85310. ** This routine checks to see if pE is a simple identifier which corresponds
  85311. ** to the AS-name of one of the terms of the expression list. If it is,
  85312. ** this routine return an integer between 1 and N where N is the number of
  85313. ** elements in pEList, corresponding to the matching entry. If there is
  85314. ** no match, or if pE is not a simple identifier, then this routine
  85315. ** return 0.
  85316. **
  85317. ** pEList has been resolved. pE has not.
  85318. */
  85319. static int resolveAsName(
  85320. Parse *pParse, /* Parsing context for error messages */
  85321. ExprList *pEList, /* List of expressions to scan */
  85322. Expr *pE /* Expression we are trying to match */
  85323. ){
  85324. int i; /* Loop counter */
  85325. UNUSED_PARAMETER(pParse);
  85326. if( pE->op==TK_ID ){
  85327. char *zCol = pE->u.zToken;
  85328. for(i=0; i<pEList->nExpr; i++){
  85329. char *zAs = pEList->a[i].zName;
  85330. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  85331. return i+1;
  85332. }
  85333. }
  85334. }
  85335. return 0;
  85336. }
  85337. /*
  85338. ** pE is a pointer to an expression which is a single term in the
  85339. ** ORDER BY of a compound SELECT. The expression has not been
  85340. ** name resolved.
  85341. **
  85342. ** At the point this routine is called, we already know that the
  85343. ** ORDER BY term is not an integer index into the result set. That
  85344. ** case is handled by the calling routine.
  85345. **
  85346. ** Attempt to match pE against result set columns in the left-most
  85347. ** SELECT statement. Return the index i of the matching column,
  85348. ** as an indication to the caller that it should sort by the i-th column.
  85349. ** The left-most column is 1. In other words, the value returned is the
  85350. ** same integer value that would be used in the SQL statement to indicate
  85351. ** the column.
  85352. **
  85353. ** If there is no match, return 0. Return -1 if an error occurs.
  85354. */
  85355. static int resolveOrderByTermToExprList(
  85356. Parse *pParse, /* Parsing context for error messages */
  85357. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  85358. Expr *pE /* The specific ORDER BY term */
  85359. ){
  85360. int i; /* Loop counter */
  85361. ExprList *pEList; /* The columns of the result set */
  85362. NameContext nc; /* Name context for resolving pE */
  85363. sqlite3 *db; /* Database connection */
  85364. int rc; /* Return code from subprocedures */
  85365. u8 savedSuppErr; /* Saved value of db->suppressErr */
  85366. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  85367. pEList = pSelect->pEList;
  85368. /* Resolve all names in the ORDER BY term expression
  85369. */
  85370. memset(&nc, 0, sizeof(nc));
  85371. nc.pParse = pParse;
  85372. nc.pSrcList = pSelect->pSrc;
  85373. nc.pEList = pEList;
  85374. nc.ncFlags = NC_AllowAgg;
  85375. nc.nErr = 0;
  85376. db = pParse->db;
  85377. savedSuppErr = db->suppressErr;
  85378. db->suppressErr = 1;
  85379. rc = sqlite3ResolveExprNames(&nc, pE);
  85380. db->suppressErr = savedSuppErr;
  85381. if( rc ) return 0;
  85382. /* Try to match the ORDER BY expression against an expression
  85383. ** in the result set. Return an 1-based index of the matching
  85384. ** result-set entry.
  85385. */
  85386. for(i=0; i<pEList->nExpr; i++){
  85387. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  85388. return i+1;
  85389. }
  85390. }
  85391. /* If no match, return 0. */
  85392. return 0;
  85393. }
  85394. /*
  85395. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  85396. */
  85397. static void resolveOutOfRangeError(
  85398. Parse *pParse, /* The error context into which to write the error */
  85399. const char *zType, /* "ORDER" or "GROUP" */
  85400. int i, /* The index (1-based) of the term out of range */
  85401. int mx /* Largest permissible value of i */
  85402. ){
  85403. sqlite3ErrorMsg(pParse,
  85404. "%r %s BY term out of range - should be "
  85405. "between 1 and %d", i, zType, mx);
  85406. }
  85407. /*
  85408. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  85409. ** each term of the ORDER BY clause is a constant integer between 1
  85410. ** and N where N is the number of columns in the compound SELECT.
  85411. **
  85412. ** ORDER BY terms that are already an integer between 1 and N are
  85413. ** unmodified. ORDER BY terms that are integers outside the range of
  85414. ** 1 through N generate an error. ORDER BY terms that are expressions
  85415. ** are matched against result set expressions of compound SELECT
  85416. ** beginning with the left-most SELECT and working toward the right.
  85417. ** At the first match, the ORDER BY expression is transformed into
  85418. ** the integer column number.
  85419. **
  85420. ** Return the number of errors seen.
  85421. */
  85422. static int resolveCompoundOrderBy(
  85423. Parse *pParse, /* Parsing context. Leave error messages here */
  85424. Select *pSelect /* The SELECT statement containing the ORDER BY */
  85425. ){
  85426. int i;
  85427. ExprList *pOrderBy;
  85428. ExprList *pEList;
  85429. sqlite3 *db;
  85430. int moreToDo = 1;
  85431. pOrderBy = pSelect->pOrderBy;
  85432. if( pOrderBy==0 ) return 0;
  85433. db = pParse->db;
  85434. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  85435. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  85436. return 1;
  85437. }
  85438. for(i=0; i<pOrderBy->nExpr; i++){
  85439. pOrderBy->a[i].done = 0;
  85440. }
  85441. pSelect->pNext = 0;
  85442. while( pSelect->pPrior ){
  85443. pSelect->pPrior->pNext = pSelect;
  85444. pSelect = pSelect->pPrior;
  85445. }
  85446. while( pSelect && moreToDo ){
  85447. struct ExprList_item *pItem;
  85448. moreToDo = 0;
  85449. pEList = pSelect->pEList;
  85450. assert( pEList!=0 );
  85451. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  85452. int iCol = -1;
  85453. Expr *pE, *pDup;
  85454. if( pItem->done ) continue;
  85455. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  85456. if( sqlite3ExprIsInteger(pE, &iCol) ){
  85457. if( iCol<=0 || iCol>pEList->nExpr ){
  85458. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  85459. return 1;
  85460. }
  85461. }else{
  85462. iCol = resolveAsName(pParse, pEList, pE);
  85463. if( iCol==0 ){
  85464. pDup = sqlite3ExprDup(db, pE, 0);
  85465. if( !db->mallocFailed ){
  85466. assert(pDup);
  85467. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  85468. }
  85469. sqlite3ExprDelete(db, pDup);
  85470. }
  85471. }
  85472. if( iCol>0 ){
  85473. /* Convert the ORDER BY term into an integer column number iCol,
  85474. ** taking care to preserve the COLLATE clause if it exists */
  85475. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  85476. if( pNew==0 ) return 1;
  85477. pNew->flags |= EP_IntValue;
  85478. pNew->u.iValue = iCol;
  85479. if( pItem->pExpr==pE ){
  85480. pItem->pExpr = pNew;
  85481. }else{
  85482. Expr *pParent = pItem->pExpr;
  85483. assert( pParent->op==TK_COLLATE );
  85484. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  85485. assert( pParent->pLeft==pE );
  85486. pParent->pLeft = pNew;
  85487. }
  85488. sqlite3ExprDelete(db, pE);
  85489. pItem->u.x.iOrderByCol = (u16)iCol;
  85490. pItem->done = 1;
  85491. }else{
  85492. moreToDo = 1;
  85493. }
  85494. }
  85495. pSelect = pSelect->pNext;
  85496. }
  85497. for(i=0; i<pOrderBy->nExpr; i++){
  85498. if( pOrderBy->a[i].done==0 ){
  85499. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  85500. "column in the result set", i+1);
  85501. return 1;
  85502. }
  85503. }
  85504. return 0;
  85505. }
  85506. /*
  85507. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  85508. ** the SELECT statement pSelect. If any term is reference to a
  85509. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  85510. ** field) then convert that term into a copy of the corresponding result set
  85511. ** column.
  85512. **
  85513. ** If any errors are detected, add an error message to pParse and
  85514. ** return non-zero. Return zero if no errors are seen.
  85515. */
  85516. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  85517. Parse *pParse, /* Parsing context. Leave error messages here */
  85518. Select *pSelect, /* The SELECT statement containing the clause */
  85519. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  85520. const char *zType /* "ORDER" or "GROUP" */
  85521. ){
  85522. int i;
  85523. sqlite3 *db = pParse->db;
  85524. ExprList *pEList;
  85525. struct ExprList_item *pItem;
  85526. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  85527. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  85528. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  85529. return 1;
  85530. }
  85531. pEList = pSelect->pEList;
  85532. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  85533. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  85534. if( pItem->u.x.iOrderByCol ){
  85535. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  85536. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  85537. return 1;
  85538. }
  85539. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  85540. zType,0);
  85541. }
  85542. }
  85543. return 0;
  85544. }
  85545. /*
  85546. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  85547. ** The Name context of the SELECT statement is pNC. zType is either
  85548. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  85549. **
  85550. ** This routine resolves each term of the clause into an expression.
  85551. ** If the order-by term is an integer I between 1 and N (where N is the
  85552. ** number of columns in the result set of the SELECT) then the expression
  85553. ** in the resolution is a copy of the I-th result-set expression. If
  85554. ** the order-by term is an identifier that corresponds to the AS-name of
  85555. ** a result-set expression, then the term resolves to a copy of the
  85556. ** result-set expression. Otherwise, the expression is resolved in
  85557. ** the usual way - using sqlite3ResolveExprNames().
  85558. **
  85559. ** This routine returns the number of errors. If errors occur, then
  85560. ** an appropriate error message might be left in pParse. (OOM errors
  85561. ** excepted.)
  85562. */
  85563. static int resolveOrderGroupBy(
  85564. NameContext *pNC, /* The name context of the SELECT statement */
  85565. Select *pSelect, /* The SELECT statement holding pOrderBy */
  85566. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  85567. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  85568. ){
  85569. int i, j; /* Loop counters */
  85570. int iCol; /* Column number */
  85571. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  85572. Parse *pParse; /* Parsing context */
  85573. int nResult; /* Number of terms in the result set */
  85574. if( pOrderBy==0 ) return 0;
  85575. nResult = pSelect->pEList->nExpr;
  85576. pParse = pNC->pParse;
  85577. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  85578. Expr *pE = pItem->pExpr;
  85579. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  85580. if( zType[0]!='G' ){
  85581. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  85582. if( iCol>0 ){
  85583. /* If an AS-name match is found, mark this ORDER BY column as being
  85584. ** a copy of the iCol-th result-set column. The subsequent call to
  85585. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  85586. ** copy of the iCol-th result-set expression. */
  85587. pItem->u.x.iOrderByCol = (u16)iCol;
  85588. continue;
  85589. }
  85590. }
  85591. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  85592. /* The ORDER BY term is an integer constant. Again, set the column
  85593. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  85594. ** order-by term to a copy of the result-set expression */
  85595. if( iCol<1 || iCol>0xffff ){
  85596. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  85597. return 1;
  85598. }
  85599. pItem->u.x.iOrderByCol = (u16)iCol;
  85600. continue;
  85601. }
  85602. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  85603. pItem->u.x.iOrderByCol = 0;
  85604. if( sqlite3ResolveExprNames(pNC, pE) ){
  85605. return 1;
  85606. }
  85607. for(j=0; j<pSelect->pEList->nExpr; j++){
  85608. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  85609. pItem->u.x.iOrderByCol = j+1;
  85610. }
  85611. }
  85612. }
  85613. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  85614. }
  85615. /*
  85616. ** Resolve names in the SELECT statement p and all of its descendants.
  85617. */
  85618. static int resolveSelectStep(Walker *pWalker, Select *p){
  85619. NameContext *pOuterNC; /* Context that contains this SELECT */
  85620. NameContext sNC; /* Name context of this SELECT */
  85621. int isCompound; /* True if p is a compound select */
  85622. int nCompound; /* Number of compound terms processed so far */
  85623. Parse *pParse; /* Parsing context */
  85624. int i; /* Loop counter */
  85625. ExprList *pGroupBy; /* The GROUP BY clause */
  85626. Select *pLeftmost; /* Left-most of SELECT of a compound */
  85627. sqlite3 *db; /* Database connection */
  85628. assert( p!=0 );
  85629. if( p->selFlags & SF_Resolved ){
  85630. return WRC_Prune;
  85631. }
  85632. pOuterNC = pWalker->u.pNC;
  85633. pParse = pWalker->pParse;
  85634. db = pParse->db;
  85635. /* Normally sqlite3SelectExpand() will be called first and will have
  85636. ** already expanded this SELECT. However, if this is a subquery within
  85637. ** an expression, sqlite3ResolveExprNames() will be called without a
  85638. ** prior call to sqlite3SelectExpand(). When that happens, let
  85639. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  85640. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  85641. ** this routine in the correct order.
  85642. */
  85643. if( (p->selFlags & SF_Expanded)==0 ){
  85644. sqlite3SelectPrep(pParse, p, pOuterNC);
  85645. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  85646. }
  85647. isCompound = p->pPrior!=0;
  85648. nCompound = 0;
  85649. pLeftmost = p;
  85650. while( p ){
  85651. assert( (p->selFlags & SF_Expanded)!=0 );
  85652. assert( (p->selFlags & SF_Resolved)==0 );
  85653. p->selFlags |= SF_Resolved;
  85654. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  85655. ** are not allowed to refer to any names, so pass an empty NameContext.
  85656. */
  85657. memset(&sNC, 0, sizeof(sNC));
  85658. sNC.pParse = pParse;
  85659. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  85660. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  85661. return WRC_Abort;
  85662. }
  85663. /* If the SF_Converted flags is set, then this Select object was
  85664. ** was created by the convertCompoundSelectToSubquery() function.
  85665. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  85666. ** as if it were part of the sub-query, not the parent. This block
  85667. ** moves the pOrderBy down to the sub-query. It will be moved back
  85668. ** after the names have been resolved. */
  85669. if( p->selFlags & SF_Converted ){
  85670. Select *pSub = p->pSrc->a[0].pSelect;
  85671. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  85672. assert( pSub->pPrior && pSub->pOrderBy==0 );
  85673. pSub->pOrderBy = p->pOrderBy;
  85674. p->pOrderBy = 0;
  85675. }
  85676. /* Recursively resolve names in all subqueries
  85677. */
  85678. for(i=0; i<p->pSrc->nSrc; i++){
  85679. struct SrcList_item *pItem = &p->pSrc->a[i];
  85680. if( pItem->pSelect ){
  85681. NameContext *pNC; /* Used to iterate name contexts */
  85682. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  85683. const char *zSavedContext = pParse->zAuthContext;
  85684. /* Count the total number of references to pOuterNC and all of its
  85685. ** parent contexts. After resolving references to expressions in
  85686. ** pItem->pSelect, check if this value has changed. If so, then
  85687. ** SELECT statement pItem->pSelect must be correlated. Set the
  85688. ** pItem->fg.isCorrelated flag if this is the case. */
  85689. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  85690. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  85691. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  85692. pParse->zAuthContext = zSavedContext;
  85693. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  85694. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  85695. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  85696. pItem->fg.isCorrelated = (nRef!=0);
  85697. }
  85698. }
  85699. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  85700. ** resolve the result-set expression list.
  85701. */
  85702. sNC.ncFlags = NC_AllowAgg;
  85703. sNC.pSrcList = p->pSrc;
  85704. sNC.pNext = pOuterNC;
  85705. /* Resolve names in the result set. */
  85706. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  85707. /* If there are no aggregate functions in the result-set, and no GROUP BY
  85708. ** expression, do not allow aggregates in any of the other expressions.
  85709. */
  85710. assert( (p->selFlags & SF_Aggregate)==0 );
  85711. pGroupBy = p->pGroupBy;
  85712. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  85713. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  85714. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  85715. }else{
  85716. sNC.ncFlags &= ~NC_AllowAgg;
  85717. }
  85718. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  85719. */
  85720. if( p->pHaving && !pGroupBy ){
  85721. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  85722. return WRC_Abort;
  85723. }
  85724. /* Add the output column list to the name-context before parsing the
  85725. ** other expressions in the SELECT statement. This is so that
  85726. ** expressions in the WHERE clause (etc.) can refer to expressions by
  85727. ** aliases in the result set.
  85728. **
  85729. ** Minor point: If this is the case, then the expression will be
  85730. ** re-evaluated for each reference to it.
  85731. */
  85732. sNC.pEList = p->pEList;
  85733. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  85734. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  85735. /* Resolve names in table-valued-function arguments */
  85736. for(i=0; i<p->pSrc->nSrc; i++){
  85737. struct SrcList_item *pItem = &p->pSrc->a[i];
  85738. if( pItem->fg.isTabFunc
  85739. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  85740. ){
  85741. return WRC_Abort;
  85742. }
  85743. }
  85744. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  85745. ** outer queries
  85746. */
  85747. sNC.pNext = 0;
  85748. sNC.ncFlags |= NC_AllowAgg;
  85749. /* If this is a converted compound query, move the ORDER BY clause from
  85750. ** the sub-query back to the parent query. At this point each term
  85751. ** within the ORDER BY clause has been transformed to an integer value.
  85752. ** These integers will be replaced by copies of the corresponding result
  85753. ** set expressions by the call to resolveOrderGroupBy() below. */
  85754. if( p->selFlags & SF_Converted ){
  85755. Select *pSub = p->pSrc->a[0].pSelect;
  85756. p->pOrderBy = pSub->pOrderBy;
  85757. pSub->pOrderBy = 0;
  85758. }
  85759. /* Process the ORDER BY clause for singleton SELECT statements.
  85760. ** The ORDER BY clause for compounds SELECT statements is handled
  85761. ** below, after all of the result-sets for all of the elements of
  85762. ** the compound have been resolved.
  85763. **
  85764. ** If there is an ORDER BY clause on a term of a compound-select other
  85765. ** than the right-most term, then that is a syntax error. But the error
  85766. ** is not detected until much later, and so we need to go ahead and
  85767. ** resolve those symbols on the incorrect ORDER BY for consistency.
  85768. */
  85769. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  85770. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  85771. ){
  85772. return WRC_Abort;
  85773. }
  85774. if( db->mallocFailed ){
  85775. return WRC_Abort;
  85776. }
  85777. /* Resolve the GROUP BY clause. At the same time, make sure
  85778. ** the GROUP BY clause does not contain aggregate functions.
  85779. */
  85780. if( pGroupBy ){
  85781. struct ExprList_item *pItem;
  85782. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  85783. return WRC_Abort;
  85784. }
  85785. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  85786. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  85787. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  85788. "the GROUP BY clause");
  85789. return WRC_Abort;
  85790. }
  85791. }
  85792. }
  85793. /* If this is part of a compound SELECT, check that it has the right
  85794. ** number of expressions in the select list. */
  85795. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  85796. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  85797. return WRC_Abort;
  85798. }
  85799. /* Advance to the next term of the compound
  85800. */
  85801. p = p->pPrior;
  85802. nCompound++;
  85803. }
  85804. /* Resolve the ORDER BY on a compound SELECT after all terms of
  85805. ** the compound have been resolved.
  85806. */
  85807. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  85808. return WRC_Abort;
  85809. }
  85810. return WRC_Prune;
  85811. }
  85812. /*
  85813. ** This routine walks an expression tree and resolves references to
  85814. ** table columns and result-set columns. At the same time, do error
  85815. ** checking on function usage and set a flag if any aggregate functions
  85816. ** are seen.
  85817. **
  85818. ** To resolve table columns references we look for nodes (or subtrees) of the
  85819. ** form X.Y.Z or Y.Z or just Z where
  85820. **
  85821. ** X: The name of a database. Ex: "main" or "temp" or
  85822. ** the symbolic name assigned to an ATTACH-ed database.
  85823. **
  85824. ** Y: The name of a table in a FROM clause. Or in a trigger
  85825. ** one of the special names "old" or "new".
  85826. **
  85827. ** Z: The name of a column in table Y.
  85828. **
  85829. ** The node at the root of the subtree is modified as follows:
  85830. **
  85831. ** Expr.op Changed to TK_COLUMN
  85832. ** Expr.pTab Points to the Table object for X.Y
  85833. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  85834. ** Expr.iTable The VDBE cursor number for X.Y
  85835. **
  85836. **
  85837. ** To resolve result-set references, look for expression nodes of the
  85838. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  85839. ** size of an AS clause in the result-set of a SELECT. The Z expression
  85840. ** is replaced by a copy of the left-hand side of the result-set expression.
  85841. ** Table-name and function resolution occurs on the substituted expression
  85842. ** tree. For example, in:
  85843. **
  85844. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  85845. **
  85846. ** The "x" term of the order by is replaced by "a+b" to render:
  85847. **
  85848. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  85849. **
  85850. ** Function calls are checked to make sure that the function is
  85851. ** defined and that the correct number of arguments are specified.
  85852. ** If the function is an aggregate function, then the NC_HasAgg flag is
  85853. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  85854. ** If an expression contains aggregate functions then the EP_Agg
  85855. ** property on the expression is set.
  85856. **
  85857. ** An error message is left in pParse if anything is amiss. The number
  85858. ** if errors is returned.
  85859. */
  85860. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  85861. NameContext *pNC, /* Namespace to resolve expressions in. */
  85862. Expr *pExpr /* The expression to be analyzed. */
  85863. ){
  85864. u16 savedHasAgg;
  85865. Walker w;
  85866. if( pExpr==0 ) return SQLITE_OK;
  85867. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  85868. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  85869. w.pParse = pNC->pParse;
  85870. w.xExprCallback = resolveExprStep;
  85871. w.xSelectCallback = resolveSelectStep;
  85872. w.xSelectCallback2 = 0;
  85873. w.u.pNC = pNC;
  85874. #if SQLITE_MAX_EXPR_DEPTH>0
  85875. w.pParse->nHeight += pExpr->nHeight;
  85876. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  85877. return SQLITE_ERROR;
  85878. }
  85879. #endif
  85880. sqlite3WalkExpr(&w, pExpr);
  85881. #if SQLITE_MAX_EXPR_DEPTH>0
  85882. w.pParse->nHeight -= pExpr->nHeight;
  85883. #endif
  85884. if( pNC->ncFlags & NC_HasAgg ){
  85885. ExprSetProperty(pExpr, EP_Agg);
  85886. }
  85887. pNC->ncFlags |= savedHasAgg;
  85888. return pNC->nErr>0 || w.pParse->nErr>0;
  85889. }
  85890. /*
  85891. ** Resolve all names for all expression in an expression list. This is
  85892. ** just like sqlite3ResolveExprNames() except that it works for an expression
  85893. ** list rather than a single expression.
  85894. */
  85895. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  85896. NameContext *pNC, /* Namespace to resolve expressions in. */
  85897. ExprList *pList /* The expression list to be analyzed. */
  85898. ){
  85899. int i;
  85900. if( pList ){
  85901. for(i=0; i<pList->nExpr; i++){
  85902. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  85903. }
  85904. }
  85905. return WRC_Continue;
  85906. }
  85907. /*
  85908. ** Resolve all names in all expressions of a SELECT and in all
  85909. ** decendents of the SELECT, including compounds off of p->pPrior,
  85910. ** subqueries in expressions, and subqueries used as FROM clause
  85911. ** terms.
  85912. **
  85913. ** See sqlite3ResolveExprNames() for a description of the kinds of
  85914. ** transformations that occur.
  85915. **
  85916. ** All SELECT statements should have been expanded using
  85917. ** sqlite3SelectExpand() prior to invoking this routine.
  85918. */
  85919. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  85920. Parse *pParse, /* The parser context */
  85921. Select *p, /* The SELECT statement being coded. */
  85922. NameContext *pOuterNC /* Name context for parent SELECT statement */
  85923. ){
  85924. Walker w;
  85925. assert( p!=0 );
  85926. w.xExprCallback = resolveExprStep;
  85927. w.xSelectCallback = resolveSelectStep;
  85928. w.xSelectCallback2 = 0;
  85929. w.pParse = pParse;
  85930. w.u.pNC = pOuterNC;
  85931. sqlite3WalkSelect(&w, p);
  85932. }
  85933. /*
  85934. ** Resolve names in expressions that can only reference a single table:
  85935. **
  85936. ** * CHECK constraints
  85937. ** * WHERE clauses on partial indices
  85938. **
  85939. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  85940. ** is set to -1 and the Expr.iColumn value is set to the column number.
  85941. **
  85942. ** Any errors cause an error message to be set in pParse.
  85943. */
  85944. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  85945. Parse *pParse, /* Parsing context */
  85946. Table *pTab, /* The table being referenced */
  85947. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  85948. Expr *pExpr, /* Expression to resolve. May be NULL. */
  85949. ExprList *pList /* Expression list to resolve. May be NUL. */
  85950. ){
  85951. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  85952. NameContext sNC; /* Name context for pParse->pNewTable */
  85953. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  85954. memset(&sNC, 0, sizeof(sNC));
  85955. memset(&sSrc, 0, sizeof(sSrc));
  85956. sSrc.nSrc = 1;
  85957. sSrc.a[0].zName = pTab->zName;
  85958. sSrc.a[0].pTab = pTab;
  85959. sSrc.a[0].iCursor = -1;
  85960. sNC.pParse = pParse;
  85961. sNC.pSrcList = &sSrc;
  85962. sNC.ncFlags = type;
  85963. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  85964. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  85965. }
  85966. /************** End of resolve.c *********************************************/
  85967. /************** Begin file expr.c ********************************************/
  85968. /*
  85969. ** 2001 September 15
  85970. **
  85971. ** The author disclaims copyright to this source code. In place of
  85972. ** a legal notice, here is a blessing:
  85973. **
  85974. ** May you do good and not evil.
  85975. ** May you find forgiveness for yourself and forgive others.
  85976. ** May you share freely, never taking more than you give.
  85977. **
  85978. *************************************************************************
  85979. ** This file contains routines used for analyzing expressions and
  85980. ** for generating VDBE code that evaluates expressions in SQLite.
  85981. */
  85982. /* #include "sqliteInt.h" */
  85983. /* Forward declarations */
  85984. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  85985. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  85986. /*
  85987. ** Return the affinity character for a single column of a table.
  85988. */
  85989. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  85990. assert( iCol<pTab->nCol );
  85991. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  85992. }
  85993. /*
  85994. ** Return the 'affinity' of the expression pExpr if any.
  85995. **
  85996. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  85997. ** or a sub-select with a column as the return value, then the
  85998. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  85999. ** indicating no affinity for the expression.
  86000. **
  86001. ** i.e. the WHERE clause expressions in the following statements all
  86002. ** have an affinity:
  86003. **
  86004. ** CREATE TABLE t1(a);
  86005. ** SELECT * FROM t1 WHERE a;
  86006. ** SELECT a AS b FROM t1 WHERE b;
  86007. ** SELECT * FROM t1 WHERE (select a from t1);
  86008. */
  86009. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  86010. int op;
  86011. pExpr = sqlite3ExprSkipCollate(pExpr);
  86012. if( pExpr->flags & EP_Generic ) return 0;
  86013. op = pExpr->op;
  86014. if( op==TK_SELECT ){
  86015. assert( pExpr->flags&EP_xIsSelect );
  86016. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  86017. }
  86018. if( op==TK_REGISTER ) op = pExpr->op2;
  86019. #ifndef SQLITE_OMIT_CAST
  86020. if( op==TK_CAST ){
  86021. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  86022. return sqlite3AffinityType(pExpr->u.zToken, 0);
  86023. }
  86024. #endif
  86025. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
  86026. return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
  86027. }
  86028. if( op==TK_SELECT_COLUMN ){
  86029. assert( pExpr->pLeft->flags&EP_xIsSelect );
  86030. return sqlite3ExprAffinity(
  86031. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  86032. );
  86033. }
  86034. return pExpr->affinity;
  86035. }
  86036. /*
  86037. ** Set the collating sequence for expression pExpr to be the collating
  86038. ** sequence named by pToken. Return a pointer to a new Expr node that
  86039. ** implements the COLLATE operator.
  86040. **
  86041. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  86042. ** and the pExpr parameter is returned unchanged.
  86043. */
  86044. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  86045. Parse *pParse, /* Parsing context */
  86046. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  86047. const Token *pCollName, /* Name of collating sequence */
  86048. int dequote /* True to dequote pCollName */
  86049. ){
  86050. if( pCollName->n>0 ){
  86051. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  86052. if( pNew ){
  86053. pNew->pLeft = pExpr;
  86054. pNew->flags |= EP_Collate|EP_Skip;
  86055. pExpr = pNew;
  86056. }
  86057. }
  86058. return pExpr;
  86059. }
  86060. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  86061. Token s;
  86062. assert( zC!=0 );
  86063. sqlite3TokenInit(&s, (char*)zC);
  86064. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  86065. }
  86066. /*
  86067. ** Skip over any TK_COLLATE operators and any unlikely()
  86068. ** or likelihood() function at the root of an expression.
  86069. */
  86070. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  86071. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  86072. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  86073. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  86074. assert( pExpr->x.pList->nExpr>0 );
  86075. assert( pExpr->op==TK_FUNCTION );
  86076. pExpr = pExpr->x.pList->a[0].pExpr;
  86077. }else{
  86078. assert( pExpr->op==TK_COLLATE );
  86079. pExpr = pExpr->pLeft;
  86080. }
  86081. }
  86082. return pExpr;
  86083. }
  86084. /*
  86085. ** Return the collation sequence for the expression pExpr. If
  86086. ** there is no defined collating sequence, return NULL.
  86087. **
  86088. ** See also: sqlite3ExprNNCollSeq()
  86089. **
  86090. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  86091. ** default collation if pExpr has no defined collation.
  86092. **
  86093. ** The collating sequence might be determined by a COLLATE operator
  86094. ** or by the presence of a column with a defined collating sequence.
  86095. ** COLLATE operators take first precedence. Left operands take
  86096. ** precedence over right operands.
  86097. */
  86098. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  86099. sqlite3 *db = pParse->db;
  86100. CollSeq *pColl = 0;
  86101. Expr *p = pExpr;
  86102. while( p ){
  86103. int op = p->op;
  86104. if( p->flags & EP_Generic ) break;
  86105. if( op==TK_CAST || op==TK_UPLUS ){
  86106. p = p->pLeft;
  86107. continue;
  86108. }
  86109. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  86110. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  86111. break;
  86112. }
  86113. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  86114. || op==TK_REGISTER || op==TK_TRIGGER)
  86115. && p->pTab!=0
  86116. ){
  86117. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  86118. ** a TK_COLUMN but was previously evaluated and cached in a register */
  86119. int j = p->iColumn;
  86120. if( j>=0 ){
  86121. const char *zColl = p->pTab->aCol[j].zColl;
  86122. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  86123. }
  86124. break;
  86125. }
  86126. if( p->flags & EP_Collate ){
  86127. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  86128. p = p->pLeft;
  86129. }else{
  86130. Expr *pNext = p->pRight;
  86131. /* The Expr.x union is never used at the same time as Expr.pRight */
  86132. assert( p->x.pList==0 || p->pRight==0 );
  86133. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  86134. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  86135. ** least one EP_Collate. Thus the following two ALWAYS. */
  86136. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  86137. int i;
  86138. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  86139. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  86140. pNext = p->x.pList->a[i].pExpr;
  86141. break;
  86142. }
  86143. }
  86144. }
  86145. p = pNext;
  86146. }
  86147. }else{
  86148. break;
  86149. }
  86150. }
  86151. if( sqlite3CheckCollSeq(pParse, pColl) ){
  86152. pColl = 0;
  86153. }
  86154. return pColl;
  86155. }
  86156. /*
  86157. ** Return the collation sequence for the expression pExpr. If
  86158. ** there is no defined collating sequence, return a pointer to the
  86159. ** defautl collation sequence.
  86160. **
  86161. ** See also: sqlite3ExprCollSeq()
  86162. **
  86163. ** The sqlite3ExprCollSeq() routine works the same except that it
  86164. ** returns NULL if there is no defined collation.
  86165. */
  86166. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  86167. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  86168. if( p==0 ) p = pParse->db->pDfltColl;
  86169. assert( p!=0 );
  86170. return p;
  86171. }
  86172. /*
  86173. ** Return TRUE if the two expressions have equivalent collating sequences.
  86174. */
  86175. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  86176. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  86177. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  86178. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  86179. }
  86180. /*
  86181. ** pExpr is an operand of a comparison operator. aff2 is the
  86182. ** type affinity of the other operand. This routine returns the
  86183. ** type affinity that should be used for the comparison operator.
  86184. */
  86185. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  86186. char aff1 = sqlite3ExprAffinity(pExpr);
  86187. if( aff1 && aff2 ){
  86188. /* Both sides of the comparison are columns. If one has numeric
  86189. ** affinity, use that. Otherwise use no affinity.
  86190. */
  86191. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  86192. return SQLITE_AFF_NUMERIC;
  86193. }else{
  86194. return SQLITE_AFF_BLOB;
  86195. }
  86196. }else if( !aff1 && !aff2 ){
  86197. /* Neither side of the comparison is a column. Compare the
  86198. ** results directly.
  86199. */
  86200. return SQLITE_AFF_BLOB;
  86201. }else{
  86202. /* One side is a column, the other is not. Use the columns affinity. */
  86203. assert( aff1==0 || aff2==0 );
  86204. return (aff1 + aff2);
  86205. }
  86206. }
  86207. /*
  86208. ** pExpr is a comparison operator. Return the type affinity that should
  86209. ** be applied to both operands prior to doing the comparison.
  86210. */
  86211. static char comparisonAffinity(Expr *pExpr){
  86212. char aff;
  86213. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  86214. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  86215. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  86216. assert( pExpr->pLeft );
  86217. aff = sqlite3ExprAffinity(pExpr->pLeft);
  86218. if( pExpr->pRight ){
  86219. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  86220. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86221. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  86222. }else if( aff==0 ){
  86223. aff = SQLITE_AFF_BLOB;
  86224. }
  86225. return aff;
  86226. }
  86227. /*
  86228. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  86229. ** idx_affinity is the affinity of an indexed column. Return true
  86230. ** if the index with affinity idx_affinity may be used to implement
  86231. ** the comparison in pExpr.
  86232. */
  86233. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  86234. char aff = comparisonAffinity(pExpr);
  86235. switch( aff ){
  86236. case SQLITE_AFF_BLOB:
  86237. return 1;
  86238. case SQLITE_AFF_TEXT:
  86239. return idx_affinity==SQLITE_AFF_TEXT;
  86240. default:
  86241. return sqlite3IsNumericAffinity(idx_affinity);
  86242. }
  86243. }
  86244. /*
  86245. ** Return the P5 value that should be used for a binary comparison
  86246. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  86247. */
  86248. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  86249. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  86250. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  86251. return aff;
  86252. }
  86253. /*
  86254. ** Return a pointer to the collation sequence that should be used by
  86255. ** a binary comparison operator comparing pLeft and pRight.
  86256. **
  86257. ** If the left hand expression has a collating sequence type, then it is
  86258. ** used. Otherwise the collation sequence for the right hand expression
  86259. ** is used, or the default (BINARY) if neither expression has a collating
  86260. ** type.
  86261. **
  86262. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  86263. ** it is not considered.
  86264. */
  86265. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  86266. Parse *pParse,
  86267. Expr *pLeft,
  86268. Expr *pRight
  86269. ){
  86270. CollSeq *pColl;
  86271. assert( pLeft );
  86272. if( pLeft->flags & EP_Collate ){
  86273. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  86274. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  86275. pColl = sqlite3ExprCollSeq(pParse, pRight);
  86276. }else{
  86277. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  86278. if( !pColl ){
  86279. pColl = sqlite3ExprCollSeq(pParse, pRight);
  86280. }
  86281. }
  86282. return pColl;
  86283. }
  86284. /*
  86285. ** Generate code for a comparison operator.
  86286. */
  86287. static int codeCompare(
  86288. Parse *pParse, /* The parsing (and code generating) context */
  86289. Expr *pLeft, /* The left operand */
  86290. Expr *pRight, /* The right operand */
  86291. int opcode, /* The comparison opcode */
  86292. int in1, int in2, /* Register holding operands */
  86293. int dest, /* Jump here if true. */
  86294. int jumpIfNull /* If true, jump if either operand is NULL */
  86295. ){
  86296. int p5;
  86297. int addr;
  86298. CollSeq *p4;
  86299. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  86300. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  86301. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  86302. (void*)p4, P4_COLLSEQ);
  86303. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  86304. return addr;
  86305. }
  86306. /*
  86307. ** Return true if expression pExpr is a vector, or false otherwise.
  86308. **
  86309. ** A vector is defined as any expression that results in two or more
  86310. ** columns of result. Every TK_VECTOR node is an vector because the
  86311. ** parser will not generate a TK_VECTOR with fewer than two entries.
  86312. ** But a TK_SELECT might be either a vector or a scalar. It is only
  86313. ** considered a vector if it has two or more result columns.
  86314. */
  86315. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  86316. return sqlite3ExprVectorSize(pExpr)>1;
  86317. }
  86318. /*
  86319. ** If the expression passed as the only argument is of type TK_VECTOR
  86320. ** return the number of expressions in the vector. Or, if the expression
  86321. ** is a sub-select, return the number of columns in the sub-select. For
  86322. ** any other type of expression, return 1.
  86323. */
  86324. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  86325. u8 op = pExpr->op;
  86326. if( op==TK_REGISTER ) op = pExpr->op2;
  86327. if( op==TK_VECTOR ){
  86328. return pExpr->x.pList->nExpr;
  86329. }else if( op==TK_SELECT ){
  86330. return pExpr->x.pSelect->pEList->nExpr;
  86331. }else{
  86332. return 1;
  86333. }
  86334. }
  86335. /*
  86336. ** Return a pointer to a subexpression of pVector that is the i-th
  86337. ** column of the vector (numbered starting with 0). The caller must
  86338. ** ensure that i is within range.
  86339. **
  86340. ** If pVector is really a scalar (and "scalar" here includes subqueries
  86341. ** that return a single column!) then return pVector unmodified.
  86342. **
  86343. ** pVector retains ownership of the returned subexpression.
  86344. **
  86345. ** If the vector is a (SELECT ...) then the expression returned is
  86346. ** just the expression for the i-th term of the result set, and may
  86347. ** not be ready for evaluation because the table cursor has not yet
  86348. ** been positioned.
  86349. */
  86350. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  86351. assert( i<sqlite3ExprVectorSize(pVector) );
  86352. if( sqlite3ExprIsVector(pVector) ){
  86353. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  86354. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  86355. return pVector->x.pSelect->pEList->a[i].pExpr;
  86356. }else{
  86357. return pVector->x.pList->a[i].pExpr;
  86358. }
  86359. }
  86360. return pVector;
  86361. }
  86362. /*
  86363. ** Compute and return a new Expr object which when passed to
  86364. ** sqlite3ExprCode() will generate all necessary code to compute
  86365. ** the iField-th column of the vector expression pVector.
  86366. **
  86367. ** It is ok for pVector to be a scalar (as long as iField==0).
  86368. ** In that case, this routine works like sqlite3ExprDup().
  86369. **
  86370. ** The caller owns the returned Expr object and is responsible for
  86371. ** ensuring that the returned value eventually gets freed.
  86372. **
  86373. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  86374. ** then the returned object will reference pVector and so pVector must remain
  86375. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  86376. ** or a scalar expression, then it can be deleted as soon as this routine
  86377. ** returns.
  86378. **
  86379. ** A trick to cause a TK_SELECT pVector to be deleted together with
  86380. ** the returned Expr object is to attach the pVector to the pRight field
  86381. ** of the returned TK_SELECT_COLUMN Expr object.
  86382. */
  86383. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  86384. Parse *pParse, /* Parsing context */
  86385. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  86386. int iField /* Which column of the vector to return */
  86387. ){
  86388. Expr *pRet;
  86389. if( pVector->op==TK_SELECT ){
  86390. assert( pVector->flags & EP_xIsSelect );
  86391. /* The TK_SELECT_COLUMN Expr node:
  86392. **
  86393. ** pLeft: pVector containing TK_SELECT. Not deleted.
  86394. ** pRight: not used. But recursively deleted.
  86395. ** iColumn: Index of a column in pVector
  86396. ** iTable: 0 or the number of columns on the LHS of an assignment
  86397. ** pLeft->iTable: First in an array of register holding result, or 0
  86398. ** if the result is not yet computed.
  86399. **
  86400. ** sqlite3ExprDelete() specifically skips the recursive delete of
  86401. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  86402. ** can be attached to pRight to cause this node to take ownership of
  86403. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  86404. ** with the same pLeft pointer to the pVector, but only one of them
  86405. ** will own the pVector.
  86406. */
  86407. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  86408. if( pRet ){
  86409. pRet->iColumn = iField;
  86410. pRet->pLeft = pVector;
  86411. }
  86412. assert( pRet==0 || pRet->iTable==0 );
  86413. }else{
  86414. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  86415. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  86416. }
  86417. return pRet;
  86418. }
  86419. /*
  86420. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  86421. ** it. Return the register in which the result is stored (or, if the
  86422. ** sub-select returns more than one column, the first in an array
  86423. ** of registers in which the result is stored).
  86424. **
  86425. ** If pExpr is not a TK_SELECT expression, return 0.
  86426. */
  86427. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  86428. int reg = 0;
  86429. #ifndef SQLITE_OMIT_SUBQUERY
  86430. if( pExpr->op==TK_SELECT ){
  86431. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  86432. }
  86433. #endif
  86434. return reg;
  86435. }
  86436. /*
  86437. ** Argument pVector points to a vector expression - either a TK_VECTOR
  86438. ** or TK_SELECT that returns more than one column. This function returns
  86439. ** the register number of a register that contains the value of
  86440. ** element iField of the vector.
  86441. **
  86442. ** If pVector is a TK_SELECT expression, then code for it must have
  86443. ** already been generated using the exprCodeSubselect() routine. In this
  86444. ** case parameter regSelect should be the first in an array of registers
  86445. ** containing the results of the sub-select.
  86446. **
  86447. ** If pVector is of type TK_VECTOR, then code for the requested field
  86448. ** is generated. In this case (*pRegFree) may be set to the number of
  86449. ** a temporary register to be freed by the caller before returning.
  86450. **
  86451. ** Before returning, output parameter (*ppExpr) is set to point to the
  86452. ** Expr object corresponding to element iElem of the vector.
  86453. */
  86454. static int exprVectorRegister(
  86455. Parse *pParse, /* Parse context */
  86456. Expr *pVector, /* Vector to extract element from */
  86457. int iField, /* Field to extract from pVector */
  86458. int regSelect, /* First in array of registers */
  86459. Expr **ppExpr, /* OUT: Expression element */
  86460. int *pRegFree /* OUT: Temp register to free */
  86461. ){
  86462. u8 op = pVector->op;
  86463. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  86464. if( op==TK_REGISTER ){
  86465. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  86466. return pVector->iTable+iField;
  86467. }
  86468. if( op==TK_SELECT ){
  86469. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  86470. return regSelect+iField;
  86471. }
  86472. *ppExpr = pVector->x.pList->a[iField].pExpr;
  86473. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  86474. }
  86475. /*
  86476. ** Expression pExpr is a comparison between two vector values. Compute
  86477. ** the result of the comparison (1, 0, or NULL) and write that
  86478. ** result into register dest.
  86479. **
  86480. ** The caller must satisfy the following preconditions:
  86481. **
  86482. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  86483. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  86484. ** otherwise: op==pExpr->op and p5==0
  86485. */
  86486. static void codeVectorCompare(
  86487. Parse *pParse, /* Code generator context */
  86488. Expr *pExpr, /* The comparison operation */
  86489. int dest, /* Write results into this register */
  86490. u8 op, /* Comparison operator */
  86491. u8 p5 /* SQLITE_NULLEQ or zero */
  86492. ){
  86493. Vdbe *v = pParse->pVdbe;
  86494. Expr *pLeft = pExpr->pLeft;
  86495. Expr *pRight = pExpr->pRight;
  86496. int nLeft = sqlite3ExprVectorSize(pLeft);
  86497. int i;
  86498. int regLeft = 0;
  86499. int regRight = 0;
  86500. u8 opx = op;
  86501. int addrDone = sqlite3VdbeMakeLabel(v);
  86502. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  86503. sqlite3ErrorMsg(pParse, "row value misused");
  86504. return;
  86505. }
  86506. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  86507. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  86508. || pExpr->op==TK_LT || pExpr->op==TK_GT
  86509. || pExpr->op==TK_LE || pExpr->op==TK_GE
  86510. );
  86511. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  86512. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  86513. assert( p5==0 || pExpr->op!=op );
  86514. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  86515. p5 |= SQLITE_STOREP2;
  86516. if( opx==TK_LE ) opx = TK_LT;
  86517. if( opx==TK_GE ) opx = TK_GT;
  86518. regLeft = exprCodeSubselect(pParse, pLeft);
  86519. regRight = exprCodeSubselect(pParse, pRight);
  86520. for(i=0; 1 /*Loop exits by "break"*/; i++){
  86521. int regFree1 = 0, regFree2 = 0;
  86522. Expr *pL, *pR;
  86523. int r1, r2;
  86524. assert( i>=0 && i<nLeft );
  86525. if( i>0 ) sqlite3ExprCachePush(pParse);
  86526. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  86527. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  86528. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  86529. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  86530. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  86531. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  86532. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  86533. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  86534. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  86535. sqlite3ReleaseTempReg(pParse, regFree1);
  86536. sqlite3ReleaseTempReg(pParse, regFree2);
  86537. if( i>0 ) sqlite3ExprCachePop(pParse);
  86538. if( i==nLeft-1 ){
  86539. break;
  86540. }
  86541. if( opx==TK_EQ ){
  86542. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  86543. p5 |= SQLITE_KEEPNULL;
  86544. }else if( opx==TK_NE ){
  86545. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  86546. p5 |= SQLITE_KEEPNULL;
  86547. }else{
  86548. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  86549. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  86550. VdbeCoverageIf(v, op==TK_LT);
  86551. VdbeCoverageIf(v, op==TK_GT);
  86552. VdbeCoverageIf(v, op==TK_LE);
  86553. VdbeCoverageIf(v, op==TK_GE);
  86554. if( i==nLeft-2 ) opx = op;
  86555. }
  86556. }
  86557. sqlite3VdbeResolveLabel(v, addrDone);
  86558. }
  86559. #if SQLITE_MAX_EXPR_DEPTH>0
  86560. /*
  86561. ** Check that argument nHeight is less than or equal to the maximum
  86562. ** expression depth allowed. If it is not, leave an error message in
  86563. ** pParse.
  86564. */
  86565. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  86566. int rc = SQLITE_OK;
  86567. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  86568. if( nHeight>mxHeight ){
  86569. sqlite3ErrorMsg(pParse,
  86570. "Expression tree is too large (maximum depth %d)", mxHeight
  86571. );
  86572. rc = SQLITE_ERROR;
  86573. }
  86574. return rc;
  86575. }
  86576. /* The following three functions, heightOfExpr(), heightOfExprList()
  86577. ** and heightOfSelect(), are used to determine the maximum height
  86578. ** of any expression tree referenced by the structure passed as the
  86579. ** first argument.
  86580. **
  86581. ** If this maximum height is greater than the current value pointed
  86582. ** to by pnHeight, the second parameter, then set *pnHeight to that
  86583. ** value.
  86584. */
  86585. static void heightOfExpr(Expr *p, int *pnHeight){
  86586. if( p ){
  86587. if( p->nHeight>*pnHeight ){
  86588. *pnHeight = p->nHeight;
  86589. }
  86590. }
  86591. }
  86592. static void heightOfExprList(ExprList *p, int *pnHeight){
  86593. if( p ){
  86594. int i;
  86595. for(i=0; i<p->nExpr; i++){
  86596. heightOfExpr(p->a[i].pExpr, pnHeight);
  86597. }
  86598. }
  86599. }
  86600. static void heightOfSelect(Select *p, int *pnHeight){
  86601. if( p ){
  86602. heightOfExpr(p->pWhere, pnHeight);
  86603. heightOfExpr(p->pHaving, pnHeight);
  86604. heightOfExpr(p->pLimit, pnHeight);
  86605. heightOfExpr(p->pOffset, pnHeight);
  86606. heightOfExprList(p->pEList, pnHeight);
  86607. heightOfExprList(p->pGroupBy, pnHeight);
  86608. heightOfExprList(p->pOrderBy, pnHeight);
  86609. heightOfSelect(p->pPrior, pnHeight);
  86610. }
  86611. }
  86612. /*
  86613. ** Set the Expr.nHeight variable in the structure passed as an
  86614. ** argument. An expression with no children, Expr.pList or
  86615. ** Expr.pSelect member has a height of 1. Any other expression
  86616. ** has a height equal to the maximum height of any other
  86617. ** referenced Expr plus one.
  86618. **
  86619. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  86620. ** if appropriate.
  86621. */
  86622. static void exprSetHeight(Expr *p){
  86623. int nHeight = 0;
  86624. heightOfExpr(p->pLeft, &nHeight);
  86625. heightOfExpr(p->pRight, &nHeight);
  86626. if( ExprHasProperty(p, EP_xIsSelect) ){
  86627. heightOfSelect(p->x.pSelect, &nHeight);
  86628. }else if( p->x.pList ){
  86629. heightOfExprList(p->x.pList, &nHeight);
  86630. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  86631. }
  86632. p->nHeight = nHeight + 1;
  86633. }
  86634. /*
  86635. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  86636. ** the height is greater than the maximum allowed expression depth,
  86637. ** leave an error in pParse.
  86638. **
  86639. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  86640. ** Expr.flags.
  86641. */
  86642. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  86643. if( pParse->nErr ) return;
  86644. exprSetHeight(p);
  86645. sqlite3ExprCheckHeight(pParse, p->nHeight);
  86646. }
  86647. /*
  86648. ** Return the maximum height of any expression tree referenced
  86649. ** by the select statement passed as an argument.
  86650. */
  86651. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  86652. int nHeight = 0;
  86653. heightOfSelect(p, &nHeight);
  86654. return nHeight;
  86655. }
  86656. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  86657. /*
  86658. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  86659. ** Expr.flags.
  86660. */
  86661. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  86662. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  86663. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  86664. }
  86665. }
  86666. #define exprSetHeight(y)
  86667. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  86668. /*
  86669. ** This routine is the core allocator for Expr nodes.
  86670. **
  86671. ** Construct a new expression node and return a pointer to it. Memory
  86672. ** for this node and for the pToken argument is a single allocation
  86673. ** obtained from sqlite3DbMalloc(). The calling function
  86674. ** is responsible for making sure the node eventually gets freed.
  86675. **
  86676. ** If dequote is true, then the token (if it exists) is dequoted.
  86677. ** If dequote is false, no dequoting is performed. The deQuote
  86678. ** parameter is ignored if pToken is NULL or if the token does not
  86679. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  86680. ** then the EP_DblQuoted flag is set on the expression node.
  86681. **
  86682. ** Special case: If op==TK_INTEGER and pToken points to a string that
  86683. ** can be translated into a 32-bit integer, then the token is not
  86684. ** stored in u.zToken. Instead, the integer values is written
  86685. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  86686. ** is allocated to hold the integer text and the dequote flag is ignored.
  86687. */
  86688. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  86689. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  86690. int op, /* Expression opcode */
  86691. const Token *pToken, /* Token argument. Might be NULL */
  86692. int dequote /* True to dequote */
  86693. ){
  86694. Expr *pNew;
  86695. int nExtra = 0;
  86696. int iValue = 0;
  86697. assert( db!=0 );
  86698. if( pToken ){
  86699. if( op!=TK_INTEGER || pToken->z==0
  86700. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  86701. nExtra = pToken->n+1;
  86702. assert( iValue>=0 );
  86703. }
  86704. }
  86705. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  86706. if( pNew ){
  86707. memset(pNew, 0, sizeof(Expr));
  86708. pNew->op = (u8)op;
  86709. pNew->iAgg = -1;
  86710. if( pToken ){
  86711. if( nExtra==0 ){
  86712. pNew->flags |= EP_IntValue|EP_Leaf;
  86713. pNew->u.iValue = iValue;
  86714. }else{
  86715. pNew->u.zToken = (char*)&pNew[1];
  86716. assert( pToken->z!=0 || pToken->n==0 );
  86717. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  86718. pNew->u.zToken[pToken->n] = 0;
  86719. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  86720. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  86721. sqlite3Dequote(pNew->u.zToken);
  86722. }
  86723. }
  86724. }
  86725. #if SQLITE_MAX_EXPR_DEPTH>0
  86726. pNew->nHeight = 1;
  86727. #endif
  86728. }
  86729. return pNew;
  86730. }
  86731. /*
  86732. ** Allocate a new expression node from a zero-terminated token that has
  86733. ** already been dequoted.
  86734. */
  86735. SQLITE_PRIVATE Expr *sqlite3Expr(
  86736. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  86737. int op, /* Expression opcode */
  86738. const char *zToken /* Token argument. Might be NULL */
  86739. ){
  86740. Token x;
  86741. x.z = zToken;
  86742. x.n = sqlite3Strlen30(zToken);
  86743. return sqlite3ExprAlloc(db, op, &x, 0);
  86744. }
  86745. /*
  86746. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  86747. **
  86748. ** If pRoot==NULL that means that a memory allocation error has occurred.
  86749. ** In that case, delete the subtrees pLeft and pRight.
  86750. */
  86751. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  86752. sqlite3 *db,
  86753. Expr *pRoot,
  86754. Expr *pLeft,
  86755. Expr *pRight
  86756. ){
  86757. if( pRoot==0 ){
  86758. assert( db->mallocFailed );
  86759. sqlite3ExprDelete(db, pLeft);
  86760. sqlite3ExprDelete(db, pRight);
  86761. }else{
  86762. if( pRight ){
  86763. pRoot->pRight = pRight;
  86764. pRoot->flags |= EP_Propagate & pRight->flags;
  86765. }
  86766. if( pLeft ){
  86767. pRoot->pLeft = pLeft;
  86768. pRoot->flags |= EP_Propagate & pLeft->flags;
  86769. }
  86770. exprSetHeight(pRoot);
  86771. }
  86772. }
  86773. /*
  86774. ** Allocate an Expr node which joins as many as two subtrees.
  86775. **
  86776. ** One or both of the subtrees can be NULL. Return a pointer to the new
  86777. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  86778. ** free the subtrees and return NULL.
  86779. */
  86780. SQLITE_PRIVATE Expr *sqlite3PExpr(
  86781. Parse *pParse, /* Parsing context */
  86782. int op, /* Expression opcode */
  86783. Expr *pLeft, /* Left operand */
  86784. Expr *pRight /* Right operand */
  86785. ){
  86786. Expr *p;
  86787. if( op==TK_AND && pParse->nErr==0 ){
  86788. /* Take advantage of short-circuit false optimization for AND */
  86789. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  86790. }else{
  86791. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  86792. if( p ){
  86793. memset(p, 0, sizeof(Expr));
  86794. p->op = op & TKFLG_MASK;
  86795. p->iAgg = -1;
  86796. }
  86797. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  86798. }
  86799. if( p ) {
  86800. sqlite3ExprCheckHeight(pParse, p->nHeight);
  86801. }
  86802. return p;
  86803. }
  86804. /*
  86805. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  86806. ** do a memory allocation failure) then delete the pSelect object.
  86807. */
  86808. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  86809. if( pExpr ){
  86810. pExpr->x.pSelect = pSelect;
  86811. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  86812. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  86813. }else{
  86814. assert( pParse->db->mallocFailed );
  86815. sqlite3SelectDelete(pParse->db, pSelect);
  86816. }
  86817. }
  86818. /*
  86819. ** If the expression is always either TRUE or FALSE (respectively),
  86820. ** then return 1. If one cannot determine the truth value of the
  86821. ** expression at compile-time return 0.
  86822. **
  86823. ** This is an optimization. If is OK to return 0 here even if
  86824. ** the expression really is always false or false (a false negative).
  86825. ** But it is a bug to return 1 if the expression might have different
  86826. ** boolean values in different circumstances (a false positive.)
  86827. **
  86828. ** Note that if the expression is part of conditional for a
  86829. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  86830. ** is it true or false, so always return 0.
  86831. */
  86832. static int exprAlwaysTrue(Expr *p){
  86833. int v = 0;
  86834. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  86835. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  86836. return v!=0;
  86837. }
  86838. static int exprAlwaysFalse(Expr *p){
  86839. int v = 0;
  86840. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  86841. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  86842. return v==0;
  86843. }
  86844. /*
  86845. ** Join two expressions using an AND operator. If either expression is
  86846. ** NULL, then just return the other expression.
  86847. **
  86848. ** If one side or the other of the AND is known to be false, then instead
  86849. ** of returning an AND expression, just return a constant expression with
  86850. ** a value of false.
  86851. */
  86852. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  86853. if( pLeft==0 ){
  86854. return pRight;
  86855. }else if( pRight==0 ){
  86856. return pLeft;
  86857. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  86858. sqlite3ExprDelete(db, pLeft);
  86859. sqlite3ExprDelete(db, pRight);
  86860. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  86861. }else{
  86862. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  86863. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  86864. return pNew;
  86865. }
  86866. }
  86867. /*
  86868. ** Construct a new expression node for a function with multiple
  86869. ** arguments.
  86870. */
  86871. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  86872. Expr *pNew;
  86873. sqlite3 *db = pParse->db;
  86874. assert( pToken );
  86875. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  86876. if( pNew==0 ){
  86877. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  86878. return 0;
  86879. }
  86880. pNew->x.pList = pList;
  86881. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  86882. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  86883. return pNew;
  86884. }
  86885. /*
  86886. ** Assign a variable number to an expression that encodes a wildcard
  86887. ** in the original SQL statement.
  86888. **
  86889. ** Wildcards consisting of a single "?" are assigned the next sequential
  86890. ** variable number.
  86891. **
  86892. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  86893. ** sure "nnn" is not too big to avoid a denial of service attack when
  86894. ** the SQL statement comes from an external source.
  86895. **
  86896. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  86897. ** as the previous instance of the same wildcard. Or if this is the first
  86898. ** instance of the wildcard, the next sequential variable number is
  86899. ** assigned.
  86900. */
  86901. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  86902. sqlite3 *db = pParse->db;
  86903. const char *z;
  86904. ynVar x;
  86905. if( pExpr==0 ) return;
  86906. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  86907. z = pExpr->u.zToken;
  86908. assert( z!=0 );
  86909. assert( z[0]!=0 );
  86910. assert( n==(u32)sqlite3Strlen30(z) );
  86911. if( z[1]==0 ){
  86912. /* Wildcard of the form "?". Assign the next variable number */
  86913. assert( z[0]=='?' );
  86914. x = (ynVar)(++pParse->nVar);
  86915. }else{
  86916. int doAdd = 0;
  86917. if( z[0]=='?' ){
  86918. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  86919. ** use it as the variable number */
  86920. i64 i;
  86921. int bOk;
  86922. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  86923. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  86924. bOk = 1;
  86925. }else{
  86926. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  86927. }
  86928. testcase( i==0 );
  86929. testcase( i==1 );
  86930. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  86931. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  86932. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86933. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  86934. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  86935. return;
  86936. }
  86937. x = (ynVar)i;
  86938. if( x>pParse->nVar ){
  86939. pParse->nVar = (int)x;
  86940. doAdd = 1;
  86941. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  86942. doAdd = 1;
  86943. }
  86944. }else{
  86945. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  86946. ** number as the prior appearance of the same name, or if the name
  86947. ** has never appeared before, reuse the same variable number
  86948. */
  86949. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  86950. if( x==0 ){
  86951. x = (ynVar)(++pParse->nVar);
  86952. doAdd = 1;
  86953. }
  86954. }
  86955. if( doAdd ){
  86956. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  86957. }
  86958. }
  86959. pExpr->iColumn = x;
  86960. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86961. sqlite3ErrorMsg(pParse, "too many SQL variables");
  86962. }
  86963. }
  86964. /*
  86965. ** Recursively delete an expression tree.
  86966. */
  86967. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  86968. assert( p!=0 );
  86969. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  86970. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  86971. #ifdef SQLITE_DEBUG
  86972. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  86973. assert( p->pLeft==0 );
  86974. assert( p->pRight==0 );
  86975. assert( p->x.pSelect==0 );
  86976. }
  86977. #endif
  86978. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  86979. /* The Expr.x union is never used at the same time as Expr.pRight */
  86980. assert( p->x.pList==0 || p->pRight==0 );
  86981. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  86982. if( p->pRight ){
  86983. sqlite3ExprDeleteNN(db, p->pRight);
  86984. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  86985. sqlite3SelectDelete(db, p->x.pSelect);
  86986. }else{
  86987. sqlite3ExprListDelete(db, p->x.pList);
  86988. }
  86989. }
  86990. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  86991. if( !ExprHasProperty(p, EP_Static) ){
  86992. sqlite3DbFreeNN(db, p);
  86993. }
  86994. }
  86995. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  86996. if( p ) sqlite3ExprDeleteNN(db, p);
  86997. }
  86998. /*
  86999. ** Return the number of bytes allocated for the expression structure
  87000. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  87001. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  87002. */
  87003. static int exprStructSize(Expr *p){
  87004. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  87005. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  87006. return EXPR_FULLSIZE;
  87007. }
  87008. /*
  87009. ** The dupedExpr*Size() routines each return the number of bytes required
  87010. ** to store a copy of an expression or expression tree. They differ in
  87011. ** how much of the tree is measured.
  87012. **
  87013. ** dupedExprStructSize() Size of only the Expr structure
  87014. ** dupedExprNodeSize() Size of Expr + space for token
  87015. ** dupedExprSize() Expr + token + subtree components
  87016. **
  87017. ***************************************************************************
  87018. **
  87019. ** The dupedExprStructSize() function returns two values OR-ed together:
  87020. ** (1) the space required for a copy of the Expr structure only and
  87021. ** (2) the EP_xxx flags that indicate what the structure size should be.
  87022. ** The return values is always one of:
  87023. **
  87024. ** EXPR_FULLSIZE
  87025. ** EXPR_REDUCEDSIZE | EP_Reduced
  87026. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  87027. **
  87028. ** The size of the structure can be found by masking the return value
  87029. ** of this routine with 0xfff. The flags can be found by masking the
  87030. ** return value with EP_Reduced|EP_TokenOnly.
  87031. **
  87032. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  87033. ** (unreduced) Expr objects as they or originally constructed by the parser.
  87034. ** During expression analysis, extra information is computed and moved into
  87035. ** later parts of teh Expr object and that extra information might get chopped
  87036. ** off if the expression is reduced. Note also that it does not work to
  87037. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  87038. ** to reduce a pristine expression tree from the parser. The implementation
  87039. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  87040. ** to enforce this constraint.
  87041. */
  87042. static int dupedExprStructSize(Expr *p, int flags){
  87043. int nSize;
  87044. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  87045. assert( EXPR_FULLSIZE<=0xfff );
  87046. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  87047. if( 0==flags || p->op==TK_SELECT_COLUMN ){
  87048. nSize = EXPR_FULLSIZE;
  87049. }else{
  87050. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  87051. assert( !ExprHasProperty(p, EP_FromJoin) );
  87052. assert( !ExprHasProperty(p, EP_MemToken) );
  87053. assert( !ExprHasProperty(p, EP_NoReduce) );
  87054. if( p->pLeft || p->x.pList ){
  87055. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  87056. }else{
  87057. assert( p->pRight==0 );
  87058. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  87059. }
  87060. }
  87061. return nSize;
  87062. }
  87063. /*
  87064. ** This function returns the space in bytes required to store the copy
  87065. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  87066. ** string is defined.)
  87067. */
  87068. static int dupedExprNodeSize(Expr *p, int flags){
  87069. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  87070. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  87071. nByte += sqlite3Strlen30(p->u.zToken)+1;
  87072. }
  87073. return ROUND8(nByte);
  87074. }
  87075. /*
  87076. ** Return the number of bytes required to create a duplicate of the
  87077. ** expression passed as the first argument. The second argument is a
  87078. ** mask containing EXPRDUP_XXX flags.
  87079. **
  87080. ** The value returned includes space to create a copy of the Expr struct
  87081. ** itself and the buffer referred to by Expr.u.zToken, if any.
  87082. **
  87083. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  87084. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  87085. ** and Expr.pRight variables (but not for any structures pointed to or
  87086. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  87087. */
  87088. static int dupedExprSize(Expr *p, int flags){
  87089. int nByte = 0;
  87090. if( p ){
  87091. nByte = dupedExprNodeSize(p, flags);
  87092. if( flags&EXPRDUP_REDUCE ){
  87093. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  87094. }
  87095. }
  87096. return nByte;
  87097. }
  87098. /*
  87099. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  87100. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  87101. ** to store the copy of expression p, the copies of p->u.zToken
  87102. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  87103. ** if any. Before returning, *pzBuffer is set to the first byte past the
  87104. ** portion of the buffer copied into by this function.
  87105. */
  87106. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  87107. Expr *pNew; /* Value to return */
  87108. u8 *zAlloc; /* Memory space from which to build Expr object */
  87109. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  87110. assert( db!=0 );
  87111. assert( p );
  87112. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  87113. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  87114. /* Figure out where to write the new Expr structure. */
  87115. if( pzBuffer ){
  87116. zAlloc = *pzBuffer;
  87117. staticFlag = EP_Static;
  87118. }else{
  87119. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  87120. staticFlag = 0;
  87121. }
  87122. pNew = (Expr *)zAlloc;
  87123. if( pNew ){
  87124. /* Set nNewSize to the size allocated for the structure pointed to
  87125. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  87126. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  87127. ** by the copy of the p->u.zToken string (if any).
  87128. */
  87129. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  87130. const int nNewSize = nStructSize & 0xfff;
  87131. int nToken;
  87132. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  87133. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  87134. }else{
  87135. nToken = 0;
  87136. }
  87137. if( dupFlags ){
  87138. assert( ExprHasProperty(p, EP_Reduced)==0 );
  87139. memcpy(zAlloc, p, nNewSize);
  87140. }else{
  87141. u32 nSize = (u32)exprStructSize(p);
  87142. memcpy(zAlloc, p, nSize);
  87143. if( nSize<EXPR_FULLSIZE ){
  87144. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  87145. }
  87146. }
  87147. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  87148. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  87149. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  87150. pNew->flags |= staticFlag;
  87151. /* Copy the p->u.zToken string, if any. */
  87152. if( nToken ){
  87153. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  87154. memcpy(zToken, p->u.zToken, nToken);
  87155. }
  87156. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  87157. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  87158. if( ExprHasProperty(p, EP_xIsSelect) ){
  87159. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  87160. }else{
  87161. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  87162. }
  87163. }
  87164. /* Fill in pNew->pLeft and pNew->pRight. */
  87165. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  87166. zAlloc += dupedExprNodeSize(p, dupFlags);
  87167. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  87168. pNew->pLeft = p->pLeft ?
  87169. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  87170. pNew->pRight = p->pRight ?
  87171. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  87172. }
  87173. if( pzBuffer ){
  87174. *pzBuffer = zAlloc;
  87175. }
  87176. }else{
  87177. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  87178. if( pNew->op==TK_SELECT_COLUMN ){
  87179. pNew->pLeft = p->pLeft;
  87180. assert( p->iColumn==0 || p->pRight==0 );
  87181. assert( p->pRight==0 || p->pRight==p->pLeft );
  87182. }else{
  87183. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  87184. }
  87185. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  87186. }
  87187. }
  87188. }
  87189. return pNew;
  87190. }
  87191. /*
  87192. ** Create and return a deep copy of the object passed as the second
  87193. ** argument. If an OOM condition is encountered, NULL is returned
  87194. ** and the db->mallocFailed flag set.
  87195. */
  87196. #ifndef SQLITE_OMIT_CTE
  87197. static With *withDup(sqlite3 *db, With *p){
  87198. With *pRet = 0;
  87199. if( p ){
  87200. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  87201. pRet = sqlite3DbMallocZero(db, nByte);
  87202. if( pRet ){
  87203. int i;
  87204. pRet->nCte = p->nCte;
  87205. for(i=0; i<p->nCte; i++){
  87206. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  87207. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  87208. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  87209. }
  87210. }
  87211. }
  87212. return pRet;
  87213. }
  87214. #else
  87215. # define withDup(x,y) 0
  87216. #endif
  87217. /*
  87218. ** The following group of routines make deep copies of expressions,
  87219. ** expression lists, ID lists, and select statements. The copies can
  87220. ** be deleted (by being passed to their respective ...Delete() routines)
  87221. ** without effecting the originals.
  87222. **
  87223. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  87224. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  87225. ** by subsequent calls to sqlite*ListAppend() routines.
  87226. **
  87227. ** Any tables that the SrcList might point to are not duplicated.
  87228. **
  87229. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  87230. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  87231. ** truncated version of the usual Expr structure that will be stored as
  87232. ** part of the in-memory representation of the database schema.
  87233. */
  87234. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  87235. assert( flags==0 || flags==EXPRDUP_REDUCE );
  87236. return p ? exprDup(db, p, flags, 0) : 0;
  87237. }
  87238. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  87239. ExprList *pNew;
  87240. struct ExprList_item *pItem, *pOldItem;
  87241. int i;
  87242. Expr *pPriorSelectCol = 0;
  87243. assert( db!=0 );
  87244. if( p==0 ) return 0;
  87245. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  87246. if( pNew==0 ) return 0;
  87247. pNew->nExpr = p->nExpr;
  87248. pItem = pNew->a;
  87249. pOldItem = p->a;
  87250. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  87251. Expr *pOldExpr = pOldItem->pExpr;
  87252. Expr *pNewExpr;
  87253. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  87254. if( pOldExpr
  87255. && pOldExpr->op==TK_SELECT_COLUMN
  87256. && (pNewExpr = pItem->pExpr)!=0
  87257. ){
  87258. assert( pNewExpr->iColumn==0 || i>0 );
  87259. if( pNewExpr->iColumn==0 ){
  87260. assert( pOldExpr->pLeft==pOldExpr->pRight );
  87261. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  87262. }else{
  87263. assert( i>0 );
  87264. assert( pItem[-1].pExpr!=0 );
  87265. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  87266. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  87267. pNewExpr->pLeft = pPriorSelectCol;
  87268. }
  87269. }
  87270. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  87271. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  87272. pItem->sortOrder = pOldItem->sortOrder;
  87273. pItem->done = 0;
  87274. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  87275. pItem->u = pOldItem->u;
  87276. }
  87277. return pNew;
  87278. }
  87279. /*
  87280. ** If cursors, triggers, views and subqueries are all omitted from
  87281. ** the build, then none of the following routines, except for
  87282. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  87283. ** called with a NULL argument.
  87284. */
  87285. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  87286. || !defined(SQLITE_OMIT_SUBQUERY)
  87287. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  87288. SrcList *pNew;
  87289. int i;
  87290. int nByte;
  87291. assert( db!=0 );
  87292. if( p==0 ) return 0;
  87293. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  87294. pNew = sqlite3DbMallocRawNN(db, nByte );
  87295. if( pNew==0 ) return 0;
  87296. pNew->nSrc = pNew->nAlloc = p->nSrc;
  87297. for(i=0; i<p->nSrc; i++){
  87298. struct SrcList_item *pNewItem = &pNew->a[i];
  87299. struct SrcList_item *pOldItem = &p->a[i];
  87300. Table *pTab;
  87301. pNewItem->pSchema = pOldItem->pSchema;
  87302. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  87303. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  87304. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  87305. pNewItem->fg = pOldItem->fg;
  87306. pNewItem->iCursor = pOldItem->iCursor;
  87307. pNewItem->addrFillSub = pOldItem->addrFillSub;
  87308. pNewItem->regReturn = pOldItem->regReturn;
  87309. if( pNewItem->fg.isIndexedBy ){
  87310. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  87311. }
  87312. pNewItem->pIBIndex = pOldItem->pIBIndex;
  87313. if( pNewItem->fg.isTabFunc ){
  87314. pNewItem->u1.pFuncArg =
  87315. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  87316. }
  87317. pTab = pNewItem->pTab = pOldItem->pTab;
  87318. if( pTab ){
  87319. pTab->nTabRef++;
  87320. }
  87321. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  87322. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  87323. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  87324. pNewItem->colUsed = pOldItem->colUsed;
  87325. }
  87326. return pNew;
  87327. }
  87328. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  87329. IdList *pNew;
  87330. int i;
  87331. assert( db!=0 );
  87332. if( p==0 ) return 0;
  87333. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  87334. if( pNew==0 ) return 0;
  87335. pNew->nId = p->nId;
  87336. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  87337. if( pNew->a==0 ){
  87338. sqlite3DbFreeNN(db, pNew);
  87339. return 0;
  87340. }
  87341. /* Note that because the size of the allocation for p->a[] is not
  87342. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  87343. ** on the duplicate created by this function. */
  87344. for(i=0; i<p->nId; i++){
  87345. struct IdList_item *pNewItem = &pNew->a[i];
  87346. struct IdList_item *pOldItem = &p->a[i];
  87347. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  87348. pNewItem->idx = pOldItem->idx;
  87349. }
  87350. return pNew;
  87351. }
  87352. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  87353. Select *pRet = 0;
  87354. Select *pNext = 0;
  87355. Select **pp = &pRet;
  87356. Select *p;
  87357. assert( db!=0 );
  87358. for(p=pDup; p; p=p->pPrior){
  87359. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  87360. if( pNew==0 ) break;
  87361. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  87362. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  87363. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  87364. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  87365. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  87366. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  87367. pNew->op = p->op;
  87368. pNew->pNext = pNext;
  87369. pNew->pPrior = 0;
  87370. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  87371. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  87372. pNew->iLimit = 0;
  87373. pNew->iOffset = 0;
  87374. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  87375. pNew->addrOpenEphm[0] = -1;
  87376. pNew->addrOpenEphm[1] = -1;
  87377. pNew->nSelectRow = p->nSelectRow;
  87378. pNew->pWith = withDup(db, p->pWith);
  87379. sqlite3SelectSetName(pNew, p->zSelName);
  87380. *pp = pNew;
  87381. pp = &pNew->pPrior;
  87382. pNext = pNew;
  87383. }
  87384. return pRet;
  87385. }
  87386. #else
  87387. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  87388. assert( p==0 );
  87389. return 0;
  87390. }
  87391. #endif
  87392. /*
  87393. ** Add a new element to the end of an expression list. If pList is
  87394. ** initially NULL, then create a new expression list.
  87395. **
  87396. ** The pList argument must be either NULL or a pointer to an ExprList
  87397. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  87398. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  87399. ** Reason: This routine assumes that the number of slots in pList->a[]
  87400. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  87401. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  87402. **
  87403. ** If a memory allocation error occurs, the entire list is freed and
  87404. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  87405. ** that the new entry was successfully appended.
  87406. */
  87407. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  87408. Parse *pParse, /* Parsing context */
  87409. ExprList *pList, /* List to which to append. Might be NULL */
  87410. Expr *pExpr /* Expression to be appended. Might be NULL */
  87411. ){
  87412. struct ExprList_item *pItem;
  87413. sqlite3 *db = pParse->db;
  87414. assert( db!=0 );
  87415. if( pList==0 ){
  87416. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  87417. if( pList==0 ){
  87418. goto no_mem;
  87419. }
  87420. pList->nExpr = 0;
  87421. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  87422. ExprList *pNew;
  87423. pNew = sqlite3DbRealloc(db, pList,
  87424. sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
  87425. if( pNew==0 ){
  87426. goto no_mem;
  87427. }
  87428. pList = pNew;
  87429. }
  87430. pItem = &pList->a[pList->nExpr++];
  87431. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  87432. assert( offsetof(struct ExprList_item,pExpr)==0 );
  87433. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  87434. pItem->pExpr = pExpr;
  87435. return pList;
  87436. no_mem:
  87437. /* Avoid leaking memory if malloc has failed. */
  87438. sqlite3ExprDelete(db, pExpr);
  87439. sqlite3ExprListDelete(db, pList);
  87440. return 0;
  87441. }
  87442. /*
  87443. ** pColumns and pExpr form a vector assignment which is part of the SET
  87444. ** clause of an UPDATE statement. Like this:
  87445. **
  87446. ** (a,b,c) = (expr1,expr2,expr3)
  87447. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  87448. **
  87449. ** For each term of the vector assignment, append new entries to the
  87450. ** expression list pList. In the case of a subquery on the RHS, append
  87451. ** TK_SELECT_COLUMN expressions.
  87452. */
  87453. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  87454. Parse *pParse, /* Parsing context */
  87455. ExprList *pList, /* List to which to append. Might be NULL */
  87456. IdList *pColumns, /* List of names of LHS of the assignment */
  87457. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  87458. ){
  87459. sqlite3 *db = pParse->db;
  87460. int n;
  87461. int i;
  87462. int iFirst = pList ? pList->nExpr : 0;
  87463. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  87464. ** exit prior to this routine being invoked */
  87465. if( NEVER(pColumns==0) ) goto vector_append_error;
  87466. if( pExpr==0 ) goto vector_append_error;
  87467. /* If the RHS is a vector, then we can immediately check to see that
  87468. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  87469. ** wildcards ("*") in the result set of the SELECT must be expanded before
  87470. ** we can do the size check, so defer the size check until code generation.
  87471. */
  87472. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  87473. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  87474. pColumns->nId, n);
  87475. goto vector_append_error;
  87476. }
  87477. for(i=0; i<pColumns->nId; i++){
  87478. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  87479. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  87480. if( pList ){
  87481. assert( pList->nExpr==iFirst+i+1 );
  87482. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  87483. pColumns->a[i].zName = 0;
  87484. }
  87485. }
  87486. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  87487. Expr *pFirst = pList->a[iFirst].pExpr;
  87488. assert( pFirst!=0 );
  87489. assert( pFirst->op==TK_SELECT_COLUMN );
  87490. /* Store the SELECT statement in pRight so it will be deleted when
  87491. ** sqlite3ExprListDelete() is called */
  87492. pFirst->pRight = pExpr;
  87493. pExpr = 0;
  87494. /* Remember the size of the LHS in iTable so that we can check that
  87495. ** the RHS and LHS sizes match during code generation. */
  87496. pFirst->iTable = pColumns->nId;
  87497. }
  87498. vector_append_error:
  87499. sqlite3ExprDelete(db, pExpr);
  87500. sqlite3IdListDelete(db, pColumns);
  87501. return pList;
  87502. }
  87503. /*
  87504. ** Set the sort order for the last element on the given ExprList.
  87505. */
  87506. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  87507. if( p==0 ) return;
  87508. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  87509. assert( p->nExpr>0 );
  87510. if( iSortOrder<0 ){
  87511. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  87512. return;
  87513. }
  87514. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  87515. }
  87516. /*
  87517. ** Set the ExprList.a[].zName element of the most recently added item
  87518. ** on the expression list.
  87519. **
  87520. ** pList might be NULL following an OOM error. But pName should never be
  87521. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  87522. ** is set.
  87523. */
  87524. SQLITE_PRIVATE void sqlite3ExprListSetName(
  87525. Parse *pParse, /* Parsing context */
  87526. ExprList *pList, /* List to which to add the span. */
  87527. Token *pName, /* Name to be added */
  87528. int dequote /* True to cause the name to be dequoted */
  87529. ){
  87530. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  87531. if( pList ){
  87532. struct ExprList_item *pItem;
  87533. assert( pList->nExpr>0 );
  87534. pItem = &pList->a[pList->nExpr-1];
  87535. assert( pItem->zName==0 );
  87536. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  87537. if( dequote ) sqlite3Dequote(pItem->zName);
  87538. }
  87539. }
  87540. /*
  87541. ** Set the ExprList.a[].zSpan element of the most recently added item
  87542. ** on the expression list.
  87543. **
  87544. ** pList might be NULL following an OOM error. But pSpan should never be
  87545. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  87546. ** is set.
  87547. */
  87548. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  87549. Parse *pParse, /* Parsing context */
  87550. ExprList *pList, /* List to which to add the span. */
  87551. ExprSpan *pSpan /* The span to be added */
  87552. ){
  87553. sqlite3 *db = pParse->db;
  87554. assert( pList!=0 || db->mallocFailed!=0 );
  87555. if( pList ){
  87556. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  87557. assert( pList->nExpr>0 );
  87558. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  87559. sqlite3DbFree(db, pItem->zSpan);
  87560. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  87561. (int)(pSpan->zEnd - pSpan->zStart));
  87562. }
  87563. }
  87564. /*
  87565. ** If the expression list pEList contains more than iLimit elements,
  87566. ** leave an error message in pParse.
  87567. */
  87568. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  87569. Parse *pParse,
  87570. ExprList *pEList,
  87571. const char *zObject
  87572. ){
  87573. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  87574. testcase( pEList && pEList->nExpr==mx );
  87575. testcase( pEList && pEList->nExpr==mx+1 );
  87576. if( pEList && pEList->nExpr>mx ){
  87577. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  87578. }
  87579. }
  87580. /*
  87581. ** Delete an entire expression list.
  87582. */
  87583. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  87584. int i = pList->nExpr;
  87585. struct ExprList_item *pItem = pList->a;
  87586. assert( pList->nExpr>0 );
  87587. do{
  87588. sqlite3ExprDelete(db, pItem->pExpr);
  87589. sqlite3DbFree(db, pItem->zName);
  87590. sqlite3DbFree(db, pItem->zSpan);
  87591. pItem++;
  87592. }while( --i>0 );
  87593. sqlite3DbFreeNN(db, pList);
  87594. }
  87595. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  87596. if( pList ) exprListDeleteNN(db, pList);
  87597. }
  87598. /*
  87599. ** Return the bitwise-OR of all Expr.flags fields in the given
  87600. ** ExprList.
  87601. */
  87602. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  87603. int i;
  87604. u32 m = 0;
  87605. assert( pList!=0 );
  87606. for(i=0; i<pList->nExpr; i++){
  87607. Expr *pExpr = pList->a[i].pExpr;
  87608. assert( pExpr!=0 );
  87609. m |= pExpr->flags;
  87610. }
  87611. return m;
  87612. }
  87613. /*
  87614. ** This is a SELECT-node callback for the expression walker that
  87615. ** always "fails". By "fail" in this case, we mean set
  87616. ** pWalker->eCode to zero and abort.
  87617. **
  87618. ** This callback is used by multiple expression walkers.
  87619. */
  87620. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  87621. UNUSED_PARAMETER(NotUsed);
  87622. pWalker->eCode = 0;
  87623. return WRC_Abort;
  87624. }
  87625. /*
  87626. ** These routines are Walker callbacks used to check expressions to
  87627. ** see if they are "constant" for some definition of constant. The
  87628. ** Walker.eCode value determines the type of "constant" we are looking
  87629. ** for.
  87630. **
  87631. ** These callback routines are used to implement the following:
  87632. **
  87633. ** sqlite3ExprIsConstant() pWalker->eCode==1
  87634. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  87635. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  87636. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  87637. **
  87638. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  87639. ** is found to not be a constant.
  87640. **
  87641. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  87642. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  87643. ** an existing schema and 4 when processing a new statement. A bound
  87644. ** parameter raises an error for new statements, but is silently converted
  87645. ** to NULL for existing schemas. This allows sqlite_master tables that
  87646. ** contain a bound parameter because they were generated by older versions
  87647. ** of SQLite to be parsed by newer versions of SQLite without raising a
  87648. ** malformed schema error.
  87649. */
  87650. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  87651. /* If pWalker->eCode is 2 then any term of the expression that comes from
  87652. ** the ON or USING clauses of a left join disqualifies the expression
  87653. ** from being considered constant. */
  87654. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  87655. pWalker->eCode = 0;
  87656. return WRC_Abort;
  87657. }
  87658. switch( pExpr->op ){
  87659. /* Consider functions to be constant if all their arguments are constant
  87660. ** and either pWalker->eCode==4 or 5 or the function has the
  87661. ** SQLITE_FUNC_CONST flag. */
  87662. case TK_FUNCTION:
  87663. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  87664. return WRC_Continue;
  87665. }else{
  87666. pWalker->eCode = 0;
  87667. return WRC_Abort;
  87668. }
  87669. case TK_ID:
  87670. case TK_COLUMN:
  87671. case TK_AGG_FUNCTION:
  87672. case TK_AGG_COLUMN:
  87673. testcase( pExpr->op==TK_ID );
  87674. testcase( pExpr->op==TK_COLUMN );
  87675. testcase( pExpr->op==TK_AGG_FUNCTION );
  87676. testcase( pExpr->op==TK_AGG_COLUMN );
  87677. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  87678. return WRC_Continue;
  87679. }
  87680. /* Fall through */
  87681. case TK_IF_NULL_ROW:
  87682. testcase( pExpr->op==TK_IF_NULL_ROW );
  87683. pWalker->eCode = 0;
  87684. return WRC_Abort;
  87685. case TK_VARIABLE:
  87686. if( pWalker->eCode==5 ){
  87687. /* Silently convert bound parameters that appear inside of CREATE
  87688. ** statements into a NULL when parsing the CREATE statement text out
  87689. ** of the sqlite_master table */
  87690. pExpr->op = TK_NULL;
  87691. }else if( pWalker->eCode==4 ){
  87692. /* A bound parameter in a CREATE statement that originates from
  87693. ** sqlite3_prepare() causes an error */
  87694. pWalker->eCode = 0;
  87695. return WRC_Abort;
  87696. }
  87697. /* Fall through */
  87698. default:
  87699. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */
  87700. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */
  87701. return WRC_Continue;
  87702. }
  87703. }
  87704. static int exprIsConst(Expr *p, int initFlag, int iCur){
  87705. Walker w;
  87706. w.eCode = initFlag;
  87707. w.xExprCallback = exprNodeIsConstant;
  87708. w.xSelectCallback = sqlite3SelectWalkFail;
  87709. #ifdef SQLITE_DEBUG
  87710. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  87711. #endif
  87712. w.u.iCur = iCur;
  87713. sqlite3WalkExpr(&w, p);
  87714. return w.eCode;
  87715. }
  87716. /*
  87717. ** Walk an expression tree. Return non-zero if the expression is constant
  87718. ** and 0 if it involves variables or function calls.
  87719. **
  87720. ** For the purposes of this function, a double-quoted string (ex: "abc")
  87721. ** is considered a variable but a single-quoted string (ex: 'abc') is
  87722. ** a constant.
  87723. */
  87724. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  87725. return exprIsConst(p, 1, 0);
  87726. }
  87727. /*
  87728. ** Walk an expression tree. Return non-zero if the expression is constant
  87729. ** that does no originate from the ON or USING clauses of a join.
  87730. ** Return 0 if it involves variables or function calls or terms from
  87731. ** an ON or USING clause.
  87732. */
  87733. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  87734. return exprIsConst(p, 2, 0);
  87735. }
  87736. /*
  87737. ** Walk an expression tree. Return non-zero if the expression is constant
  87738. ** for any single row of the table with cursor iCur. In other words, the
  87739. ** expression must not refer to any non-deterministic function nor any
  87740. ** table other than iCur.
  87741. */
  87742. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  87743. return exprIsConst(p, 3, iCur);
  87744. }
  87745. /*
  87746. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  87747. */
  87748. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  87749. ExprList *pGroupBy = pWalker->u.pGroupBy;
  87750. int i;
  87751. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  87752. ** it constant. */
  87753. for(i=0; i<pGroupBy->nExpr; i++){
  87754. Expr *p = pGroupBy->a[i].pExpr;
  87755. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  87756. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  87757. if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
  87758. return WRC_Prune;
  87759. }
  87760. }
  87761. }
  87762. /* Check if pExpr is a sub-select. If so, consider it variable. */
  87763. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87764. pWalker->eCode = 0;
  87765. return WRC_Abort;
  87766. }
  87767. return exprNodeIsConstant(pWalker, pExpr);
  87768. }
  87769. /*
  87770. ** Walk the expression tree passed as the first argument. Return non-zero
  87771. ** if the expression consists entirely of constants or copies of terms
  87772. ** in pGroupBy that sort with the BINARY collation sequence.
  87773. **
  87774. ** This routine is used to determine if a term of the HAVING clause can
  87775. ** be promoted into the WHERE clause. In order for such a promotion to work,
  87776. ** the value of the HAVING clause term must be the same for all members of
  87777. ** a "group". The requirement that the GROUP BY term must be BINARY
  87778. ** assumes that no other collating sequence will have a finer-grained
  87779. ** grouping than binary. In other words (A=B COLLATE binary) implies
  87780. ** A=B in every other collating sequence. The requirement that the
  87781. ** GROUP BY be BINARY is stricter than necessary. It would also work
  87782. ** to promote HAVING clauses that use the same alternative collating
  87783. ** sequence as the GROUP BY term, but that is much harder to check,
  87784. ** alternative collating sequences are uncommon, and this is only an
  87785. ** optimization, so we take the easy way out and simply require the
  87786. ** GROUP BY to use the BINARY collating sequence.
  87787. */
  87788. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  87789. Walker w;
  87790. w.eCode = 1;
  87791. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  87792. w.xSelectCallback = 0;
  87793. w.u.pGroupBy = pGroupBy;
  87794. w.pParse = pParse;
  87795. sqlite3WalkExpr(&w, p);
  87796. return w.eCode;
  87797. }
  87798. /*
  87799. ** Walk an expression tree. Return non-zero if the expression is constant
  87800. ** or a function call with constant arguments. Return and 0 if there
  87801. ** are any variables.
  87802. **
  87803. ** For the purposes of this function, a double-quoted string (ex: "abc")
  87804. ** is considered a variable but a single-quoted string (ex: 'abc') is
  87805. ** a constant.
  87806. */
  87807. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  87808. assert( isInit==0 || isInit==1 );
  87809. return exprIsConst(p, 4+isInit, 0);
  87810. }
  87811. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  87812. /*
  87813. ** Walk an expression tree. Return 1 if the expression contains a
  87814. ** subquery of some kind. Return 0 if there are no subqueries.
  87815. */
  87816. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  87817. Walker w;
  87818. w.eCode = 1;
  87819. w.xExprCallback = sqlite3ExprWalkNoop;
  87820. w.xSelectCallback = sqlite3SelectWalkFail;
  87821. #ifdef SQLITE_DEBUG
  87822. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  87823. #endif
  87824. sqlite3WalkExpr(&w, p);
  87825. return w.eCode==0;
  87826. }
  87827. #endif
  87828. /*
  87829. ** If the expression p codes a constant integer that is small enough
  87830. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  87831. ** in *pValue. If the expression is not an integer or if it is too big
  87832. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  87833. */
  87834. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  87835. int rc = 0;
  87836. if( p==0 ) return 0; /* Can only happen following on OOM */
  87837. /* If an expression is an integer literal that fits in a signed 32-bit
  87838. ** integer, then the EP_IntValue flag will have already been set */
  87839. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  87840. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  87841. if( p->flags & EP_IntValue ){
  87842. *pValue = p->u.iValue;
  87843. return 1;
  87844. }
  87845. switch( p->op ){
  87846. case TK_UPLUS: {
  87847. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  87848. break;
  87849. }
  87850. case TK_UMINUS: {
  87851. int v;
  87852. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  87853. assert( v!=(-2147483647-1) );
  87854. *pValue = -v;
  87855. rc = 1;
  87856. }
  87857. break;
  87858. }
  87859. default: break;
  87860. }
  87861. return rc;
  87862. }
  87863. /*
  87864. ** Return FALSE if there is no chance that the expression can be NULL.
  87865. **
  87866. ** If the expression might be NULL or if the expression is too complex
  87867. ** to tell return TRUE.
  87868. **
  87869. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  87870. ** when we know that a value cannot be NULL. Hence, a false positive
  87871. ** (returning TRUE when in fact the expression can never be NULL) might
  87872. ** be a small performance hit but is otherwise harmless. On the other
  87873. ** hand, a false negative (returning FALSE when the result could be NULL)
  87874. ** will likely result in an incorrect answer. So when in doubt, return
  87875. ** TRUE.
  87876. */
  87877. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  87878. u8 op;
  87879. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  87880. op = p->op;
  87881. if( op==TK_REGISTER ) op = p->op2;
  87882. switch( op ){
  87883. case TK_INTEGER:
  87884. case TK_STRING:
  87885. case TK_FLOAT:
  87886. case TK_BLOB:
  87887. return 0;
  87888. case TK_COLUMN:
  87889. return ExprHasProperty(p, EP_CanBeNull) ||
  87890. p->pTab==0 || /* Reference to column of index on expression */
  87891. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  87892. default:
  87893. return 1;
  87894. }
  87895. }
  87896. /*
  87897. ** Return TRUE if the given expression is a constant which would be
  87898. ** unchanged by OP_Affinity with the affinity given in the second
  87899. ** argument.
  87900. **
  87901. ** This routine is used to determine if the OP_Affinity operation
  87902. ** can be omitted. When in doubt return FALSE. A false negative
  87903. ** is harmless. A false positive, however, can result in the wrong
  87904. ** answer.
  87905. */
  87906. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  87907. u8 op;
  87908. if( aff==SQLITE_AFF_BLOB ) return 1;
  87909. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  87910. op = p->op;
  87911. if( op==TK_REGISTER ) op = p->op2;
  87912. switch( op ){
  87913. case TK_INTEGER: {
  87914. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  87915. }
  87916. case TK_FLOAT: {
  87917. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  87918. }
  87919. case TK_STRING: {
  87920. return aff==SQLITE_AFF_TEXT;
  87921. }
  87922. case TK_BLOB: {
  87923. return 1;
  87924. }
  87925. case TK_COLUMN: {
  87926. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  87927. return p->iColumn<0
  87928. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  87929. }
  87930. default: {
  87931. return 0;
  87932. }
  87933. }
  87934. }
  87935. /*
  87936. ** Return TRUE if the given string is a row-id column name.
  87937. */
  87938. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  87939. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  87940. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  87941. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  87942. return 0;
  87943. }
  87944. /*
  87945. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  87946. ** that can be simplified to a direct table access, then return
  87947. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  87948. ** or if the SELECT statement needs to be manifested into a transient
  87949. ** table, then return NULL.
  87950. */
  87951. #ifndef SQLITE_OMIT_SUBQUERY
  87952. static Select *isCandidateForInOpt(Expr *pX){
  87953. Select *p;
  87954. SrcList *pSrc;
  87955. ExprList *pEList;
  87956. Table *pTab;
  87957. int i;
  87958. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  87959. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  87960. p = pX->x.pSelect;
  87961. if( p->pPrior ) return 0; /* Not a compound SELECT */
  87962. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  87963. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  87964. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  87965. return 0; /* No DISTINCT keyword and no aggregate functions */
  87966. }
  87967. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  87968. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  87969. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  87970. if( p->pWhere ) return 0; /* Has no WHERE clause */
  87971. pSrc = p->pSrc;
  87972. assert( pSrc!=0 );
  87973. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  87974. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  87975. pTab = pSrc->a[0].pTab;
  87976. assert( pTab!=0 );
  87977. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  87978. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  87979. pEList = p->pEList;
  87980. assert( pEList!=0 );
  87981. /* All SELECT results must be columns. */
  87982. for(i=0; i<pEList->nExpr; i++){
  87983. Expr *pRes = pEList->a[i].pExpr;
  87984. if( pRes->op!=TK_COLUMN ) return 0;
  87985. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  87986. }
  87987. return p;
  87988. }
  87989. #endif /* SQLITE_OMIT_SUBQUERY */
  87990. #ifndef SQLITE_OMIT_SUBQUERY
  87991. /*
  87992. ** Generate code that checks the left-most column of index table iCur to see if
  87993. ** it contains any NULL entries. Cause the register at regHasNull to be set
  87994. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  87995. ** to be set to NULL if iCur contains one or more NULL values.
  87996. */
  87997. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  87998. int addr1;
  87999. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  88000. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  88001. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  88002. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  88003. VdbeComment((v, "first_entry_in(%d)", iCur));
  88004. sqlite3VdbeJumpHere(v, addr1);
  88005. }
  88006. #endif
  88007. #ifndef SQLITE_OMIT_SUBQUERY
  88008. /*
  88009. ** The argument is an IN operator with a list (not a subquery) on the
  88010. ** right-hand side. Return TRUE if that list is constant.
  88011. */
  88012. static int sqlite3InRhsIsConstant(Expr *pIn){
  88013. Expr *pLHS;
  88014. int res;
  88015. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  88016. pLHS = pIn->pLeft;
  88017. pIn->pLeft = 0;
  88018. res = sqlite3ExprIsConstant(pIn);
  88019. pIn->pLeft = pLHS;
  88020. return res;
  88021. }
  88022. #endif
  88023. /*
  88024. ** This function is used by the implementation of the IN (...) operator.
  88025. ** The pX parameter is the expression on the RHS of the IN operator, which
  88026. ** might be either a list of expressions or a subquery.
  88027. **
  88028. ** The job of this routine is to find or create a b-tree object that can
  88029. ** be used either to test for membership in the RHS set or to iterate through
  88030. ** all members of the RHS set, skipping duplicates.
  88031. **
  88032. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  88033. ** and pX->iTable is set to the index of that cursor.
  88034. **
  88035. ** The returned value of this function indicates the b-tree type, as follows:
  88036. **
  88037. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  88038. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  88039. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  88040. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  88041. ** populated epheremal table.
  88042. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  88043. ** implemented as a sequence of comparisons.
  88044. **
  88045. ** An existing b-tree might be used if the RHS expression pX is a simple
  88046. ** subquery such as:
  88047. **
  88048. ** SELECT <column1>, <column2>... FROM <table>
  88049. **
  88050. ** If the RHS of the IN operator is a list or a more complex subquery, then
  88051. ** an ephemeral table might need to be generated from the RHS and then
  88052. ** pX->iTable made to point to the ephemeral table instead of an
  88053. ** existing table.
  88054. **
  88055. ** The inFlags parameter must contain exactly one of the bits
  88056. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  88057. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  88058. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  88059. ** IN index will be used to loop over all values of the RHS of the
  88060. ** IN operator.
  88061. **
  88062. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  88063. ** through the set members) then the b-tree must not contain duplicates.
  88064. ** An epheremal table must be used unless the selected columns are guaranteed
  88065. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  88066. ** a UNIQUE constraint or index.
  88067. **
  88068. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  88069. ** for fast set membership tests) then an epheremal table must
  88070. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  88071. ** index can be found with the specified <columns> as its left-most.
  88072. **
  88073. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  88074. ** if the RHS of the IN operator is a list (not a subquery) then this
  88075. ** routine might decide that creating an ephemeral b-tree for membership
  88076. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  88077. ** calling routine should implement the IN operator using a sequence
  88078. ** of Eq or Ne comparison operations.
  88079. **
  88080. ** When the b-tree is being used for membership tests, the calling function
  88081. ** might need to know whether or not the RHS side of the IN operator
  88082. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  88083. ** if there is any chance that the (...) might contain a NULL value at
  88084. ** runtime, then a register is allocated and the register number written
  88085. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  88086. ** NULL value, then *prRhsHasNull is left unchanged.
  88087. **
  88088. ** If a register is allocated and its location stored in *prRhsHasNull, then
  88089. ** the value in that register will be NULL if the b-tree contains one or more
  88090. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  88091. ** NULL values.
  88092. **
  88093. ** If the aiMap parameter is not NULL, it must point to an array containing
  88094. ** one element for each column returned by the SELECT statement on the RHS
  88095. ** of the IN(...) operator. The i'th entry of the array is populated with the
  88096. ** offset of the index column that matches the i'th column returned by the
  88097. ** SELECT. For example, if the expression and selected index are:
  88098. **
  88099. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  88100. ** CREATE INDEX i1 ON t1(b, c, a);
  88101. **
  88102. ** then aiMap[] is populated with {2, 0, 1}.
  88103. */
  88104. #ifndef SQLITE_OMIT_SUBQUERY
  88105. SQLITE_PRIVATE int sqlite3FindInIndex(
  88106. Parse *pParse, /* Parsing context */
  88107. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  88108. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  88109. int *prRhsHasNull, /* Register holding NULL status. See notes */
  88110. int *aiMap /* Mapping from Index fields to RHS fields */
  88111. ){
  88112. Select *p; /* SELECT to the right of IN operator */
  88113. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  88114. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  88115. int mustBeUnique; /* True if RHS must be unique */
  88116. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  88117. assert( pX->op==TK_IN );
  88118. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  88119. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  88120. ** whether or not the SELECT result contains NULL values, check whether
  88121. ** or not NULL is actually possible (it may not be, for example, due
  88122. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  88123. ** set prRhsHasNull to 0 before continuing. */
  88124. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  88125. int i;
  88126. ExprList *pEList = pX->x.pSelect->pEList;
  88127. for(i=0; i<pEList->nExpr; i++){
  88128. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  88129. }
  88130. if( i==pEList->nExpr ){
  88131. prRhsHasNull = 0;
  88132. }
  88133. }
  88134. /* Check to see if an existing table or index can be used to
  88135. ** satisfy the query. This is preferable to generating a new
  88136. ** ephemeral table. */
  88137. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  88138. sqlite3 *db = pParse->db; /* Database connection */
  88139. Table *pTab; /* Table <table>. */
  88140. i16 iDb; /* Database idx for pTab */
  88141. ExprList *pEList = p->pEList;
  88142. int nExpr = pEList->nExpr;
  88143. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  88144. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  88145. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  88146. pTab = p->pSrc->a[0].pTab;
  88147. /* Code an OP_Transaction and OP_TableLock for <table>. */
  88148. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88149. sqlite3CodeVerifySchema(pParse, iDb);
  88150. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  88151. assert(v); /* sqlite3GetVdbe() has always been previously called */
  88152. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  88153. /* The "x IN (SELECT rowid FROM table)" case */
  88154. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  88155. VdbeCoverage(v);
  88156. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  88157. eType = IN_INDEX_ROWID;
  88158. sqlite3VdbeJumpHere(v, iAddr);
  88159. }else{
  88160. Index *pIdx; /* Iterator variable */
  88161. int affinity_ok = 1;
  88162. int i;
  88163. /* Check that the affinity that will be used to perform each
  88164. ** comparison is the same as the affinity of each column in table
  88165. ** on the RHS of the IN operator. If it not, it is not possible to
  88166. ** use any index of the RHS table. */
  88167. for(i=0; i<nExpr && affinity_ok; i++){
  88168. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  88169. int iCol = pEList->a[i].pExpr->iColumn;
  88170. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  88171. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  88172. testcase( cmpaff==SQLITE_AFF_BLOB );
  88173. testcase( cmpaff==SQLITE_AFF_TEXT );
  88174. switch( cmpaff ){
  88175. case SQLITE_AFF_BLOB:
  88176. break;
  88177. case SQLITE_AFF_TEXT:
  88178. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  88179. ** other has no affinity and the other side is TEXT. Hence,
  88180. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  88181. ** and for the term on the LHS of the IN to have no affinity. */
  88182. assert( idxaff==SQLITE_AFF_TEXT );
  88183. break;
  88184. default:
  88185. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  88186. }
  88187. }
  88188. if( affinity_ok ){
  88189. /* Search for an existing index that will work for this IN operator */
  88190. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  88191. Bitmask colUsed; /* Columns of the index used */
  88192. Bitmask mCol; /* Mask for the current column */
  88193. if( pIdx->nColumn<nExpr ) continue;
  88194. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  88195. ** BITMASK(nExpr) without overflowing */
  88196. testcase( pIdx->nColumn==BMS-2 );
  88197. testcase( pIdx->nColumn==BMS-1 );
  88198. if( pIdx->nColumn>=BMS-1 ) continue;
  88199. if( mustBeUnique ){
  88200. if( pIdx->nKeyCol>nExpr
  88201. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  88202. ){
  88203. continue; /* This index is not unique over the IN RHS columns */
  88204. }
  88205. }
  88206. colUsed = 0; /* Columns of index used so far */
  88207. for(i=0; i<nExpr; i++){
  88208. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  88209. Expr *pRhs = pEList->a[i].pExpr;
  88210. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  88211. int j;
  88212. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  88213. for(j=0; j<nExpr; j++){
  88214. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  88215. assert( pIdx->azColl[j] );
  88216. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  88217. continue;
  88218. }
  88219. break;
  88220. }
  88221. if( j==nExpr ) break;
  88222. mCol = MASKBIT(j);
  88223. if( mCol & colUsed ) break; /* Each column used only once */
  88224. colUsed |= mCol;
  88225. if( aiMap ) aiMap[i] = j;
  88226. }
  88227. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  88228. if( colUsed==(MASKBIT(nExpr)-1) ){
  88229. /* If we reach this point, that means the index pIdx is usable */
  88230. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  88231. #ifndef SQLITE_OMIT_EXPLAIN
  88232. sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
  88233. sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
  88234. P4_DYNAMIC);
  88235. #endif
  88236. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  88237. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  88238. VdbeComment((v, "%s", pIdx->zName));
  88239. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  88240. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  88241. if( prRhsHasNull ){
  88242. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  88243. i64 mask = (1<<nExpr)-1;
  88244. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  88245. iTab, 0, 0, (u8*)&mask, P4_INT64);
  88246. #endif
  88247. *prRhsHasNull = ++pParse->nMem;
  88248. if( nExpr==1 ){
  88249. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  88250. }
  88251. }
  88252. sqlite3VdbeJumpHere(v, iAddr);
  88253. }
  88254. } /* End loop over indexes */
  88255. } /* End if( affinity_ok ) */
  88256. } /* End if not an rowid index */
  88257. } /* End attempt to optimize using an index */
  88258. /* If no preexisting index is available for the IN clause
  88259. ** and IN_INDEX_NOOP is an allowed reply
  88260. ** and the RHS of the IN operator is a list, not a subquery
  88261. ** and the RHS is not constant or has two or fewer terms,
  88262. ** then it is not worth creating an ephemeral table to evaluate
  88263. ** the IN operator so return IN_INDEX_NOOP.
  88264. */
  88265. if( eType==0
  88266. && (inFlags & IN_INDEX_NOOP_OK)
  88267. && !ExprHasProperty(pX, EP_xIsSelect)
  88268. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  88269. ){
  88270. eType = IN_INDEX_NOOP;
  88271. }
  88272. if( eType==0 ){
  88273. /* Could not find an existing table or index to use as the RHS b-tree.
  88274. ** We will have to generate an ephemeral table to do the job.
  88275. */
  88276. u32 savedNQueryLoop = pParse->nQueryLoop;
  88277. int rMayHaveNull = 0;
  88278. eType = IN_INDEX_EPH;
  88279. if( inFlags & IN_INDEX_LOOP ){
  88280. pParse->nQueryLoop = 0;
  88281. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  88282. eType = IN_INDEX_ROWID;
  88283. }
  88284. }else if( prRhsHasNull ){
  88285. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  88286. }
  88287. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  88288. pParse->nQueryLoop = savedNQueryLoop;
  88289. }else{
  88290. pX->iTable = iTab;
  88291. }
  88292. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  88293. int i, n;
  88294. n = sqlite3ExprVectorSize(pX->pLeft);
  88295. for(i=0; i<n; i++) aiMap[i] = i;
  88296. }
  88297. return eType;
  88298. }
  88299. #endif
  88300. #ifndef SQLITE_OMIT_SUBQUERY
  88301. /*
  88302. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  88303. ** function allocates and returns a nul-terminated string containing
  88304. ** the affinities to be used for each column of the comparison.
  88305. **
  88306. ** It is the responsibility of the caller to ensure that the returned
  88307. ** string is eventually freed using sqlite3DbFree().
  88308. */
  88309. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  88310. Expr *pLeft = pExpr->pLeft;
  88311. int nVal = sqlite3ExprVectorSize(pLeft);
  88312. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  88313. char *zRet;
  88314. assert( pExpr->op==TK_IN );
  88315. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  88316. if( zRet ){
  88317. int i;
  88318. for(i=0; i<nVal; i++){
  88319. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  88320. char a = sqlite3ExprAffinity(pA);
  88321. if( pSelect ){
  88322. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  88323. }else{
  88324. zRet[i] = a;
  88325. }
  88326. }
  88327. zRet[nVal] = '\0';
  88328. }
  88329. return zRet;
  88330. }
  88331. #endif
  88332. #ifndef SQLITE_OMIT_SUBQUERY
  88333. /*
  88334. ** Load the Parse object passed as the first argument with an error
  88335. ** message of the form:
  88336. **
  88337. ** "sub-select returns N columns - expected M"
  88338. */
  88339. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  88340. const char *zFmt = "sub-select returns %d columns - expected %d";
  88341. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  88342. }
  88343. #endif
  88344. /*
  88345. ** Expression pExpr is a vector that has been used in a context where
  88346. ** it is not permitted. If pExpr is a sub-select vector, this routine
  88347. ** loads the Parse object with a message of the form:
  88348. **
  88349. ** "sub-select returns N columns - expected 1"
  88350. **
  88351. ** Or, if it is a regular scalar vector:
  88352. **
  88353. ** "row value misused"
  88354. */
  88355. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  88356. #ifndef SQLITE_OMIT_SUBQUERY
  88357. if( pExpr->flags & EP_xIsSelect ){
  88358. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  88359. }else
  88360. #endif
  88361. {
  88362. sqlite3ErrorMsg(pParse, "row value misused");
  88363. }
  88364. }
  88365. /*
  88366. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  88367. ** or IN operators. Examples:
  88368. **
  88369. ** (SELECT a FROM b) -- subquery
  88370. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  88371. ** x IN (4,5,11) -- IN operator with list on right-hand side
  88372. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  88373. **
  88374. ** The pExpr parameter describes the expression that contains the IN
  88375. ** operator or subquery.
  88376. **
  88377. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  88378. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  88379. ** to some integer key column of a table B-Tree. In this case, use an
  88380. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  88381. ** (slower) variable length keys B-Tree.
  88382. **
  88383. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  88384. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  88385. ** All this routine does is initialize the register given by rMayHaveNull
  88386. ** to NULL. Calling routines will take care of changing this register
  88387. ** value to non-NULL if the RHS is NULL-free.
  88388. **
  88389. ** For a SELECT or EXISTS operator, return the register that holds the
  88390. ** result. For a multi-column SELECT, the result is stored in a contiguous
  88391. ** array of registers and the return value is the register of the left-most
  88392. ** result column. Return 0 for IN operators or if an error occurs.
  88393. */
  88394. #ifndef SQLITE_OMIT_SUBQUERY
  88395. SQLITE_PRIVATE int sqlite3CodeSubselect(
  88396. Parse *pParse, /* Parsing context */
  88397. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  88398. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  88399. int isRowid /* If true, LHS of IN operator is a rowid */
  88400. ){
  88401. int jmpIfDynamic = -1; /* One-time test address */
  88402. int rReg = 0; /* Register storing resulting */
  88403. Vdbe *v = sqlite3GetVdbe(pParse);
  88404. if( NEVER(v==0) ) return 0;
  88405. sqlite3ExprCachePush(pParse);
  88406. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  88407. ** is encountered if any of the following is true:
  88408. **
  88409. ** * The right-hand side is a correlated subquery
  88410. ** * The right-hand side is an expression list containing variables
  88411. ** * We are inside a trigger
  88412. **
  88413. ** If all of the above are false, then we can run this code just once
  88414. ** save the results, and reuse the same result on subsequent invocations.
  88415. */
  88416. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  88417. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  88418. }
  88419. #ifndef SQLITE_OMIT_EXPLAIN
  88420. if( pParse->explain==2 ){
  88421. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  88422. jmpIfDynamic>=0?"":"CORRELATED ",
  88423. pExpr->op==TK_IN?"LIST":"SCALAR",
  88424. pParse->iNextSelectId
  88425. );
  88426. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  88427. }
  88428. #endif
  88429. switch( pExpr->op ){
  88430. case TK_IN: {
  88431. int addr; /* Address of OP_OpenEphemeral instruction */
  88432. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  88433. KeyInfo *pKeyInfo = 0; /* Key information */
  88434. int nVal; /* Size of vector pLeft */
  88435. nVal = sqlite3ExprVectorSize(pLeft);
  88436. assert( !isRowid || nVal==1 );
  88437. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  88438. ** expression it is handled the same way. An ephemeral table is
  88439. ** filled with index keys representing the results from the
  88440. ** SELECT or the <exprlist>.
  88441. **
  88442. ** If the 'x' expression is a column value, or the SELECT...
  88443. ** statement returns a column value, then the affinity of that
  88444. ** column is used to build the index keys. If both 'x' and the
  88445. ** SELECT... statement are columns, then numeric affinity is used
  88446. ** if either column has NUMERIC or INTEGER affinity. If neither
  88447. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  88448. ** is used.
  88449. */
  88450. pExpr->iTable = pParse->nTab++;
  88451. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  88452. pExpr->iTable, (isRowid?0:nVal));
  88453. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  88454. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  88455. /* Case 1: expr IN (SELECT ...)
  88456. **
  88457. ** Generate code to write the results of the select into the temporary
  88458. ** table allocated and opened above.
  88459. */
  88460. Select *pSelect = pExpr->x.pSelect;
  88461. ExprList *pEList = pSelect->pEList;
  88462. assert( !isRowid );
  88463. /* If the LHS and RHS of the IN operator do not match, that
  88464. ** error will have been caught long before we reach this point. */
  88465. if( ALWAYS(pEList->nExpr==nVal) ){
  88466. SelectDest dest;
  88467. int i;
  88468. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  88469. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  88470. pSelect->iLimit = 0;
  88471. testcase( pSelect->selFlags & SF_Distinct );
  88472. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  88473. if( sqlite3Select(pParse, pSelect, &dest) ){
  88474. sqlite3DbFree(pParse->db, dest.zAffSdst);
  88475. sqlite3KeyInfoUnref(pKeyInfo);
  88476. return 0;
  88477. }
  88478. sqlite3DbFree(pParse->db, dest.zAffSdst);
  88479. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  88480. assert( pEList!=0 );
  88481. assert( pEList->nExpr>0 );
  88482. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  88483. for(i=0; i<nVal; i++){
  88484. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  88485. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  88486. pParse, p, pEList->a[i].pExpr
  88487. );
  88488. }
  88489. }
  88490. }else if( ALWAYS(pExpr->x.pList!=0) ){
  88491. /* Case 2: expr IN (exprlist)
  88492. **
  88493. ** For each expression, build an index key from the evaluation and
  88494. ** store it in the temporary table. If <expr> is a column, then use
  88495. ** that columns affinity when building index keys. If <expr> is not
  88496. ** a column, use numeric affinity.
  88497. */
  88498. char affinity; /* Affinity of the LHS of the IN */
  88499. int i;
  88500. ExprList *pList = pExpr->x.pList;
  88501. struct ExprList_item *pItem;
  88502. int r1, r2, r3;
  88503. affinity = sqlite3ExprAffinity(pLeft);
  88504. if( !affinity ){
  88505. affinity = SQLITE_AFF_BLOB;
  88506. }
  88507. if( pKeyInfo ){
  88508. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  88509. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  88510. }
  88511. /* Loop through each expression in <exprlist>. */
  88512. r1 = sqlite3GetTempReg(pParse);
  88513. r2 = sqlite3GetTempReg(pParse);
  88514. if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
  88515. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  88516. Expr *pE2 = pItem->pExpr;
  88517. int iValToIns;
  88518. /* If the expression is not constant then we will need to
  88519. ** disable the test that was generated above that makes sure
  88520. ** this code only executes once. Because for a non-constant
  88521. ** expression we need to rerun this code each time.
  88522. */
  88523. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  88524. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  88525. jmpIfDynamic = -1;
  88526. }
  88527. /* Evaluate the expression and insert it into the temp table */
  88528. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  88529. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  88530. }else{
  88531. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  88532. if( isRowid ){
  88533. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  88534. sqlite3VdbeCurrentAddr(v)+2);
  88535. VdbeCoverage(v);
  88536. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  88537. }else{
  88538. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  88539. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  88540. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  88541. }
  88542. }
  88543. }
  88544. sqlite3ReleaseTempReg(pParse, r1);
  88545. sqlite3ReleaseTempReg(pParse, r2);
  88546. }
  88547. if( pKeyInfo ){
  88548. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  88549. }
  88550. break;
  88551. }
  88552. case TK_EXISTS:
  88553. case TK_SELECT:
  88554. default: {
  88555. /* Case 3: (SELECT ... FROM ...)
  88556. ** or: EXISTS(SELECT ... FROM ...)
  88557. **
  88558. ** For a SELECT, generate code to put the values for all columns of
  88559. ** the first row into an array of registers and return the index of
  88560. ** the first register.
  88561. **
  88562. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  88563. ** into a register and return that register number.
  88564. **
  88565. ** In both cases, the query is augmented with "LIMIT 1". Any
  88566. ** preexisting limit is discarded in place of the new LIMIT 1.
  88567. */
  88568. Select *pSel; /* SELECT statement to encode */
  88569. SelectDest dest; /* How to deal with SELECT result */
  88570. int nReg; /* Registers to allocate */
  88571. testcase( pExpr->op==TK_EXISTS );
  88572. testcase( pExpr->op==TK_SELECT );
  88573. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  88574. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  88575. pSel = pExpr->x.pSelect;
  88576. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  88577. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  88578. pParse->nMem += nReg;
  88579. if( pExpr->op==TK_SELECT ){
  88580. dest.eDest = SRT_Mem;
  88581. dest.iSdst = dest.iSDParm;
  88582. dest.nSdst = nReg;
  88583. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  88584. VdbeComment((v, "Init subquery result"));
  88585. }else{
  88586. dest.eDest = SRT_Exists;
  88587. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  88588. VdbeComment((v, "Init EXISTS result"));
  88589. }
  88590. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  88591. pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
  88592. &sqlite3IntTokens[1], 0);
  88593. pSel->iLimit = 0;
  88594. pSel->selFlags &= ~SF_MultiValue;
  88595. if( sqlite3Select(pParse, pSel, &dest) ){
  88596. return 0;
  88597. }
  88598. rReg = dest.iSDParm;
  88599. ExprSetVVAProperty(pExpr, EP_NoReduce);
  88600. break;
  88601. }
  88602. }
  88603. if( rHasNullFlag ){
  88604. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  88605. }
  88606. if( jmpIfDynamic>=0 ){
  88607. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  88608. }
  88609. sqlite3ExprCachePop(pParse);
  88610. return rReg;
  88611. }
  88612. #endif /* SQLITE_OMIT_SUBQUERY */
  88613. #ifndef SQLITE_OMIT_SUBQUERY
  88614. /*
  88615. ** Expr pIn is an IN(...) expression. This function checks that the
  88616. ** sub-select on the RHS of the IN() operator has the same number of
  88617. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  88618. ** a sub-query, that the LHS is a vector of size 1.
  88619. */
  88620. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  88621. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  88622. if( (pIn->flags & EP_xIsSelect) ){
  88623. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  88624. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  88625. return 1;
  88626. }
  88627. }else if( nVector!=1 ){
  88628. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  88629. return 1;
  88630. }
  88631. return 0;
  88632. }
  88633. #endif
  88634. #ifndef SQLITE_OMIT_SUBQUERY
  88635. /*
  88636. ** Generate code for an IN expression.
  88637. **
  88638. ** x IN (SELECT ...)
  88639. ** x IN (value, value, ...)
  88640. **
  88641. ** The left-hand side (LHS) is a scalar or vector expression. The
  88642. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  88643. ** subquery. If the RHS is a subquery, the number of result columns must
  88644. ** match the number of columns in the vector on the LHS. If the RHS is
  88645. ** a list of values, the LHS must be a scalar.
  88646. **
  88647. ** The IN operator is true if the LHS value is contained within the RHS.
  88648. ** The result is false if the LHS is definitely not in the RHS. The
  88649. ** result is NULL if the presence of the LHS in the RHS cannot be
  88650. ** determined due to NULLs.
  88651. **
  88652. ** This routine generates code that jumps to destIfFalse if the LHS is not
  88653. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  88654. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  88655. ** within the RHS then fall through.
  88656. **
  88657. ** See the separate in-operator.md documentation file in the canonical
  88658. ** SQLite source tree for additional information.
  88659. */
  88660. static void sqlite3ExprCodeIN(
  88661. Parse *pParse, /* Parsing and code generating context */
  88662. Expr *pExpr, /* The IN expression */
  88663. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  88664. int destIfNull /* Jump here if the results are unknown due to NULLs */
  88665. ){
  88666. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  88667. int eType; /* Type of the RHS */
  88668. int rLhs; /* Register(s) holding the LHS values */
  88669. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  88670. Vdbe *v; /* Statement under construction */
  88671. int *aiMap = 0; /* Map from vector field to index column */
  88672. char *zAff = 0; /* Affinity string for comparisons */
  88673. int nVector; /* Size of vectors for this IN operator */
  88674. int iDummy; /* Dummy parameter to exprCodeVector() */
  88675. Expr *pLeft; /* The LHS of the IN operator */
  88676. int i; /* loop counter */
  88677. int destStep2; /* Where to jump when NULLs seen in step 2 */
  88678. int destStep6 = 0; /* Start of code for Step 6 */
  88679. int addrTruthOp; /* Address of opcode that determines the IN is true */
  88680. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  88681. int addrTop; /* Top of the step-6 loop */
  88682. pLeft = pExpr->pLeft;
  88683. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  88684. zAff = exprINAffinity(pParse, pExpr);
  88685. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  88686. aiMap = (int*)sqlite3DbMallocZero(
  88687. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  88688. );
  88689. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  88690. /* Attempt to compute the RHS. After this step, if anything other than
  88691. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  88692. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  88693. ** the RHS has not yet been coded. */
  88694. v = pParse->pVdbe;
  88695. assert( v!=0 ); /* OOM detected prior to this routine */
  88696. VdbeNoopComment((v, "begin IN expr"));
  88697. eType = sqlite3FindInIndex(pParse, pExpr,
  88698. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  88699. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  88700. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  88701. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  88702. );
  88703. #ifdef SQLITE_DEBUG
  88704. /* Confirm that aiMap[] contains nVector integer values between 0 and
  88705. ** nVector-1. */
  88706. for(i=0; i<nVector; i++){
  88707. int j, cnt;
  88708. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  88709. assert( cnt==1 );
  88710. }
  88711. #endif
  88712. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  88713. ** vector, then it is stored in an array of nVector registers starting
  88714. ** at r1.
  88715. **
  88716. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  88717. ** so that the fields are in the same order as an existing index. The
  88718. ** aiMap[] array contains a mapping from the original LHS field order to
  88719. ** the field order that matches the RHS index.
  88720. */
  88721. sqlite3ExprCachePush(pParse);
  88722. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  88723. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  88724. if( i==nVector ){
  88725. /* LHS fields are not reordered */
  88726. rLhs = rLhsOrig;
  88727. }else{
  88728. /* Need to reorder the LHS fields according to aiMap */
  88729. rLhs = sqlite3GetTempRange(pParse, nVector);
  88730. for(i=0; i<nVector; i++){
  88731. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  88732. }
  88733. }
  88734. /* If sqlite3FindInIndex() did not find or create an index that is
  88735. ** suitable for evaluating the IN operator, then evaluate using a
  88736. ** sequence of comparisons.
  88737. **
  88738. ** This is step (1) in the in-operator.md optimized algorithm.
  88739. */
  88740. if( eType==IN_INDEX_NOOP ){
  88741. ExprList *pList = pExpr->x.pList;
  88742. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  88743. int labelOk = sqlite3VdbeMakeLabel(v);
  88744. int r2, regToFree;
  88745. int regCkNull = 0;
  88746. int ii;
  88747. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  88748. if( destIfNull!=destIfFalse ){
  88749. regCkNull = sqlite3GetTempReg(pParse);
  88750. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  88751. }
  88752. for(ii=0; ii<pList->nExpr; ii++){
  88753. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  88754. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  88755. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  88756. }
  88757. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  88758. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  88759. (void*)pColl, P4_COLLSEQ);
  88760. VdbeCoverageIf(v, ii<pList->nExpr-1);
  88761. VdbeCoverageIf(v, ii==pList->nExpr-1);
  88762. sqlite3VdbeChangeP5(v, zAff[0]);
  88763. }else{
  88764. assert( destIfNull==destIfFalse );
  88765. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  88766. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  88767. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  88768. }
  88769. sqlite3ReleaseTempReg(pParse, regToFree);
  88770. }
  88771. if( regCkNull ){
  88772. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  88773. sqlite3VdbeGoto(v, destIfFalse);
  88774. }
  88775. sqlite3VdbeResolveLabel(v, labelOk);
  88776. sqlite3ReleaseTempReg(pParse, regCkNull);
  88777. goto sqlite3ExprCodeIN_finished;
  88778. }
  88779. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  88780. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  88781. ** We will then skip the binary search of the RHS.
  88782. */
  88783. if( destIfNull==destIfFalse ){
  88784. destStep2 = destIfFalse;
  88785. }else{
  88786. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  88787. }
  88788. for(i=0; i<nVector; i++){
  88789. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  88790. if( sqlite3ExprCanBeNull(p) ){
  88791. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  88792. VdbeCoverage(v);
  88793. }
  88794. }
  88795. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  88796. ** of the RHS using the LHS as a probe. If found, the result is
  88797. ** true.
  88798. */
  88799. if( eType==IN_INDEX_ROWID ){
  88800. /* In this case, the RHS is the ROWID of table b-tree and so we also
  88801. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  88802. ** into a single opcode. */
  88803. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  88804. VdbeCoverage(v);
  88805. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  88806. }else{
  88807. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  88808. if( destIfFalse==destIfNull ){
  88809. /* Combine Step 3 and Step 5 into a single opcode */
  88810. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  88811. rLhs, nVector); VdbeCoverage(v);
  88812. goto sqlite3ExprCodeIN_finished;
  88813. }
  88814. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  88815. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  88816. rLhs, nVector); VdbeCoverage(v);
  88817. }
  88818. /* Step 4. If the RHS is known to be non-NULL and we did not find
  88819. ** an match on the search above, then the result must be FALSE.
  88820. */
  88821. if( rRhsHasNull && nVector==1 ){
  88822. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  88823. VdbeCoverage(v);
  88824. }
  88825. /* Step 5. If we do not care about the difference between NULL and
  88826. ** FALSE, then just return false.
  88827. */
  88828. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  88829. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  88830. ** If any comparison is NULL, then the result is NULL. If all
  88831. ** comparisons are FALSE then the final result is FALSE.
  88832. **
  88833. ** For a scalar LHS, it is sufficient to check just the first row
  88834. ** of the RHS.
  88835. */
  88836. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  88837. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  88838. VdbeCoverage(v);
  88839. if( nVector>1 ){
  88840. destNotNull = sqlite3VdbeMakeLabel(v);
  88841. }else{
  88842. /* For nVector==1, combine steps 6 and 7 by immediately returning
  88843. ** FALSE if the first comparison is not NULL */
  88844. destNotNull = destIfFalse;
  88845. }
  88846. for(i=0; i<nVector; i++){
  88847. Expr *p;
  88848. CollSeq *pColl;
  88849. int r3 = sqlite3GetTempReg(pParse);
  88850. p = sqlite3VectorFieldSubexpr(pLeft, i);
  88851. pColl = sqlite3ExprCollSeq(pParse, p);
  88852. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  88853. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  88854. (void*)pColl, P4_COLLSEQ);
  88855. VdbeCoverage(v);
  88856. sqlite3ReleaseTempReg(pParse, r3);
  88857. }
  88858. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  88859. if( nVector>1 ){
  88860. sqlite3VdbeResolveLabel(v, destNotNull);
  88861. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  88862. VdbeCoverage(v);
  88863. /* Step 7: If we reach this point, we know that the result must
  88864. ** be false. */
  88865. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  88866. }
  88867. /* Jumps here in order to return true. */
  88868. sqlite3VdbeJumpHere(v, addrTruthOp);
  88869. sqlite3ExprCodeIN_finished:
  88870. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  88871. sqlite3ExprCachePop(pParse);
  88872. VdbeComment((v, "end IN expr"));
  88873. sqlite3ExprCodeIN_oom_error:
  88874. sqlite3DbFree(pParse->db, aiMap);
  88875. sqlite3DbFree(pParse->db, zAff);
  88876. }
  88877. #endif /* SQLITE_OMIT_SUBQUERY */
  88878. #ifndef SQLITE_OMIT_FLOATING_POINT
  88879. /*
  88880. ** Generate an instruction that will put the floating point
  88881. ** value described by z[0..n-1] into register iMem.
  88882. **
  88883. ** The z[] string will probably not be zero-terminated. But the
  88884. ** z[n] character is guaranteed to be something that does not look
  88885. ** like the continuation of the number.
  88886. */
  88887. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  88888. if( ALWAYS(z!=0) ){
  88889. double value;
  88890. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  88891. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  88892. if( negateFlag ) value = -value;
  88893. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  88894. }
  88895. }
  88896. #endif
  88897. /*
  88898. ** Generate an instruction that will put the integer describe by
  88899. ** text z[0..n-1] into register iMem.
  88900. **
  88901. ** Expr.u.zToken is always UTF8 and zero-terminated.
  88902. */
  88903. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  88904. Vdbe *v = pParse->pVdbe;
  88905. if( pExpr->flags & EP_IntValue ){
  88906. int i = pExpr->u.iValue;
  88907. assert( i>=0 );
  88908. if( negFlag ) i = -i;
  88909. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  88910. }else{
  88911. int c;
  88912. i64 value;
  88913. const char *z = pExpr->u.zToken;
  88914. assert( z!=0 );
  88915. c = sqlite3DecOrHexToI64(z, &value);
  88916. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  88917. #ifdef SQLITE_OMIT_FLOATING_POINT
  88918. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  88919. #else
  88920. #ifndef SQLITE_OMIT_HEX_INTEGER
  88921. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  88922. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  88923. }else
  88924. #endif
  88925. {
  88926. codeReal(v, z, negFlag, iMem);
  88927. }
  88928. #endif
  88929. }else{
  88930. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  88931. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  88932. }
  88933. }
  88934. }
  88935. /*
  88936. ** Erase column-cache entry number i
  88937. */
  88938. static void cacheEntryClear(Parse *pParse, int i){
  88939. if( pParse->aColCache[i].tempReg ){
  88940. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  88941. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  88942. }
  88943. }
  88944. pParse->nColCache--;
  88945. if( i<pParse->nColCache ){
  88946. pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
  88947. }
  88948. }
  88949. /*
  88950. ** Record in the column cache that a particular column from a
  88951. ** particular table is stored in a particular register.
  88952. */
  88953. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  88954. int i;
  88955. int minLru;
  88956. int idxLru;
  88957. struct yColCache *p;
  88958. /* Unless an error has occurred, register numbers are always positive. */
  88959. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  88960. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  88961. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  88962. ** for testing only - to verify that SQLite always gets the same answer
  88963. ** with and without the column cache.
  88964. */
  88965. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  88966. /* First replace any existing entry.
  88967. **
  88968. ** Actually, the way the column cache is currently used, we are guaranteed
  88969. ** that the object will never already be in cache. Verify this guarantee.
  88970. */
  88971. #ifndef NDEBUG
  88972. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88973. assert( p->iTable!=iTab || p->iColumn!=iCol );
  88974. }
  88975. #endif
  88976. /* If the cache is already full, delete the least recently used entry */
  88977. if( pParse->nColCache>=SQLITE_N_COLCACHE ){
  88978. minLru = 0x7fffffff;
  88979. idxLru = -1;
  88980. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  88981. if( p->lru<minLru ){
  88982. idxLru = i;
  88983. minLru = p->lru;
  88984. }
  88985. }
  88986. p = &pParse->aColCache[idxLru];
  88987. }else{
  88988. p = &pParse->aColCache[pParse->nColCache++];
  88989. }
  88990. /* Add the new entry to the end of the cache */
  88991. p->iLevel = pParse->iCacheLevel;
  88992. p->iTable = iTab;
  88993. p->iColumn = iCol;
  88994. p->iReg = iReg;
  88995. p->tempReg = 0;
  88996. p->lru = pParse->iCacheCnt++;
  88997. }
  88998. /*
  88999. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  89000. ** Purge the range of registers from the column cache.
  89001. */
  89002. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  89003. int i = 0;
  89004. while( i<pParse->nColCache ){
  89005. struct yColCache *p = &pParse->aColCache[i];
  89006. if( p->iReg >= iReg && p->iReg < iReg+nReg ){
  89007. cacheEntryClear(pParse, i);
  89008. }else{
  89009. i++;
  89010. }
  89011. }
  89012. }
  89013. /*
  89014. ** Remember the current column cache context. Any new entries added
  89015. ** added to the column cache after this call are removed when the
  89016. ** corresponding pop occurs.
  89017. */
  89018. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  89019. pParse->iCacheLevel++;
  89020. #ifdef SQLITE_DEBUG
  89021. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  89022. printf("PUSH to %d\n", pParse->iCacheLevel);
  89023. }
  89024. #endif
  89025. }
  89026. /*
  89027. ** Remove from the column cache any entries that were added since the
  89028. ** the previous sqlite3ExprCachePush operation. In other words, restore
  89029. ** the cache to the state it was in prior the most recent Push.
  89030. */
  89031. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  89032. int i = 0;
  89033. assert( pParse->iCacheLevel>=1 );
  89034. pParse->iCacheLevel--;
  89035. #ifdef SQLITE_DEBUG
  89036. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  89037. printf("POP to %d\n", pParse->iCacheLevel);
  89038. }
  89039. #endif
  89040. while( i<pParse->nColCache ){
  89041. if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
  89042. cacheEntryClear(pParse, i);
  89043. }else{
  89044. i++;
  89045. }
  89046. }
  89047. }
  89048. /*
  89049. ** When a cached column is reused, make sure that its register is
  89050. ** no longer available as a temp register. ticket #3879: that same
  89051. ** register might be in the cache in multiple places, so be sure to
  89052. ** get them all.
  89053. */
  89054. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  89055. int i;
  89056. struct yColCache *p;
  89057. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  89058. if( p->iReg==iReg ){
  89059. p->tempReg = 0;
  89060. }
  89061. }
  89062. }
  89063. /* Generate code that will load into register regOut a value that is
  89064. ** appropriate for the iIdxCol-th column of index pIdx.
  89065. */
  89066. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  89067. Parse *pParse, /* The parsing context */
  89068. Index *pIdx, /* The index whose column is to be loaded */
  89069. int iTabCur, /* Cursor pointing to a table row */
  89070. int iIdxCol, /* The column of the index to be loaded */
  89071. int regOut /* Store the index column value in this register */
  89072. ){
  89073. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  89074. if( iTabCol==XN_EXPR ){
  89075. assert( pIdx->aColExpr );
  89076. assert( pIdx->aColExpr->nExpr>iIdxCol );
  89077. pParse->iSelfTab = iTabCur + 1;
  89078. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  89079. pParse->iSelfTab = 0;
  89080. }else{
  89081. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  89082. iTabCol, regOut);
  89083. }
  89084. }
  89085. /*
  89086. ** Generate code to extract the value of the iCol-th column of a table.
  89087. */
  89088. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  89089. Vdbe *v, /* The VDBE under construction */
  89090. Table *pTab, /* The table containing the value */
  89091. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  89092. int iCol, /* Index of the column to extract */
  89093. int regOut /* Extract the value into this register */
  89094. ){
  89095. if( pTab==0 ){
  89096. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  89097. return;
  89098. }
  89099. if( iCol<0 || iCol==pTab->iPKey ){
  89100. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  89101. }else{
  89102. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  89103. int x = iCol;
  89104. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  89105. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  89106. }
  89107. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  89108. }
  89109. if( iCol>=0 ){
  89110. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  89111. }
  89112. }
  89113. /*
  89114. ** Generate code that will extract the iColumn-th column from
  89115. ** table pTab and store the column value in a register.
  89116. **
  89117. ** An effort is made to store the column value in register iReg. This
  89118. ** is not garanteeed for GetColumn() - the result can be stored in
  89119. ** any register. But the result is guaranteed to land in register iReg
  89120. ** for GetColumnToReg().
  89121. **
  89122. ** There must be an open cursor to pTab in iTable when this routine
  89123. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  89124. */
  89125. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  89126. Parse *pParse, /* Parsing and code generating context */
  89127. Table *pTab, /* Description of the table we are reading from */
  89128. int iColumn, /* Index of the table column */
  89129. int iTable, /* The cursor pointing to the table */
  89130. int iReg, /* Store results here */
  89131. u8 p5 /* P5 value for OP_Column + FLAGS */
  89132. ){
  89133. Vdbe *v = pParse->pVdbe;
  89134. int i;
  89135. struct yColCache *p;
  89136. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  89137. if( p->iTable==iTable && p->iColumn==iColumn ){
  89138. p->lru = pParse->iCacheCnt++;
  89139. sqlite3ExprCachePinRegister(pParse, p->iReg);
  89140. return p->iReg;
  89141. }
  89142. }
  89143. assert( v!=0 );
  89144. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  89145. if( p5 ){
  89146. sqlite3VdbeChangeP5(v, p5);
  89147. }else{
  89148. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  89149. }
  89150. return iReg;
  89151. }
  89152. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  89153. Parse *pParse, /* Parsing and code generating context */
  89154. Table *pTab, /* Description of the table we are reading from */
  89155. int iColumn, /* Index of the table column */
  89156. int iTable, /* The cursor pointing to the table */
  89157. int iReg /* Store results here */
  89158. ){
  89159. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  89160. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  89161. }
  89162. /*
  89163. ** Clear all column cache entries.
  89164. */
  89165. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  89166. int i;
  89167. #ifdef SQLITE_DEBUG
  89168. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  89169. printf("CLEAR\n");
  89170. }
  89171. #endif
  89172. for(i=0; i<pParse->nColCache; i++){
  89173. if( pParse->aColCache[i].tempReg
  89174. && pParse->nTempReg<ArraySize(pParse->aTempReg)
  89175. ){
  89176. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  89177. }
  89178. }
  89179. pParse->nColCache = 0;
  89180. }
  89181. /*
  89182. ** Record the fact that an affinity change has occurred on iCount
  89183. ** registers starting with iStart.
  89184. */
  89185. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  89186. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  89187. }
  89188. /*
  89189. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  89190. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  89191. */
  89192. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  89193. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  89194. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  89195. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  89196. }
  89197. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  89198. /*
  89199. ** Return true if any register in the range iFrom..iTo (inclusive)
  89200. ** is used as part of the column cache.
  89201. **
  89202. ** This routine is used within assert() and testcase() macros only
  89203. ** and does not appear in a normal build.
  89204. */
  89205. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  89206. int i;
  89207. struct yColCache *p;
  89208. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  89209. int r = p->iReg;
  89210. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  89211. }
  89212. return 0;
  89213. }
  89214. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  89215. /*
  89216. ** Convert a scalar expression node to a TK_REGISTER referencing
  89217. ** register iReg. The caller must ensure that iReg already contains
  89218. ** the correct value for the expression.
  89219. */
  89220. static void exprToRegister(Expr *p, int iReg){
  89221. p->op2 = p->op;
  89222. p->op = TK_REGISTER;
  89223. p->iTable = iReg;
  89224. ExprClearProperty(p, EP_Skip);
  89225. }
  89226. /*
  89227. ** Evaluate an expression (either a vector or a scalar expression) and store
  89228. ** the result in continguous temporary registers. Return the index of
  89229. ** the first register used to store the result.
  89230. **
  89231. ** If the returned result register is a temporary scalar, then also write
  89232. ** that register number into *piFreeable. If the returned result register
  89233. ** is not a temporary or if the expression is a vector set *piFreeable
  89234. ** to 0.
  89235. */
  89236. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  89237. int iResult;
  89238. int nResult = sqlite3ExprVectorSize(p);
  89239. if( nResult==1 ){
  89240. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  89241. }else{
  89242. *piFreeable = 0;
  89243. if( p->op==TK_SELECT ){
  89244. #if SQLITE_OMIT_SUBQUERY
  89245. iResult = 0;
  89246. #else
  89247. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  89248. #endif
  89249. }else{
  89250. int i;
  89251. iResult = pParse->nMem+1;
  89252. pParse->nMem += nResult;
  89253. for(i=0; i<nResult; i++){
  89254. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  89255. }
  89256. }
  89257. }
  89258. return iResult;
  89259. }
  89260. /*
  89261. ** Generate code into the current Vdbe to evaluate the given
  89262. ** expression. Attempt to store the results in register "target".
  89263. ** Return the register where results are stored.
  89264. **
  89265. ** With this routine, there is no guarantee that results will
  89266. ** be stored in target. The result might be stored in some other
  89267. ** register if it is convenient to do so. The calling function
  89268. ** must check the return code and move the results to the desired
  89269. ** register.
  89270. */
  89271. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  89272. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  89273. int op; /* The opcode being coded */
  89274. int inReg = target; /* Results stored in register inReg */
  89275. int regFree1 = 0; /* If non-zero free this temporary register */
  89276. int regFree2 = 0; /* If non-zero free this temporary register */
  89277. int r1, r2; /* Various register numbers */
  89278. Expr tempX; /* Temporary expression node */
  89279. int p5 = 0;
  89280. assert( target>0 && target<=pParse->nMem );
  89281. if( v==0 ){
  89282. assert( pParse->db->mallocFailed );
  89283. return 0;
  89284. }
  89285. if( pExpr==0 ){
  89286. op = TK_NULL;
  89287. }else{
  89288. op = pExpr->op;
  89289. }
  89290. switch( op ){
  89291. case TK_AGG_COLUMN: {
  89292. AggInfo *pAggInfo = pExpr->pAggInfo;
  89293. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  89294. if( !pAggInfo->directMode ){
  89295. assert( pCol->iMem>0 );
  89296. return pCol->iMem;
  89297. }else if( pAggInfo->useSortingIdx ){
  89298. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  89299. pCol->iSorterColumn, target);
  89300. return target;
  89301. }
  89302. /* Otherwise, fall thru into the TK_COLUMN case */
  89303. }
  89304. case TK_COLUMN: {
  89305. int iTab = pExpr->iTable;
  89306. if( iTab<0 ){
  89307. if( pParse->iSelfTab<0 ){
  89308. /* Generating CHECK constraints or inserting into partial index */
  89309. return pExpr->iColumn - pParse->iSelfTab;
  89310. }else{
  89311. /* Coding an expression that is part of an index where column names
  89312. ** in the index refer to the table to which the index belongs */
  89313. iTab = pParse->iSelfTab - 1;
  89314. }
  89315. }
  89316. return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  89317. pExpr->iColumn, iTab, target,
  89318. pExpr->op2);
  89319. }
  89320. case TK_INTEGER: {
  89321. codeInteger(pParse, pExpr, 0, target);
  89322. return target;
  89323. }
  89324. #ifndef SQLITE_OMIT_FLOATING_POINT
  89325. case TK_FLOAT: {
  89326. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89327. codeReal(v, pExpr->u.zToken, 0, target);
  89328. return target;
  89329. }
  89330. #endif
  89331. case TK_STRING: {
  89332. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89333. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  89334. return target;
  89335. }
  89336. case TK_NULL: {
  89337. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  89338. return target;
  89339. }
  89340. #ifndef SQLITE_OMIT_BLOB_LITERAL
  89341. case TK_BLOB: {
  89342. int n;
  89343. const char *z;
  89344. char *zBlob;
  89345. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89346. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  89347. assert( pExpr->u.zToken[1]=='\'' );
  89348. z = &pExpr->u.zToken[2];
  89349. n = sqlite3Strlen30(z) - 1;
  89350. assert( z[n]=='\'' );
  89351. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  89352. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  89353. return target;
  89354. }
  89355. #endif
  89356. case TK_VARIABLE: {
  89357. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89358. assert( pExpr->u.zToken!=0 );
  89359. assert( pExpr->u.zToken[0]!=0 );
  89360. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  89361. if( pExpr->u.zToken[1]!=0 ){
  89362. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  89363. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  89364. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  89365. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  89366. }
  89367. return target;
  89368. }
  89369. case TK_REGISTER: {
  89370. return pExpr->iTable;
  89371. }
  89372. #ifndef SQLITE_OMIT_CAST
  89373. case TK_CAST: {
  89374. /* Expressions of the form: CAST(pLeft AS token) */
  89375. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  89376. if( inReg!=target ){
  89377. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  89378. inReg = target;
  89379. }
  89380. sqlite3VdbeAddOp2(v, OP_Cast, target,
  89381. sqlite3AffinityType(pExpr->u.zToken, 0));
  89382. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  89383. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  89384. return inReg;
  89385. }
  89386. #endif /* SQLITE_OMIT_CAST */
  89387. case TK_IS:
  89388. case TK_ISNOT:
  89389. op = (op==TK_IS) ? TK_EQ : TK_NE;
  89390. p5 = SQLITE_NULLEQ;
  89391. /* fall-through */
  89392. case TK_LT:
  89393. case TK_LE:
  89394. case TK_GT:
  89395. case TK_GE:
  89396. case TK_NE:
  89397. case TK_EQ: {
  89398. Expr *pLeft = pExpr->pLeft;
  89399. if( sqlite3ExprIsVector(pLeft) ){
  89400. codeVectorCompare(pParse, pExpr, target, op, p5);
  89401. }else{
  89402. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  89403. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89404. codeCompare(pParse, pLeft, pExpr->pRight, op,
  89405. r1, r2, inReg, SQLITE_STOREP2 | p5);
  89406. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89407. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89408. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89409. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89410. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  89411. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  89412. testcase( regFree1==0 );
  89413. testcase( regFree2==0 );
  89414. }
  89415. break;
  89416. }
  89417. case TK_AND:
  89418. case TK_OR:
  89419. case TK_PLUS:
  89420. case TK_STAR:
  89421. case TK_MINUS:
  89422. case TK_REM:
  89423. case TK_BITAND:
  89424. case TK_BITOR:
  89425. case TK_SLASH:
  89426. case TK_LSHIFT:
  89427. case TK_RSHIFT:
  89428. case TK_CONCAT: {
  89429. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  89430. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  89431. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  89432. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  89433. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  89434. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  89435. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  89436. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  89437. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  89438. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  89439. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  89440. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89441. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89442. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  89443. testcase( regFree1==0 );
  89444. testcase( regFree2==0 );
  89445. break;
  89446. }
  89447. case TK_UMINUS: {
  89448. Expr *pLeft = pExpr->pLeft;
  89449. assert( pLeft );
  89450. if( pLeft->op==TK_INTEGER ){
  89451. codeInteger(pParse, pLeft, 1, target);
  89452. return target;
  89453. #ifndef SQLITE_OMIT_FLOATING_POINT
  89454. }else if( pLeft->op==TK_FLOAT ){
  89455. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89456. codeReal(v, pLeft->u.zToken, 1, target);
  89457. return target;
  89458. #endif
  89459. }else{
  89460. tempX.op = TK_INTEGER;
  89461. tempX.flags = EP_IntValue|EP_TokenOnly;
  89462. tempX.u.iValue = 0;
  89463. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  89464. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  89465. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  89466. testcase( regFree2==0 );
  89467. }
  89468. break;
  89469. }
  89470. case TK_BITNOT:
  89471. case TK_NOT: {
  89472. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  89473. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  89474. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89475. testcase( regFree1==0 );
  89476. sqlite3VdbeAddOp2(v, op, r1, inReg);
  89477. break;
  89478. }
  89479. case TK_ISNULL:
  89480. case TK_NOTNULL: {
  89481. int addr;
  89482. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  89483. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  89484. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  89485. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89486. testcase( regFree1==0 );
  89487. addr = sqlite3VdbeAddOp1(v, op, r1);
  89488. VdbeCoverageIf(v, op==TK_ISNULL);
  89489. VdbeCoverageIf(v, op==TK_NOTNULL);
  89490. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  89491. sqlite3VdbeJumpHere(v, addr);
  89492. break;
  89493. }
  89494. case TK_AGG_FUNCTION: {
  89495. AggInfo *pInfo = pExpr->pAggInfo;
  89496. if( pInfo==0 ){
  89497. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89498. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  89499. }else{
  89500. return pInfo->aFunc[pExpr->iAgg].iMem;
  89501. }
  89502. break;
  89503. }
  89504. case TK_FUNCTION: {
  89505. ExprList *pFarg; /* List of function arguments */
  89506. int nFarg; /* Number of function arguments */
  89507. FuncDef *pDef; /* The function definition object */
  89508. const char *zId; /* The function name */
  89509. u32 constMask = 0; /* Mask of function arguments that are constant */
  89510. int i; /* Loop counter */
  89511. sqlite3 *db = pParse->db; /* The database connection */
  89512. u8 enc = ENC(db); /* The text encoding used by this database */
  89513. CollSeq *pColl = 0; /* A collating sequence */
  89514. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  89515. /* SQL functions can be expensive. So try to move constant functions
  89516. ** out of the inner loop, even if that means an extra OP_Copy. */
  89517. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  89518. }
  89519. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89520. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  89521. pFarg = 0;
  89522. }else{
  89523. pFarg = pExpr->x.pList;
  89524. }
  89525. nFarg = pFarg ? pFarg->nExpr : 0;
  89526. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89527. zId = pExpr->u.zToken;
  89528. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  89529. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  89530. if( pDef==0 && pParse->explain ){
  89531. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  89532. }
  89533. #endif
  89534. if( pDef==0 || pDef->xFinalize!=0 ){
  89535. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  89536. break;
  89537. }
  89538. /* Attempt a direct implementation of the built-in COALESCE() and
  89539. ** IFNULL() functions. This avoids unnecessary evaluation of
  89540. ** arguments past the first non-NULL argument.
  89541. */
  89542. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  89543. int endCoalesce = sqlite3VdbeMakeLabel(v);
  89544. assert( nFarg>=2 );
  89545. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  89546. for(i=1; i<nFarg; i++){
  89547. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  89548. VdbeCoverage(v);
  89549. sqlite3ExprCacheRemove(pParse, target, 1);
  89550. sqlite3ExprCachePush(pParse);
  89551. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  89552. sqlite3ExprCachePop(pParse);
  89553. }
  89554. sqlite3VdbeResolveLabel(v, endCoalesce);
  89555. break;
  89556. }
  89557. /* The UNLIKELY() function is a no-op. The result is the value
  89558. ** of the first argument.
  89559. */
  89560. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  89561. assert( nFarg>=1 );
  89562. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  89563. }
  89564. #ifdef SQLITE_DEBUG
  89565. /* The AFFINITY() function evaluates to a string that describes
  89566. ** the type affinity of the argument. This is used for testing of
  89567. ** the SQLite type logic.
  89568. */
  89569. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  89570. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  89571. char aff;
  89572. assert( nFarg==1 );
  89573. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  89574. sqlite3VdbeLoadString(v, target,
  89575. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  89576. return target;
  89577. }
  89578. #endif
  89579. for(i=0; i<nFarg; i++){
  89580. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  89581. testcase( i==31 );
  89582. constMask |= MASKBIT32(i);
  89583. }
  89584. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  89585. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  89586. }
  89587. }
  89588. if( pFarg ){
  89589. if( constMask ){
  89590. r1 = pParse->nMem+1;
  89591. pParse->nMem += nFarg;
  89592. }else{
  89593. r1 = sqlite3GetTempRange(pParse, nFarg);
  89594. }
  89595. /* For length() and typeof() functions with a column argument,
  89596. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  89597. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  89598. ** loading.
  89599. */
  89600. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  89601. u8 exprOp;
  89602. assert( nFarg==1 );
  89603. assert( pFarg->a[0].pExpr!=0 );
  89604. exprOp = pFarg->a[0].pExpr->op;
  89605. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  89606. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  89607. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  89608. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  89609. pFarg->a[0].pExpr->op2 =
  89610. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  89611. }
  89612. }
  89613. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  89614. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  89615. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  89616. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  89617. }else{
  89618. r1 = 0;
  89619. }
  89620. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89621. /* Possibly overload the function if the first argument is
  89622. ** a virtual table column.
  89623. **
  89624. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  89625. ** second argument, not the first, as the argument to test to
  89626. ** see if it is a column in a virtual table. This is done because
  89627. ** the left operand of infix functions (the operand we want to
  89628. ** control overloading) ends up as the second argument to the
  89629. ** function. The expression "A glob B" is equivalent to
  89630. ** "glob(B,A). We want to use the A in "A glob B" to test
  89631. ** for function overloading. But we use the B term in "glob(B,A)".
  89632. */
  89633. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  89634. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  89635. }else if( nFarg>0 ){
  89636. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  89637. }
  89638. #endif
  89639. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  89640. if( !pColl ) pColl = db->pDfltColl;
  89641. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  89642. }
  89643. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  89644. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  89645. sqlite3VdbeChangeP5(v, (u8)nFarg);
  89646. if( nFarg && constMask==0 ){
  89647. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  89648. }
  89649. return target;
  89650. }
  89651. #ifndef SQLITE_OMIT_SUBQUERY
  89652. case TK_EXISTS:
  89653. case TK_SELECT: {
  89654. int nCol;
  89655. testcase( op==TK_EXISTS );
  89656. testcase( op==TK_SELECT );
  89657. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  89658. sqlite3SubselectError(pParse, nCol, 1);
  89659. }else{
  89660. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  89661. }
  89662. break;
  89663. }
  89664. case TK_SELECT_COLUMN: {
  89665. int n;
  89666. if( pExpr->pLeft->iTable==0 ){
  89667. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  89668. }
  89669. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  89670. if( pExpr->iTable
  89671. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  89672. ){
  89673. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  89674. pExpr->iTable, n);
  89675. }
  89676. return pExpr->pLeft->iTable + pExpr->iColumn;
  89677. }
  89678. case TK_IN: {
  89679. int destIfFalse = sqlite3VdbeMakeLabel(v);
  89680. int destIfNull = sqlite3VdbeMakeLabel(v);
  89681. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  89682. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  89683. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  89684. sqlite3VdbeResolveLabel(v, destIfFalse);
  89685. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  89686. sqlite3VdbeResolveLabel(v, destIfNull);
  89687. return target;
  89688. }
  89689. #endif /* SQLITE_OMIT_SUBQUERY */
  89690. /*
  89691. ** x BETWEEN y AND z
  89692. **
  89693. ** This is equivalent to
  89694. **
  89695. ** x>=y AND x<=z
  89696. **
  89697. ** X is stored in pExpr->pLeft.
  89698. ** Y is stored in pExpr->pList->a[0].pExpr.
  89699. ** Z is stored in pExpr->pList->a[1].pExpr.
  89700. */
  89701. case TK_BETWEEN: {
  89702. exprCodeBetween(pParse, pExpr, target, 0, 0);
  89703. return target;
  89704. }
  89705. case TK_SPAN:
  89706. case TK_COLLATE:
  89707. case TK_UPLUS: {
  89708. return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  89709. }
  89710. case TK_TRIGGER: {
  89711. /* If the opcode is TK_TRIGGER, then the expression is a reference
  89712. ** to a column in the new.* or old.* pseudo-tables available to
  89713. ** trigger programs. In this case Expr.iTable is set to 1 for the
  89714. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  89715. ** is set to the column of the pseudo-table to read, or to -1 to
  89716. ** read the rowid field.
  89717. **
  89718. ** The expression is implemented using an OP_Param opcode. The p1
  89719. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  89720. ** to reference another column of the old.* pseudo-table, where
  89721. ** i is the index of the column. For a new.rowid reference, p1 is
  89722. ** set to (n+1), where n is the number of columns in each pseudo-table.
  89723. ** For a reference to any other column in the new.* pseudo-table, p1
  89724. ** is set to (n+2+i), where n and i are as defined previously. For
  89725. ** example, if the table on which triggers are being fired is
  89726. ** declared as:
  89727. **
  89728. ** CREATE TABLE t1(a, b);
  89729. **
  89730. ** Then p1 is interpreted as follows:
  89731. **
  89732. ** p1==0 -> old.rowid p1==3 -> new.rowid
  89733. ** p1==1 -> old.a p1==4 -> new.a
  89734. ** p1==2 -> old.b p1==5 -> new.b
  89735. */
  89736. Table *pTab = pExpr->pTab;
  89737. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  89738. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  89739. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  89740. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  89741. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  89742. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  89743. VdbeComment((v, "%s.%s -> $%d",
  89744. (pExpr->iTable ? "new" : "old"),
  89745. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  89746. target
  89747. ));
  89748. #ifndef SQLITE_OMIT_FLOATING_POINT
  89749. /* If the column has REAL affinity, it may currently be stored as an
  89750. ** integer. Use OP_RealAffinity to make sure it is really real.
  89751. **
  89752. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  89753. ** floating point when extracting it from the record. */
  89754. if( pExpr->iColumn>=0
  89755. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  89756. ){
  89757. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  89758. }
  89759. #endif
  89760. break;
  89761. }
  89762. case TK_VECTOR: {
  89763. sqlite3ErrorMsg(pParse, "row value misused");
  89764. break;
  89765. }
  89766. case TK_IF_NULL_ROW: {
  89767. int addrINR;
  89768. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  89769. sqlite3ExprCachePush(pParse);
  89770. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  89771. sqlite3ExprCachePop(pParse);
  89772. sqlite3VdbeJumpHere(v, addrINR);
  89773. sqlite3VdbeChangeP3(v, addrINR, inReg);
  89774. break;
  89775. }
  89776. /*
  89777. ** Form A:
  89778. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  89779. **
  89780. ** Form B:
  89781. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  89782. **
  89783. ** Form A is can be transformed into the equivalent form B as follows:
  89784. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  89785. ** WHEN x=eN THEN rN ELSE y END
  89786. **
  89787. ** X (if it exists) is in pExpr->pLeft.
  89788. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  89789. ** odd. The Y is also optional. If the number of elements in x.pList
  89790. ** is even, then Y is omitted and the "otherwise" result is NULL.
  89791. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  89792. **
  89793. ** The result of the expression is the Ri for the first matching Ei,
  89794. ** or if there is no matching Ei, the ELSE term Y, or if there is
  89795. ** no ELSE term, NULL.
  89796. */
  89797. default: assert( op==TK_CASE ); {
  89798. int endLabel; /* GOTO label for end of CASE stmt */
  89799. int nextCase; /* GOTO label for next WHEN clause */
  89800. int nExpr; /* 2x number of WHEN terms */
  89801. int i; /* Loop counter */
  89802. ExprList *pEList; /* List of WHEN terms */
  89803. struct ExprList_item *aListelem; /* Array of WHEN terms */
  89804. Expr opCompare; /* The X==Ei expression */
  89805. Expr *pX; /* The X expression */
  89806. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  89807. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  89808. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  89809. assert(pExpr->x.pList->nExpr > 0);
  89810. pEList = pExpr->x.pList;
  89811. aListelem = pEList->a;
  89812. nExpr = pEList->nExpr;
  89813. endLabel = sqlite3VdbeMakeLabel(v);
  89814. if( (pX = pExpr->pLeft)!=0 ){
  89815. tempX = *pX;
  89816. testcase( pX->op==TK_COLUMN );
  89817. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  89818. testcase( regFree1==0 );
  89819. memset(&opCompare, 0, sizeof(opCompare));
  89820. opCompare.op = TK_EQ;
  89821. opCompare.pLeft = &tempX;
  89822. pTest = &opCompare;
  89823. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  89824. ** The value in regFree1 might get SCopy-ed into the file result.
  89825. ** So make sure that the regFree1 register is not reused for other
  89826. ** purposes and possibly overwritten. */
  89827. regFree1 = 0;
  89828. }
  89829. for(i=0; i<nExpr-1; i=i+2){
  89830. sqlite3ExprCachePush(pParse);
  89831. if( pX ){
  89832. assert( pTest!=0 );
  89833. opCompare.pRight = aListelem[i].pExpr;
  89834. }else{
  89835. pTest = aListelem[i].pExpr;
  89836. }
  89837. nextCase = sqlite3VdbeMakeLabel(v);
  89838. testcase( pTest->op==TK_COLUMN );
  89839. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  89840. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  89841. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  89842. sqlite3VdbeGoto(v, endLabel);
  89843. sqlite3ExprCachePop(pParse);
  89844. sqlite3VdbeResolveLabel(v, nextCase);
  89845. }
  89846. if( (nExpr&1)!=0 ){
  89847. sqlite3ExprCachePush(pParse);
  89848. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  89849. sqlite3ExprCachePop(pParse);
  89850. }else{
  89851. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  89852. }
  89853. assert( pParse->db->mallocFailed || pParse->nErr>0
  89854. || pParse->iCacheLevel==iCacheLevel );
  89855. sqlite3VdbeResolveLabel(v, endLabel);
  89856. break;
  89857. }
  89858. #ifndef SQLITE_OMIT_TRIGGER
  89859. case TK_RAISE: {
  89860. assert( pExpr->affinity==OE_Rollback
  89861. || pExpr->affinity==OE_Abort
  89862. || pExpr->affinity==OE_Fail
  89863. || pExpr->affinity==OE_Ignore
  89864. );
  89865. if( !pParse->pTriggerTab ){
  89866. sqlite3ErrorMsg(pParse,
  89867. "RAISE() may only be used within a trigger-program");
  89868. return 0;
  89869. }
  89870. if( pExpr->affinity==OE_Abort ){
  89871. sqlite3MayAbort(pParse);
  89872. }
  89873. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89874. if( pExpr->affinity==OE_Ignore ){
  89875. sqlite3VdbeAddOp4(
  89876. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  89877. VdbeCoverage(v);
  89878. }else{
  89879. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  89880. pExpr->affinity, pExpr->u.zToken, 0, 0);
  89881. }
  89882. break;
  89883. }
  89884. #endif
  89885. }
  89886. sqlite3ReleaseTempReg(pParse, regFree1);
  89887. sqlite3ReleaseTempReg(pParse, regFree2);
  89888. return inReg;
  89889. }
  89890. /*
  89891. ** Factor out the code of the given expression to initialization time.
  89892. **
  89893. ** If regDest>=0 then the result is always stored in that register and the
  89894. ** result is not reusable. If regDest<0 then this routine is free to
  89895. ** store the value whereever it wants. The register where the expression
  89896. ** is stored is returned. When regDest<0, two identical expressions will
  89897. ** code to the same register.
  89898. */
  89899. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  89900. Parse *pParse, /* Parsing context */
  89901. Expr *pExpr, /* The expression to code when the VDBE initializes */
  89902. int regDest /* Store the value in this register */
  89903. ){
  89904. ExprList *p;
  89905. assert( ConstFactorOk(pParse) );
  89906. p = pParse->pConstExpr;
  89907. if( regDest<0 && p ){
  89908. struct ExprList_item *pItem;
  89909. int i;
  89910. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  89911. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  89912. return pItem->u.iConstExprReg;
  89913. }
  89914. }
  89915. }
  89916. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  89917. p = sqlite3ExprListAppend(pParse, p, pExpr);
  89918. if( p ){
  89919. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  89920. pItem->reusable = regDest<0;
  89921. if( regDest<0 ) regDest = ++pParse->nMem;
  89922. pItem->u.iConstExprReg = regDest;
  89923. }
  89924. pParse->pConstExpr = p;
  89925. return regDest;
  89926. }
  89927. /*
  89928. ** Generate code to evaluate an expression and store the results
  89929. ** into a register. Return the register number where the results
  89930. ** are stored.
  89931. **
  89932. ** If the register is a temporary register that can be deallocated,
  89933. ** then write its number into *pReg. If the result register is not
  89934. ** a temporary, then set *pReg to zero.
  89935. **
  89936. ** If pExpr is a constant, then this routine might generate this
  89937. ** code to fill the register in the initialization section of the
  89938. ** VDBE program, in order to factor it out of the evaluation loop.
  89939. */
  89940. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  89941. int r2;
  89942. pExpr = sqlite3ExprSkipCollate(pExpr);
  89943. if( ConstFactorOk(pParse)
  89944. && pExpr->op!=TK_REGISTER
  89945. && sqlite3ExprIsConstantNotJoin(pExpr)
  89946. ){
  89947. *pReg = 0;
  89948. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  89949. }else{
  89950. int r1 = sqlite3GetTempReg(pParse);
  89951. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  89952. if( r2==r1 ){
  89953. *pReg = r1;
  89954. }else{
  89955. sqlite3ReleaseTempReg(pParse, r1);
  89956. *pReg = 0;
  89957. }
  89958. }
  89959. return r2;
  89960. }
  89961. /*
  89962. ** Generate code that will evaluate expression pExpr and store the
  89963. ** results in register target. The results are guaranteed to appear
  89964. ** in register target.
  89965. */
  89966. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  89967. int inReg;
  89968. assert( target>0 && target<=pParse->nMem );
  89969. if( pExpr && pExpr->op==TK_REGISTER ){
  89970. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  89971. }else{
  89972. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  89973. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  89974. if( inReg!=target && pParse->pVdbe ){
  89975. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  89976. }
  89977. }
  89978. }
  89979. /*
  89980. ** Make a transient copy of expression pExpr and then code it using
  89981. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  89982. ** except that the input expression is guaranteed to be unchanged.
  89983. */
  89984. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  89985. sqlite3 *db = pParse->db;
  89986. pExpr = sqlite3ExprDup(db, pExpr, 0);
  89987. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  89988. sqlite3ExprDelete(db, pExpr);
  89989. }
  89990. /*
  89991. ** Generate code that will evaluate expression pExpr and store the
  89992. ** results in register target. The results are guaranteed to appear
  89993. ** in register target. If the expression is constant, then this routine
  89994. ** might choose to code the expression at initialization time.
  89995. */
  89996. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  89997. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  89998. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  89999. }else{
  90000. sqlite3ExprCode(pParse, pExpr, target);
  90001. }
  90002. }
  90003. /*
  90004. ** Generate code that evaluates the given expression and puts the result
  90005. ** in register target.
  90006. **
  90007. ** Also make a copy of the expression results into another "cache" register
  90008. ** and modify the expression so that the next time it is evaluated,
  90009. ** the result is a copy of the cache register.
  90010. **
  90011. ** This routine is used for expressions that are used multiple
  90012. ** times. They are evaluated once and the results of the expression
  90013. ** are reused.
  90014. */
  90015. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  90016. Vdbe *v = pParse->pVdbe;
  90017. int iMem;
  90018. assert( target>0 );
  90019. assert( pExpr->op!=TK_REGISTER );
  90020. sqlite3ExprCode(pParse, pExpr, target);
  90021. iMem = ++pParse->nMem;
  90022. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  90023. exprToRegister(pExpr, iMem);
  90024. }
  90025. /*
  90026. ** Generate code that pushes the value of every element of the given
  90027. ** expression list into a sequence of registers beginning at target.
  90028. **
  90029. ** Return the number of elements evaluated. The number returned will
  90030. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  90031. ** is defined.
  90032. **
  90033. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  90034. ** filled using OP_SCopy. OP_Copy must be used instead.
  90035. **
  90036. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  90037. ** factored out into initialization code.
  90038. **
  90039. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  90040. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  90041. ** in registers at srcReg, and so the value can be copied from there.
  90042. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  90043. ** are simply omitted rather than being copied from srcReg.
  90044. */
  90045. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  90046. Parse *pParse, /* Parsing context */
  90047. ExprList *pList, /* The expression list to be coded */
  90048. int target, /* Where to write results */
  90049. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  90050. u8 flags /* SQLITE_ECEL_* flags */
  90051. ){
  90052. struct ExprList_item *pItem;
  90053. int i, j, n;
  90054. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  90055. Vdbe *v = pParse->pVdbe;
  90056. assert( pList!=0 );
  90057. assert( target>0 );
  90058. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  90059. n = pList->nExpr;
  90060. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  90061. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  90062. Expr *pExpr = pItem->pExpr;
  90063. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  90064. if( flags & SQLITE_ECEL_OMITREF ){
  90065. i--;
  90066. n--;
  90067. }else{
  90068. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  90069. }
  90070. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  90071. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  90072. }else{
  90073. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  90074. if( inReg!=target+i ){
  90075. VdbeOp *pOp;
  90076. if( copyOp==OP_Copy
  90077. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  90078. && pOp->p1+pOp->p3+1==inReg
  90079. && pOp->p2+pOp->p3+1==target+i
  90080. ){
  90081. pOp->p3++;
  90082. }else{
  90083. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  90084. }
  90085. }
  90086. }
  90087. }
  90088. return n;
  90089. }
  90090. /*
  90091. ** Generate code for a BETWEEN operator.
  90092. **
  90093. ** x BETWEEN y AND z
  90094. **
  90095. ** The above is equivalent to
  90096. **
  90097. ** x>=y AND x<=z
  90098. **
  90099. ** Code it as such, taking care to do the common subexpression
  90100. ** elimination of x.
  90101. **
  90102. ** The xJumpIf parameter determines details:
  90103. **
  90104. ** NULL: Store the boolean result in reg[dest]
  90105. ** sqlite3ExprIfTrue: Jump to dest if true
  90106. ** sqlite3ExprIfFalse: Jump to dest if false
  90107. **
  90108. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  90109. */
  90110. static void exprCodeBetween(
  90111. Parse *pParse, /* Parsing and code generating context */
  90112. Expr *pExpr, /* The BETWEEN expression */
  90113. int dest, /* Jump destination or storage location */
  90114. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  90115. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  90116. ){
  90117. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  90118. Expr compLeft; /* The x>=y term */
  90119. Expr compRight; /* The x<=z term */
  90120. Expr exprX; /* The x subexpression */
  90121. int regFree1 = 0; /* Temporary use register */
  90122. memset(&compLeft, 0, sizeof(Expr));
  90123. memset(&compRight, 0, sizeof(Expr));
  90124. memset(&exprAnd, 0, sizeof(Expr));
  90125. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90126. exprX = *pExpr->pLeft;
  90127. exprAnd.op = TK_AND;
  90128. exprAnd.pLeft = &compLeft;
  90129. exprAnd.pRight = &compRight;
  90130. compLeft.op = TK_GE;
  90131. compLeft.pLeft = &exprX;
  90132. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  90133. compRight.op = TK_LE;
  90134. compRight.pLeft = &exprX;
  90135. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  90136. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  90137. if( xJump ){
  90138. xJump(pParse, &exprAnd, dest, jumpIfNull);
  90139. }else{
  90140. /* Mark the expression is being from the ON or USING clause of a join
  90141. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  90142. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  90143. ** for clarity, but we are out of bits in the Expr.flags field so we
  90144. ** have to reuse the EP_FromJoin bit. Bummer. */
  90145. exprX.flags |= EP_FromJoin;
  90146. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  90147. }
  90148. sqlite3ReleaseTempReg(pParse, regFree1);
  90149. /* Ensure adequate test coverage */
  90150. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  90151. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  90152. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  90153. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  90154. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  90155. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  90156. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  90157. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  90158. testcase( xJump==0 );
  90159. }
  90160. /*
  90161. ** Generate code for a boolean expression such that a jump is made
  90162. ** to the label "dest" if the expression is true but execution
  90163. ** continues straight thru if the expression is false.
  90164. **
  90165. ** If the expression evaluates to NULL (neither true nor false), then
  90166. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  90167. **
  90168. ** This code depends on the fact that certain token values (ex: TK_EQ)
  90169. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  90170. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  90171. ** the make process cause these values to align. Assert()s in the code
  90172. ** below verify that the numbers are aligned correctly.
  90173. */
  90174. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  90175. Vdbe *v = pParse->pVdbe;
  90176. int op = 0;
  90177. int regFree1 = 0;
  90178. int regFree2 = 0;
  90179. int r1, r2;
  90180. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  90181. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  90182. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  90183. op = pExpr->op;
  90184. switch( op ){
  90185. case TK_AND: {
  90186. int d2 = sqlite3VdbeMakeLabel(v);
  90187. testcase( jumpIfNull==0 );
  90188. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  90189. sqlite3ExprCachePush(pParse);
  90190. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  90191. sqlite3VdbeResolveLabel(v, d2);
  90192. sqlite3ExprCachePop(pParse);
  90193. break;
  90194. }
  90195. case TK_OR: {
  90196. testcase( jumpIfNull==0 );
  90197. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  90198. sqlite3ExprCachePush(pParse);
  90199. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  90200. sqlite3ExprCachePop(pParse);
  90201. break;
  90202. }
  90203. case TK_NOT: {
  90204. testcase( jumpIfNull==0 );
  90205. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  90206. break;
  90207. }
  90208. case TK_IS:
  90209. case TK_ISNOT:
  90210. testcase( op==TK_IS );
  90211. testcase( op==TK_ISNOT );
  90212. op = (op==TK_IS) ? TK_EQ : TK_NE;
  90213. jumpIfNull = SQLITE_NULLEQ;
  90214. /* Fall thru */
  90215. case TK_LT:
  90216. case TK_LE:
  90217. case TK_GT:
  90218. case TK_GE:
  90219. case TK_NE:
  90220. case TK_EQ: {
  90221. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  90222. testcase( jumpIfNull==0 );
  90223. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  90224. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  90225. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  90226. r1, r2, dest, jumpIfNull);
  90227. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  90228. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  90229. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  90230. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  90231. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  90232. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  90233. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  90234. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  90235. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  90236. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  90237. testcase( regFree1==0 );
  90238. testcase( regFree2==0 );
  90239. break;
  90240. }
  90241. case TK_ISNULL:
  90242. case TK_NOTNULL: {
  90243. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  90244. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  90245. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  90246. sqlite3VdbeAddOp2(v, op, r1, dest);
  90247. VdbeCoverageIf(v, op==TK_ISNULL);
  90248. VdbeCoverageIf(v, op==TK_NOTNULL);
  90249. testcase( regFree1==0 );
  90250. break;
  90251. }
  90252. case TK_BETWEEN: {
  90253. testcase( jumpIfNull==0 );
  90254. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  90255. break;
  90256. }
  90257. #ifndef SQLITE_OMIT_SUBQUERY
  90258. case TK_IN: {
  90259. int destIfFalse = sqlite3VdbeMakeLabel(v);
  90260. int destIfNull = jumpIfNull ? dest : destIfFalse;
  90261. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  90262. sqlite3VdbeGoto(v, dest);
  90263. sqlite3VdbeResolveLabel(v, destIfFalse);
  90264. break;
  90265. }
  90266. #endif
  90267. default: {
  90268. default_expr:
  90269. if( exprAlwaysTrue(pExpr) ){
  90270. sqlite3VdbeGoto(v, dest);
  90271. }else if( exprAlwaysFalse(pExpr) ){
  90272. /* No-op */
  90273. }else{
  90274. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  90275. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  90276. VdbeCoverage(v);
  90277. testcase( regFree1==0 );
  90278. testcase( jumpIfNull==0 );
  90279. }
  90280. break;
  90281. }
  90282. }
  90283. sqlite3ReleaseTempReg(pParse, regFree1);
  90284. sqlite3ReleaseTempReg(pParse, regFree2);
  90285. }
  90286. /*
  90287. ** Generate code for a boolean expression such that a jump is made
  90288. ** to the label "dest" if the expression is false but execution
  90289. ** continues straight thru if the expression is true.
  90290. **
  90291. ** If the expression evaluates to NULL (neither true nor false) then
  90292. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  90293. ** is 0.
  90294. */
  90295. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  90296. Vdbe *v = pParse->pVdbe;
  90297. int op = 0;
  90298. int regFree1 = 0;
  90299. int regFree2 = 0;
  90300. int r1, r2;
  90301. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  90302. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  90303. if( pExpr==0 ) return;
  90304. /* The value of pExpr->op and op are related as follows:
  90305. **
  90306. ** pExpr->op op
  90307. ** --------- ----------
  90308. ** TK_ISNULL OP_NotNull
  90309. ** TK_NOTNULL OP_IsNull
  90310. ** TK_NE OP_Eq
  90311. ** TK_EQ OP_Ne
  90312. ** TK_GT OP_Le
  90313. ** TK_LE OP_Gt
  90314. ** TK_GE OP_Lt
  90315. ** TK_LT OP_Ge
  90316. **
  90317. ** For other values of pExpr->op, op is undefined and unused.
  90318. ** The value of TK_ and OP_ constants are arranged such that we
  90319. ** can compute the mapping above using the following expression.
  90320. ** Assert()s verify that the computation is correct.
  90321. */
  90322. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  90323. /* Verify correct alignment of TK_ and OP_ constants
  90324. */
  90325. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  90326. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  90327. assert( pExpr->op!=TK_NE || op==OP_Eq );
  90328. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  90329. assert( pExpr->op!=TK_LT || op==OP_Ge );
  90330. assert( pExpr->op!=TK_LE || op==OP_Gt );
  90331. assert( pExpr->op!=TK_GT || op==OP_Le );
  90332. assert( pExpr->op!=TK_GE || op==OP_Lt );
  90333. switch( pExpr->op ){
  90334. case TK_AND: {
  90335. testcase( jumpIfNull==0 );
  90336. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  90337. sqlite3ExprCachePush(pParse);
  90338. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  90339. sqlite3ExprCachePop(pParse);
  90340. break;
  90341. }
  90342. case TK_OR: {
  90343. int d2 = sqlite3VdbeMakeLabel(v);
  90344. testcase( jumpIfNull==0 );
  90345. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  90346. sqlite3ExprCachePush(pParse);
  90347. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  90348. sqlite3VdbeResolveLabel(v, d2);
  90349. sqlite3ExprCachePop(pParse);
  90350. break;
  90351. }
  90352. case TK_NOT: {
  90353. testcase( jumpIfNull==0 );
  90354. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  90355. break;
  90356. }
  90357. case TK_IS:
  90358. case TK_ISNOT:
  90359. testcase( pExpr->op==TK_IS );
  90360. testcase( pExpr->op==TK_ISNOT );
  90361. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  90362. jumpIfNull = SQLITE_NULLEQ;
  90363. /* Fall thru */
  90364. case TK_LT:
  90365. case TK_LE:
  90366. case TK_GT:
  90367. case TK_GE:
  90368. case TK_NE:
  90369. case TK_EQ: {
  90370. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  90371. testcase( jumpIfNull==0 );
  90372. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  90373. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  90374. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  90375. r1, r2, dest, jumpIfNull);
  90376. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  90377. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  90378. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  90379. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  90380. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  90381. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  90382. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  90383. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  90384. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  90385. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  90386. testcase( regFree1==0 );
  90387. testcase( regFree2==0 );
  90388. break;
  90389. }
  90390. case TK_ISNULL:
  90391. case TK_NOTNULL: {
  90392. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  90393. sqlite3VdbeAddOp2(v, op, r1, dest);
  90394. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  90395. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  90396. testcase( regFree1==0 );
  90397. break;
  90398. }
  90399. case TK_BETWEEN: {
  90400. testcase( jumpIfNull==0 );
  90401. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  90402. break;
  90403. }
  90404. #ifndef SQLITE_OMIT_SUBQUERY
  90405. case TK_IN: {
  90406. if( jumpIfNull ){
  90407. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  90408. }else{
  90409. int destIfNull = sqlite3VdbeMakeLabel(v);
  90410. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  90411. sqlite3VdbeResolveLabel(v, destIfNull);
  90412. }
  90413. break;
  90414. }
  90415. #endif
  90416. default: {
  90417. default_expr:
  90418. if( exprAlwaysFalse(pExpr) ){
  90419. sqlite3VdbeGoto(v, dest);
  90420. }else if( exprAlwaysTrue(pExpr) ){
  90421. /* no-op */
  90422. }else{
  90423. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  90424. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  90425. VdbeCoverage(v);
  90426. testcase( regFree1==0 );
  90427. testcase( jumpIfNull==0 );
  90428. }
  90429. break;
  90430. }
  90431. }
  90432. sqlite3ReleaseTempReg(pParse, regFree1);
  90433. sqlite3ReleaseTempReg(pParse, regFree2);
  90434. }
  90435. /*
  90436. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  90437. ** code generation, and that copy is deleted after code generation. This
  90438. ** ensures that the original pExpr is unchanged.
  90439. */
  90440. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  90441. sqlite3 *db = pParse->db;
  90442. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  90443. if( db->mallocFailed==0 ){
  90444. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  90445. }
  90446. sqlite3ExprDelete(db, pCopy);
  90447. }
  90448. /*
  90449. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  90450. ** type of expression.
  90451. **
  90452. ** If pExpr is a simple SQL value - an integer, real, string, blob
  90453. ** or NULL value - then the VDBE currently being prepared is configured
  90454. ** to re-prepare each time a new value is bound to variable pVar.
  90455. **
  90456. ** Additionally, if pExpr is a simple SQL value and the value is the
  90457. ** same as that currently bound to variable pVar, non-zero is returned.
  90458. ** Otherwise, if the values are not the same or if pExpr is not a simple
  90459. ** SQL value, zero is returned.
  90460. */
  90461. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  90462. int res = 0;
  90463. int iVar;
  90464. sqlite3_value *pL, *pR = 0;
  90465. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  90466. if( pR ){
  90467. iVar = pVar->iColumn;
  90468. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  90469. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  90470. if( pL ){
  90471. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  90472. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  90473. }
  90474. res = 0==sqlite3MemCompare(pL, pR, 0);
  90475. }
  90476. sqlite3ValueFree(pR);
  90477. sqlite3ValueFree(pL);
  90478. }
  90479. return res;
  90480. }
  90481. /*
  90482. ** Do a deep comparison of two expression trees. Return 0 if the two
  90483. ** expressions are completely identical. Return 1 if they differ only
  90484. ** by a COLLATE operator at the top level. Return 2 if there are differences
  90485. ** other than the top-level COLLATE operator.
  90486. **
  90487. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  90488. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  90489. **
  90490. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  90491. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  90492. **
  90493. ** Sometimes this routine will return 2 even if the two expressions
  90494. ** really are equivalent. If we cannot prove that the expressions are
  90495. ** identical, we return 2 just to be safe. So if this routine
  90496. ** returns 2, then you do not really know for certain if the two
  90497. ** expressions are the same. But if you get a 0 or 1 return, then you
  90498. ** can be sure the expressions are the same. In the places where
  90499. ** this routine is used, it does not hurt to get an extra 2 - that
  90500. ** just might result in some slightly slower code. But returning
  90501. ** an incorrect 0 or 1 could lead to a malfunction.
  90502. **
  90503. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  90504. ** pParse->pReprepare can be matched against literals in pB. The
  90505. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  90506. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  90507. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  90508. ** pB causes a return value of 2.
  90509. */
  90510. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  90511. u32 combinedFlags;
  90512. if( pA==0 || pB==0 ){
  90513. return pB==pA ? 0 : 2;
  90514. }
  90515. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  90516. return 0;
  90517. }
  90518. combinedFlags = pA->flags | pB->flags;
  90519. if( combinedFlags & EP_IntValue ){
  90520. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  90521. return 0;
  90522. }
  90523. return 2;
  90524. }
  90525. if( pA->op!=pB->op ){
  90526. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  90527. return 1;
  90528. }
  90529. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  90530. return 1;
  90531. }
  90532. return 2;
  90533. }
  90534. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  90535. if( pA->op==TK_FUNCTION ){
  90536. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  90537. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  90538. return pA->op==TK_COLLATE ? 1 : 2;
  90539. }
  90540. }
  90541. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  90542. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  90543. if( combinedFlags & EP_xIsSelect ) return 2;
  90544. if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  90545. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  90546. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  90547. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  90548. if( pA->iColumn!=pB->iColumn ) return 2;
  90549. if( pA->iTable!=pB->iTable
  90550. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  90551. }
  90552. }
  90553. return 0;
  90554. }
  90555. /*
  90556. ** Compare two ExprList objects. Return 0 if they are identical and
  90557. ** non-zero if they differ in any way.
  90558. **
  90559. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  90560. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  90561. **
  90562. ** This routine might return non-zero for equivalent ExprLists. The
  90563. ** only consequence will be disabled optimizations. But this routine
  90564. ** must never return 0 if the two ExprList objects are different, or
  90565. ** a malfunction will result.
  90566. **
  90567. ** Two NULL pointers are considered to be the same. But a NULL pointer
  90568. ** always differs from a non-NULL pointer.
  90569. */
  90570. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  90571. int i;
  90572. if( pA==0 && pB==0 ) return 0;
  90573. if( pA==0 || pB==0 ) return 1;
  90574. if( pA->nExpr!=pB->nExpr ) return 1;
  90575. for(i=0; i<pA->nExpr; i++){
  90576. Expr *pExprA = pA->a[i].pExpr;
  90577. Expr *pExprB = pB->a[i].pExpr;
  90578. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  90579. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  90580. }
  90581. return 0;
  90582. }
  90583. /*
  90584. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  90585. ** are ignored.
  90586. */
  90587. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  90588. return sqlite3ExprCompare(0,
  90589. sqlite3ExprSkipCollate(pA),
  90590. sqlite3ExprSkipCollate(pB),
  90591. iTab);
  90592. }
  90593. /*
  90594. ** Return true if we can prove the pE2 will always be true if pE1 is
  90595. ** true. Return false if we cannot complete the proof or if pE2 might
  90596. ** be false. Examples:
  90597. **
  90598. ** pE1: x==5 pE2: x==5 Result: true
  90599. ** pE1: x>0 pE2: x==5 Result: false
  90600. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  90601. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  90602. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  90603. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  90604. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  90605. **
  90606. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  90607. ** Expr.iTable<0 then assume a table number given by iTab.
  90608. **
  90609. ** If pParse is not NULL, then the values of bound variables in pE1 are
  90610. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  90611. ** modified to record which bound variables are referenced. If pParse
  90612. ** is NULL, then false will be returned if pE1 contains any bound variables.
  90613. **
  90614. ** When in doubt, return false. Returning true might give a performance
  90615. ** improvement. Returning false might cause a performance reduction, but
  90616. ** it will always give the correct answer and is hence always safe.
  90617. */
  90618. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  90619. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  90620. return 1;
  90621. }
  90622. if( pE2->op==TK_OR
  90623. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  90624. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  90625. ){
  90626. return 1;
  90627. }
  90628. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  90629. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  90630. testcase( pX!=pE1->pLeft );
  90631. if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
  90632. }
  90633. return 0;
  90634. }
  90635. /*
  90636. ** An instance of the following structure is used by the tree walker
  90637. ** to determine if an expression can be evaluated by reference to the
  90638. ** index only, without having to do a search for the corresponding
  90639. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  90640. ** is the cursor for the table.
  90641. */
  90642. struct IdxCover {
  90643. Index *pIdx; /* The index to be tested for coverage */
  90644. int iCur; /* Cursor number for the table corresponding to the index */
  90645. };
  90646. /*
  90647. ** Check to see if there are references to columns in table
  90648. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  90649. ** pWalker->u.pIdxCover->pIdx.
  90650. */
  90651. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  90652. if( pExpr->op==TK_COLUMN
  90653. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  90654. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  90655. ){
  90656. pWalker->eCode = 1;
  90657. return WRC_Abort;
  90658. }
  90659. return WRC_Continue;
  90660. }
  90661. /*
  90662. ** Determine if an index pIdx on table with cursor iCur contains will
  90663. ** the expression pExpr. Return true if the index does cover the
  90664. ** expression and false if the pExpr expression references table columns
  90665. ** that are not found in the index pIdx.
  90666. **
  90667. ** An index covering an expression means that the expression can be
  90668. ** evaluated using only the index and without having to lookup the
  90669. ** corresponding table entry.
  90670. */
  90671. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  90672. Expr *pExpr, /* The index to be tested */
  90673. int iCur, /* The cursor number for the corresponding table */
  90674. Index *pIdx /* The index that might be used for coverage */
  90675. ){
  90676. Walker w;
  90677. struct IdxCover xcov;
  90678. memset(&w, 0, sizeof(w));
  90679. xcov.iCur = iCur;
  90680. xcov.pIdx = pIdx;
  90681. w.xExprCallback = exprIdxCover;
  90682. w.u.pIdxCover = &xcov;
  90683. sqlite3WalkExpr(&w, pExpr);
  90684. return !w.eCode;
  90685. }
  90686. /*
  90687. ** An instance of the following structure is used by the tree walker
  90688. ** to count references to table columns in the arguments of an
  90689. ** aggregate function, in order to implement the
  90690. ** sqlite3FunctionThisSrc() routine.
  90691. */
  90692. struct SrcCount {
  90693. SrcList *pSrc; /* One particular FROM clause in a nested query */
  90694. int nThis; /* Number of references to columns in pSrcList */
  90695. int nOther; /* Number of references to columns in other FROM clauses */
  90696. };
  90697. /*
  90698. ** Count the number of references to columns.
  90699. */
  90700. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  90701. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  90702. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  90703. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  90704. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  90705. ** NEVER() will need to be removed. */
  90706. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  90707. int i;
  90708. struct SrcCount *p = pWalker->u.pSrcCount;
  90709. SrcList *pSrc = p->pSrc;
  90710. int nSrc = pSrc ? pSrc->nSrc : 0;
  90711. for(i=0; i<nSrc; i++){
  90712. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  90713. }
  90714. if( i<nSrc ){
  90715. p->nThis++;
  90716. }else{
  90717. p->nOther++;
  90718. }
  90719. }
  90720. return WRC_Continue;
  90721. }
  90722. /*
  90723. ** Determine if any of the arguments to the pExpr Function reference
  90724. ** pSrcList. Return true if they do. Also return true if the function
  90725. ** has no arguments or has only constant arguments. Return false if pExpr
  90726. ** references columns but not columns of tables found in pSrcList.
  90727. */
  90728. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  90729. Walker w;
  90730. struct SrcCount cnt;
  90731. assert( pExpr->op==TK_AGG_FUNCTION );
  90732. w.xExprCallback = exprSrcCount;
  90733. w.xSelectCallback = 0;
  90734. w.u.pSrcCount = &cnt;
  90735. cnt.pSrc = pSrcList;
  90736. cnt.nThis = 0;
  90737. cnt.nOther = 0;
  90738. sqlite3WalkExprList(&w, pExpr->x.pList);
  90739. return cnt.nThis>0 || cnt.nOther==0;
  90740. }
  90741. /*
  90742. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  90743. ** the new element. Return a negative number if malloc fails.
  90744. */
  90745. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  90746. int i;
  90747. pInfo->aCol = sqlite3ArrayAllocate(
  90748. db,
  90749. pInfo->aCol,
  90750. sizeof(pInfo->aCol[0]),
  90751. &pInfo->nColumn,
  90752. &i
  90753. );
  90754. return i;
  90755. }
  90756. /*
  90757. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  90758. ** the new element. Return a negative number if malloc fails.
  90759. */
  90760. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  90761. int i;
  90762. pInfo->aFunc = sqlite3ArrayAllocate(
  90763. db,
  90764. pInfo->aFunc,
  90765. sizeof(pInfo->aFunc[0]),
  90766. &pInfo->nFunc,
  90767. &i
  90768. );
  90769. return i;
  90770. }
  90771. /*
  90772. ** This is the xExprCallback for a tree walker. It is used to
  90773. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  90774. ** for additional information.
  90775. */
  90776. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  90777. int i;
  90778. NameContext *pNC = pWalker->u.pNC;
  90779. Parse *pParse = pNC->pParse;
  90780. SrcList *pSrcList = pNC->pSrcList;
  90781. AggInfo *pAggInfo = pNC->pAggInfo;
  90782. switch( pExpr->op ){
  90783. case TK_AGG_COLUMN:
  90784. case TK_COLUMN: {
  90785. testcase( pExpr->op==TK_AGG_COLUMN );
  90786. testcase( pExpr->op==TK_COLUMN );
  90787. /* Check to see if the column is in one of the tables in the FROM
  90788. ** clause of the aggregate query */
  90789. if( ALWAYS(pSrcList!=0) ){
  90790. struct SrcList_item *pItem = pSrcList->a;
  90791. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  90792. struct AggInfo_col *pCol;
  90793. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  90794. if( pExpr->iTable==pItem->iCursor ){
  90795. /* If we reach this point, it means that pExpr refers to a table
  90796. ** that is in the FROM clause of the aggregate query.
  90797. **
  90798. ** Make an entry for the column in pAggInfo->aCol[] if there
  90799. ** is not an entry there already.
  90800. */
  90801. int k;
  90802. pCol = pAggInfo->aCol;
  90803. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  90804. if( pCol->iTable==pExpr->iTable &&
  90805. pCol->iColumn==pExpr->iColumn ){
  90806. break;
  90807. }
  90808. }
  90809. if( (k>=pAggInfo->nColumn)
  90810. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  90811. ){
  90812. pCol = &pAggInfo->aCol[k];
  90813. pCol->pTab = pExpr->pTab;
  90814. pCol->iTable = pExpr->iTable;
  90815. pCol->iColumn = pExpr->iColumn;
  90816. pCol->iMem = ++pParse->nMem;
  90817. pCol->iSorterColumn = -1;
  90818. pCol->pExpr = pExpr;
  90819. if( pAggInfo->pGroupBy ){
  90820. int j, n;
  90821. ExprList *pGB = pAggInfo->pGroupBy;
  90822. struct ExprList_item *pTerm = pGB->a;
  90823. n = pGB->nExpr;
  90824. for(j=0; j<n; j++, pTerm++){
  90825. Expr *pE = pTerm->pExpr;
  90826. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  90827. pE->iColumn==pExpr->iColumn ){
  90828. pCol->iSorterColumn = j;
  90829. break;
  90830. }
  90831. }
  90832. }
  90833. if( pCol->iSorterColumn<0 ){
  90834. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  90835. }
  90836. }
  90837. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  90838. ** because it was there before or because we just created it).
  90839. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  90840. ** pAggInfo->aCol[] entry.
  90841. */
  90842. ExprSetVVAProperty(pExpr, EP_NoReduce);
  90843. pExpr->pAggInfo = pAggInfo;
  90844. pExpr->op = TK_AGG_COLUMN;
  90845. pExpr->iAgg = (i16)k;
  90846. break;
  90847. } /* endif pExpr->iTable==pItem->iCursor */
  90848. } /* end loop over pSrcList */
  90849. }
  90850. return WRC_Prune;
  90851. }
  90852. case TK_AGG_FUNCTION: {
  90853. if( (pNC->ncFlags & NC_InAggFunc)==0
  90854. && pWalker->walkerDepth==pExpr->op2
  90855. ){
  90856. /* Check to see if pExpr is a duplicate of another aggregate
  90857. ** function that is already in the pAggInfo structure
  90858. */
  90859. struct AggInfo_func *pItem = pAggInfo->aFunc;
  90860. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  90861. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  90862. break;
  90863. }
  90864. }
  90865. if( i>=pAggInfo->nFunc ){
  90866. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  90867. */
  90868. u8 enc = ENC(pParse->db);
  90869. i = addAggInfoFunc(pParse->db, pAggInfo);
  90870. if( i>=0 ){
  90871. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90872. pItem = &pAggInfo->aFunc[i];
  90873. pItem->pExpr = pExpr;
  90874. pItem->iMem = ++pParse->nMem;
  90875. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  90876. pItem->pFunc = sqlite3FindFunction(pParse->db,
  90877. pExpr->u.zToken,
  90878. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  90879. if( pExpr->flags & EP_Distinct ){
  90880. pItem->iDistinct = pParse->nTab++;
  90881. }else{
  90882. pItem->iDistinct = -1;
  90883. }
  90884. }
  90885. }
  90886. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  90887. */
  90888. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  90889. ExprSetVVAProperty(pExpr, EP_NoReduce);
  90890. pExpr->iAgg = (i16)i;
  90891. pExpr->pAggInfo = pAggInfo;
  90892. return WRC_Prune;
  90893. }else{
  90894. return WRC_Continue;
  90895. }
  90896. }
  90897. }
  90898. return WRC_Continue;
  90899. }
  90900. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  90901. UNUSED_PARAMETER(pSelect);
  90902. pWalker->walkerDepth++;
  90903. return WRC_Continue;
  90904. }
  90905. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  90906. UNUSED_PARAMETER(pSelect);
  90907. pWalker->walkerDepth--;
  90908. }
  90909. /*
  90910. ** Analyze the pExpr expression looking for aggregate functions and
  90911. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  90912. ** points to. Additional entries are made on the AggInfo object as
  90913. ** necessary.
  90914. **
  90915. ** This routine should only be called after the expression has been
  90916. ** analyzed by sqlite3ResolveExprNames().
  90917. */
  90918. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  90919. Walker w;
  90920. w.xExprCallback = analyzeAggregate;
  90921. w.xSelectCallback = analyzeAggregatesInSelect;
  90922. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  90923. w.walkerDepth = 0;
  90924. w.u.pNC = pNC;
  90925. assert( pNC->pSrcList!=0 );
  90926. sqlite3WalkExpr(&w, pExpr);
  90927. }
  90928. /*
  90929. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  90930. ** expression list. Return the number of errors.
  90931. **
  90932. ** If an error is found, the analysis is cut short.
  90933. */
  90934. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  90935. struct ExprList_item *pItem;
  90936. int i;
  90937. if( pList ){
  90938. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  90939. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  90940. }
  90941. }
  90942. }
  90943. /*
  90944. ** Allocate a single new register for use to hold some intermediate result.
  90945. */
  90946. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  90947. if( pParse->nTempReg==0 ){
  90948. return ++pParse->nMem;
  90949. }
  90950. return pParse->aTempReg[--pParse->nTempReg];
  90951. }
  90952. /*
  90953. ** Deallocate a register, making available for reuse for some other
  90954. ** purpose.
  90955. **
  90956. ** If a register is currently being used by the column cache, then
  90957. ** the deallocation is deferred until the column cache line that uses
  90958. ** the register becomes stale.
  90959. */
  90960. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  90961. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  90962. int i;
  90963. struct yColCache *p;
  90964. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  90965. if( p->iReg==iReg ){
  90966. p->tempReg = 1;
  90967. return;
  90968. }
  90969. }
  90970. pParse->aTempReg[pParse->nTempReg++] = iReg;
  90971. }
  90972. }
  90973. /*
  90974. ** Allocate or deallocate a block of nReg consecutive registers.
  90975. */
  90976. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  90977. int i, n;
  90978. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  90979. i = pParse->iRangeReg;
  90980. n = pParse->nRangeReg;
  90981. if( nReg<=n ){
  90982. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  90983. pParse->iRangeReg += nReg;
  90984. pParse->nRangeReg -= nReg;
  90985. }else{
  90986. i = pParse->nMem+1;
  90987. pParse->nMem += nReg;
  90988. }
  90989. return i;
  90990. }
  90991. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  90992. if( nReg==1 ){
  90993. sqlite3ReleaseTempReg(pParse, iReg);
  90994. return;
  90995. }
  90996. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  90997. if( nReg>pParse->nRangeReg ){
  90998. pParse->nRangeReg = nReg;
  90999. pParse->iRangeReg = iReg;
  91000. }
  91001. }
  91002. /*
  91003. ** Mark all temporary registers as being unavailable for reuse.
  91004. */
  91005. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  91006. pParse->nTempReg = 0;
  91007. pParse->nRangeReg = 0;
  91008. }
  91009. /*
  91010. ** Validate that no temporary register falls within the range of
  91011. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  91012. ** statements.
  91013. */
  91014. #ifdef SQLITE_DEBUG
  91015. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  91016. int i;
  91017. if( pParse->nRangeReg>0
  91018. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  91019. && pParse->iRangeReg <= iLast
  91020. ){
  91021. return 0;
  91022. }
  91023. for(i=0; i<pParse->nTempReg; i++){
  91024. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  91025. return 0;
  91026. }
  91027. }
  91028. return 1;
  91029. }
  91030. #endif /* SQLITE_DEBUG */
  91031. /************** End of expr.c ************************************************/
  91032. /************** Begin file alter.c *******************************************/
  91033. /*
  91034. ** 2005 February 15
  91035. **
  91036. ** The author disclaims copyright to this source code. In place of
  91037. ** a legal notice, here is a blessing:
  91038. **
  91039. ** May you do good and not evil.
  91040. ** May you find forgiveness for yourself and forgive others.
  91041. ** May you share freely, never taking more than you give.
  91042. **
  91043. *************************************************************************
  91044. ** This file contains C code routines that used to generate VDBE code
  91045. ** that implements the ALTER TABLE command.
  91046. */
  91047. /* #include "sqliteInt.h" */
  91048. /*
  91049. ** The code in this file only exists if we are not omitting the
  91050. ** ALTER TABLE logic from the build.
  91051. */
  91052. #ifndef SQLITE_OMIT_ALTERTABLE
  91053. /*
  91054. ** This function is used by SQL generated to implement the
  91055. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  91056. ** CREATE INDEX command. The second is a table name. The table name in
  91057. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  91058. ** argument and the result returned. Examples:
  91059. **
  91060. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  91061. ** -> 'CREATE TABLE def(a, b, c)'
  91062. **
  91063. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  91064. ** -> 'CREATE INDEX i ON def(a, b, c)'
  91065. */
  91066. static void renameTableFunc(
  91067. sqlite3_context *context,
  91068. int NotUsed,
  91069. sqlite3_value **argv
  91070. ){
  91071. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  91072. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  91073. int token;
  91074. Token tname;
  91075. unsigned char const *zCsr = zSql;
  91076. int len = 0;
  91077. char *zRet;
  91078. sqlite3 *db = sqlite3_context_db_handle(context);
  91079. UNUSED_PARAMETER(NotUsed);
  91080. /* The principle used to locate the table name in the CREATE TABLE
  91081. ** statement is that the table name is the first non-space token that
  91082. ** is immediately followed by a TK_LP or TK_USING token.
  91083. */
  91084. if( zSql ){
  91085. do {
  91086. if( !*zCsr ){
  91087. /* Ran out of input before finding an opening bracket. Return NULL. */
  91088. return;
  91089. }
  91090. /* Store the token that zCsr points to in tname. */
  91091. tname.z = (char*)zCsr;
  91092. tname.n = len;
  91093. /* Advance zCsr to the next token. Store that token type in 'token',
  91094. ** and its length in 'len' (to be used next iteration of this loop).
  91095. */
  91096. do {
  91097. zCsr += len;
  91098. len = sqlite3GetToken(zCsr, &token);
  91099. } while( token==TK_SPACE );
  91100. assert( len>0 );
  91101. } while( token!=TK_LP && token!=TK_USING );
  91102. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  91103. zSql, zTableName, tname.z+tname.n);
  91104. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  91105. }
  91106. }
  91107. /*
  91108. ** This C function implements an SQL user function that is used by SQL code
  91109. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  91110. ** of any foreign key constraints that use the table being renamed as the
  91111. ** parent table. It is passed three arguments:
  91112. **
  91113. ** 1) The complete text of the CREATE TABLE statement being modified,
  91114. ** 2) The old name of the table being renamed, and
  91115. ** 3) The new name of the table being renamed.
  91116. **
  91117. ** It returns the new CREATE TABLE statement. For example:
  91118. **
  91119. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  91120. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  91121. */
  91122. #ifndef SQLITE_OMIT_FOREIGN_KEY
  91123. static void renameParentFunc(
  91124. sqlite3_context *context,
  91125. int NotUsed,
  91126. sqlite3_value **argv
  91127. ){
  91128. sqlite3 *db = sqlite3_context_db_handle(context);
  91129. char *zOutput = 0;
  91130. char *zResult;
  91131. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  91132. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  91133. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  91134. unsigned const char *z; /* Pointer to token */
  91135. int n; /* Length of token z */
  91136. int token; /* Type of token */
  91137. UNUSED_PARAMETER(NotUsed);
  91138. if( zInput==0 || zOld==0 ) return;
  91139. for(z=zInput; *z; z=z+n){
  91140. n = sqlite3GetToken(z, &token);
  91141. if( token==TK_REFERENCES ){
  91142. char *zParent;
  91143. do {
  91144. z += n;
  91145. n = sqlite3GetToken(z, &token);
  91146. }while( token==TK_SPACE );
  91147. if( token==TK_ILLEGAL ) break;
  91148. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  91149. if( zParent==0 ) break;
  91150. sqlite3Dequote(zParent);
  91151. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  91152. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  91153. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  91154. );
  91155. sqlite3DbFree(db, zOutput);
  91156. zOutput = zOut;
  91157. zInput = &z[n];
  91158. }
  91159. sqlite3DbFree(db, zParent);
  91160. }
  91161. }
  91162. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  91163. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  91164. sqlite3DbFree(db, zOutput);
  91165. }
  91166. #endif
  91167. #ifndef SQLITE_OMIT_TRIGGER
  91168. /* This function is used by SQL generated to implement the
  91169. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  91170. ** statement. The second is a table name. The table name in the CREATE
  91171. ** TRIGGER statement is replaced with the third argument and the result
  91172. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  91173. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  91174. */
  91175. static void renameTriggerFunc(
  91176. sqlite3_context *context,
  91177. int NotUsed,
  91178. sqlite3_value **argv
  91179. ){
  91180. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  91181. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  91182. int token;
  91183. Token tname;
  91184. int dist = 3;
  91185. unsigned char const *zCsr = zSql;
  91186. int len = 0;
  91187. char *zRet;
  91188. sqlite3 *db = sqlite3_context_db_handle(context);
  91189. UNUSED_PARAMETER(NotUsed);
  91190. /* The principle used to locate the table name in the CREATE TRIGGER
  91191. ** statement is that the table name is the first token that is immediately
  91192. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  91193. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  91194. */
  91195. if( zSql ){
  91196. do {
  91197. if( !*zCsr ){
  91198. /* Ran out of input before finding the table name. Return NULL. */
  91199. return;
  91200. }
  91201. /* Store the token that zCsr points to in tname. */
  91202. tname.z = (char*)zCsr;
  91203. tname.n = len;
  91204. /* Advance zCsr to the next token. Store that token type in 'token',
  91205. ** and its length in 'len' (to be used next iteration of this loop).
  91206. */
  91207. do {
  91208. zCsr += len;
  91209. len = sqlite3GetToken(zCsr, &token);
  91210. }while( token==TK_SPACE );
  91211. assert( len>0 );
  91212. /* Variable 'dist' stores the number of tokens read since the most
  91213. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  91214. ** token is read and 'dist' equals 2, the condition stated above
  91215. ** to be met.
  91216. **
  91217. ** Note that ON cannot be a database, table or column name, so
  91218. ** there is no need to worry about syntax like
  91219. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  91220. */
  91221. dist++;
  91222. if( token==TK_DOT || token==TK_ON ){
  91223. dist = 0;
  91224. }
  91225. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  91226. /* Variable tname now contains the token that is the old table-name
  91227. ** in the CREATE TRIGGER statement.
  91228. */
  91229. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  91230. zSql, zTableName, tname.z+tname.n);
  91231. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  91232. }
  91233. }
  91234. #endif /* !SQLITE_OMIT_TRIGGER */
  91235. /*
  91236. ** Register built-in functions used to help implement ALTER TABLE
  91237. */
  91238. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  91239. static FuncDef aAlterTableFuncs[] = {
  91240. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  91241. #ifndef SQLITE_OMIT_TRIGGER
  91242. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  91243. #endif
  91244. #ifndef SQLITE_OMIT_FOREIGN_KEY
  91245. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  91246. #endif
  91247. };
  91248. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  91249. }
  91250. /*
  91251. ** This function is used to create the text of expressions of the form:
  91252. **
  91253. ** name=<constant1> OR name=<constant2> OR ...
  91254. **
  91255. ** If argument zWhere is NULL, then a pointer string containing the text
  91256. ** "name=<constant>" is returned, where <constant> is the quoted version
  91257. ** of the string passed as argument zConstant. The returned buffer is
  91258. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  91259. ** caller to ensure that it is eventually freed.
  91260. **
  91261. ** If argument zWhere is not NULL, then the string returned is
  91262. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  91263. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  91264. **
  91265. */
  91266. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  91267. char *zNew;
  91268. if( !zWhere ){
  91269. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  91270. }else{
  91271. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  91272. sqlite3DbFree(db, zWhere);
  91273. }
  91274. return zNew;
  91275. }
  91276. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  91277. /*
  91278. ** Generate the text of a WHERE expression which can be used to select all
  91279. ** tables that have foreign key constraints that refer to table pTab (i.e.
  91280. ** constraints for which pTab is the parent table) from the sqlite_master
  91281. ** table.
  91282. */
  91283. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  91284. FKey *p;
  91285. char *zWhere = 0;
  91286. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  91287. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  91288. }
  91289. return zWhere;
  91290. }
  91291. #endif
  91292. /*
  91293. ** Generate the text of a WHERE expression which can be used to select all
  91294. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  91295. ** table pTab has no temporary triggers, or is itself stored in the
  91296. ** temporary database, NULL is returned.
  91297. */
  91298. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  91299. Trigger *pTrig;
  91300. char *zWhere = 0;
  91301. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  91302. /* If the table is not located in the temp-db (in which case NULL is
  91303. ** returned, loop through the tables list of triggers. For each trigger
  91304. ** that is not part of the temp-db schema, add a clause to the WHERE
  91305. ** expression being built up in zWhere.
  91306. */
  91307. if( pTab->pSchema!=pTempSchema ){
  91308. sqlite3 *db = pParse->db;
  91309. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  91310. if( pTrig->pSchema==pTempSchema ){
  91311. zWhere = whereOrName(db, zWhere, pTrig->zName);
  91312. }
  91313. }
  91314. }
  91315. if( zWhere ){
  91316. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  91317. sqlite3DbFree(pParse->db, zWhere);
  91318. zWhere = zNew;
  91319. }
  91320. return zWhere;
  91321. }
  91322. /*
  91323. ** Generate code to drop and reload the internal representation of table
  91324. ** pTab from the database, including triggers and temporary triggers.
  91325. ** Argument zName is the name of the table in the database schema at
  91326. ** the time the generated code is executed. This can be different from
  91327. ** pTab->zName if this function is being called to code part of an
  91328. ** "ALTER TABLE RENAME TO" statement.
  91329. */
  91330. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  91331. Vdbe *v;
  91332. char *zWhere;
  91333. int iDb; /* Index of database containing pTab */
  91334. #ifndef SQLITE_OMIT_TRIGGER
  91335. Trigger *pTrig;
  91336. #endif
  91337. v = sqlite3GetVdbe(pParse);
  91338. if( NEVER(v==0) ) return;
  91339. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  91340. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  91341. assert( iDb>=0 );
  91342. #ifndef SQLITE_OMIT_TRIGGER
  91343. /* Drop any table triggers from the internal schema. */
  91344. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  91345. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  91346. assert( iTrigDb==iDb || iTrigDb==1 );
  91347. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  91348. }
  91349. #endif
  91350. /* Drop the table and index from the internal schema. */
  91351. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  91352. /* Reload the table, index and permanent trigger schemas. */
  91353. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  91354. if( !zWhere ) return;
  91355. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  91356. #ifndef SQLITE_OMIT_TRIGGER
  91357. /* Now, if the table is not stored in the temp database, reload any temp
  91358. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  91359. */
  91360. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  91361. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  91362. }
  91363. #endif
  91364. }
  91365. /*
  91366. ** Parameter zName is the name of a table that is about to be altered
  91367. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  91368. ** If the table is a system table, this function leaves an error message
  91369. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  91370. **
  91371. ** Or, if zName is not a system table, zero is returned.
  91372. */
  91373. static int isSystemTable(Parse *pParse, const char *zName){
  91374. if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  91375. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  91376. return 1;
  91377. }
  91378. return 0;
  91379. }
  91380. /*
  91381. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  91382. ** command.
  91383. */
  91384. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  91385. Parse *pParse, /* Parser context. */
  91386. SrcList *pSrc, /* The table to rename. */
  91387. Token *pName /* The new table name. */
  91388. ){
  91389. int iDb; /* Database that contains the table */
  91390. char *zDb; /* Name of database iDb */
  91391. Table *pTab; /* Table being renamed */
  91392. char *zName = 0; /* NULL-terminated version of pName */
  91393. sqlite3 *db = pParse->db; /* Database connection */
  91394. int nTabName; /* Number of UTF-8 characters in zTabName */
  91395. const char *zTabName; /* Original name of the table */
  91396. Vdbe *v;
  91397. #ifndef SQLITE_OMIT_TRIGGER
  91398. char *zWhere = 0; /* Where clause to locate temp triggers */
  91399. #endif
  91400. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  91401. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  91402. savedDbFlags = db->mDbFlags;
  91403. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  91404. assert( pSrc->nSrc==1 );
  91405. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  91406. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  91407. if( !pTab ) goto exit_rename_table;
  91408. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  91409. zDb = db->aDb[iDb].zDbSName;
  91410. db->mDbFlags |= DBFLAG_PreferBuiltin;
  91411. /* Get a NULL terminated version of the new table name. */
  91412. zName = sqlite3NameFromToken(db, pName);
  91413. if( !zName ) goto exit_rename_table;
  91414. /* Check that a table or index named 'zName' does not already exist
  91415. ** in database iDb. If so, this is an error.
  91416. */
  91417. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  91418. sqlite3ErrorMsg(pParse,
  91419. "there is already another table or index with this name: %s", zName);
  91420. goto exit_rename_table;
  91421. }
  91422. /* Make sure it is not a system table being altered, or a reserved name
  91423. ** that the table is being renamed to.
  91424. */
  91425. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  91426. goto exit_rename_table;
  91427. }
  91428. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  91429. exit_rename_table;
  91430. }
  91431. #ifndef SQLITE_OMIT_VIEW
  91432. if( pTab->pSelect ){
  91433. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  91434. goto exit_rename_table;
  91435. }
  91436. #endif
  91437. #ifndef SQLITE_OMIT_AUTHORIZATION
  91438. /* Invoke the authorization callback. */
  91439. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  91440. goto exit_rename_table;
  91441. }
  91442. #endif
  91443. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91444. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  91445. goto exit_rename_table;
  91446. }
  91447. if( IsVirtual(pTab) ){
  91448. pVTab = sqlite3GetVTable(db, pTab);
  91449. if( pVTab->pVtab->pModule->xRename==0 ){
  91450. pVTab = 0;
  91451. }
  91452. }
  91453. #endif
  91454. /* Begin a transaction for database iDb.
  91455. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  91456. ** schema). Open a statement transaction if the table is a virtual
  91457. ** table.
  91458. */
  91459. v = sqlite3GetVdbe(pParse);
  91460. if( v==0 ){
  91461. goto exit_rename_table;
  91462. }
  91463. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  91464. sqlite3ChangeCookie(pParse, iDb);
  91465. /* If this is a virtual table, invoke the xRename() function if
  91466. ** one is defined. The xRename() callback will modify the names
  91467. ** of any resources used by the v-table implementation (including other
  91468. ** SQLite tables) that are identified by the name of the virtual table.
  91469. */
  91470. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91471. if( pVTab ){
  91472. int i = ++pParse->nMem;
  91473. sqlite3VdbeLoadString(v, i, zName);
  91474. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  91475. sqlite3MayAbort(pParse);
  91476. }
  91477. #endif
  91478. /* figure out how many UTF-8 characters are in zName */
  91479. zTabName = pTab->zName;
  91480. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  91481. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  91482. if( db->flags&SQLITE_ForeignKeys ){
  91483. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  91484. ** statements corresponding to all child tables of foreign key constraints
  91485. ** for which the renamed table is the parent table. */
  91486. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  91487. sqlite3NestedParse(pParse,
  91488. "UPDATE \"%w\".%s SET "
  91489. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  91490. "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
  91491. sqlite3DbFree(db, zWhere);
  91492. }
  91493. }
  91494. #endif
  91495. /* Modify the sqlite_master table to use the new table name. */
  91496. sqlite3NestedParse(pParse,
  91497. "UPDATE %Q.%s SET "
  91498. #ifdef SQLITE_OMIT_TRIGGER
  91499. "sql = sqlite_rename_table(sql, %Q), "
  91500. #else
  91501. "sql = CASE "
  91502. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  91503. "ELSE sqlite_rename_table(sql, %Q) END, "
  91504. #endif
  91505. "tbl_name = %Q, "
  91506. "name = CASE "
  91507. "WHEN type='table' THEN %Q "
  91508. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  91509. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  91510. "ELSE name END "
  91511. "WHERE tbl_name=%Q COLLATE nocase AND "
  91512. "(type='table' OR type='index' OR type='trigger');",
  91513. zDb, MASTER_NAME, zName, zName, zName,
  91514. #ifndef SQLITE_OMIT_TRIGGER
  91515. zName,
  91516. #endif
  91517. zName, nTabName, zTabName
  91518. );
  91519. #ifndef SQLITE_OMIT_AUTOINCREMENT
  91520. /* If the sqlite_sequence table exists in this database, then update
  91521. ** it with the new table name.
  91522. */
  91523. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  91524. sqlite3NestedParse(pParse,
  91525. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  91526. zDb, zName, pTab->zName);
  91527. }
  91528. #endif
  91529. #ifndef SQLITE_OMIT_TRIGGER
  91530. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  91531. ** table. Don't do this if the table being ALTERed is itself located in
  91532. ** the temp database.
  91533. */
  91534. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  91535. sqlite3NestedParse(pParse,
  91536. "UPDATE sqlite_temp_master SET "
  91537. "sql = sqlite_rename_trigger(sql, %Q), "
  91538. "tbl_name = %Q "
  91539. "WHERE %s;", zName, zName, zWhere);
  91540. sqlite3DbFree(db, zWhere);
  91541. }
  91542. #endif
  91543. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  91544. if( db->flags&SQLITE_ForeignKeys ){
  91545. FKey *p;
  91546. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  91547. Table *pFrom = p->pFrom;
  91548. if( pFrom!=pTab ){
  91549. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  91550. }
  91551. }
  91552. }
  91553. #endif
  91554. /* Drop and reload the internal table schema. */
  91555. reloadTableSchema(pParse, pTab, zName);
  91556. exit_rename_table:
  91557. sqlite3SrcListDelete(db, pSrc);
  91558. sqlite3DbFree(db, zName);
  91559. db->mDbFlags = savedDbFlags;
  91560. }
  91561. /*
  91562. ** This function is called after an "ALTER TABLE ... ADD" statement
  91563. ** has been parsed. Argument pColDef contains the text of the new
  91564. ** column definition.
  91565. **
  91566. ** The Table structure pParse->pNewTable was extended to include
  91567. ** the new column during parsing.
  91568. */
  91569. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  91570. Table *pNew; /* Copy of pParse->pNewTable */
  91571. Table *pTab; /* Table being altered */
  91572. int iDb; /* Database number */
  91573. const char *zDb; /* Database name */
  91574. const char *zTab; /* Table name */
  91575. char *zCol; /* Null-terminated column definition */
  91576. Column *pCol; /* The new column */
  91577. Expr *pDflt; /* Default value for the new column */
  91578. sqlite3 *db; /* The database connection; */
  91579. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  91580. int r1; /* Temporary registers */
  91581. db = pParse->db;
  91582. if( pParse->nErr || db->mallocFailed ) return;
  91583. assert( v!=0 );
  91584. pNew = pParse->pNewTable;
  91585. assert( pNew );
  91586. assert( sqlite3BtreeHoldsAllMutexes(db) );
  91587. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  91588. zDb = db->aDb[iDb].zDbSName;
  91589. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  91590. pCol = &pNew->aCol[pNew->nCol-1];
  91591. pDflt = pCol->pDflt;
  91592. pTab = sqlite3FindTable(db, zTab, zDb);
  91593. assert( pTab );
  91594. #ifndef SQLITE_OMIT_AUTHORIZATION
  91595. /* Invoke the authorization callback. */
  91596. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  91597. return;
  91598. }
  91599. #endif
  91600. /* If the default value for the new column was specified with a
  91601. ** literal NULL, then set pDflt to 0. This simplifies checking
  91602. ** for an SQL NULL default below.
  91603. */
  91604. assert( pDflt==0 || pDflt->op==TK_SPAN );
  91605. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  91606. pDflt = 0;
  91607. }
  91608. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  91609. ** If there is a NOT NULL constraint, then the default value for the
  91610. ** column must not be NULL.
  91611. */
  91612. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  91613. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  91614. return;
  91615. }
  91616. if( pNew->pIndex ){
  91617. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  91618. return;
  91619. }
  91620. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  91621. sqlite3ErrorMsg(pParse,
  91622. "Cannot add a REFERENCES column with non-NULL default value");
  91623. return;
  91624. }
  91625. if( pCol->notNull && !pDflt ){
  91626. sqlite3ErrorMsg(pParse,
  91627. "Cannot add a NOT NULL column with default value NULL");
  91628. return;
  91629. }
  91630. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  91631. ** can handle (i.e. not CURRENT_TIME etc.)
  91632. */
  91633. if( pDflt ){
  91634. sqlite3_value *pVal = 0;
  91635. int rc;
  91636. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  91637. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  91638. if( rc!=SQLITE_OK ){
  91639. assert( db->mallocFailed == 1 );
  91640. return;
  91641. }
  91642. if( !pVal ){
  91643. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  91644. return;
  91645. }
  91646. sqlite3ValueFree(pVal);
  91647. }
  91648. /* Modify the CREATE TABLE statement. */
  91649. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  91650. if( zCol ){
  91651. char *zEnd = &zCol[pColDef->n-1];
  91652. u32 savedDbFlags = db->mDbFlags;
  91653. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  91654. *zEnd-- = '\0';
  91655. }
  91656. db->mDbFlags |= DBFLAG_PreferBuiltin;
  91657. sqlite3NestedParse(pParse,
  91658. "UPDATE \"%w\".%s SET "
  91659. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  91660. "WHERE type = 'table' AND name = %Q",
  91661. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  91662. zTab
  91663. );
  91664. sqlite3DbFree(db, zCol);
  91665. db->mDbFlags = savedDbFlags;
  91666. }
  91667. /* Make sure the schema version is at least 3. But do not upgrade
  91668. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  91669. ** index.
  91670. */
  91671. r1 = sqlite3GetTempReg(pParse);
  91672. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  91673. sqlite3VdbeUsesBtree(v, iDb);
  91674. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  91675. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  91676. VdbeCoverage(v);
  91677. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  91678. sqlite3ReleaseTempReg(pParse, r1);
  91679. /* Reload the schema of the modified table. */
  91680. reloadTableSchema(pParse, pTab, pTab->zName);
  91681. }
  91682. /*
  91683. ** This function is called by the parser after the table-name in
  91684. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  91685. ** pSrc is the full-name of the table being altered.
  91686. **
  91687. ** This routine makes a (partial) copy of the Table structure
  91688. ** for the table being altered and sets Parse.pNewTable to point
  91689. ** to it. Routines called by the parser as the column definition
  91690. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  91691. ** the copy. The copy of the Table structure is deleted by tokenize.c
  91692. ** after parsing is finished.
  91693. **
  91694. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  91695. ** coding the "ALTER TABLE ... ADD" statement.
  91696. */
  91697. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  91698. Table *pNew;
  91699. Table *pTab;
  91700. Vdbe *v;
  91701. int iDb;
  91702. int i;
  91703. int nAlloc;
  91704. sqlite3 *db = pParse->db;
  91705. /* Look up the table being altered. */
  91706. assert( pParse->pNewTable==0 );
  91707. assert( sqlite3BtreeHoldsAllMutexes(db) );
  91708. if( db->mallocFailed ) goto exit_begin_add_column;
  91709. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  91710. if( !pTab ) goto exit_begin_add_column;
  91711. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91712. if( IsVirtual(pTab) ){
  91713. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  91714. goto exit_begin_add_column;
  91715. }
  91716. #endif
  91717. /* Make sure this is not an attempt to ALTER a view. */
  91718. if( pTab->pSelect ){
  91719. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  91720. goto exit_begin_add_column;
  91721. }
  91722. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  91723. goto exit_begin_add_column;
  91724. }
  91725. assert( pTab->addColOffset>0 );
  91726. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91727. /* Put a copy of the Table struct in Parse.pNewTable for the
  91728. ** sqlite3AddColumn() function and friends to modify. But modify
  91729. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  91730. ** prefix, we insure that the name will not collide with an existing
  91731. ** table because user table are not allowed to have the "sqlite_"
  91732. ** prefix on their name.
  91733. */
  91734. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  91735. if( !pNew ) goto exit_begin_add_column;
  91736. pParse->pNewTable = pNew;
  91737. pNew->nTabRef = 1;
  91738. pNew->nCol = pTab->nCol;
  91739. assert( pNew->nCol>0 );
  91740. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  91741. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  91742. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  91743. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  91744. if( !pNew->aCol || !pNew->zName ){
  91745. assert( db->mallocFailed );
  91746. goto exit_begin_add_column;
  91747. }
  91748. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  91749. for(i=0; i<pNew->nCol; i++){
  91750. Column *pCol = &pNew->aCol[i];
  91751. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  91752. pCol->zColl = 0;
  91753. pCol->pDflt = 0;
  91754. }
  91755. pNew->pSchema = db->aDb[iDb].pSchema;
  91756. pNew->addColOffset = pTab->addColOffset;
  91757. pNew->nTabRef = 1;
  91758. /* Begin a transaction and increment the schema cookie. */
  91759. sqlite3BeginWriteOperation(pParse, 0, iDb);
  91760. v = sqlite3GetVdbe(pParse);
  91761. if( !v ) goto exit_begin_add_column;
  91762. sqlite3ChangeCookie(pParse, iDb);
  91763. exit_begin_add_column:
  91764. sqlite3SrcListDelete(db, pSrc);
  91765. return;
  91766. }
  91767. #endif /* SQLITE_ALTER_TABLE */
  91768. /************** End of alter.c ***********************************************/
  91769. /************** Begin file analyze.c *****************************************/
  91770. /*
  91771. ** 2005-07-08
  91772. **
  91773. ** The author disclaims copyright to this source code. In place of
  91774. ** a legal notice, here is a blessing:
  91775. **
  91776. ** May you do good and not evil.
  91777. ** May you find forgiveness for yourself and forgive others.
  91778. ** May you share freely, never taking more than you give.
  91779. **
  91780. *************************************************************************
  91781. ** This file contains code associated with the ANALYZE command.
  91782. **
  91783. ** The ANALYZE command gather statistics about the content of tables
  91784. ** and indices. These statistics are made available to the query planner
  91785. ** to help it make better decisions about how to perform queries.
  91786. **
  91787. ** The following system tables are or have been supported:
  91788. **
  91789. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  91790. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  91791. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  91792. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  91793. **
  91794. ** Additional tables might be added in future releases of SQLite.
  91795. ** The sqlite_stat2 table is not created or used unless the SQLite version
  91796. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  91797. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  91798. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  91799. ** created and used by SQLite versions 3.7.9 and later and with
  91800. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  91801. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  91802. ** version of sqlite_stat3 and is only available when compiled with
  91803. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  91804. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  91805. ** are both enabled, then STAT4 takes precedence.
  91806. **
  91807. ** For most applications, sqlite_stat1 provides all the statistics required
  91808. ** for the query planner to make good choices.
  91809. **
  91810. ** Format of sqlite_stat1:
  91811. **
  91812. ** There is normally one row per index, with the index identified by the
  91813. ** name in the idx column. The tbl column is the name of the table to
  91814. ** which the index belongs. In each such row, the stat column will be
  91815. ** a string consisting of a list of integers. The first integer in this
  91816. ** list is the number of rows in the index. (This is the same as the
  91817. ** number of rows in the table, except for partial indices.) The second
  91818. ** integer is the average number of rows in the index that have the same
  91819. ** value in the first column of the index. The third integer is the average
  91820. ** number of rows in the index that have the same value for the first two
  91821. ** columns. The N-th integer (for N>1) is the average number of rows in
  91822. ** the index which have the same value for the first N-1 columns. For
  91823. ** a K-column index, there will be K+1 integers in the stat column. If
  91824. ** the index is unique, then the last integer will be 1.
  91825. **
  91826. ** The list of integers in the stat column can optionally be followed
  91827. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  91828. ** must be separated from the last integer by a single space. If the
  91829. ** "unordered" keyword is present, then the query planner assumes that
  91830. ** the index is unordered and will not use the index for a range query.
  91831. **
  91832. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  91833. ** column contains a single integer which is the (estimated) number of
  91834. ** rows in the table identified by sqlite_stat1.tbl.
  91835. **
  91836. ** Format of sqlite_stat2:
  91837. **
  91838. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  91839. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  91840. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  91841. ** about the distribution of keys within an index. The index is identified by
  91842. ** the "idx" column and the "tbl" column is the name of the table to which
  91843. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  91844. ** table for each index.
  91845. **
  91846. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  91847. ** inclusive are samples of the left-most key value in the index taken at
  91848. ** evenly spaced points along the index. Let the number of samples be S
  91849. ** (10 in the standard build) and let C be the number of rows in the index.
  91850. ** Then the sampled rows are given by:
  91851. **
  91852. ** rownumber = (i*C*2 + C)/(S*2)
  91853. **
  91854. ** For i between 0 and S-1. Conceptually, the index space is divided into
  91855. ** S uniform buckets and the samples are the middle row from each bucket.
  91856. **
  91857. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  91858. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  91859. ** writes the sqlite_stat2 table. This version of SQLite only supports
  91860. ** sqlite_stat3.
  91861. **
  91862. ** Format for sqlite_stat3:
  91863. **
  91864. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  91865. ** sqlite_stat4 format will be described first. Further information
  91866. ** about sqlite_stat3 follows the sqlite_stat4 description.
  91867. **
  91868. ** Format for sqlite_stat4:
  91869. **
  91870. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  91871. ** to aid the query planner in choosing good indices based on the values
  91872. ** that indexed columns are compared against in the WHERE clauses of
  91873. ** queries.
  91874. **
  91875. ** The sqlite_stat4 table contains multiple entries for each index.
  91876. ** The idx column names the index and the tbl column is the table of the
  91877. ** index. If the idx and tbl columns are the same, then the sample is
  91878. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  91879. ** binary encoding of a key from the index. The nEq column is a
  91880. ** list of integers. The first integer is the approximate number
  91881. ** of entries in the index whose left-most column exactly matches
  91882. ** the left-most column of the sample. The second integer in nEq
  91883. ** is the approximate number of entries in the index where the
  91884. ** first two columns match the first two columns of the sample.
  91885. ** And so forth. nLt is another list of integers that show the approximate
  91886. ** number of entries that are strictly less than the sample. The first
  91887. ** integer in nLt contains the number of entries in the index where the
  91888. ** left-most column is less than the left-most column of the sample.
  91889. ** The K-th integer in the nLt entry is the number of index entries
  91890. ** where the first K columns are less than the first K columns of the
  91891. ** sample. The nDLt column is like nLt except that it contains the
  91892. ** number of distinct entries in the index that are less than the
  91893. ** sample.
  91894. **
  91895. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  91896. ** The ANALYZE command will typically generate sqlite_stat4 tables
  91897. ** that contain between 10 and 40 samples which are distributed across
  91898. ** the key space, though not uniformly, and which include samples with
  91899. ** large nEq values.
  91900. **
  91901. ** Format for sqlite_stat3 redux:
  91902. **
  91903. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  91904. ** looks at the left-most column of the index. The sqlite_stat3.sample
  91905. ** column contains the actual value of the left-most column instead
  91906. ** of a blob encoding of the complete index key as is found in
  91907. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  91908. ** all contain just a single integer which is the same as the first
  91909. ** integer in the equivalent columns in sqlite_stat4.
  91910. */
  91911. #ifndef SQLITE_OMIT_ANALYZE
  91912. /* #include "sqliteInt.h" */
  91913. #if defined(SQLITE_ENABLE_STAT4)
  91914. # define IsStat4 1
  91915. # define IsStat3 0
  91916. #elif defined(SQLITE_ENABLE_STAT3)
  91917. # define IsStat4 0
  91918. # define IsStat3 1
  91919. #else
  91920. # define IsStat4 0
  91921. # define IsStat3 0
  91922. # undef SQLITE_STAT4_SAMPLES
  91923. # define SQLITE_STAT4_SAMPLES 1
  91924. #endif
  91925. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  91926. /*
  91927. ** This routine generates code that opens the sqlite_statN tables.
  91928. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  91929. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  91930. ** appropriate compile-time options are provided.
  91931. **
  91932. ** If the sqlite_statN tables do not previously exist, it is created.
  91933. **
  91934. ** Argument zWhere may be a pointer to a buffer containing a table name,
  91935. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  91936. ** the sqlite_statN tables associated with the named table are deleted.
  91937. ** If zWhere==0, then code is generated to delete all stat table entries.
  91938. */
  91939. static void openStatTable(
  91940. Parse *pParse, /* Parsing context */
  91941. int iDb, /* The database we are looking in */
  91942. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  91943. const char *zWhere, /* Delete entries for this table or index */
  91944. const char *zWhereType /* Either "tbl" or "idx" */
  91945. ){
  91946. static const struct {
  91947. const char *zName;
  91948. const char *zCols;
  91949. } aTable[] = {
  91950. { "sqlite_stat1", "tbl,idx,stat" },
  91951. #if defined(SQLITE_ENABLE_STAT4)
  91952. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  91953. { "sqlite_stat3", 0 },
  91954. #elif defined(SQLITE_ENABLE_STAT3)
  91955. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  91956. { "sqlite_stat4", 0 },
  91957. #else
  91958. { "sqlite_stat3", 0 },
  91959. { "sqlite_stat4", 0 },
  91960. #endif
  91961. };
  91962. int i;
  91963. sqlite3 *db = pParse->db;
  91964. Db *pDb;
  91965. Vdbe *v = sqlite3GetVdbe(pParse);
  91966. int aRoot[ArraySize(aTable)];
  91967. u8 aCreateTbl[ArraySize(aTable)];
  91968. if( v==0 ) return;
  91969. assert( sqlite3BtreeHoldsAllMutexes(db) );
  91970. assert( sqlite3VdbeDb(v)==db );
  91971. pDb = &db->aDb[iDb];
  91972. /* Create new statistic tables if they do not exist, or clear them
  91973. ** if they do already exist.
  91974. */
  91975. for(i=0; i<ArraySize(aTable); i++){
  91976. const char *zTab = aTable[i].zName;
  91977. Table *pStat;
  91978. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  91979. if( aTable[i].zCols ){
  91980. /* The sqlite_statN table does not exist. Create it. Note that a
  91981. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  91982. ** of the new table in register pParse->regRoot. This is important
  91983. ** because the OpenWrite opcode below will be needing it. */
  91984. sqlite3NestedParse(pParse,
  91985. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  91986. );
  91987. aRoot[i] = pParse->regRoot;
  91988. aCreateTbl[i] = OPFLAG_P2ISREG;
  91989. }
  91990. }else{
  91991. /* The table already exists. If zWhere is not NULL, delete all entries
  91992. ** associated with the table zWhere. If zWhere is NULL, delete the
  91993. ** entire contents of the table. */
  91994. aRoot[i] = pStat->tnum;
  91995. aCreateTbl[i] = 0;
  91996. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  91997. if( zWhere ){
  91998. sqlite3NestedParse(pParse,
  91999. "DELETE FROM %Q.%s WHERE %s=%Q",
  92000. pDb->zDbSName, zTab, zWhereType, zWhere
  92001. );
  92002. }else{
  92003. /* The sqlite_stat[134] table already exists. Delete all rows. */
  92004. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  92005. }
  92006. }
  92007. }
  92008. /* Open the sqlite_stat[134] tables for writing. */
  92009. for(i=0; aTable[i].zCols; i++){
  92010. assert( i<ArraySize(aTable) );
  92011. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  92012. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  92013. VdbeComment((v, aTable[i].zName));
  92014. }
  92015. }
  92016. /*
  92017. ** Recommended number of samples for sqlite_stat4
  92018. */
  92019. #ifndef SQLITE_STAT4_SAMPLES
  92020. # define SQLITE_STAT4_SAMPLES 24
  92021. #endif
  92022. /*
  92023. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  92024. ** share an instance of the following structure to hold their state
  92025. ** information.
  92026. */
  92027. typedef struct Stat4Accum Stat4Accum;
  92028. typedef struct Stat4Sample Stat4Sample;
  92029. struct Stat4Sample {
  92030. tRowcnt *anEq; /* sqlite_stat4.nEq */
  92031. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  92032. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92033. tRowcnt *anLt; /* sqlite_stat4.nLt */
  92034. union {
  92035. i64 iRowid; /* Rowid in main table of the key */
  92036. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  92037. } u;
  92038. u32 nRowid; /* Sizeof aRowid[] */
  92039. u8 isPSample; /* True if a periodic sample */
  92040. int iCol; /* If !isPSample, the reason for inclusion */
  92041. u32 iHash; /* Tiebreaker hash */
  92042. #endif
  92043. };
  92044. struct Stat4Accum {
  92045. tRowcnt nRow; /* Number of rows in the entire table */
  92046. tRowcnt nPSample; /* How often to do a periodic sample */
  92047. int nCol; /* Number of columns in index + pk/rowid */
  92048. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  92049. int mxSample; /* Maximum number of samples to accumulate */
  92050. Stat4Sample current; /* Current row as a Stat4Sample */
  92051. u32 iPrn; /* Pseudo-random number used for sampling */
  92052. Stat4Sample *aBest; /* Array of nCol best samples */
  92053. int iMin; /* Index in a[] of entry with minimum score */
  92054. int nSample; /* Current number of samples */
  92055. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  92056. int iGet; /* Index of current sample accessed by stat_get() */
  92057. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  92058. sqlite3 *db; /* Database connection, for malloc() */
  92059. };
  92060. /* Reclaim memory used by a Stat4Sample
  92061. */
  92062. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92063. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  92064. assert( db!=0 );
  92065. if( p->nRowid ){
  92066. sqlite3DbFree(db, p->u.aRowid);
  92067. p->nRowid = 0;
  92068. }
  92069. }
  92070. #endif
  92071. /* Initialize the BLOB value of a ROWID
  92072. */
  92073. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92074. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  92075. assert( db!=0 );
  92076. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  92077. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  92078. if( p->u.aRowid ){
  92079. p->nRowid = n;
  92080. memcpy(p->u.aRowid, pData, n);
  92081. }else{
  92082. p->nRowid = 0;
  92083. }
  92084. }
  92085. #endif
  92086. /* Initialize the INTEGER value of a ROWID.
  92087. */
  92088. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92089. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  92090. assert( db!=0 );
  92091. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  92092. p->nRowid = 0;
  92093. p->u.iRowid = iRowid;
  92094. }
  92095. #endif
  92096. /*
  92097. ** Copy the contents of object (*pFrom) into (*pTo).
  92098. */
  92099. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92100. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  92101. pTo->isPSample = pFrom->isPSample;
  92102. pTo->iCol = pFrom->iCol;
  92103. pTo->iHash = pFrom->iHash;
  92104. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  92105. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  92106. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  92107. if( pFrom->nRowid ){
  92108. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  92109. }else{
  92110. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  92111. }
  92112. }
  92113. #endif
  92114. /*
  92115. ** Reclaim all memory of a Stat4Accum structure.
  92116. */
  92117. static void stat4Destructor(void *pOld){
  92118. Stat4Accum *p = (Stat4Accum*)pOld;
  92119. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92120. int i;
  92121. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  92122. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  92123. sampleClear(p->db, &p->current);
  92124. #endif
  92125. sqlite3DbFree(p->db, p);
  92126. }
  92127. /*
  92128. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  92129. ** are:
  92130. ** N: The number of columns in the index including the rowid/pk (note 1)
  92131. ** K: The number of columns in the index excluding the rowid/pk.
  92132. ** C: The number of rows in the index (note 2)
  92133. **
  92134. ** Note 1: In the special case of the covering index that implements a
  92135. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  92136. ** total number of columns in the table.
  92137. **
  92138. ** Note 2: C is only used for STAT3 and STAT4.
  92139. **
  92140. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  92141. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  92142. ** PRIMARY KEY of the table. The covering index that implements the
  92143. ** original WITHOUT ROWID table as N==K as a special case.
  92144. **
  92145. ** This routine allocates the Stat4Accum object in heap memory. The return
  92146. ** value is a pointer to the Stat4Accum object. The datatype of the
  92147. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  92148. ** object.
  92149. */
  92150. static void statInit(
  92151. sqlite3_context *context,
  92152. int argc,
  92153. sqlite3_value **argv
  92154. ){
  92155. Stat4Accum *p;
  92156. int nCol; /* Number of columns in index being sampled */
  92157. int nKeyCol; /* Number of key columns */
  92158. int nColUp; /* nCol rounded up for alignment */
  92159. int n; /* Bytes of space to allocate */
  92160. sqlite3 *db; /* Database connection */
  92161. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92162. int mxSample = SQLITE_STAT4_SAMPLES;
  92163. #endif
  92164. /* Decode the three function arguments */
  92165. UNUSED_PARAMETER(argc);
  92166. nCol = sqlite3_value_int(argv[0]);
  92167. assert( nCol>0 );
  92168. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  92169. nKeyCol = sqlite3_value_int(argv[1]);
  92170. assert( nKeyCol<=nCol );
  92171. assert( nKeyCol>0 );
  92172. /* Allocate the space required for the Stat4Accum object */
  92173. n = sizeof(*p)
  92174. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  92175. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  92176. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92177. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  92178. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  92179. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  92180. #endif
  92181. ;
  92182. db = sqlite3_context_db_handle(context);
  92183. p = sqlite3DbMallocZero(db, n);
  92184. if( p==0 ){
  92185. sqlite3_result_error_nomem(context);
  92186. return;
  92187. }
  92188. p->db = db;
  92189. p->nRow = 0;
  92190. p->nCol = nCol;
  92191. p->nKeyCol = nKeyCol;
  92192. p->current.anDLt = (tRowcnt*)&p[1];
  92193. p->current.anEq = &p->current.anDLt[nColUp];
  92194. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92195. {
  92196. u8 *pSpace; /* Allocated space not yet assigned */
  92197. int i; /* Used to iterate through p->aSample[] */
  92198. p->iGet = -1;
  92199. p->mxSample = mxSample;
  92200. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  92201. p->current.anLt = &p->current.anEq[nColUp];
  92202. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  92203. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  92204. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  92205. p->aBest = &p->a[mxSample];
  92206. pSpace = (u8*)(&p->a[mxSample+nCol]);
  92207. for(i=0; i<(mxSample+nCol); i++){
  92208. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  92209. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  92210. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  92211. }
  92212. assert( (pSpace - (u8*)p)==n );
  92213. for(i=0; i<nCol; i++){
  92214. p->aBest[i].iCol = i;
  92215. }
  92216. }
  92217. #endif
  92218. /* Return a pointer to the allocated object to the caller. Note that
  92219. ** only the pointer (the 2nd parameter) matters. The size of the object
  92220. ** (given by the 3rd parameter) is never used and can be any positive
  92221. ** value. */
  92222. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  92223. }
  92224. static const FuncDef statInitFuncdef = {
  92225. 2+IsStat34, /* nArg */
  92226. SQLITE_UTF8, /* funcFlags */
  92227. 0, /* pUserData */
  92228. 0, /* pNext */
  92229. statInit, /* xSFunc */
  92230. 0, /* xFinalize */
  92231. "stat_init", /* zName */
  92232. {0}
  92233. };
  92234. #ifdef SQLITE_ENABLE_STAT4
  92235. /*
  92236. ** pNew and pOld are both candidate non-periodic samples selected for
  92237. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  92238. ** considering only any trailing columns and the sample hash value, this
  92239. ** function returns true if sample pNew is to be preferred over pOld.
  92240. ** In other words, if we assume that the cardinalities of the selected
  92241. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  92242. **
  92243. ** This function assumes that for each argument sample, the contents of
  92244. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  92245. */
  92246. static int sampleIsBetterPost(
  92247. Stat4Accum *pAccum,
  92248. Stat4Sample *pNew,
  92249. Stat4Sample *pOld
  92250. ){
  92251. int nCol = pAccum->nCol;
  92252. int i;
  92253. assert( pNew->iCol==pOld->iCol );
  92254. for(i=pNew->iCol+1; i<nCol; i++){
  92255. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  92256. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  92257. }
  92258. if( pNew->iHash>pOld->iHash ) return 1;
  92259. return 0;
  92260. }
  92261. #endif
  92262. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92263. /*
  92264. ** Return true if pNew is to be preferred over pOld.
  92265. **
  92266. ** This function assumes that for each argument sample, the contents of
  92267. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  92268. */
  92269. static int sampleIsBetter(
  92270. Stat4Accum *pAccum,
  92271. Stat4Sample *pNew,
  92272. Stat4Sample *pOld
  92273. ){
  92274. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  92275. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  92276. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  92277. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  92278. if( (nEqNew>nEqOld) ) return 1;
  92279. #ifdef SQLITE_ENABLE_STAT4
  92280. if( nEqNew==nEqOld ){
  92281. if( pNew->iCol<pOld->iCol ) return 1;
  92282. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  92283. }
  92284. return 0;
  92285. #else
  92286. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  92287. #endif
  92288. }
  92289. /*
  92290. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  92291. ** remove the least desirable sample from p->a[] to make room.
  92292. */
  92293. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  92294. Stat4Sample *pSample = 0;
  92295. int i;
  92296. assert( IsStat4 || nEqZero==0 );
  92297. #ifdef SQLITE_ENABLE_STAT4
  92298. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  92299. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  92300. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  92301. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  92302. if( nEqZero>p->nMaxEqZero ){
  92303. p->nMaxEqZero = nEqZero;
  92304. }
  92305. if( pNew->isPSample==0 ){
  92306. Stat4Sample *pUpgrade = 0;
  92307. assert( pNew->anEq[pNew->iCol]>0 );
  92308. /* This sample is being added because the prefix that ends in column
  92309. ** iCol occurs many times in the table. However, if we have already
  92310. ** added a sample that shares this prefix, there is no need to add
  92311. ** this one. Instead, upgrade the priority of the highest priority
  92312. ** existing sample that shares this prefix. */
  92313. for(i=p->nSample-1; i>=0; i--){
  92314. Stat4Sample *pOld = &p->a[i];
  92315. if( pOld->anEq[pNew->iCol]==0 ){
  92316. if( pOld->isPSample ) return;
  92317. assert( pOld->iCol>pNew->iCol );
  92318. assert( sampleIsBetter(p, pNew, pOld) );
  92319. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  92320. pUpgrade = pOld;
  92321. }
  92322. }
  92323. }
  92324. if( pUpgrade ){
  92325. pUpgrade->iCol = pNew->iCol;
  92326. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  92327. goto find_new_min;
  92328. }
  92329. }
  92330. #endif
  92331. /* If necessary, remove sample iMin to make room for the new sample. */
  92332. if( p->nSample>=p->mxSample ){
  92333. Stat4Sample *pMin = &p->a[p->iMin];
  92334. tRowcnt *anEq = pMin->anEq;
  92335. tRowcnt *anLt = pMin->anLt;
  92336. tRowcnt *anDLt = pMin->anDLt;
  92337. sampleClear(p->db, pMin);
  92338. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  92339. pSample = &p->a[p->nSample-1];
  92340. pSample->nRowid = 0;
  92341. pSample->anEq = anEq;
  92342. pSample->anDLt = anDLt;
  92343. pSample->anLt = anLt;
  92344. p->nSample = p->mxSample-1;
  92345. }
  92346. /* The "rows less-than" for the rowid column must be greater than that
  92347. ** for the last sample in the p->a[] array. Otherwise, the samples would
  92348. ** be out of order. */
  92349. #ifdef SQLITE_ENABLE_STAT4
  92350. assert( p->nSample==0
  92351. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  92352. #endif
  92353. /* Insert the new sample */
  92354. pSample = &p->a[p->nSample];
  92355. sampleCopy(p, pSample, pNew);
  92356. p->nSample++;
  92357. /* Zero the first nEqZero entries in the anEq[] array. */
  92358. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  92359. #ifdef SQLITE_ENABLE_STAT4
  92360. find_new_min:
  92361. #endif
  92362. if( p->nSample>=p->mxSample ){
  92363. int iMin = -1;
  92364. for(i=0; i<p->mxSample; i++){
  92365. if( p->a[i].isPSample ) continue;
  92366. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  92367. iMin = i;
  92368. }
  92369. }
  92370. assert( iMin>=0 );
  92371. p->iMin = iMin;
  92372. }
  92373. }
  92374. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92375. /*
  92376. ** Field iChng of the index being scanned has changed. So at this point
  92377. ** p->current contains a sample that reflects the previous row of the
  92378. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  92379. ** correct at this point.
  92380. */
  92381. static void samplePushPrevious(Stat4Accum *p, int iChng){
  92382. #ifdef SQLITE_ENABLE_STAT4
  92383. int i;
  92384. /* Check if any samples from the aBest[] array should be pushed
  92385. ** into IndexSample.a[] at this point. */
  92386. for(i=(p->nCol-2); i>=iChng; i--){
  92387. Stat4Sample *pBest = &p->aBest[i];
  92388. pBest->anEq[i] = p->current.anEq[i];
  92389. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  92390. sampleInsert(p, pBest, i);
  92391. }
  92392. }
  92393. /* Check that no sample contains an anEq[] entry with an index of
  92394. ** p->nMaxEqZero or greater set to zero. */
  92395. for(i=p->nSample-1; i>=0; i--){
  92396. int j;
  92397. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  92398. }
  92399. /* Update the anEq[] fields of any samples already collected. */
  92400. if( iChng<p->nMaxEqZero ){
  92401. for(i=p->nSample-1; i>=0; i--){
  92402. int j;
  92403. for(j=iChng; j<p->nCol; j++){
  92404. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  92405. }
  92406. }
  92407. p->nMaxEqZero = iChng;
  92408. }
  92409. #endif
  92410. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  92411. if( iChng==0 ){
  92412. tRowcnt nLt = p->current.anLt[0];
  92413. tRowcnt nEq = p->current.anEq[0];
  92414. /* Check if this is to be a periodic sample. If so, add it. */
  92415. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  92416. p->current.isPSample = 1;
  92417. sampleInsert(p, &p->current, 0);
  92418. p->current.isPSample = 0;
  92419. }else
  92420. /* Or if it is a non-periodic sample. Add it in this case too. */
  92421. if( p->nSample<p->mxSample
  92422. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  92423. ){
  92424. sampleInsert(p, &p->current, 0);
  92425. }
  92426. }
  92427. #endif
  92428. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  92429. UNUSED_PARAMETER( p );
  92430. UNUSED_PARAMETER( iChng );
  92431. #endif
  92432. }
  92433. /*
  92434. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  92435. ** Arguments:
  92436. **
  92437. ** P Pointer to the Stat4Accum object created by stat_init()
  92438. ** C Index of left-most column to differ from previous row
  92439. ** R Rowid for the current row. Might be a key record for
  92440. ** WITHOUT ROWID tables.
  92441. **
  92442. ** This SQL function always returns NULL. It's purpose it to accumulate
  92443. ** statistical data and/or samples in the Stat4Accum object about the
  92444. ** index being analyzed. The stat_get() SQL function will later be used to
  92445. ** extract relevant information for constructing the sqlite_statN tables.
  92446. **
  92447. ** The R parameter is only used for STAT3 and STAT4
  92448. */
  92449. static void statPush(
  92450. sqlite3_context *context,
  92451. int argc,
  92452. sqlite3_value **argv
  92453. ){
  92454. int i;
  92455. /* The three function arguments */
  92456. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  92457. int iChng = sqlite3_value_int(argv[1]);
  92458. UNUSED_PARAMETER( argc );
  92459. UNUSED_PARAMETER( context );
  92460. assert( p->nCol>0 );
  92461. assert( iChng<p->nCol );
  92462. if( p->nRow==0 ){
  92463. /* This is the first call to this function. Do initialization. */
  92464. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  92465. }else{
  92466. /* Second and subsequent calls get processed here */
  92467. samplePushPrevious(p, iChng);
  92468. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  92469. ** to the current row of the index. */
  92470. for(i=0; i<iChng; i++){
  92471. p->current.anEq[i]++;
  92472. }
  92473. for(i=iChng; i<p->nCol; i++){
  92474. p->current.anDLt[i]++;
  92475. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92476. p->current.anLt[i] += p->current.anEq[i];
  92477. #endif
  92478. p->current.anEq[i] = 1;
  92479. }
  92480. }
  92481. p->nRow++;
  92482. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92483. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  92484. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  92485. }else{
  92486. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  92487. sqlite3_value_blob(argv[2]));
  92488. }
  92489. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  92490. #endif
  92491. #ifdef SQLITE_ENABLE_STAT4
  92492. {
  92493. tRowcnt nLt = p->current.anLt[p->nCol-1];
  92494. /* Check if this is to be a periodic sample. If so, add it. */
  92495. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  92496. p->current.isPSample = 1;
  92497. p->current.iCol = 0;
  92498. sampleInsert(p, &p->current, p->nCol-1);
  92499. p->current.isPSample = 0;
  92500. }
  92501. /* Update the aBest[] array. */
  92502. for(i=0; i<(p->nCol-1); i++){
  92503. p->current.iCol = i;
  92504. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  92505. sampleCopy(p, &p->aBest[i], &p->current);
  92506. }
  92507. }
  92508. }
  92509. #endif
  92510. }
  92511. static const FuncDef statPushFuncdef = {
  92512. 2+IsStat34, /* nArg */
  92513. SQLITE_UTF8, /* funcFlags */
  92514. 0, /* pUserData */
  92515. 0, /* pNext */
  92516. statPush, /* xSFunc */
  92517. 0, /* xFinalize */
  92518. "stat_push", /* zName */
  92519. {0}
  92520. };
  92521. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  92522. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  92523. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  92524. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  92525. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  92526. /*
  92527. ** Implementation of the stat_get(P,J) SQL function. This routine is
  92528. ** used to query statistical information that has been gathered into
  92529. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  92530. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  92531. ** The content to returned is determined by the parameter J
  92532. ** which is one of the STAT_GET_xxxx values defined above.
  92533. **
  92534. ** The stat_get(P,J) function is not available to generic SQL. It is
  92535. ** inserted as part of a manually constructed bytecode program. (See
  92536. ** the callStatGet() routine below.) It is guaranteed that the P
  92537. ** parameter will always be a poiner to a Stat4Accum object, never a
  92538. ** NULL.
  92539. **
  92540. ** If neither STAT3 nor STAT4 are enabled, then J is always
  92541. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  92542. ** a one-parameter function, stat_get(P), that always returns the
  92543. ** stat1 table entry information.
  92544. */
  92545. static void statGet(
  92546. sqlite3_context *context,
  92547. int argc,
  92548. sqlite3_value **argv
  92549. ){
  92550. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  92551. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92552. /* STAT3 and STAT4 have a parameter on this routine. */
  92553. int eCall = sqlite3_value_int(argv[1]);
  92554. assert( argc==2 );
  92555. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  92556. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  92557. || eCall==STAT_GET_NDLT
  92558. );
  92559. if( eCall==STAT_GET_STAT1 )
  92560. #else
  92561. assert( argc==1 );
  92562. #endif
  92563. {
  92564. /* Return the value to store in the "stat" column of the sqlite_stat1
  92565. ** table for this index.
  92566. **
  92567. ** The value is a string composed of a list of integers describing
  92568. ** the index. The first integer in the list is the total number of
  92569. ** entries in the index. There is one additional integer in the list
  92570. ** for each indexed column. This additional integer is an estimate of
  92571. ** the number of rows matched by a stabbing query on the index using
  92572. ** a key with the corresponding number of fields. In other words,
  92573. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  92574. ** "100 10 2", then SQLite estimates that:
  92575. **
  92576. ** * the index contains 100 rows,
  92577. ** * "WHERE a=?" matches 10 rows, and
  92578. ** * "WHERE a=? AND b=?" matches 2 rows.
  92579. **
  92580. ** If D is the count of distinct values and K is the total number of
  92581. ** rows, then each estimate is computed as:
  92582. **
  92583. ** I = (K+D-1)/D
  92584. */
  92585. char *z;
  92586. int i;
  92587. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  92588. if( zRet==0 ){
  92589. sqlite3_result_error_nomem(context);
  92590. return;
  92591. }
  92592. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  92593. z = zRet + sqlite3Strlen30(zRet);
  92594. for(i=0; i<p->nKeyCol; i++){
  92595. u64 nDistinct = p->current.anDLt[i] + 1;
  92596. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  92597. sqlite3_snprintf(24, z, " %llu", iVal);
  92598. z += sqlite3Strlen30(z);
  92599. assert( p->current.anEq[i] );
  92600. }
  92601. assert( z[0]=='\0' && z>zRet );
  92602. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  92603. }
  92604. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92605. else if( eCall==STAT_GET_ROWID ){
  92606. if( p->iGet<0 ){
  92607. samplePushPrevious(p, 0);
  92608. p->iGet = 0;
  92609. }
  92610. if( p->iGet<p->nSample ){
  92611. Stat4Sample *pS = p->a + p->iGet;
  92612. if( pS->nRowid==0 ){
  92613. sqlite3_result_int64(context, pS->u.iRowid);
  92614. }else{
  92615. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  92616. SQLITE_TRANSIENT);
  92617. }
  92618. }
  92619. }else{
  92620. tRowcnt *aCnt = 0;
  92621. assert( p->iGet<p->nSample );
  92622. switch( eCall ){
  92623. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  92624. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  92625. default: {
  92626. aCnt = p->a[p->iGet].anDLt;
  92627. p->iGet++;
  92628. break;
  92629. }
  92630. }
  92631. if( IsStat3 ){
  92632. sqlite3_result_int64(context, (i64)aCnt[0]);
  92633. }else{
  92634. char *zRet = sqlite3MallocZero(p->nCol * 25);
  92635. if( zRet==0 ){
  92636. sqlite3_result_error_nomem(context);
  92637. }else{
  92638. int i;
  92639. char *z = zRet;
  92640. for(i=0; i<p->nCol; i++){
  92641. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  92642. z += sqlite3Strlen30(z);
  92643. }
  92644. assert( z[0]=='\0' && z>zRet );
  92645. z[-1] = '\0';
  92646. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  92647. }
  92648. }
  92649. }
  92650. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92651. #ifndef SQLITE_DEBUG
  92652. UNUSED_PARAMETER( argc );
  92653. #endif
  92654. }
  92655. static const FuncDef statGetFuncdef = {
  92656. 1+IsStat34, /* nArg */
  92657. SQLITE_UTF8, /* funcFlags */
  92658. 0, /* pUserData */
  92659. 0, /* pNext */
  92660. statGet, /* xSFunc */
  92661. 0, /* xFinalize */
  92662. "stat_get", /* zName */
  92663. {0}
  92664. };
  92665. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  92666. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  92667. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92668. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  92669. #elif SQLITE_DEBUG
  92670. assert( iParam==STAT_GET_STAT1 );
  92671. #else
  92672. UNUSED_PARAMETER( iParam );
  92673. #endif
  92674. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  92675. (char*)&statGetFuncdef, P4_FUNCDEF);
  92676. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  92677. }
  92678. /*
  92679. ** Generate code to do an analysis of all indices associated with
  92680. ** a single table.
  92681. */
  92682. static void analyzeOneTable(
  92683. Parse *pParse, /* Parser context */
  92684. Table *pTab, /* Table whose indices are to be analyzed */
  92685. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  92686. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  92687. int iMem, /* Available memory locations begin here */
  92688. int iTab /* Next available cursor */
  92689. ){
  92690. sqlite3 *db = pParse->db; /* Database handle */
  92691. Index *pIdx; /* An index to being analyzed */
  92692. int iIdxCur; /* Cursor open on index being analyzed */
  92693. int iTabCur; /* Table cursor */
  92694. Vdbe *v; /* The virtual machine being built up */
  92695. int i; /* Loop counter */
  92696. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  92697. int iDb; /* Index of database containing pTab */
  92698. u8 needTableCnt = 1; /* True to count the table */
  92699. int regNewRowid = iMem++; /* Rowid for the inserted record */
  92700. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  92701. int regChng = iMem++; /* Index of changed index field */
  92702. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92703. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  92704. #endif
  92705. int regTemp = iMem++; /* Temporary use register */
  92706. int regTabname = iMem++; /* Register containing table name */
  92707. int regIdxname = iMem++; /* Register containing index name */
  92708. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  92709. int regPrev = iMem; /* MUST BE LAST (see below) */
  92710. pParse->nMem = MAX(pParse->nMem, iMem);
  92711. v = sqlite3GetVdbe(pParse);
  92712. if( v==0 || NEVER(pTab==0) ){
  92713. return;
  92714. }
  92715. if( pTab->tnum==0 ){
  92716. /* Do not gather statistics on views or virtual tables */
  92717. return;
  92718. }
  92719. if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
  92720. /* Do not gather statistics on system tables */
  92721. return;
  92722. }
  92723. assert( sqlite3BtreeHoldsAllMutexes(db) );
  92724. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  92725. assert( iDb>=0 );
  92726. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92727. #ifndef SQLITE_OMIT_AUTHORIZATION
  92728. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  92729. db->aDb[iDb].zDbSName ) ){
  92730. return;
  92731. }
  92732. #endif
  92733. /* Establish a read-lock on the table at the shared-cache level.
  92734. ** Open a read-only cursor on the table. Also allocate a cursor number
  92735. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  92736. ** this time though. */
  92737. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  92738. iTabCur = iTab++;
  92739. iIdxCur = iTab++;
  92740. pParse->nTab = MAX(pParse->nTab, iTab);
  92741. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  92742. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  92743. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  92744. int nCol; /* Number of columns in pIdx. "N" */
  92745. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  92746. int addrNextRow; /* Address of "next_row:" */
  92747. const char *zIdxName; /* Name of the index */
  92748. int nColTest; /* Number of columns to test for changes */
  92749. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  92750. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  92751. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  92752. nCol = pIdx->nKeyCol;
  92753. zIdxName = pTab->zName;
  92754. nColTest = nCol - 1;
  92755. }else{
  92756. nCol = pIdx->nColumn;
  92757. zIdxName = pIdx->zName;
  92758. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  92759. }
  92760. /* Populate the register containing the index name. */
  92761. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  92762. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  92763. /*
  92764. ** Pseudo-code for loop that calls stat_push():
  92765. **
  92766. ** Rewind csr
  92767. ** if eof(csr) goto end_of_scan;
  92768. ** regChng = 0
  92769. ** goto chng_addr_0;
  92770. **
  92771. ** next_row:
  92772. ** regChng = 0
  92773. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  92774. ** regChng = 1
  92775. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  92776. ** ...
  92777. ** regChng = N
  92778. ** goto chng_addr_N
  92779. **
  92780. ** chng_addr_0:
  92781. ** regPrev(0) = idx(0)
  92782. ** chng_addr_1:
  92783. ** regPrev(1) = idx(1)
  92784. ** ...
  92785. **
  92786. ** endDistinctTest:
  92787. ** regRowid = idx(rowid)
  92788. ** stat_push(P, regChng, regRowid)
  92789. ** Next csr
  92790. ** if !eof(csr) goto next_row;
  92791. **
  92792. ** end_of_scan:
  92793. */
  92794. /* Make sure there are enough memory cells allocated to accommodate
  92795. ** the regPrev array and a trailing rowid (the rowid slot is required
  92796. ** when building a record to insert into the sample column of
  92797. ** the sqlite_stat4 table. */
  92798. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  92799. /* Open a read-only cursor on the index being analyzed. */
  92800. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  92801. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  92802. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  92803. VdbeComment((v, "%s", pIdx->zName));
  92804. /* Invoke the stat_init() function. The arguments are:
  92805. **
  92806. ** (1) the number of columns in the index including the rowid
  92807. ** (or for a WITHOUT ROWID table, the number of PK columns),
  92808. ** (2) the number of columns in the key without the rowid/pk
  92809. ** (3) the number of rows in the index,
  92810. **
  92811. **
  92812. ** The third argument is only used for STAT3 and STAT4
  92813. */
  92814. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92815. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  92816. #endif
  92817. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  92818. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  92819. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  92820. (char*)&statInitFuncdef, P4_FUNCDEF);
  92821. sqlite3VdbeChangeP5(v, 2+IsStat34);
  92822. /* Implementation of the following:
  92823. **
  92824. ** Rewind csr
  92825. ** if eof(csr) goto end_of_scan;
  92826. ** regChng = 0
  92827. ** goto next_push_0;
  92828. **
  92829. */
  92830. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  92831. VdbeCoverage(v);
  92832. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  92833. addrNextRow = sqlite3VdbeCurrentAddr(v);
  92834. if( nColTest>0 ){
  92835. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  92836. int *aGotoChng; /* Array of jump instruction addresses */
  92837. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  92838. if( aGotoChng==0 ) continue;
  92839. /*
  92840. ** next_row:
  92841. ** regChng = 0
  92842. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  92843. ** regChng = 1
  92844. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  92845. ** ...
  92846. ** regChng = N
  92847. ** goto endDistinctTest
  92848. */
  92849. sqlite3VdbeAddOp0(v, OP_Goto);
  92850. addrNextRow = sqlite3VdbeCurrentAddr(v);
  92851. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  92852. /* For a single-column UNIQUE index, once we have found a non-NULL
  92853. ** row, we know that all the rest will be distinct, so skip
  92854. ** subsequent distinctness tests. */
  92855. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  92856. VdbeCoverage(v);
  92857. }
  92858. for(i=0; i<nColTest; i++){
  92859. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  92860. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  92861. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  92862. aGotoChng[i] =
  92863. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  92864. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  92865. VdbeCoverage(v);
  92866. }
  92867. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  92868. sqlite3VdbeGoto(v, endDistinctTest);
  92869. /*
  92870. ** chng_addr_0:
  92871. ** regPrev(0) = idx(0)
  92872. ** chng_addr_1:
  92873. ** regPrev(1) = idx(1)
  92874. ** ...
  92875. */
  92876. sqlite3VdbeJumpHere(v, addrNextRow-1);
  92877. for(i=0; i<nColTest; i++){
  92878. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  92879. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  92880. }
  92881. sqlite3VdbeResolveLabel(v, endDistinctTest);
  92882. sqlite3DbFree(db, aGotoChng);
  92883. }
  92884. /*
  92885. ** chng_addr_N:
  92886. ** regRowid = idx(rowid) // STAT34 only
  92887. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  92888. ** Next csr
  92889. ** if !eof(csr) goto next_row;
  92890. */
  92891. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92892. assert( regRowid==(regStat4+2) );
  92893. if( HasRowid(pTab) ){
  92894. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  92895. }else{
  92896. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  92897. int j, k, regKey;
  92898. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  92899. for(j=0; j<pPk->nKeyCol; j++){
  92900. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  92901. assert( k>=0 && k<pIdx->nColumn );
  92902. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  92903. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  92904. }
  92905. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  92906. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  92907. }
  92908. #endif
  92909. assert( regChng==(regStat4+1) );
  92910. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  92911. (char*)&statPushFuncdef, P4_FUNCDEF);
  92912. sqlite3VdbeChangeP5(v, 2+IsStat34);
  92913. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  92914. /* Add the entry to the stat1 table. */
  92915. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  92916. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  92917. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  92918. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  92919. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  92920. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  92921. /* Add the entries to the stat3 or stat4 table. */
  92922. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92923. {
  92924. int regEq = regStat1;
  92925. int regLt = regStat1+1;
  92926. int regDLt = regStat1+2;
  92927. int regSample = regStat1+3;
  92928. int regCol = regStat1+4;
  92929. int regSampleRowid = regCol + nCol;
  92930. int addrNext;
  92931. int addrIsNull;
  92932. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  92933. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  92934. addrNext = sqlite3VdbeCurrentAddr(v);
  92935. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  92936. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  92937. VdbeCoverage(v);
  92938. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  92939. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  92940. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  92941. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  92942. /* We know that the regSampleRowid row exists because it was read by
  92943. ** the previous loop. Thus the not-found jump of seekOp will never
  92944. ** be taken */
  92945. VdbeCoverageNeverTaken(v);
  92946. #ifdef SQLITE_ENABLE_STAT3
  92947. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  92948. #else
  92949. for(i=0; i<nCol; i++){
  92950. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  92951. }
  92952. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  92953. #endif
  92954. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  92955. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  92956. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  92957. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  92958. sqlite3VdbeJumpHere(v, addrIsNull);
  92959. }
  92960. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92961. /* End of analysis */
  92962. sqlite3VdbeJumpHere(v, addrRewind);
  92963. }
  92964. /* Create a single sqlite_stat1 entry containing NULL as the index
  92965. ** name and the row count as the content.
  92966. */
  92967. if( pOnlyIdx==0 && needTableCnt ){
  92968. VdbeComment((v, "%s", pTab->zName));
  92969. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  92970. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  92971. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  92972. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  92973. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  92974. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  92975. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  92976. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  92977. sqlite3VdbeJumpHere(v, jZeroRows);
  92978. }
  92979. }
  92980. /*
  92981. ** Generate code that will cause the most recent index analysis to
  92982. ** be loaded into internal hash tables where is can be used.
  92983. */
  92984. static void loadAnalysis(Parse *pParse, int iDb){
  92985. Vdbe *v = sqlite3GetVdbe(pParse);
  92986. if( v ){
  92987. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  92988. }
  92989. }
  92990. /*
  92991. ** Generate code that will do an analysis of an entire database
  92992. */
  92993. static void analyzeDatabase(Parse *pParse, int iDb){
  92994. sqlite3 *db = pParse->db;
  92995. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  92996. HashElem *k;
  92997. int iStatCur;
  92998. int iMem;
  92999. int iTab;
  93000. sqlite3BeginWriteOperation(pParse, 0, iDb);
  93001. iStatCur = pParse->nTab;
  93002. pParse->nTab += 3;
  93003. openStatTable(pParse, iDb, iStatCur, 0, 0);
  93004. iMem = pParse->nMem+1;
  93005. iTab = pParse->nTab;
  93006. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93007. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  93008. Table *pTab = (Table*)sqliteHashData(k);
  93009. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  93010. }
  93011. loadAnalysis(pParse, iDb);
  93012. }
  93013. /*
  93014. ** Generate code that will do an analysis of a single table in
  93015. ** a database. If pOnlyIdx is not NULL then it is a single index
  93016. ** in pTab that should be analyzed.
  93017. */
  93018. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  93019. int iDb;
  93020. int iStatCur;
  93021. assert( pTab!=0 );
  93022. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  93023. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  93024. sqlite3BeginWriteOperation(pParse, 0, iDb);
  93025. iStatCur = pParse->nTab;
  93026. pParse->nTab += 3;
  93027. if( pOnlyIdx ){
  93028. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  93029. }else{
  93030. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  93031. }
  93032. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  93033. loadAnalysis(pParse, iDb);
  93034. }
  93035. /*
  93036. ** Generate code for the ANALYZE command. The parser calls this routine
  93037. ** when it recognizes an ANALYZE command.
  93038. **
  93039. ** ANALYZE -- 1
  93040. ** ANALYZE <database> -- 2
  93041. ** ANALYZE ?<database>.?<tablename> -- 3
  93042. **
  93043. ** Form 1 causes all indices in all attached databases to be analyzed.
  93044. ** Form 2 analyzes all indices the single database named.
  93045. ** Form 3 analyzes all indices associated with the named table.
  93046. */
  93047. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  93048. sqlite3 *db = pParse->db;
  93049. int iDb;
  93050. int i;
  93051. char *z, *zDb;
  93052. Table *pTab;
  93053. Index *pIdx;
  93054. Token *pTableName;
  93055. Vdbe *v;
  93056. /* Read the database schema. If an error occurs, leave an error message
  93057. ** and code in pParse and return NULL. */
  93058. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  93059. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  93060. return;
  93061. }
  93062. assert( pName2!=0 || pName1==0 );
  93063. if( pName1==0 ){
  93064. /* Form 1: Analyze everything */
  93065. for(i=0; i<db->nDb; i++){
  93066. if( i==1 ) continue; /* Do not analyze the TEMP database */
  93067. analyzeDatabase(pParse, i);
  93068. }
  93069. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  93070. /* Analyze the schema named as the argument */
  93071. analyzeDatabase(pParse, iDb);
  93072. }else{
  93073. /* Form 3: Analyze the table or index named as an argument */
  93074. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  93075. if( iDb>=0 ){
  93076. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  93077. z = sqlite3NameFromToken(db, pTableName);
  93078. if( z ){
  93079. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  93080. analyzeTable(pParse, pIdx->pTable, pIdx);
  93081. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  93082. analyzeTable(pParse, pTab, 0);
  93083. }
  93084. sqlite3DbFree(db, z);
  93085. }
  93086. }
  93087. }
  93088. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  93089. sqlite3VdbeAddOp0(v, OP_Expire);
  93090. }
  93091. }
  93092. /*
  93093. ** Used to pass information from the analyzer reader through to the
  93094. ** callback routine.
  93095. */
  93096. typedef struct analysisInfo analysisInfo;
  93097. struct analysisInfo {
  93098. sqlite3 *db;
  93099. const char *zDatabase;
  93100. };
  93101. /*
  93102. ** The first argument points to a nul-terminated string containing a
  93103. ** list of space separated integers. Read the first nOut of these into
  93104. ** the array aOut[].
  93105. */
  93106. static void decodeIntArray(
  93107. char *zIntArray, /* String containing int array to decode */
  93108. int nOut, /* Number of slots in aOut[] */
  93109. tRowcnt *aOut, /* Store integers here */
  93110. LogEst *aLog, /* Or, if aOut==0, here */
  93111. Index *pIndex /* Handle extra flags for this index, if not NULL */
  93112. ){
  93113. char *z = zIntArray;
  93114. int c;
  93115. int i;
  93116. tRowcnt v;
  93117. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93118. if( z==0 ) z = "";
  93119. #else
  93120. assert( z!=0 );
  93121. #endif
  93122. for(i=0; *z && i<nOut; i++){
  93123. v = 0;
  93124. while( (c=z[0])>='0' && c<='9' ){
  93125. v = v*10 + c - '0';
  93126. z++;
  93127. }
  93128. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93129. if( aOut ) aOut[i] = v;
  93130. if( aLog ) aLog[i] = sqlite3LogEst(v);
  93131. #else
  93132. assert( aOut==0 );
  93133. UNUSED_PARAMETER(aOut);
  93134. assert( aLog!=0 );
  93135. aLog[i] = sqlite3LogEst(v);
  93136. #endif
  93137. if( *z==' ' ) z++;
  93138. }
  93139. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  93140. assert( pIndex!=0 ); {
  93141. #else
  93142. if( pIndex ){
  93143. #endif
  93144. pIndex->bUnordered = 0;
  93145. pIndex->noSkipScan = 0;
  93146. while( z[0] ){
  93147. if( sqlite3_strglob("unordered*", z)==0 ){
  93148. pIndex->bUnordered = 1;
  93149. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  93150. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  93151. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  93152. pIndex->noSkipScan = 1;
  93153. }
  93154. #ifdef SQLITE_ENABLE_COSTMULT
  93155. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  93156. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  93157. }
  93158. #endif
  93159. while( z[0]!=0 && z[0]!=' ' ) z++;
  93160. while( z[0]==' ' ) z++;
  93161. }
  93162. }
  93163. }
  93164. /*
  93165. ** This callback is invoked once for each index when reading the
  93166. ** sqlite_stat1 table.
  93167. **
  93168. ** argv[0] = name of the table
  93169. ** argv[1] = name of the index (might be NULL)
  93170. ** argv[2] = results of analysis - on integer for each column
  93171. **
  93172. ** Entries for which argv[1]==NULL simply record the number of rows in
  93173. ** the table.
  93174. */
  93175. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  93176. analysisInfo *pInfo = (analysisInfo*)pData;
  93177. Index *pIndex;
  93178. Table *pTable;
  93179. const char *z;
  93180. assert( argc==3 );
  93181. UNUSED_PARAMETER2(NotUsed, argc);
  93182. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  93183. return 0;
  93184. }
  93185. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  93186. if( pTable==0 ){
  93187. return 0;
  93188. }
  93189. if( argv[1]==0 ){
  93190. pIndex = 0;
  93191. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  93192. pIndex = sqlite3PrimaryKeyIndex(pTable);
  93193. }else{
  93194. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  93195. }
  93196. z = argv[2];
  93197. if( pIndex ){
  93198. tRowcnt *aiRowEst = 0;
  93199. int nCol = pIndex->nKeyCol+1;
  93200. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93201. /* Index.aiRowEst may already be set here if there are duplicate
  93202. ** sqlite_stat1 entries for this index. In that case just clobber
  93203. ** the old data with the new instead of allocating a new array. */
  93204. if( pIndex->aiRowEst==0 ){
  93205. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  93206. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  93207. }
  93208. aiRowEst = pIndex->aiRowEst;
  93209. #endif
  93210. pIndex->bUnordered = 0;
  93211. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  93212. pIndex->hasStat1 = 1;
  93213. if( pIndex->pPartIdxWhere==0 ){
  93214. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  93215. pTable->tabFlags |= TF_HasStat1;
  93216. }
  93217. }else{
  93218. Index fakeIdx;
  93219. fakeIdx.szIdxRow = pTable->szTabRow;
  93220. #ifdef SQLITE_ENABLE_COSTMULT
  93221. fakeIdx.pTable = pTable;
  93222. #endif
  93223. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  93224. pTable->szTabRow = fakeIdx.szIdxRow;
  93225. pTable->tabFlags |= TF_HasStat1;
  93226. }
  93227. return 0;
  93228. }
  93229. /*
  93230. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  93231. ** and its contents.
  93232. */
  93233. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  93234. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93235. if( pIdx->aSample ){
  93236. int j;
  93237. for(j=0; j<pIdx->nSample; j++){
  93238. IndexSample *p = &pIdx->aSample[j];
  93239. sqlite3DbFree(db, p->p);
  93240. }
  93241. sqlite3DbFree(db, pIdx->aSample);
  93242. }
  93243. if( db && db->pnBytesFreed==0 ){
  93244. pIdx->nSample = 0;
  93245. pIdx->aSample = 0;
  93246. }
  93247. #else
  93248. UNUSED_PARAMETER(db);
  93249. UNUSED_PARAMETER(pIdx);
  93250. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  93251. }
  93252. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93253. /*
  93254. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  93255. ** stored in pIdx->aSample[].
  93256. */
  93257. static void initAvgEq(Index *pIdx){
  93258. if( pIdx ){
  93259. IndexSample *aSample = pIdx->aSample;
  93260. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  93261. int iCol;
  93262. int nCol = 1;
  93263. if( pIdx->nSampleCol>1 ){
  93264. /* If this is stat4 data, then calculate aAvgEq[] values for all
  93265. ** sample columns except the last. The last is always set to 1, as
  93266. ** once the trailing PK fields are considered all index keys are
  93267. ** unique. */
  93268. nCol = pIdx->nSampleCol-1;
  93269. pIdx->aAvgEq[nCol] = 1;
  93270. }
  93271. for(iCol=0; iCol<nCol; iCol++){
  93272. int nSample = pIdx->nSample;
  93273. int i; /* Used to iterate through samples */
  93274. tRowcnt sumEq = 0; /* Sum of the nEq values */
  93275. tRowcnt avgEq = 0;
  93276. tRowcnt nRow; /* Number of rows in index */
  93277. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  93278. i64 nDist100; /* Number of distinct values in index */
  93279. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  93280. nRow = pFinal->anLt[iCol];
  93281. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  93282. nSample--;
  93283. }else{
  93284. nRow = pIdx->aiRowEst[0];
  93285. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  93286. }
  93287. pIdx->nRowEst0 = nRow;
  93288. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  93289. ** occur in the stat4 table for this index. Set sumEq to the sum of
  93290. ** the nEq values for column iCol for the same set (adding the value
  93291. ** only once where there exist duplicate prefixes). */
  93292. for(i=0; i<nSample; i++){
  93293. if( i==(pIdx->nSample-1)
  93294. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  93295. ){
  93296. sumEq += aSample[i].anEq[iCol];
  93297. nSum100 += 100;
  93298. }
  93299. }
  93300. if( nDist100>nSum100 && sumEq<nRow ){
  93301. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  93302. }
  93303. if( avgEq==0 ) avgEq = 1;
  93304. pIdx->aAvgEq[iCol] = avgEq;
  93305. }
  93306. }
  93307. }
  93308. /*
  93309. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  93310. ** is supplied instead, find the PRIMARY KEY index for that table.
  93311. */
  93312. static Index *findIndexOrPrimaryKey(
  93313. sqlite3 *db,
  93314. const char *zName,
  93315. const char *zDb
  93316. ){
  93317. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  93318. if( pIdx==0 ){
  93319. Table *pTab = sqlite3FindTable(db, zName, zDb);
  93320. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  93321. }
  93322. return pIdx;
  93323. }
  93324. /*
  93325. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  93326. ** into the relevant Index.aSample[] arrays.
  93327. **
  93328. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  93329. ** data equivalent to the following (statements are different for stat3,
  93330. ** see the caller of this function for details):
  93331. **
  93332. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  93333. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  93334. **
  93335. ** where %Q is replaced with the database name before the SQL is executed.
  93336. */
  93337. static int loadStatTbl(
  93338. sqlite3 *db, /* Database handle */
  93339. int bStat3, /* Assume single column records only */
  93340. const char *zSql1, /* SQL statement 1 (see above) */
  93341. const char *zSql2, /* SQL statement 2 (see above) */
  93342. const char *zDb /* Database name (e.g. "main") */
  93343. ){
  93344. int rc; /* Result codes from subroutines */
  93345. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  93346. char *zSql; /* Text of the SQL statement */
  93347. Index *pPrevIdx = 0; /* Previous index in the loop */
  93348. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  93349. assert( db->lookaside.bDisable );
  93350. zSql = sqlite3MPrintf(db, zSql1, zDb);
  93351. if( !zSql ){
  93352. return SQLITE_NOMEM_BKPT;
  93353. }
  93354. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  93355. sqlite3DbFree(db, zSql);
  93356. if( rc ) return rc;
  93357. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  93358. int nIdxCol = 1; /* Number of columns in stat4 records */
  93359. char *zIndex; /* Index name */
  93360. Index *pIdx; /* Pointer to the index object */
  93361. int nSample; /* Number of samples */
  93362. int nByte; /* Bytes of space required */
  93363. int i; /* Bytes of space required */
  93364. tRowcnt *pSpace;
  93365. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  93366. if( zIndex==0 ) continue;
  93367. nSample = sqlite3_column_int(pStmt, 1);
  93368. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  93369. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  93370. /* Index.nSample is non-zero at this point if data has already been
  93371. ** loaded from the stat4 table. In this case ignore stat3 data. */
  93372. if( pIdx==0 || pIdx->nSample ) continue;
  93373. if( bStat3==0 ){
  93374. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  93375. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  93376. nIdxCol = pIdx->nKeyCol;
  93377. }else{
  93378. nIdxCol = pIdx->nColumn;
  93379. }
  93380. }
  93381. pIdx->nSampleCol = nIdxCol;
  93382. nByte = sizeof(IndexSample) * nSample;
  93383. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  93384. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  93385. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  93386. if( pIdx->aSample==0 ){
  93387. sqlite3_finalize(pStmt);
  93388. return SQLITE_NOMEM_BKPT;
  93389. }
  93390. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  93391. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  93392. for(i=0; i<nSample; i++){
  93393. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  93394. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  93395. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  93396. }
  93397. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  93398. }
  93399. rc = sqlite3_finalize(pStmt);
  93400. if( rc ) return rc;
  93401. zSql = sqlite3MPrintf(db, zSql2, zDb);
  93402. if( !zSql ){
  93403. return SQLITE_NOMEM_BKPT;
  93404. }
  93405. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  93406. sqlite3DbFree(db, zSql);
  93407. if( rc ) return rc;
  93408. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  93409. char *zIndex; /* Index name */
  93410. Index *pIdx; /* Pointer to the index object */
  93411. int nCol = 1; /* Number of columns in index */
  93412. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  93413. if( zIndex==0 ) continue;
  93414. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  93415. if( pIdx==0 ) continue;
  93416. /* This next condition is true if data has already been loaded from
  93417. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  93418. nCol = pIdx->nSampleCol;
  93419. if( bStat3 && nCol>1 ) continue;
  93420. if( pIdx!=pPrevIdx ){
  93421. initAvgEq(pPrevIdx);
  93422. pPrevIdx = pIdx;
  93423. }
  93424. pSample = &pIdx->aSample[pIdx->nSample];
  93425. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  93426. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  93427. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  93428. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  93429. ** This is in case the sample record is corrupted. In that case, the
  93430. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  93431. ** end of the allocated buffer before it realizes it is dealing with
  93432. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  93433. ** a buffer overread. */
  93434. pSample->n = sqlite3_column_bytes(pStmt, 4);
  93435. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  93436. if( pSample->p==0 ){
  93437. sqlite3_finalize(pStmt);
  93438. return SQLITE_NOMEM_BKPT;
  93439. }
  93440. if( pSample->n ){
  93441. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  93442. }
  93443. pIdx->nSample++;
  93444. }
  93445. rc = sqlite3_finalize(pStmt);
  93446. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  93447. return rc;
  93448. }
  93449. /*
  93450. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  93451. ** the Index.aSample[] arrays of all indices.
  93452. */
  93453. static int loadStat4(sqlite3 *db, const char *zDb){
  93454. int rc = SQLITE_OK; /* Result codes from subroutines */
  93455. assert( db->lookaside.bDisable );
  93456. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  93457. rc = loadStatTbl(db, 0,
  93458. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  93459. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  93460. zDb
  93461. );
  93462. }
  93463. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  93464. rc = loadStatTbl(db, 1,
  93465. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  93466. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  93467. zDb
  93468. );
  93469. }
  93470. return rc;
  93471. }
  93472. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  93473. /*
  93474. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  93475. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  93476. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  93477. ** Index.aSample[] arrays.
  93478. **
  93479. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  93480. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  93481. ** during compilation and the sqlite_stat3/4 table is present, no data is
  93482. ** read from it.
  93483. **
  93484. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  93485. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  93486. ** returned. However, in this case, data is read from the sqlite_stat1
  93487. ** table (if it is present) before returning.
  93488. **
  93489. ** If an OOM error occurs, this function always sets db->mallocFailed.
  93490. ** This means if the caller does not care about other errors, the return
  93491. ** code may be ignored.
  93492. */
  93493. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  93494. analysisInfo sInfo;
  93495. HashElem *i;
  93496. char *zSql;
  93497. int rc = SQLITE_OK;
  93498. Schema *pSchema = db->aDb[iDb].pSchema;
  93499. assert( iDb>=0 && iDb<db->nDb );
  93500. assert( db->aDb[iDb].pBt!=0 );
  93501. /* Clear any prior statistics */
  93502. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93503. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  93504. Table *pTab = sqliteHashData(i);
  93505. pTab->tabFlags &= ~TF_HasStat1;
  93506. }
  93507. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  93508. Index *pIdx = sqliteHashData(i);
  93509. pIdx->hasStat1 = 0;
  93510. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93511. sqlite3DeleteIndexSamples(db, pIdx);
  93512. pIdx->aSample = 0;
  93513. #endif
  93514. }
  93515. /* Load new statistics out of the sqlite_stat1 table */
  93516. sInfo.db = db;
  93517. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  93518. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  93519. zSql = sqlite3MPrintf(db,
  93520. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  93521. if( zSql==0 ){
  93522. rc = SQLITE_NOMEM_BKPT;
  93523. }else{
  93524. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  93525. sqlite3DbFree(db, zSql);
  93526. }
  93527. }
  93528. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  93529. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93530. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  93531. Index *pIdx = sqliteHashData(i);
  93532. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  93533. }
  93534. /* Load the statistics from the sqlite_stat4 table. */
  93535. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93536. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  93537. db->lookaside.bDisable++;
  93538. rc = loadStat4(db, sInfo.zDatabase);
  93539. db->lookaside.bDisable--;
  93540. }
  93541. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  93542. Index *pIdx = sqliteHashData(i);
  93543. sqlite3_free(pIdx->aiRowEst);
  93544. pIdx->aiRowEst = 0;
  93545. }
  93546. #endif
  93547. if( rc==SQLITE_NOMEM ){
  93548. sqlite3OomFault(db);
  93549. }
  93550. return rc;
  93551. }
  93552. #endif /* SQLITE_OMIT_ANALYZE */
  93553. /************** End of analyze.c *********************************************/
  93554. /************** Begin file attach.c ******************************************/
  93555. /*
  93556. ** 2003 April 6
  93557. **
  93558. ** The author disclaims copyright to this source code. In place of
  93559. ** a legal notice, here is a blessing:
  93560. **
  93561. ** May you do good and not evil.
  93562. ** May you find forgiveness for yourself and forgive others.
  93563. ** May you share freely, never taking more than you give.
  93564. **
  93565. *************************************************************************
  93566. ** This file contains code used to implement the ATTACH and DETACH commands.
  93567. */
  93568. /* #include "sqliteInt.h" */
  93569. #ifndef SQLITE_OMIT_ATTACH
  93570. /*
  93571. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  93572. ** is slightly different from resolving a normal SQL expression, because simple
  93573. ** identifiers are treated as strings, not possible column names or aliases.
  93574. **
  93575. ** i.e. if the parser sees:
  93576. **
  93577. ** ATTACH DATABASE abc AS def
  93578. **
  93579. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  93580. ** looking for columns of the same name.
  93581. **
  93582. ** This only applies to the root node of pExpr, so the statement:
  93583. **
  93584. ** ATTACH DATABASE abc||def AS 'db2'
  93585. **
  93586. ** will fail because neither abc or def can be resolved.
  93587. */
  93588. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  93589. {
  93590. int rc = SQLITE_OK;
  93591. if( pExpr ){
  93592. if( pExpr->op!=TK_ID ){
  93593. rc = sqlite3ResolveExprNames(pName, pExpr);
  93594. }else{
  93595. pExpr->op = TK_STRING;
  93596. }
  93597. }
  93598. return rc;
  93599. }
  93600. /*
  93601. ** An SQL user-function registered to do the work of an ATTACH statement. The
  93602. ** three arguments to the function come directly from an attach statement:
  93603. **
  93604. ** ATTACH DATABASE x AS y KEY z
  93605. **
  93606. ** SELECT sqlite_attach(x, y, z)
  93607. **
  93608. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  93609. ** third argument.
  93610. */
  93611. static void attachFunc(
  93612. sqlite3_context *context,
  93613. int NotUsed,
  93614. sqlite3_value **argv
  93615. ){
  93616. int i;
  93617. int rc = 0;
  93618. sqlite3 *db = sqlite3_context_db_handle(context);
  93619. const char *zName;
  93620. const char *zFile;
  93621. char *zPath = 0;
  93622. char *zErr = 0;
  93623. unsigned int flags;
  93624. Db *aNew; /* New array of Db pointers */
  93625. Db *pNew; /* Db object for the newly attached database */
  93626. char *zErrDyn = 0;
  93627. sqlite3_vfs *pVfs;
  93628. UNUSED_PARAMETER(NotUsed);
  93629. zFile = (const char *)sqlite3_value_text(argv[0]);
  93630. zName = (const char *)sqlite3_value_text(argv[1]);
  93631. if( zFile==0 ) zFile = "";
  93632. if( zName==0 ) zName = "";
  93633. /* Check for the following errors:
  93634. **
  93635. ** * Too many attached databases,
  93636. ** * Transaction currently open
  93637. ** * Specified database name already being used.
  93638. */
  93639. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  93640. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  93641. db->aLimit[SQLITE_LIMIT_ATTACHED]
  93642. );
  93643. goto attach_error;
  93644. }
  93645. for(i=0; i<db->nDb; i++){
  93646. char *z = db->aDb[i].zDbSName;
  93647. assert( z && zName );
  93648. if( sqlite3StrICmp(z, zName)==0 ){
  93649. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  93650. goto attach_error;
  93651. }
  93652. }
  93653. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  93654. ** hash tables.
  93655. */
  93656. if( db->aDb==db->aDbStatic ){
  93657. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  93658. if( aNew==0 ) return;
  93659. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  93660. }else{
  93661. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  93662. if( aNew==0 ) return;
  93663. }
  93664. db->aDb = aNew;
  93665. pNew = &db->aDb[db->nDb];
  93666. memset(pNew, 0, sizeof(*pNew));
  93667. /* Open the database file. If the btree is successfully opened, use
  93668. ** it to obtain the database schema. At this point the schema may
  93669. ** or may not be initialized.
  93670. */
  93671. flags = db->openFlags;
  93672. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  93673. if( rc!=SQLITE_OK ){
  93674. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  93675. sqlite3_result_error(context, zErr, -1);
  93676. sqlite3_free(zErr);
  93677. return;
  93678. }
  93679. assert( pVfs );
  93680. flags |= SQLITE_OPEN_MAIN_DB;
  93681. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  93682. sqlite3_free( zPath );
  93683. db->nDb++;
  93684. db->skipBtreeMutex = 0;
  93685. if( rc==SQLITE_CONSTRAINT ){
  93686. rc = SQLITE_ERROR;
  93687. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  93688. }else if( rc==SQLITE_OK ){
  93689. Pager *pPager;
  93690. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  93691. if( !pNew->pSchema ){
  93692. rc = SQLITE_NOMEM_BKPT;
  93693. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  93694. zErrDyn = sqlite3MPrintf(db,
  93695. "attached databases must use the same text encoding as main database");
  93696. rc = SQLITE_ERROR;
  93697. }
  93698. sqlite3BtreeEnter(pNew->pBt);
  93699. pPager = sqlite3BtreePager(pNew->pBt);
  93700. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  93701. sqlite3BtreeSecureDelete(pNew->pBt,
  93702. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  93703. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  93704. sqlite3BtreeSetPagerFlags(pNew->pBt,
  93705. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  93706. #endif
  93707. sqlite3BtreeLeave(pNew->pBt);
  93708. }
  93709. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  93710. pNew->zDbSName = sqlite3DbStrDup(db, zName);
  93711. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  93712. rc = SQLITE_NOMEM_BKPT;
  93713. }
  93714. #ifdef SQLITE_HAS_CODEC
  93715. if( rc==SQLITE_OK ){
  93716. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  93717. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  93718. int nKey;
  93719. char *zKey;
  93720. int t = sqlite3_value_type(argv[2]);
  93721. switch( t ){
  93722. case SQLITE_INTEGER:
  93723. case SQLITE_FLOAT:
  93724. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  93725. rc = SQLITE_ERROR;
  93726. break;
  93727. case SQLITE_TEXT:
  93728. case SQLITE_BLOB:
  93729. nKey = sqlite3_value_bytes(argv[2]);
  93730. zKey = (char *)sqlite3_value_blob(argv[2]);
  93731. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  93732. break;
  93733. case SQLITE_NULL:
  93734. /* No key specified. Use the key from the main database */
  93735. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  93736. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  93737. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  93738. }
  93739. break;
  93740. }
  93741. }
  93742. #endif
  93743. /* If the file was opened successfully, read the schema for the new database.
  93744. ** If this fails, or if opening the file failed, then close the file and
  93745. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  93746. ** we found it.
  93747. */
  93748. if( rc==SQLITE_OK ){
  93749. sqlite3BtreeEnterAll(db);
  93750. rc = sqlite3Init(db, &zErrDyn);
  93751. sqlite3BtreeLeaveAll(db);
  93752. }
  93753. #ifdef SQLITE_USER_AUTHENTICATION
  93754. if( rc==SQLITE_OK ){
  93755. u8 newAuth = 0;
  93756. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  93757. if( newAuth<db->auth.authLevel ){
  93758. rc = SQLITE_AUTH_USER;
  93759. }
  93760. }
  93761. #endif
  93762. if( rc ){
  93763. int iDb = db->nDb - 1;
  93764. assert( iDb>=2 );
  93765. if( db->aDb[iDb].pBt ){
  93766. sqlite3BtreeClose(db->aDb[iDb].pBt);
  93767. db->aDb[iDb].pBt = 0;
  93768. db->aDb[iDb].pSchema = 0;
  93769. }
  93770. sqlite3ResetAllSchemasOfConnection(db);
  93771. db->nDb = iDb;
  93772. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  93773. sqlite3OomFault(db);
  93774. sqlite3DbFree(db, zErrDyn);
  93775. zErrDyn = sqlite3MPrintf(db, "out of memory");
  93776. }else if( zErrDyn==0 ){
  93777. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  93778. }
  93779. goto attach_error;
  93780. }
  93781. return;
  93782. attach_error:
  93783. /* Return an error if we get here */
  93784. if( zErrDyn ){
  93785. sqlite3_result_error(context, zErrDyn, -1);
  93786. sqlite3DbFree(db, zErrDyn);
  93787. }
  93788. if( rc ) sqlite3_result_error_code(context, rc);
  93789. }
  93790. /*
  93791. ** An SQL user-function registered to do the work of an DETACH statement. The
  93792. ** three arguments to the function come directly from a detach statement:
  93793. **
  93794. ** DETACH DATABASE x
  93795. **
  93796. ** SELECT sqlite_detach(x)
  93797. */
  93798. static void detachFunc(
  93799. sqlite3_context *context,
  93800. int NotUsed,
  93801. sqlite3_value **argv
  93802. ){
  93803. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  93804. sqlite3 *db = sqlite3_context_db_handle(context);
  93805. int i;
  93806. Db *pDb = 0;
  93807. char zErr[128];
  93808. UNUSED_PARAMETER(NotUsed);
  93809. if( zName==0 ) zName = "";
  93810. for(i=0; i<db->nDb; i++){
  93811. pDb = &db->aDb[i];
  93812. if( pDb->pBt==0 ) continue;
  93813. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  93814. }
  93815. if( i>=db->nDb ){
  93816. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  93817. goto detach_error;
  93818. }
  93819. if( i<2 ){
  93820. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  93821. goto detach_error;
  93822. }
  93823. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  93824. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  93825. goto detach_error;
  93826. }
  93827. sqlite3BtreeClose(pDb->pBt);
  93828. pDb->pBt = 0;
  93829. pDb->pSchema = 0;
  93830. sqlite3CollapseDatabaseArray(db);
  93831. return;
  93832. detach_error:
  93833. sqlite3_result_error(context, zErr, -1);
  93834. }
  93835. /*
  93836. ** This procedure generates VDBE code for a single invocation of either the
  93837. ** sqlite_detach() or sqlite_attach() SQL user functions.
  93838. */
  93839. static void codeAttach(
  93840. Parse *pParse, /* The parser context */
  93841. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  93842. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  93843. Expr *pAuthArg, /* Expression to pass to authorization callback */
  93844. Expr *pFilename, /* Name of database file */
  93845. Expr *pDbname, /* Name of the database to use internally */
  93846. Expr *pKey /* Database key for encryption extension */
  93847. ){
  93848. int rc;
  93849. NameContext sName;
  93850. Vdbe *v;
  93851. sqlite3* db = pParse->db;
  93852. int regArgs;
  93853. if( pParse->nErr ) goto attach_end;
  93854. memset(&sName, 0, sizeof(NameContext));
  93855. sName.pParse = pParse;
  93856. if(
  93857. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  93858. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  93859. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  93860. ){
  93861. goto attach_end;
  93862. }
  93863. #ifndef SQLITE_OMIT_AUTHORIZATION
  93864. if( pAuthArg ){
  93865. char *zAuthArg;
  93866. if( pAuthArg->op==TK_STRING ){
  93867. zAuthArg = pAuthArg->u.zToken;
  93868. }else{
  93869. zAuthArg = 0;
  93870. }
  93871. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  93872. if(rc!=SQLITE_OK ){
  93873. goto attach_end;
  93874. }
  93875. }
  93876. #endif /* SQLITE_OMIT_AUTHORIZATION */
  93877. v = sqlite3GetVdbe(pParse);
  93878. regArgs = sqlite3GetTempRange(pParse, 4);
  93879. sqlite3ExprCode(pParse, pFilename, regArgs);
  93880. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  93881. sqlite3ExprCode(pParse, pKey, regArgs+2);
  93882. assert( v || db->mallocFailed );
  93883. if( v ){
  93884. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  93885. (char *)pFunc, P4_FUNCDEF);
  93886. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  93887. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  93888. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  93889. ** statement only). For DETACH, set it to false (expire all existing
  93890. ** statements).
  93891. */
  93892. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  93893. }
  93894. attach_end:
  93895. sqlite3ExprDelete(db, pFilename);
  93896. sqlite3ExprDelete(db, pDbname);
  93897. sqlite3ExprDelete(db, pKey);
  93898. }
  93899. /*
  93900. ** Called by the parser to compile a DETACH statement.
  93901. **
  93902. ** DETACH pDbname
  93903. */
  93904. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  93905. static const FuncDef detach_func = {
  93906. 1, /* nArg */
  93907. SQLITE_UTF8, /* funcFlags */
  93908. 0, /* pUserData */
  93909. 0, /* pNext */
  93910. detachFunc, /* xSFunc */
  93911. 0, /* xFinalize */
  93912. "sqlite_detach", /* zName */
  93913. {0}
  93914. };
  93915. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  93916. }
  93917. /*
  93918. ** Called by the parser to compile an ATTACH statement.
  93919. **
  93920. ** ATTACH p AS pDbname KEY pKey
  93921. */
  93922. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  93923. static const FuncDef attach_func = {
  93924. 3, /* nArg */
  93925. SQLITE_UTF8, /* funcFlags */
  93926. 0, /* pUserData */
  93927. 0, /* pNext */
  93928. attachFunc, /* xSFunc */
  93929. 0, /* xFinalize */
  93930. "sqlite_attach", /* zName */
  93931. {0}
  93932. };
  93933. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  93934. }
  93935. #endif /* SQLITE_OMIT_ATTACH */
  93936. /*
  93937. ** Initialize a DbFixer structure. This routine must be called prior
  93938. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  93939. */
  93940. SQLITE_PRIVATE void sqlite3FixInit(
  93941. DbFixer *pFix, /* The fixer to be initialized */
  93942. Parse *pParse, /* Error messages will be written here */
  93943. int iDb, /* This is the database that must be used */
  93944. const char *zType, /* "view", "trigger", or "index" */
  93945. const Token *pName /* Name of the view, trigger, or index */
  93946. ){
  93947. sqlite3 *db;
  93948. db = pParse->db;
  93949. assert( db->nDb>iDb );
  93950. pFix->pParse = pParse;
  93951. pFix->zDb = db->aDb[iDb].zDbSName;
  93952. pFix->pSchema = db->aDb[iDb].pSchema;
  93953. pFix->zType = zType;
  93954. pFix->pName = pName;
  93955. pFix->bVarOnly = (iDb==1);
  93956. }
  93957. /*
  93958. ** The following set of routines walk through the parse tree and assign
  93959. ** a specific database to all table references where the database name
  93960. ** was left unspecified in the original SQL statement. The pFix structure
  93961. ** must have been initialized by a prior call to sqlite3FixInit().
  93962. **
  93963. ** These routines are used to make sure that an index, trigger, or
  93964. ** view in one database does not refer to objects in a different database.
  93965. ** (Exception: indices, triggers, and views in the TEMP database are
  93966. ** allowed to refer to anything.) If a reference is explicitly made
  93967. ** to an object in a different database, an error message is added to
  93968. ** pParse->zErrMsg and these routines return non-zero. If everything
  93969. ** checks out, these routines return 0.
  93970. */
  93971. SQLITE_PRIVATE int sqlite3FixSrcList(
  93972. DbFixer *pFix, /* Context of the fixation */
  93973. SrcList *pList /* The Source list to check and modify */
  93974. ){
  93975. int i;
  93976. const char *zDb;
  93977. struct SrcList_item *pItem;
  93978. if( NEVER(pList==0) ) return 0;
  93979. zDb = pFix->zDb;
  93980. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  93981. if( pFix->bVarOnly==0 ){
  93982. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  93983. sqlite3ErrorMsg(pFix->pParse,
  93984. "%s %T cannot reference objects in database %s",
  93985. pFix->zType, pFix->pName, pItem->zDatabase);
  93986. return 1;
  93987. }
  93988. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  93989. pItem->zDatabase = 0;
  93990. pItem->pSchema = pFix->pSchema;
  93991. }
  93992. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  93993. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  93994. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  93995. #endif
  93996. }
  93997. return 0;
  93998. }
  93999. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  94000. SQLITE_PRIVATE int sqlite3FixSelect(
  94001. DbFixer *pFix, /* Context of the fixation */
  94002. Select *pSelect /* The SELECT statement to be fixed to one database */
  94003. ){
  94004. while( pSelect ){
  94005. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  94006. return 1;
  94007. }
  94008. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  94009. return 1;
  94010. }
  94011. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  94012. return 1;
  94013. }
  94014. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  94015. return 1;
  94016. }
  94017. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  94018. return 1;
  94019. }
  94020. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  94021. return 1;
  94022. }
  94023. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  94024. return 1;
  94025. }
  94026. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  94027. return 1;
  94028. }
  94029. pSelect = pSelect->pPrior;
  94030. }
  94031. return 0;
  94032. }
  94033. SQLITE_PRIVATE int sqlite3FixExpr(
  94034. DbFixer *pFix, /* Context of the fixation */
  94035. Expr *pExpr /* The expression to be fixed to one database */
  94036. ){
  94037. while( pExpr ){
  94038. if( pExpr->op==TK_VARIABLE ){
  94039. if( pFix->pParse->db->init.busy ){
  94040. pExpr->op = TK_NULL;
  94041. }else{
  94042. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  94043. return 1;
  94044. }
  94045. }
  94046. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  94047. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  94048. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  94049. }else{
  94050. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  94051. }
  94052. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  94053. return 1;
  94054. }
  94055. pExpr = pExpr->pLeft;
  94056. }
  94057. return 0;
  94058. }
  94059. SQLITE_PRIVATE int sqlite3FixExprList(
  94060. DbFixer *pFix, /* Context of the fixation */
  94061. ExprList *pList /* The expression to be fixed to one database */
  94062. ){
  94063. int i;
  94064. struct ExprList_item *pItem;
  94065. if( pList==0 ) return 0;
  94066. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  94067. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  94068. return 1;
  94069. }
  94070. }
  94071. return 0;
  94072. }
  94073. #endif
  94074. #ifndef SQLITE_OMIT_TRIGGER
  94075. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  94076. DbFixer *pFix, /* Context of the fixation */
  94077. TriggerStep *pStep /* The trigger step be fixed to one database */
  94078. ){
  94079. while( pStep ){
  94080. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  94081. return 1;
  94082. }
  94083. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  94084. return 1;
  94085. }
  94086. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  94087. return 1;
  94088. }
  94089. pStep = pStep->pNext;
  94090. }
  94091. return 0;
  94092. }
  94093. #endif
  94094. /************** End of attach.c **********************************************/
  94095. /************** Begin file auth.c ********************************************/
  94096. /*
  94097. ** 2003 January 11
  94098. **
  94099. ** The author disclaims copyright to this source code. In place of
  94100. ** a legal notice, here is a blessing:
  94101. **
  94102. ** May you do good and not evil.
  94103. ** May you find forgiveness for yourself and forgive others.
  94104. ** May you share freely, never taking more than you give.
  94105. **
  94106. *************************************************************************
  94107. ** This file contains code used to implement the sqlite3_set_authorizer()
  94108. ** API. This facility is an optional feature of the library. Embedded
  94109. ** systems that do not need this facility may omit it by recompiling
  94110. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  94111. */
  94112. /* #include "sqliteInt.h" */
  94113. /*
  94114. ** All of the code in this file may be omitted by defining a single
  94115. ** macro.
  94116. */
  94117. #ifndef SQLITE_OMIT_AUTHORIZATION
  94118. /*
  94119. ** Set or clear the access authorization function.
  94120. **
  94121. ** The access authorization function is be called during the compilation
  94122. ** phase to verify that the user has read and/or write access permission on
  94123. ** various fields of the database. The first argument to the auth function
  94124. ** is a copy of the 3rd argument to this routine. The second argument
  94125. ** to the auth function is one of these constants:
  94126. **
  94127. ** SQLITE_CREATE_INDEX
  94128. ** SQLITE_CREATE_TABLE
  94129. ** SQLITE_CREATE_TEMP_INDEX
  94130. ** SQLITE_CREATE_TEMP_TABLE
  94131. ** SQLITE_CREATE_TEMP_TRIGGER
  94132. ** SQLITE_CREATE_TEMP_VIEW
  94133. ** SQLITE_CREATE_TRIGGER
  94134. ** SQLITE_CREATE_VIEW
  94135. ** SQLITE_DELETE
  94136. ** SQLITE_DROP_INDEX
  94137. ** SQLITE_DROP_TABLE
  94138. ** SQLITE_DROP_TEMP_INDEX
  94139. ** SQLITE_DROP_TEMP_TABLE
  94140. ** SQLITE_DROP_TEMP_TRIGGER
  94141. ** SQLITE_DROP_TEMP_VIEW
  94142. ** SQLITE_DROP_TRIGGER
  94143. ** SQLITE_DROP_VIEW
  94144. ** SQLITE_INSERT
  94145. ** SQLITE_PRAGMA
  94146. ** SQLITE_READ
  94147. ** SQLITE_SELECT
  94148. ** SQLITE_TRANSACTION
  94149. ** SQLITE_UPDATE
  94150. **
  94151. ** The third and fourth arguments to the auth function are the name of
  94152. ** the table and the column that are being accessed. The auth function
  94153. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  94154. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  94155. ** means that the SQL statement will never-run - the sqlite3_exec() call
  94156. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  94157. ** should run but attempts to read the specified column will return NULL
  94158. ** and attempts to write the column will be ignored.
  94159. **
  94160. ** Setting the auth function to NULL disables this hook. The default
  94161. ** setting of the auth function is NULL.
  94162. */
  94163. SQLITE_API int sqlite3_set_authorizer(
  94164. sqlite3 *db,
  94165. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  94166. void *pArg
  94167. ){
  94168. #ifdef SQLITE_ENABLE_API_ARMOR
  94169. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  94170. #endif
  94171. sqlite3_mutex_enter(db->mutex);
  94172. db->xAuth = (sqlite3_xauth)xAuth;
  94173. db->pAuthArg = pArg;
  94174. sqlite3ExpirePreparedStatements(db);
  94175. sqlite3_mutex_leave(db->mutex);
  94176. return SQLITE_OK;
  94177. }
  94178. /*
  94179. ** Write an error message into pParse->zErrMsg that explains that the
  94180. ** user-supplied authorization function returned an illegal value.
  94181. */
  94182. static void sqliteAuthBadReturnCode(Parse *pParse){
  94183. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  94184. pParse->rc = SQLITE_ERROR;
  94185. }
  94186. /*
  94187. ** Invoke the authorization callback for permission to read column zCol from
  94188. ** table zTab in database zDb. This function assumes that an authorization
  94189. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  94190. **
  94191. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  94192. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  94193. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  94194. */
  94195. SQLITE_PRIVATE int sqlite3AuthReadCol(
  94196. Parse *pParse, /* The parser context */
  94197. const char *zTab, /* Table name */
  94198. const char *zCol, /* Column name */
  94199. int iDb /* Index of containing database. */
  94200. ){
  94201. sqlite3 *db = pParse->db; /* Database handle */
  94202. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  94203. int rc; /* Auth callback return code */
  94204. if( db->init.busy ) return SQLITE_OK;
  94205. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  94206. #ifdef SQLITE_USER_AUTHENTICATION
  94207. ,db->auth.zAuthUser
  94208. #endif
  94209. );
  94210. if( rc==SQLITE_DENY ){
  94211. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  94212. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  94213. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  94214. pParse->rc = SQLITE_AUTH;
  94215. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  94216. sqliteAuthBadReturnCode(pParse);
  94217. }
  94218. return rc;
  94219. }
  94220. /*
  94221. ** The pExpr should be a TK_COLUMN expression. The table referred to
  94222. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  94223. ** Check to see if it is OK to read this particular column.
  94224. **
  94225. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  94226. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  94227. ** then generate an error.
  94228. */
  94229. SQLITE_PRIVATE void sqlite3AuthRead(
  94230. Parse *pParse, /* The parser context */
  94231. Expr *pExpr, /* The expression to check authorization on */
  94232. Schema *pSchema, /* The schema of the expression */
  94233. SrcList *pTabList /* All table that pExpr might refer to */
  94234. ){
  94235. sqlite3 *db = pParse->db;
  94236. Table *pTab = 0; /* The table being read */
  94237. const char *zCol; /* Name of the column of the table */
  94238. int iSrc; /* Index in pTabList->a[] of table being read */
  94239. int iDb; /* The index of the database the expression refers to */
  94240. int iCol; /* Index of column in table */
  94241. if( db->xAuth==0 ) return;
  94242. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  94243. if( iDb<0 ){
  94244. /* An attempt to read a column out of a subquery or other
  94245. ** temporary table. */
  94246. return;
  94247. }
  94248. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  94249. if( pExpr->op==TK_TRIGGER ){
  94250. pTab = pParse->pTriggerTab;
  94251. }else{
  94252. assert( pTabList );
  94253. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  94254. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  94255. pTab = pTabList->a[iSrc].pTab;
  94256. break;
  94257. }
  94258. }
  94259. }
  94260. iCol = pExpr->iColumn;
  94261. if( NEVER(pTab==0) ) return;
  94262. if( iCol>=0 ){
  94263. assert( iCol<pTab->nCol );
  94264. zCol = pTab->aCol[iCol].zName;
  94265. }else if( pTab->iPKey>=0 ){
  94266. assert( pTab->iPKey<pTab->nCol );
  94267. zCol = pTab->aCol[pTab->iPKey].zName;
  94268. }else{
  94269. zCol = "ROWID";
  94270. }
  94271. assert( iDb>=0 && iDb<db->nDb );
  94272. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  94273. pExpr->op = TK_NULL;
  94274. }
  94275. }
  94276. /*
  94277. ** Do an authorization check using the code and arguments given. Return
  94278. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  94279. ** is returned, then the error count and error message in pParse are
  94280. ** modified appropriately.
  94281. */
  94282. SQLITE_PRIVATE int sqlite3AuthCheck(
  94283. Parse *pParse,
  94284. int code,
  94285. const char *zArg1,
  94286. const char *zArg2,
  94287. const char *zArg3
  94288. ){
  94289. sqlite3 *db = pParse->db;
  94290. int rc;
  94291. /* Don't do any authorization checks if the database is initialising
  94292. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  94293. */
  94294. if( db->init.busy || IN_DECLARE_VTAB ){
  94295. return SQLITE_OK;
  94296. }
  94297. if( db->xAuth==0 ){
  94298. return SQLITE_OK;
  94299. }
  94300. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  94301. ** callback are either NULL pointers or zero-terminated strings that
  94302. ** contain additional details about the action to be authorized.
  94303. **
  94304. ** The following testcase() macros show that any of the 3rd through 6th
  94305. ** parameters can be either NULL or a string. */
  94306. testcase( zArg1==0 );
  94307. testcase( zArg2==0 );
  94308. testcase( zArg3==0 );
  94309. testcase( pParse->zAuthContext==0 );
  94310. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  94311. #ifdef SQLITE_USER_AUTHENTICATION
  94312. ,db->auth.zAuthUser
  94313. #endif
  94314. );
  94315. if( rc==SQLITE_DENY ){
  94316. sqlite3ErrorMsg(pParse, "not authorized");
  94317. pParse->rc = SQLITE_AUTH;
  94318. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  94319. rc = SQLITE_DENY;
  94320. sqliteAuthBadReturnCode(pParse);
  94321. }
  94322. return rc;
  94323. }
  94324. /*
  94325. ** Push an authorization context. After this routine is called, the
  94326. ** zArg3 argument to authorization callbacks will be zContext until
  94327. ** popped. Or if pParse==0, this routine is a no-op.
  94328. */
  94329. SQLITE_PRIVATE void sqlite3AuthContextPush(
  94330. Parse *pParse,
  94331. AuthContext *pContext,
  94332. const char *zContext
  94333. ){
  94334. assert( pParse );
  94335. pContext->pParse = pParse;
  94336. pContext->zAuthContext = pParse->zAuthContext;
  94337. pParse->zAuthContext = zContext;
  94338. }
  94339. /*
  94340. ** Pop an authorization context that was previously pushed
  94341. ** by sqlite3AuthContextPush
  94342. */
  94343. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  94344. if( pContext->pParse ){
  94345. pContext->pParse->zAuthContext = pContext->zAuthContext;
  94346. pContext->pParse = 0;
  94347. }
  94348. }
  94349. #endif /* SQLITE_OMIT_AUTHORIZATION */
  94350. /************** End of auth.c ************************************************/
  94351. /************** Begin file build.c *******************************************/
  94352. /*
  94353. ** 2001 September 15
  94354. **
  94355. ** The author disclaims copyright to this source code. In place of
  94356. ** a legal notice, here is a blessing:
  94357. **
  94358. ** May you do good and not evil.
  94359. ** May you find forgiveness for yourself and forgive others.
  94360. ** May you share freely, never taking more than you give.
  94361. **
  94362. *************************************************************************
  94363. ** This file contains C code routines that are called by the SQLite parser
  94364. ** when syntax rules are reduced. The routines in this file handle the
  94365. ** following kinds of SQL syntax:
  94366. **
  94367. ** CREATE TABLE
  94368. ** DROP TABLE
  94369. ** CREATE INDEX
  94370. ** DROP INDEX
  94371. ** creating ID lists
  94372. ** BEGIN TRANSACTION
  94373. ** COMMIT
  94374. ** ROLLBACK
  94375. */
  94376. /* #include "sqliteInt.h" */
  94377. #ifndef SQLITE_OMIT_SHARED_CACHE
  94378. /*
  94379. ** The TableLock structure is only used by the sqlite3TableLock() and
  94380. ** codeTableLocks() functions.
  94381. */
  94382. struct TableLock {
  94383. int iDb; /* The database containing the table to be locked */
  94384. int iTab; /* The root page of the table to be locked */
  94385. u8 isWriteLock; /* True for write lock. False for a read lock */
  94386. const char *zLockName; /* Name of the table */
  94387. };
  94388. /*
  94389. ** Record the fact that we want to lock a table at run-time.
  94390. **
  94391. ** The table to be locked has root page iTab and is found in database iDb.
  94392. ** A read or a write lock can be taken depending on isWritelock.
  94393. **
  94394. ** This routine just records the fact that the lock is desired. The
  94395. ** code to make the lock occur is generated by a later call to
  94396. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  94397. */
  94398. SQLITE_PRIVATE void sqlite3TableLock(
  94399. Parse *pParse, /* Parsing context */
  94400. int iDb, /* Index of the database containing the table to lock */
  94401. int iTab, /* Root page number of the table to be locked */
  94402. u8 isWriteLock, /* True for a write lock */
  94403. const char *zName /* Name of the table to be locked */
  94404. ){
  94405. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  94406. int i;
  94407. int nBytes;
  94408. TableLock *p;
  94409. assert( iDb>=0 );
  94410. if( iDb==1 ) return;
  94411. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  94412. for(i=0; i<pToplevel->nTableLock; i++){
  94413. p = &pToplevel->aTableLock[i];
  94414. if( p->iDb==iDb && p->iTab==iTab ){
  94415. p->isWriteLock = (p->isWriteLock || isWriteLock);
  94416. return;
  94417. }
  94418. }
  94419. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  94420. pToplevel->aTableLock =
  94421. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  94422. if( pToplevel->aTableLock ){
  94423. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  94424. p->iDb = iDb;
  94425. p->iTab = iTab;
  94426. p->isWriteLock = isWriteLock;
  94427. p->zLockName = zName;
  94428. }else{
  94429. pToplevel->nTableLock = 0;
  94430. sqlite3OomFault(pToplevel->db);
  94431. }
  94432. }
  94433. /*
  94434. ** Code an OP_TableLock instruction for each table locked by the
  94435. ** statement (configured by calls to sqlite3TableLock()).
  94436. */
  94437. static void codeTableLocks(Parse *pParse){
  94438. int i;
  94439. Vdbe *pVdbe;
  94440. pVdbe = sqlite3GetVdbe(pParse);
  94441. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  94442. for(i=0; i<pParse->nTableLock; i++){
  94443. TableLock *p = &pParse->aTableLock[i];
  94444. int p1 = p->iDb;
  94445. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  94446. p->zLockName, P4_STATIC);
  94447. }
  94448. }
  94449. #else
  94450. #define codeTableLocks(x)
  94451. #endif
  94452. /*
  94453. ** Return TRUE if the given yDbMask object is empty - if it contains no
  94454. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  94455. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  94456. */
  94457. #if SQLITE_MAX_ATTACHED>30
  94458. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  94459. int i;
  94460. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  94461. return 1;
  94462. }
  94463. #endif
  94464. /*
  94465. ** This routine is called after a single SQL statement has been
  94466. ** parsed and a VDBE program to execute that statement has been
  94467. ** prepared. This routine puts the finishing touches on the
  94468. ** VDBE program and resets the pParse structure for the next
  94469. ** parse.
  94470. **
  94471. ** Note that if an error occurred, it might be the case that
  94472. ** no VDBE code was generated.
  94473. */
  94474. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  94475. sqlite3 *db;
  94476. Vdbe *v;
  94477. assert( pParse->pToplevel==0 );
  94478. db = pParse->db;
  94479. if( pParse->nested ) return;
  94480. if( db->mallocFailed || pParse->nErr ){
  94481. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  94482. return;
  94483. }
  94484. /* Begin by generating some termination code at the end of the
  94485. ** vdbe program
  94486. */
  94487. v = sqlite3GetVdbe(pParse);
  94488. assert( !pParse->isMultiWrite
  94489. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  94490. if( v ){
  94491. sqlite3VdbeAddOp0(v, OP_Halt);
  94492. #if SQLITE_USER_AUTHENTICATION
  94493. if( pParse->nTableLock>0 && db->init.busy==0 ){
  94494. sqlite3UserAuthInit(db);
  94495. if( db->auth.authLevel<UAUTH_User ){
  94496. sqlite3ErrorMsg(pParse, "user not authenticated");
  94497. pParse->rc = SQLITE_AUTH_USER;
  94498. return;
  94499. }
  94500. }
  94501. #endif
  94502. /* The cookie mask contains one bit for each database file open.
  94503. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  94504. ** set for each database that is used. Generate code to start a
  94505. ** transaction on each used database and to verify the schema cookie
  94506. ** on each used database.
  94507. */
  94508. if( db->mallocFailed==0
  94509. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  94510. ){
  94511. int iDb, i;
  94512. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  94513. sqlite3VdbeJumpHere(v, 0);
  94514. for(iDb=0; iDb<db->nDb; iDb++){
  94515. Schema *pSchema;
  94516. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  94517. sqlite3VdbeUsesBtree(v, iDb);
  94518. pSchema = db->aDb[iDb].pSchema;
  94519. sqlite3VdbeAddOp4Int(v,
  94520. OP_Transaction, /* Opcode */
  94521. iDb, /* P1 */
  94522. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  94523. pSchema->schema_cookie, /* P3 */
  94524. pSchema->iGeneration /* P4 */
  94525. );
  94526. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  94527. VdbeComment((v,
  94528. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  94529. }
  94530. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94531. for(i=0; i<pParse->nVtabLock; i++){
  94532. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  94533. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  94534. }
  94535. pParse->nVtabLock = 0;
  94536. #endif
  94537. /* Once all the cookies have been verified and transactions opened,
  94538. ** obtain the required table-locks. This is a no-op unless the
  94539. ** shared-cache feature is enabled.
  94540. */
  94541. codeTableLocks(pParse);
  94542. /* Initialize any AUTOINCREMENT data structures required.
  94543. */
  94544. sqlite3AutoincrementBegin(pParse);
  94545. /* Code constant expressions that where factored out of inner loops */
  94546. if( pParse->pConstExpr ){
  94547. ExprList *pEL = pParse->pConstExpr;
  94548. pParse->okConstFactor = 0;
  94549. for(i=0; i<pEL->nExpr; i++){
  94550. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  94551. }
  94552. }
  94553. /* Finally, jump back to the beginning of the executable code. */
  94554. sqlite3VdbeGoto(v, 1);
  94555. }
  94556. }
  94557. /* Get the VDBE program ready for execution
  94558. */
  94559. if( v && pParse->nErr==0 && !db->mallocFailed ){
  94560. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  94561. /* A minimum of one cursor is required if autoincrement is used
  94562. * See ticket [a696379c1f08866] */
  94563. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  94564. sqlite3VdbeMakeReady(v, pParse);
  94565. pParse->rc = SQLITE_DONE;
  94566. }else{
  94567. pParse->rc = SQLITE_ERROR;
  94568. }
  94569. }
  94570. /*
  94571. ** Run the parser and code generator recursively in order to generate
  94572. ** code for the SQL statement given onto the end of the pParse context
  94573. ** currently under construction. When the parser is run recursively
  94574. ** this way, the final OP_Halt is not appended and other initialization
  94575. ** and finalization steps are omitted because those are handling by the
  94576. ** outermost parser.
  94577. **
  94578. ** Not everything is nestable. This facility is designed to permit
  94579. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  94580. ** care if you decide to try to use this routine for some other purposes.
  94581. */
  94582. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  94583. va_list ap;
  94584. char *zSql;
  94585. char *zErrMsg = 0;
  94586. sqlite3 *db = pParse->db;
  94587. char saveBuf[PARSE_TAIL_SZ];
  94588. if( pParse->nErr ) return;
  94589. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  94590. va_start(ap, zFormat);
  94591. zSql = sqlite3VMPrintf(db, zFormat, ap);
  94592. va_end(ap);
  94593. if( zSql==0 ){
  94594. return; /* A malloc must have failed */
  94595. }
  94596. pParse->nested++;
  94597. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  94598. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  94599. sqlite3RunParser(pParse, zSql, &zErrMsg);
  94600. sqlite3DbFree(db, zErrMsg);
  94601. sqlite3DbFree(db, zSql);
  94602. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  94603. pParse->nested--;
  94604. }
  94605. #if SQLITE_USER_AUTHENTICATION
  94606. /*
  94607. ** Return TRUE if zTable is the name of the system table that stores the
  94608. ** list of users and their access credentials.
  94609. */
  94610. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  94611. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  94612. }
  94613. #endif
  94614. /*
  94615. ** Locate the in-memory structure that describes a particular database
  94616. ** table given the name of that table and (optionally) the name of the
  94617. ** database containing the table. Return NULL if not found.
  94618. **
  94619. ** If zDatabase is 0, all databases are searched for the table and the
  94620. ** first matching table is returned. (No checking for duplicate table
  94621. ** names is done.) The search order is TEMP first, then MAIN, then any
  94622. ** auxiliary databases added using the ATTACH command.
  94623. **
  94624. ** See also sqlite3LocateTable().
  94625. */
  94626. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  94627. Table *p = 0;
  94628. int i;
  94629. /* All mutexes are required for schema access. Make sure we hold them. */
  94630. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  94631. #if SQLITE_USER_AUTHENTICATION
  94632. /* Only the admin user is allowed to know that the sqlite_user table
  94633. ** exists */
  94634. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  94635. return 0;
  94636. }
  94637. #endif
  94638. while(1){
  94639. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  94640. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  94641. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  94642. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  94643. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  94644. if( p ) return p;
  94645. }
  94646. }
  94647. /* Not found. If the name we were looking for was temp.sqlite_master
  94648. ** then change the name to sqlite_temp_master and try again. */
  94649. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  94650. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  94651. zName = TEMP_MASTER_NAME;
  94652. }
  94653. return 0;
  94654. }
  94655. /*
  94656. ** Locate the in-memory structure that describes a particular database
  94657. ** table given the name of that table and (optionally) the name of the
  94658. ** database containing the table. Return NULL if not found. Also leave an
  94659. ** error message in pParse->zErrMsg.
  94660. **
  94661. ** The difference between this routine and sqlite3FindTable() is that this
  94662. ** routine leaves an error message in pParse->zErrMsg where
  94663. ** sqlite3FindTable() does not.
  94664. */
  94665. SQLITE_PRIVATE Table *sqlite3LocateTable(
  94666. Parse *pParse, /* context in which to report errors */
  94667. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  94668. const char *zName, /* Name of the table we are looking for */
  94669. const char *zDbase /* Name of the database. Might be NULL */
  94670. ){
  94671. Table *p;
  94672. /* Read the database schema. If an error occurs, leave an error message
  94673. ** and code in pParse and return NULL. */
  94674. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  94675. return 0;
  94676. }
  94677. p = sqlite3FindTable(pParse->db, zName, zDbase);
  94678. if( p==0 ){
  94679. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  94680. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94681. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  94682. /* If zName is the not the name of a table in the schema created using
  94683. ** CREATE, then check to see if it is the name of an virtual table that
  94684. ** can be an eponymous virtual table. */
  94685. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  94686. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  94687. pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
  94688. }
  94689. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  94690. return pMod->pEpoTab;
  94691. }
  94692. }
  94693. #endif
  94694. if( (flags & LOCATE_NOERR)==0 ){
  94695. if( zDbase ){
  94696. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  94697. }else{
  94698. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  94699. }
  94700. pParse->checkSchema = 1;
  94701. }
  94702. }
  94703. return p;
  94704. }
  94705. /*
  94706. ** Locate the table identified by *p.
  94707. **
  94708. ** This is a wrapper around sqlite3LocateTable(). The difference between
  94709. ** sqlite3LocateTable() and this function is that this function restricts
  94710. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  94711. ** non-NULL if it is part of a view or trigger program definition. See
  94712. ** sqlite3FixSrcList() for details.
  94713. */
  94714. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  94715. Parse *pParse,
  94716. u32 flags,
  94717. struct SrcList_item *p
  94718. ){
  94719. const char *zDb;
  94720. assert( p->pSchema==0 || p->zDatabase==0 );
  94721. if( p->pSchema ){
  94722. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  94723. zDb = pParse->db->aDb[iDb].zDbSName;
  94724. }else{
  94725. zDb = p->zDatabase;
  94726. }
  94727. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  94728. }
  94729. /*
  94730. ** Locate the in-memory structure that describes
  94731. ** a particular index given the name of that index
  94732. ** and the name of the database that contains the index.
  94733. ** Return NULL if not found.
  94734. **
  94735. ** If zDatabase is 0, all databases are searched for the
  94736. ** table and the first matching index is returned. (No checking
  94737. ** for duplicate index names is done.) The search order is
  94738. ** TEMP first, then MAIN, then any auxiliary databases added
  94739. ** using the ATTACH command.
  94740. */
  94741. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  94742. Index *p = 0;
  94743. int i;
  94744. /* All mutexes are required for schema access. Make sure we hold them. */
  94745. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  94746. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  94747. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  94748. Schema *pSchema = db->aDb[j].pSchema;
  94749. assert( pSchema );
  94750. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  94751. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  94752. p = sqlite3HashFind(&pSchema->idxHash, zName);
  94753. if( p ) break;
  94754. }
  94755. return p;
  94756. }
  94757. /*
  94758. ** Reclaim the memory used by an index
  94759. */
  94760. static void freeIndex(sqlite3 *db, Index *p){
  94761. #ifndef SQLITE_OMIT_ANALYZE
  94762. sqlite3DeleteIndexSamples(db, p);
  94763. #endif
  94764. sqlite3ExprDelete(db, p->pPartIdxWhere);
  94765. sqlite3ExprListDelete(db, p->aColExpr);
  94766. sqlite3DbFree(db, p->zColAff);
  94767. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  94768. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94769. sqlite3_free(p->aiRowEst);
  94770. #endif
  94771. sqlite3DbFree(db, p);
  94772. }
  94773. /*
  94774. ** For the index called zIdxName which is found in the database iDb,
  94775. ** unlike that index from its Table then remove the index from
  94776. ** the index hash table and free all memory structures associated
  94777. ** with the index.
  94778. */
  94779. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  94780. Index *pIndex;
  94781. Hash *pHash;
  94782. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94783. pHash = &db->aDb[iDb].pSchema->idxHash;
  94784. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  94785. if( ALWAYS(pIndex) ){
  94786. if( pIndex->pTable->pIndex==pIndex ){
  94787. pIndex->pTable->pIndex = pIndex->pNext;
  94788. }else{
  94789. Index *p;
  94790. /* Justification of ALWAYS(); The index must be on the list of
  94791. ** indices. */
  94792. p = pIndex->pTable->pIndex;
  94793. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  94794. if( ALWAYS(p && p->pNext==pIndex) ){
  94795. p->pNext = pIndex->pNext;
  94796. }
  94797. }
  94798. freeIndex(db, pIndex);
  94799. }
  94800. db->mDbFlags |= DBFLAG_SchemaChange;
  94801. }
  94802. /*
  94803. ** Look through the list of open database files in db->aDb[] and if
  94804. ** any have been closed, remove them from the list. Reallocate the
  94805. ** db->aDb[] structure to a smaller size, if possible.
  94806. **
  94807. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  94808. ** are never candidates for being collapsed.
  94809. */
  94810. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  94811. int i, j;
  94812. for(i=j=2; i<db->nDb; i++){
  94813. struct Db *pDb = &db->aDb[i];
  94814. if( pDb->pBt==0 ){
  94815. sqlite3DbFree(db, pDb->zDbSName);
  94816. pDb->zDbSName = 0;
  94817. continue;
  94818. }
  94819. if( j<i ){
  94820. db->aDb[j] = db->aDb[i];
  94821. }
  94822. j++;
  94823. }
  94824. db->nDb = j;
  94825. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  94826. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  94827. sqlite3DbFree(db, db->aDb);
  94828. db->aDb = db->aDbStatic;
  94829. }
  94830. }
  94831. /*
  94832. ** Reset the schema for the database at index iDb. Also reset the
  94833. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  94834. ** Deferred resets may be run by calling with iDb<0.
  94835. */
  94836. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  94837. int i;
  94838. assert( iDb<db->nDb );
  94839. if( iDb>=0 ){
  94840. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94841. DbSetProperty(db, iDb, DB_ResetWanted);
  94842. DbSetProperty(db, 1, DB_ResetWanted);
  94843. }
  94844. if( db->nSchemaLock==0 ){
  94845. for(i=0; i<db->nDb; i++){
  94846. if( DbHasProperty(db, i, DB_ResetWanted) ){
  94847. sqlite3SchemaClear(db->aDb[i].pSchema);
  94848. }
  94849. }
  94850. }
  94851. }
  94852. /*
  94853. ** Erase all schema information from all attached databases (including
  94854. ** "main" and "temp") for a single database connection.
  94855. */
  94856. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  94857. int i;
  94858. sqlite3BtreeEnterAll(db);
  94859. assert( db->nSchemaLock==0 );
  94860. for(i=0; i<db->nDb; i++){
  94861. Db *pDb = &db->aDb[i];
  94862. if( pDb->pSchema ){
  94863. sqlite3SchemaClear(pDb->pSchema);
  94864. }
  94865. }
  94866. db->mDbFlags &= ~DBFLAG_SchemaChange;
  94867. sqlite3VtabUnlockList(db);
  94868. sqlite3BtreeLeaveAll(db);
  94869. sqlite3CollapseDatabaseArray(db);
  94870. }
  94871. /*
  94872. ** This routine is called when a commit occurs.
  94873. */
  94874. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  94875. db->mDbFlags &= ~DBFLAG_SchemaChange;
  94876. }
  94877. /*
  94878. ** Delete memory allocated for the column names of a table or view (the
  94879. ** Table.aCol[] array).
  94880. */
  94881. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  94882. int i;
  94883. Column *pCol;
  94884. assert( pTable!=0 );
  94885. if( (pCol = pTable->aCol)!=0 ){
  94886. for(i=0; i<pTable->nCol; i++, pCol++){
  94887. sqlite3DbFree(db, pCol->zName);
  94888. sqlite3ExprDelete(db, pCol->pDflt);
  94889. sqlite3DbFree(db, pCol->zColl);
  94890. }
  94891. sqlite3DbFree(db, pTable->aCol);
  94892. }
  94893. }
  94894. /*
  94895. ** Remove the memory data structures associated with the given
  94896. ** Table. No changes are made to disk by this routine.
  94897. **
  94898. ** This routine just deletes the data structure. It does not unlink
  94899. ** the table data structure from the hash table. But it does destroy
  94900. ** memory structures of the indices and foreign keys associated with
  94901. ** the table.
  94902. **
  94903. ** The db parameter is optional. It is needed if the Table object
  94904. ** contains lookaside memory. (Table objects in the schema do not use
  94905. ** lookaside memory, but some ephemeral Table objects do.) Or the
  94906. ** db parameter can be used with db->pnBytesFreed to measure the memory
  94907. ** used by the Table object.
  94908. */
  94909. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  94910. Index *pIndex, *pNext;
  94911. #ifdef SQLITE_DEBUG
  94912. /* Record the number of outstanding lookaside allocations in schema Tables
  94913. ** prior to doing any free() operations. Since schema Tables do not use
  94914. ** lookaside, this number should not change. */
  94915. int nLookaside = 0;
  94916. if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
  94917. nLookaside = sqlite3LookasideUsed(db, 0);
  94918. }
  94919. #endif
  94920. /* Delete all indices associated with this table. */
  94921. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  94922. pNext = pIndex->pNext;
  94923. assert( pIndex->pSchema==pTable->pSchema
  94924. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  94925. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  94926. char *zName = pIndex->zName;
  94927. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  94928. &pIndex->pSchema->idxHash, zName, 0
  94929. );
  94930. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  94931. assert( pOld==pIndex || pOld==0 );
  94932. }
  94933. freeIndex(db, pIndex);
  94934. }
  94935. /* Delete any foreign keys attached to this table. */
  94936. sqlite3FkDelete(db, pTable);
  94937. /* Delete the Table structure itself.
  94938. */
  94939. sqlite3DeleteColumnNames(db, pTable);
  94940. sqlite3DbFree(db, pTable->zName);
  94941. sqlite3DbFree(db, pTable->zColAff);
  94942. sqlite3SelectDelete(db, pTable->pSelect);
  94943. sqlite3ExprListDelete(db, pTable->pCheck);
  94944. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94945. sqlite3VtabClear(db, pTable);
  94946. #endif
  94947. sqlite3DbFree(db, pTable);
  94948. /* Verify that no lookaside memory was used by schema tables */
  94949. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  94950. }
  94951. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  94952. /* Do not delete the table until the reference count reaches zero. */
  94953. if( !pTable ) return;
  94954. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  94955. deleteTable(db, pTable);
  94956. }
  94957. /*
  94958. ** Unlink the given table from the hash tables and the delete the
  94959. ** table structure with all its indices and foreign keys.
  94960. */
  94961. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  94962. Table *p;
  94963. Db *pDb;
  94964. assert( db!=0 );
  94965. assert( iDb>=0 && iDb<db->nDb );
  94966. assert( zTabName );
  94967. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94968. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  94969. pDb = &db->aDb[iDb];
  94970. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  94971. sqlite3DeleteTable(db, p);
  94972. db->mDbFlags |= DBFLAG_SchemaChange;
  94973. }
  94974. /*
  94975. ** Given a token, return a string that consists of the text of that
  94976. ** token. Space to hold the returned string
  94977. ** is obtained from sqliteMalloc() and must be freed by the calling
  94978. ** function.
  94979. **
  94980. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  94981. ** surround the body of the token are removed.
  94982. **
  94983. ** Tokens are often just pointers into the original SQL text and so
  94984. ** are not \000 terminated and are not persistent. The returned string
  94985. ** is \000 terminated and is persistent.
  94986. */
  94987. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  94988. char *zName;
  94989. if( pName ){
  94990. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  94991. sqlite3Dequote(zName);
  94992. }else{
  94993. zName = 0;
  94994. }
  94995. return zName;
  94996. }
  94997. /*
  94998. ** Open the sqlite_master table stored in database number iDb for
  94999. ** writing. The table is opened using cursor 0.
  95000. */
  95001. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  95002. Vdbe *v = sqlite3GetVdbe(p);
  95003. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  95004. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  95005. if( p->nTab==0 ){
  95006. p->nTab = 1;
  95007. }
  95008. }
  95009. /*
  95010. ** Parameter zName points to a nul-terminated buffer containing the name
  95011. ** of a database ("main", "temp" or the name of an attached db). This
  95012. ** function returns the index of the named database in db->aDb[], or
  95013. ** -1 if the named db cannot be found.
  95014. */
  95015. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  95016. int i = -1; /* Database number */
  95017. if( zName ){
  95018. Db *pDb;
  95019. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  95020. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  95021. /* "main" is always an acceptable alias for the primary database
  95022. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  95023. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  95024. }
  95025. }
  95026. return i;
  95027. }
  95028. /*
  95029. ** The token *pName contains the name of a database (either "main" or
  95030. ** "temp" or the name of an attached db). This routine returns the
  95031. ** index of the named database in db->aDb[], or -1 if the named db
  95032. ** does not exist.
  95033. */
  95034. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  95035. int i; /* Database number */
  95036. char *zName; /* Name we are searching for */
  95037. zName = sqlite3NameFromToken(db, pName);
  95038. i = sqlite3FindDbName(db, zName);
  95039. sqlite3DbFree(db, zName);
  95040. return i;
  95041. }
  95042. /* The table or view or trigger name is passed to this routine via tokens
  95043. ** pName1 and pName2. If the table name was fully qualified, for example:
  95044. **
  95045. ** CREATE TABLE xxx.yyy (...);
  95046. **
  95047. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  95048. ** the table name is not fully qualified, i.e.:
  95049. **
  95050. ** CREATE TABLE yyy(...);
  95051. **
  95052. ** Then pName1 is set to "yyy" and pName2 is "".
  95053. **
  95054. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  95055. ** pName2) that stores the unqualified table name. The index of the
  95056. ** database "xxx" is returned.
  95057. */
  95058. SQLITE_PRIVATE int sqlite3TwoPartName(
  95059. Parse *pParse, /* Parsing and code generating context */
  95060. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  95061. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  95062. Token **pUnqual /* Write the unqualified object name here */
  95063. ){
  95064. int iDb; /* Database holding the object */
  95065. sqlite3 *db = pParse->db;
  95066. assert( pName2!=0 );
  95067. if( pName2->n>0 ){
  95068. if( db->init.busy ) {
  95069. sqlite3ErrorMsg(pParse, "corrupt database");
  95070. return -1;
  95071. }
  95072. *pUnqual = pName2;
  95073. iDb = sqlite3FindDb(db, pName1);
  95074. if( iDb<0 ){
  95075. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  95076. return -1;
  95077. }
  95078. }else{
  95079. assert( db->init.iDb==0 || db->init.busy
  95080. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  95081. iDb = db->init.iDb;
  95082. *pUnqual = pName1;
  95083. }
  95084. return iDb;
  95085. }
  95086. /*
  95087. ** This routine is used to check if the UTF-8 string zName is a legal
  95088. ** unqualified name for a new schema object (table, index, view or
  95089. ** trigger). All names are legal except those that begin with the string
  95090. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  95091. ** is reserved for internal use.
  95092. */
  95093. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  95094. if( !pParse->db->init.busy && pParse->nested==0
  95095. && (pParse->db->flags & SQLITE_WriteSchema)==0
  95096. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  95097. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  95098. return SQLITE_ERROR;
  95099. }
  95100. return SQLITE_OK;
  95101. }
  95102. /*
  95103. ** Return the PRIMARY KEY index of a table
  95104. */
  95105. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  95106. Index *p;
  95107. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  95108. return p;
  95109. }
  95110. /*
  95111. ** Return the column of index pIdx that corresponds to table
  95112. ** column iCol. Return -1 if not found.
  95113. */
  95114. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  95115. int i;
  95116. for(i=0; i<pIdx->nColumn; i++){
  95117. if( iCol==pIdx->aiColumn[i] ) return i;
  95118. }
  95119. return -1;
  95120. }
  95121. /*
  95122. ** Begin constructing a new table representation in memory. This is
  95123. ** the first of several action routines that get called in response
  95124. ** to a CREATE TABLE statement. In particular, this routine is called
  95125. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  95126. ** flag is true if the table should be stored in the auxiliary database
  95127. ** file instead of in the main database file. This is normally the case
  95128. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  95129. ** CREATE and TABLE.
  95130. **
  95131. ** The new table record is initialized and put in pParse->pNewTable.
  95132. ** As more of the CREATE TABLE statement is parsed, additional action
  95133. ** routines will be called to add more information to this record.
  95134. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  95135. ** is called to complete the construction of the new table record.
  95136. */
  95137. SQLITE_PRIVATE void sqlite3StartTable(
  95138. Parse *pParse, /* Parser context */
  95139. Token *pName1, /* First part of the name of the table or view */
  95140. Token *pName2, /* Second part of the name of the table or view */
  95141. int isTemp, /* True if this is a TEMP table */
  95142. int isView, /* True if this is a VIEW */
  95143. int isVirtual, /* True if this is a VIRTUAL table */
  95144. int noErr /* Do nothing if table already exists */
  95145. ){
  95146. Table *pTable;
  95147. char *zName = 0; /* The name of the new table */
  95148. sqlite3 *db = pParse->db;
  95149. Vdbe *v;
  95150. int iDb; /* Database number to create the table in */
  95151. Token *pName; /* Unqualified name of the table to create */
  95152. if( db->init.busy && db->init.newTnum==1 ){
  95153. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  95154. iDb = db->init.iDb;
  95155. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  95156. pName = pName1;
  95157. }else{
  95158. /* The common case */
  95159. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  95160. if( iDb<0 ) return;
  95161. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  95162. /* If creating a temp table, the name may not be qualified. Unless
  95163. ** the database name is "temp" anyway. */
  95164. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  95165. return;
  95166. }
  95167. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  95168. zName = sqlite3NameFromToken(db, pName);
  95169. }
  95170. pParse->sNameToken = *pName;
  95171. if( zName==0 ) return;
  95172. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  95173. goto begin_table_error;
  95174. }
  95175. if( db->init.iDb==1 ) isTemp = 1;
  95176. #ifndef SQLITE_OMIT_AUTHORIZATION
  95177. assert( isTemp==0 || isTemp==1 );
  95178. assert( isView==0 || isView==1 );
  95179. {
  95180. static const u8 aCode[] = {
  95181. SQLITE_CREATE_TABLE,
  95182. SQLITE_CREATE_TEMP_TABLE,
  95183. SQLITE_CREATE_VIEW,
  95184. SQLITE_CREATE_TEMP_VIEW
  95185. };
  95186. char *zDb = db->aDb[iDb].zDbSName;
  95187. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  95188. goto begin_table_error;
  95189. }
  95190. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  95191. zName, 0, zDb) ){
  95192. goto begin_table_error;
  95193. }
  95194. }
  95195. #endif
  95196. /* Make sure the new table name does not collide with an existing
  95197. ** index or table name in the same database. Issue an error message if
  95198. ** it does. The exception is if the statement being parsed was passed
  95199. ** to an sqlite3_declare_vtab() call. In that case only the column names
  95200. ** and types will be used, so there is no need to test for namespace
  95201. ** collisions.
  95202. */
  95203. if( !IN_DECLARE_VTAB ){
  95204. char *zDb = db->aDb[iDb].zDbSName;
  95205. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  95206. goto begin_table_error;
  95207. }
  95208. pTable = sqlite3FindTable(db, zName, zDb);
  95209. if( pTable ){
  95210. if( !noErr ){
  95211. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  95212. }else{
  95213. assert( !db->init.busy || CORRUPT_DB );
  95214. sqlite3CodeVerifySchema(pParse, iDb);
  95215. }
  95216. goto begin_table_error;
  95217. }
  95218. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  95219. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  95220. goto begin_table_error;
  95221. }
  95222. }
  95223. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  95224. if( pTable==0 ){
  95225. assert( db->mallocFailed );
  95226. pParse->rc = SQLITE_NOMEM_BKPT;
  95227. pParse->nErr++;
  95228. goto begin_table_error;
  95229. }
  95230. pTable->zName = zName;
  95231. pTable->iPKey = -1;
  95232. pTable->pSchema = db->aDb[iDb].pSchema;
  95233. pTable->nTabRef = 1;
  95234. #ifdef SQLITE_DEFAULT_ROWEST
  95235. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  95236. #else
  95237. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  95238. #endif
  95239. assert( pParse->pNewTable==0 );
  95240. pParse->pNewTable = pTable;
  95241. /* If this is the magic sqlite_sequence table used by autoincrement,
  95242. ** then record a pointer to this table in the main database structure
  95243. ** so that INSERT can find the table easily.
  95244. */
  95245. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95246. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  95247. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95248. pTable->pSchema->pSeqTab = pTable;
  95249. }
  95250. #endif
  95251. /* Begin generating the code that will insert the table record into
  95252. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  95253. ** and allocate the record number for the table entry now. Before any
  95254. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  95255. ** indices to be created and the table record must come before the
  95256. ** indices. Hence, the record number for the table must be allocated
  95257. ** now.
  95258. */
  95259. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  95260. int addr1;
  95261. int fileFormat;
  95262. int reg1, reg2, reg3;
  95263. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  95264. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  95265. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95266. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95267. if( isVirtual ){
  95268. sqlite3VdbeAddOp0(v, OP_VBegin);
  95269. }
  95270. #endif
  95271. /* If the file format and encoding in the database have not been set,
  95272. ** set them now.
  95273. */
  95274. reg1 = pParse->regRowid = ++pParse->nMem;
  95275. reg2 = pParse->regRoot = ++pParse->nMem;
  95276. reg3 = ++pParse->nMem;
  95277. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  95278. sqlite3VdbeUsesBtree(v, iDb);
  95279. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  95280. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  95281. 1 : SQLITE_MAX_FILE_FORMAT;
  95282. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  95283. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  95284. sqlite3VdbeJumpHere(v, addr1);
  95285. /* This just creates a place-holder record in the sqlite_master table.
  95286. ** The record created does not contain anything yet. It will be replaced
  95287. ** by the real entry in code generated at sqlite3EndTable().
  95288. **
  95289. ** The rowid for the new entry is left in register pParse->regRowid.
  95290. ** The root page number of the new table is left in reg pParse->regRoot.
  95291. ** The rowid and root page number values are needed by the code that
  95292. ** sqlite3EndTable will generate.
  95293. */
  95294. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  95295. if( isView || isVirtual ){
  95296. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  95297. }else
  95298. #endif
  95299. {
  95300. pParse->addrCrTab =
  95301. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  95302. }
  95303. sqlite3OpenMasterTable(pParse, iDb);
  95304. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  95305. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  95306. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  95307. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95308. sqlite3VdbeAddOp0(v, OP_Close);
  95309. }
  95310. /* Normal (non-error) return. */
  95311. return;
  95312. /* If an error occurs, we jump here */
  95313. begin_table_error:
  95314. sqlite3DbFree(db, zName);
  95315. return;
  95316. }
  95317. /* Set properties of a table column based on the (magical)
  95318. ** name of the column.
  95319. */
  95320. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  95321. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  95322. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  95323. pCol->colFlags |= COLFLAG_HIDDEN;
  95324. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  95325. pTab->tabFlags |= TF_OOOHidden;
  95326. }
  95327. }
  95328. #endif
  95329. /*
  95330. ** Add a new column to the table currently being constructed.
  95331. **
  95332. ** The parser calls this routine once for each column declaration
  95333. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  95334. ** first to get things going. Then this routine is called for each
  95335. ** column.
  95336. */
  95337. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  95338. Table *p;
  95339. int i;
  95340. char *z;
  95341. char *zType;
  95342. Column *pCol;
  95343. sqlite3 *db = pParse->db;
  95344. if( (p = pParse->pNewTable)==0 ) return;
  95345. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  95346. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  95347. return;
  95348. }
  95349. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  95350. if( z==0 ) return;
  95351. memcpy(z, pName->z, pName->n);
  95352. z[pName->n] = 0;
  95353. sqlite3Dequote(z);
  95354. for(i=0; i<p->nCol; i++){
  95355. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  95356. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  95357. sqlite3DbFree(db, z);
  95358. return;
  95359. }
  95360. }
  95361. if( (p->nCol & 0x7)==0 ){
  95362. Column *aNew;
  95363. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  95364. if( aNew==0 ){
  95365. sqlite3DbFree(db, z);
  95366. return;
  95367. }
  95368. p->aCol = aNew;
  95369. }
  95370. pCol = &p->aCol[p->nCol];
  95371. memset(pCol, 0, sizeof(p->aCol[0]));
  95372. pCol->zName = z;
  95373. sqlite3ColumnPropertiesFromName(p, pCol);
  95374. if( pType->n==0 ){
  95375. /* If there is no type specified, columns have the default affinity
  95376. ** 'BLOB'. */
  95377. pCol->affinity = SQLITE_AFF_BLOB;
  95378. pCol->szEst = 1;
  95379. }else{
  95380. zType = z + sqlite3Strlen30(z) + 1;
  95381. memcpy(zType, pType->z, pType->n);
  95382. zType[pType->n] = 0;
  95383. sqlite3Dequote(zType);
  95384. pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
  95385. pCol->colFlags |= COLFLAG_HASTYPE;
  95386. }
  95387. p->nCol++;
  95388. pParse->constraintName.n = 0;
  95389. }
  95390. /*
  95391. ** This routine is called by the parser while in the middle of
  95392. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  95393. ** been seen on a column. This routine sets the notNull flag on
  95394. ** the column currently under construction.
  95395. */
  95396. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  95397. Table *p;
  95398. p = pParse->pNewTable;
  95399. if( p==0 || NEVER(p->nCol<1) ) return;
  95400. p->aCol[p->nCol-1].notNull = (u8)onError;
  95401. p->tabFlags |= TF_HasNotNull;
  95402. }
  95403. /*
  95404. ** Scan the column type name zType (length nType) and return the
  95405. ** associated affinity type.
  95406. **
  95407. ** This routine does a case-independent search of zType for the
  95408. ** substrings in the following table. If one of the substrings is
  95409. ** found, the corresponding affinity is returned. If zType contains
  95410. ** more than one of the substrings, entries toward the top of
  95411. ** the table take priority. For example, if zType is 'BLOBINT',
  95412. ** SQLITE_AFF_INTEGER is returned.
  95413. **
  95414. ** Substring | Affinity
  95415. ** --------------------------------
  95416. ** 'INT' | SQLITE_AFF_INTEGER
  95417. ** 'CHAR' | SQLITE_AFF_TEXT
  95418. ** 'CLOB' | SQLITE_AFF_TEXT
  95419. ** 'TEXT' | SQLITE_AFF_TEXT
  95420. ** 'BLOB' | SQLITE_AFF_BLOB
  95421. ** 'REAL' | SQLITE_AFF_REAL
  95422. ** 'FLOA' | SQLITE_AFF_REAL
  95423. ** 'DOUB' | SQLITE_AFF_REAL
  95424. **
  95425. ** If none of the substrings in the above table are found,
  95426. ** SQLITE_AFF_NUMERIC is returned.
  95427. */
  95428. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  95429. u32 h = 0;
  95430. char aff = SQLITE_AFF_NUMERIC;
  95431. const char *zChar = 0;
  95432. assert( zIn!=0 );
  95433. while( zIn[0] ){
  95434. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  95435. zIn++;
  95436. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  95437. aff = SQLITE_AFF_TEXT;
  95438. zChar = zIn;
  95439. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  95440. aff = SQLITE_AFF_TEXT;
  95441. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  95442. aff = SQLITE_AFF_TEXT;
  95443. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  95444. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  95445. aff = SQLITE_AFF_BLOB;
  95446. if( zIn[0]=='(' ) zChar = zIn;
  95447. #ifndef SQLITE_OMIT_FLOATING_POINT
  95448. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  95449. && aff==SQLITE_AFF_NUMERIC ){
  95450. aff = SQLITE_AFF_REAL;
  95451. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  95452. && aff==SQLITE_AFF_NUMERIC ){
  95453. aff = SQLITE_AFF_REAL;
  95454. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  95455. && aff==SQLITE_AFF_NUMERIC ){
  95456. aff = SQLITE_AFF_REAL;
  95457. #endif
  95458. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  95459. aff = SQLITE_AFF_INTEGER;
  95460. break;
  95461. }
  95462. }
  95463. /* If pszEst is not NULL, store an estimate of the field size. The
  95464. ** estimate is scaled so that the size of an integer is 1. */
  95465. if( pszEst ){
  95466. *pszEst = 1; /* default size is approx 4 bytes */
  95467. if( aff<SQLITE_AFF_NUMERIC ){
  95468. if( zChar ){
  95469. while( zChar[0] ){
  95470. if( sqlite3Isdigit(zChar[0]) ){
  95471. int v = 0;
  95472. sqlite3GetInt32(zChar, &v);
  95473. v = v/4 + 1;
  95474. if( v>255 ) v = 255;
  95475. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  95476. break;
  95477. }
  95478. zChar++;
  95479. }
  95480. }else{
  95481. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  95482. }
  95483. }
  95484. }
  95485. return aff;
  95486. }
  95487. /*
  95488. ** The expression is the default value for the most recently added column
  95489. ** of the table currently under construction.
  95490. **
  95491. ** Default value expressions must be constant. Raise an exception if this
  95492. ** is not the case.
  95493. **
  95494. ** This routine is called by the parser while in the middle of
  95495. ** parsing a CREATE TABLE statement.
  95496. */
  95497. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  95498. Table *p;
  95499. Column *pCol;
  95500. sqlite3 *db = pParse->db;
  95501. p = pParse->pNewTable;
  95502. if( p!=0 ){
  95503. pCol = &(p->aCol[p->nCol-1]);
  95504. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  95505. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  95506. pCol->zName);
  95507. }else{
  95508. /* A copy of pExpr is used instead of the original, as pExpr contains
  95509. ** tokens that point to volatile memory. The 'span' of the expression
  95510. ** is required by pragma table_info.
  95511. */
  95512. Expr x;
  95513. sqlite3ExprDelete(db, pCol->pDflt);
  95514. memset(&x, 0, sizeof(x));
  95515. x.op = TK_SPAN;
  95516. x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  95517. (int)(pSpan->zEnd - pSpan->zStart));
  95518. x.pLeft = pSpan->pExpr;
  95519. x.flags = EP_Skip;
  95520. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  95521. sqlite3DbFree(db, x.u.zToken);
  95522. }
  95523. }
  95524. sqlite3ExprDelete(db, pSpan->pExpr);
  95525. }
  95526. /*
  95527. ** Backwards Compatibility Hack:
  95528. **
  95529. ** Historical versions of SQLite accepted strings as column names in
  95530. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  95531. **
  95532. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  95533. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  95534. **
  95535. ** This is goofy. But to preserve backwards compatibility we continue to
  95536. ** accept it. This routine does the necessary conversion. It converts
  95537. ** the expression given in its argument from a TK_STRING into a TK_ID
  95538. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  95539. ** If the epxression is anything other than TK_STRING, the expression is
  95540. ** unchanged.
  95541. */
  95542. static void sqlite3StringToId(Expr *p){
  95543. if( p->op==TK_STRING ){
  95544. p->op = TK_ID;
  95545. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  95546. p->pLeft->op = TK_ID;
  95547. }
  95548. }
  95549. /*
  95550. ** Designate the PRIMARY KEY for the table. pList is a list of names
  95551. ** of columns that form the primary key. If pList is NULL, then the
  95552. ** most recently added column of the table is the primary key.
  95553. **
  95554. ** A table can have at most one primary key. If the table already has
  95555. ** a primary key (and this is the second primary key) then create an
  95556. ** error.
  95557. **
  95558. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  95559. ** then we will try to use that column as the rowid. Set the Table.iPKey
  95560. ** field of the table under construction to be the index of the
  95561. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  95562. ** no INTEGER PRIMARY KEY.
  95563. **
  95564. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  95565. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  95566. */
  95567. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  95568. Parse *pParse, /* Parsing context */
  95569. ExprList *pList, /* List of field names to be indexed */
  95570. int onError, /* What to do with a uniqueness conflict */
  95571. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  95572. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  95573. ){
  95574. Table *pTab = pParse->pNewTable;
  95575. Column *pCol = 0;
  95576. int iCol = -1, i;
  95577. int nTerm;
  95578. if( pTab==0 ) goto primary_key_exit;
  95579. if( pTab->tabFlags & TF_HasPrimaryKey ){
  95580. sqlite3ErrorMsg(pParse,
  95581. "table \"%s\" has more than one primary key", pTab->zName);
  95582. goto primary_key_exit;
  95583. }
  95584. pTab->tabFlags |= TF_HasPrimaryKey;
  95585. if( pList==0 ){
  95586. iCol = pTab->nCol - 1;
  95587. pCol = &pTab->aCol[iCol];
  95588. pCol->colFlags |= COLFLAG_PRIMKEY;
  95589. nTerm = 1;
  95590. }else{
  95591. nTerm = pList->nExpr;
  95592. for(i=0; i<nTerm; i++){
  95593. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  95594. assert( pCExpr!=0 );
  95595. sqlite3StringToId(pCExpr);
  95596. if( pCExpr->op==TK_ID ){
  95597. const char *zCName = pCExpr->u.zToken;
  95598. for(iCol=0; iCol<pTab->nCol; iCol++){
  95599. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  95600. pCol = &pTab->aCol[iCol];
  95601. pCol->colFlags |= COLFLAG_PRIMKEY;
  95602. break;
  95603. }
  95604. }
  95605. }
  95606. }
  95607. }
  95608. if( nTerm==1
  95609. && pCol
  95610. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  95611. && sortOrder!=SQLITE_SO_DESC
  95612. ){
  95613. pTab->iPKey = iCol;
  95614. pTab->keyConf = (u8)onError;
  95615. assert( autoInc==0 || autoInc==1 );
  95616. pTab->tabFlags |= autoInc*TF_Autoincrement;
  95617. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  95618. }else if( autoInc ){
  95619. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95620. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  95621. "INTEGER PRIMARY KEY");
  95622. #endif
  95623. }else{
  95624. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  95625. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  95626. pList = 0;
  95627. }
  95628. primary_key_exit:
  95629. sqlite3ExprListDelete(pParse->db, pList);
  95630. return;
  95631. }
  95632. /*
  95633. ** Add a new CHECK constraint to the table currently under construction.
  95634. */
  95635. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  95636. Parse *pParse, /* Parsing context */
  95637. Expr *pCheckExpr /* The check expression */
  95638. ){
  95639. #ifndef SQLITE_OMIT_CHECK
  95640. Table *pTab = pParse->pNewTable;
  95641. sqlite3 *db = pParse->db;
  95642. if( pTab && !IN_DECLARE_VTAB
  95643. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  95644. ){
  95645. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  95646. if( pParse->constraintName.n ){
  95647. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  95648. }
  95649. }else
  95650. #endif
  95651. {
  95652. sqlite3ExprDelete(pParse->db, pCheckExpr);
  95653. }
  95654. }
  95655. /*
  95656. ** Set the collation function of the most recently parsed table column
  95657. ** to the CollSeq given.
  95658. */
  95659. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  95660. Table *p;
  95661. int i;
  95662. char *zColl; /* Dequoted name of collation sequence */
  95663. sqlite3 *db;
  95664. if( (p = pParse->pNewTable)==0 ) return;
  95665. i = p->nCol-1;
  95666. db = pParse->db;
  95667. zColl = sqlite3NameFromToken(db, pToken);
  95668. if( !zColl ) return;
  95669. if( sqlite3LocateCollSeq(pParse, zColl) ){
  95670. Index *pIdx;
  95671. sqlite3DbFree(db, p->aCol[i].zColl);
  95672. p->aCol[i].zColl = zColl;
  95673. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  95674. ** then an index may have been created on this column before the
  95675. ** collation type was added. Correct this if it is the case.
  95676. */
  95677. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  95678. assert( pIdx->nKeyCol==1 );
  95679. if( pIdx->aiColumn[0]==i ){
  95680. pIdx->azColl[0] = p->aCol[i].zColl;
  95681. }
  95682. }
  95683. }else{
  95684. sqlite3DbFree(db, zColl);
  95685. }
  95686. }
  95687. /*
  95688. ** This function returns the collation sequence for database native text
  95689. ** encoding identified by the string zName, length nName.
  95690. **
  95691. ** If the requested collation sequence is not available, or not available
  95692. ** in the database native encoding, the collation factory is invoked to
  95693. ** request it. If the collation factory does not supply such a sequence,
  95694. ** and the sequence is available in another text encoding, then that is
  95695. ** returned instead.
  95696. **
  95697. ** If no versions of the requested collations sequence are available, or
  95698. ** another error occurs, NULL is returned and an error message written into
  95699. ** pParse.
  95700. **
  95701. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  95702. ** invokes the collation factory if the named collation cannot be found
  95703. ** and generates an error message.
  95704. **
  95705. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  95706. */
  95707. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  95708. sqlite3 *db = pParse->db;
  95709. u8 enc = ENC(db);
  95710. u8 initbusy = db->init.busy;
  95711. CollSeq *pColl;
  95712. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  95713. if( !initbusy && (!pColl || !pColl->xCmp) ){
  95714. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  95715. }
  95716. return pColl;
  95717. }
  95718. /*
  95719. ** Generate code that will increment the schema cookie.
  95720. **
  95721. ** The schema cookie is used to determine when the schema for the
  95722. ** database changes. After each schema change, the cookie value
  95723. ** changes. When a process first reads the schema it records the
  95724. ** cookie. Thereafter, whenever it goes to access the database,
  95725. ** it checks the cookie to make sure the schema has not changed
  95726. ** since it was last read.
  95727. **
  95728. ** This plan is not completely bullet-proof. It is possible for
  95729. ** the schema to change multiple times and for the cookie to be
  95730. ** set back to prior value. But schema changes are infrequent
  95731. ** and the probability of hitting the same cookie value is only
  95732. ** 1 chance in 2^32. So we're safe enough.
  95733. **
  95734. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  95735. ** the schema-version whenever the schema changes.
  95736. */
  95737. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  95738. sqlite3 *db = pParse->db;
  95739. Vdbe *v = pParse->pVdbe;
  95740. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95741. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  95742. db->aDb[iDb].pSchema->schema_cookie+1);
  95743. }
  95744. /*
  95745. ** Measure the number of characters needed to output the given
  95746. ** identifier. The number returned includes any quotes used
  95747. ** but does not include the null terminator.
  95748. **
  95749. ** The estimate is conservative. It might be larger that what is
  95750. ** really needed.
  95751. */
  95752. static int identLength(const char *z){
  95753. int n;
  95754. for(n=0; *z; n++, z++){
  95755. if( *z=='"' ){ n++; }
  95756. }
  95757. return n + 2;
  95758. }
  95759. /*
  95760. ** The first parameter is a pointer to an output buffer. The second
  95761. ** parameter is a pointer to an integer that contains the offset at
  95762. ** which to write into the output buffer. This function copies the
  95763. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  95764. ** to the specified offset in the buffer and updates *pIdx to refer
  95765. ** to the first byte after the last byte written before returning.
  95766. **
  95767. ** If the string zSignedIdent consists entirely of alpha-numeric
  95768. ** characters, does not begin with a digit and is not an SQL keyword,
  95769. ** then it is copied to the output buffer exactly as it is. Otherwise,
  95770. ** it is quoted using double-quotes.
  95771. */
  95772. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  95773. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  95774. int i, j, needQuote;
  95775. i = *pIdx;
  95776. for(j=0; zIdent[j]; j++){
  95777. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  95778. }
  95779. needQuote = sqlite3Isdigit(zIdent[0])
  95780. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  95781. || zIdent[j]!=0
  95782. || j==0;
  95783. if( needQuote ) z[i++] = '"';
  95784. for(j=0; zIdent[j]; j++){
  95785. z[i++] = zIdent[j];
  95786. if( zIdent[j]=='"' ) z[i++] = '"';
  95787. }
  95788. if( needQuote ) z[i++] = '"';
  95789. z[i] = 0;
  95790. *pIdx = i;
  95791. }
  95792. /*
  95793. ** Generate a CREATE TABLE statement appropriate for the given
  95794. ** table. Memory to hold the text of the statement is obtained
  95795. ** from sqliteMalloc() and must be freed by the calling function.
  95796. */
  95797. static char *createTableStmt(sqlite3 *db, Table *p){
  95798. int i, k, n;
  95799. char *zStmt;
  95800. char *zSep, *zSep2, *zEnd;
  95801. Column *pCol;
  95802. n = 0;
  95803. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  95804. n += identLength(pCol->zName) + 5;
  95805. }
  95806. n += identLength(p->zName);
  95807. if( n<50 ){
  95808. zSep = "";
  95809. zSep2 = ",";
  95810. zEnd = ")";
  95811. }else{
  95812. zSep = "\n ";
  95813. zSep2 = ",\n ";
  95814. zEnd = "\n)";
  95815. }
  95816. n += 35 + 6*p->nCol;
  95817. zStmt = sqlite3DbMallocRaw(0, n);
  95818. if( zStmt==0 ){
  95819. sqlite3OomFault(db);
  95820. return 0;
  95821. }
  95822. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  95823. k = sqlite3Strlen30(zStmt);
  95824. identPut(zStmt, &k, p->zName);
  95825. zStmt[k++] = '(';
  95826. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  95827. static const char * const azType[] = {
  95828. /* SQLITE_AFF_BLOB */ "",
  95829. /* SQLITE_AFF_TEXT */ " TEXT",
  95830. /* SQLITE_AFF_NUMERIC */ " NUM",
  95831. /* SQLITE_AFF_INTEGER */ " INT",
  95832. /* SQLITE_AFF_REAL */ " REAL"
  95833. };
  95834. int len;
  95835. const char *zType;
  95836. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  95837. k += sqlite3Strlen30(&zStmt[k]);
  95838. zSep = zSep2;
  95839. identPut(zStmt, &k, pCol->zName);
  95840. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  95841. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  95842. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  95843. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  95844. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  95845. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  95846. testcase( pCol->affinity==SQLITE_AFF_REAL );
  95847. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  95848. len = sqlite3Strlen30(zType);
  95849. assert( pCol->affinity==SQLITE_AFF_BLOB
  95850. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  95851. memcpy(&zStmt[k], zType, len);
  95852. k += len;
  95853. assert( k<=n );
  95854. }
  95855. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  95856. return zStmt;
  95857. }
  95858. /*
  95859. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  95860. ** on success and SQLITE_NOMEM on an OOM error.
  95861. */
  95862. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  95863. char *zExtra;
  95864. int nByte;
  95865. if( pIdx->nColumn>=N ) return SQLITE_OK;
  95866. assert( pIdx->isResized==0 );
  95867. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  95868. zExtra = sqlite3DbMallocZero(db, nByte);
  95869. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  95870. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  95871. pIdx->azColl = (const char**)zExtra;
  95872. zExtra += sizeof(char*)*N;
  95873. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  95874. pIdx->aiColumn = (i16*)zExtra;
  95875. zExtra += sizeof(i16)*N;
  95876. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  95877. pIdx->aSortOrder = (u8*)zExtra;
  95878. pIdx->nColumn = N;
  95879. pIdx->isResized = 1;
  95880. return SQLITE_OK;
  95881. }
  95882. /*
  95883. ** Estimate the total row width for a table.
  95884. */
  95885. static void estimateTableWidth(Table *pTab){
  95886. unsigned wTable = 0;
  95887. const Column *pTabCol;
  95888. int i;
  95889. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  95890. wTable += pTabCol->szEst;
  95891. }
  95892. if( pTab->iPKey<0 ) wTable++;
  95893. pTab->szTabRow = sqlite3LogEst(wTable*4);
  95894. }
  95895. /*
  95896. ** Estimate the average size of a row for an index.
  95897. */
  95898. static void estimateIndexWidth(Index *pIdx){
  95899. unsigned wIndex = 0;
  95900. int i;
  95901. const Column *aCol = pIdx->pTable->aCol;
  95902. for(i=0; i<pIdx->nColumn; i++){
  95903. i16 x = pIdx->aiColumn[i];
  95904. assert( x<pIdx->pTable->nCol );
  95905. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  95906. }
  95907. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  95908. }
  95909. /* Return true if value x is found any of the first nCol entries of aiCol[]
  95910. */
  95911. static int hasColumn(const i16 *aiCol, int nCol, int x){
  95912. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  95913. return 0;
  95914. }
  95915. /*
  95916. ** This routine runs at the end of parsing a CREATE TABLE statement that
  95917. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  95918. ** internal schema data structures and the generated VDBE code so that they
  95919. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  95920. ** Changes include:
  95921. **
  95922. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  95923. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  95924. ** into BTREE_BLOBKEY.
  95925. ** (3) Bypass the creation of the sqlite_master table entry
  95926. ** for the PRIMARY KEY as the primary key index is now
  95927. ** identified by the sqlite_master table entry of the table itself.
  95928. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  95929. ** schema to the rootpage from the main table.
  95930. ** (5) Add all table columns to the PRIMARY KEY Index object
  95931. ** so that the PRIMARY KEY is a covering index. The surplus
  95932. ** columns are part of KeyInfo.nAllField and are not used for
  95933. ** sorting or lookup or uniqueness checks.
  95934. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  95935. ** indices with the PRIMARY KEY columns.
  95936. **
  95937. ** For virtual tables, only (1) is performed.
  95938. */
  95939. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  95940. Index *pIdx;
  95941. Index *pPk;
  95942. int nPk;
  95943. int i, j;
  95944. sqlite3 *db = pParse->db;
  95945. Vdbe *v = pParse->pVdbe;
  95946. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  95947. */
  95948. if( !db->init.imposterTable ){
  95949. for(i=0; i<pTab->nCol; i++){
  95950. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  95951. pTab->aCol[i].notNull = OE_Abort;
  95952. }
  95953. }
  95954. }
  95955. /* The remaining transformations only apply to b-tree tables, not to
  95956. ** virtual tables */
  95957. if( IN_DECLARE_VTAB ) return;
  95958. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  95959. ** into BTREE_BLOBKEY.
  95960. */
  95961. if( pParse->addrCrTab ){
  95962. assert( v );
  95963. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  95964. }
  95965. /* Locate the PRIMARY KEY index. Or, if this table was originally
  95966. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  95967. */
  95968. if( pTab->iPKey>=0 ){
  95969. ExprList *pList;
  95970. Token ipkToken;
  95971. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  95972. pList = sqlite3ExprListAppend(pParse, 0,
  95973. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  95974. if( pList==0 ) return;
  95975. pList->a[0].sortOrder = pParse->iPkSortOrder;
  95976. assert( pParse->pNewTable==pTab );
  95977. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  95978. SQLITE_IDXTYPE_PRIMARYKEY);
  95979. if( db->mallocFailed ) return;
  95980. pPk = sqlite3PrimaryKeyIndex(pTab);
  95981. pTab->iPKey = -1;
  95982. }else{
  95983. pPk = sqlite3PrimaryKeyIndex(pTab);
  95984. /*
  95985. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  95986. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  95987. ** code assumes the PRIMARY KEY contains no repeated columns.
  95988. */
  95989. for(i=j=1; i<pPk->nKeyCol; i++){
  95990. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  95991. pPk->nColumn--;
  95992. }else{
  95993. pPk->aiColumn[j++] = pPk->aiColumn[i];
  95994. }
  95995. }
  95996. pPk->nKeyCol = j;
  95997. }
  95998. assert( pPk!=0 );
  95999. pPk->isCovering = 1;
  96000. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  96001. nPk = pPk->nKeyCol;
  96002. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  96003. ** table entry. This is only required if currently generating VDBE
  96004. ** code for a CREATE TABLE (not when parsing one as part of reading
  96005. ** a database schema). */
  96006. if( v && pPk->tnum>0 ){
  96007. assert( db->init.busy==0 );
  96008. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  96009. }
  96010. /* The root page of the PRIMARY KEY is the table root page */
  96011. pPk->tnum = pTab->tnum;
  96012. /* Update the in-memory representation of all UNIQUE indices by converting
  96013. ** the final rowid column into one or more columns of the PRIMARY KEY.
  96014. */
  96015. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96016. int n;
  96017. if( IsPrimaryKeyIndex(pIdx) ) continue;
  96018. for(i=n=0; i<nPk; i++){
  96019. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  96020. }
  96021. if( n==0 ){
  96022. /* This index is a superset of the primary key */
  96023. pIdx->nColumn = pIdx->nKeyCol;
  96024. continue;
  96025. }
  96026. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  96027. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  96028. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  96029. pIdx->aiColumn[j] = pPk->aiColumn[i];
  96030. pIdx->azColl[j] = pPk->azColl[i];
  96031. j++;
  96032. }
  96033. }
  96034. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  96035. assert( pIdx->nColumn>=j );
  96036. }
  96037. /* Add all table columns to the PRIMARY KEY index
  96038. */
  96039. if( nPk<pTab->nCol ){
  96040. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  96041. for(i=0, j=nPk; i<pTab->nCol; i++){
  96042. if( !hasColumn(pPk->aiColumn, j, i) ){
  96043. assert( j<pPk->nColumn );
  96044. pPk->aiColumn[j] = i;
  96045. pPk->azColl[j] = sqlite3StrBINARY;
  96046. j++;
  96047. }
  96048. }
  96049. assert( pPk->nColumn==j );
  96050. assert( pTab->nCol==j );
  96051. }else{
  96052. pPk->nColumn = pTab->nCol;
  96053. }
  96054. }
  96055. /*
  96056. ** This routine is called to report the final ")" that terminates
  96057. ** a CREATE TABLE statement.
  96058. **
  96059. ** The table structure that other action routines have been building
  96060. ** is added to the internal hash tables, assuming no errors have
  96061. ** occurred.
  96062. **
  96063. ** An entry for the table is made in the master table on disk, unless
  96064. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  96065. ** it means we are reading the sqlite_master table because we just
  96066. ** connected to the database or because the sqlite_master table has
  96067. ** recently changed, so the entry for this table already exists in
  96068. ** the sqlite_master table. We do not want to create it again.
  96069. **
  96070. ** If the pSelect argument is not NULL, it means that this routine
  96071. ** was called to create a table generated from a
  96072. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  96073. ** the new table will match the result set of the SELECT.
  96074. */
  96075. SQLITE_PRIVATE void sqlite3EndTable(
  96076. Parse *pParse, /* Parse context */
  96077. Token *pCons, /* The ',' token after the last column defn. */
  96078. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  96079. u8 tabOpts, /* Extra table options. Usually 0. */
  96080. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  96081. ){
  96082. Table *p; /* The new table */
  96083. sqlite3 *db = pParse->db; /* The database connection */
  96084. int iDb; /* Database in which the table lives */
  96085. Index *pIdx; /* An implied index of the table */
  96086. if( pEnd==0 && pSelect==0 ){
  96087. return;
  96088. }
  96089. assert( !db->mallocFailed );
  96090. p = pParse->pNewTable;
  96091. if( p==0 ) return;
  96092. assert( !db->init.busy || !pSelect );
  96093. /* If the db->init.busy is 1 it means we are reading the SQL off the
  96094. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  96095. ** So do not write to the disk again. Extract the root page number
  96096. ** for the table from the db->init.newTnum field. (The page number
  96097. ** should have been put there by the sqliteOpenCb routine.)
  96098. **
  96099. ** If the root page number is 1, that means this is the sqlite_master
  96100. ** table itself. So mark it read-only.
  96101. */
  96102. if( db->init.busy ){
  96103. p->tnum = db->init.newTnum;
  96104. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  96105. }
  96106. /* Special processing for WITHOUT ROWID Tables */
  96107. if( tabOpts & TF_WithoutRowid ){
  96108. if( (p->tabFlags & TF_Autoincrement) ){
  96109. sqlite3ErrorMsg(pParse,
  96110. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  96111. return;
  96112. }
  96113. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  96114. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  96115. }else{
  96116. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  96117. convertToWithoutRowidTable(pParse, p);
  96118. }
  96119. }
  96120. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  96121. #ifndef SQLITE_OMIT_CHECK
  96122. /* Resolve names in all CHECK constraint expressions.
  96123. */
  96124. if( p->pCheck ){
  96125. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  96126. }
  96127. #endif /* !defined(SQLITE_OMIT_CHECK) */
  96128. /* Estimate the average row size for the table and for all implied indices */
  96129. estimateTableWidth(p);
  96130. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  96131. estimateIndexWidth(pIdx);
  96132. }
  96133. /* If not initializing, then create a record for the new table
  96134. ** in the SQLITE_MASTER table of the database.
  96135. **
  96136. ** If this is a TEMPORARY table, write the entry into the auxiliary
  96137. ** file instead of into the main database file.
  96138. */
  96139. if( !db->init.busy ){
  96140. int n;
  96141. Vdbe *v;
  96142. char *zType; /* "view" or "table" */
  96143. char *zType2; /* "VIEW" or "TABLE" */
  96144. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  96145. v = sqlite3GetVdbe(pParse);
  96146. if( NEVER(v==0) ) return;
  96147. sqlite3VdbeAddOp1(v, OP_Close, 0);
  96148. /*
  96149. ** Initialize zType for the new view or table.
  96150. */
  96151. if( p->pSelect==0 ){
  96152. /* A regular table */
  96153. zType = "table";
  96154. zType2 = "TABLE";
  96155. #ifndef SQLITE_OMIT_VIEW
  96156. }else{
  96157. /* A view */
  96158. zType = "view";
  96159. zType2 = "VIEW";
  96160. #endif
  96161. }
  96162. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  96163. ** statement to populate the new table. The root-page number for the
  96164. ** new table is in register pParse->regRoot.
  96165. **
  96166. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  96167. ** suitable state to query for the column names and types to be used
  96168. ** by the new table.
  96169. **
  96170. ** A shared-cache write-lock is not required to write to the new table,
  96171. ** as a schema-lock must have already been obtained to create it. Since
  96172. ** a schema-lock excludes all other database users, the write-lock would
  96173. ** be redundant.
  96174. */
  96175. if( pSelect ){
  96176. SelectDest dest; /* Where the SELECT should store results */
  96177. int regYield; /* Register holding co-routine entry-point */
  96178. int addrTop; /* Top of the co-routine */
  96179. int regRec; /* A record to be insert into the new table */
  96180. int regRowid; /* Rowid of the next row to insert */
  96181. int addrInsLoop; /* Top of the loop for inserting rows */
  96182. Table *pSelTab; /* A table that describes the SELECT results */
  96183. regYield = ++pParse->nMem;
  96184. regRec = ++pParse->nMem;
  96185. regRowid = ++pParse->nMem;
  96186. assert(pParse->nTab==1);
  96187. sqlite3MayAbort(pParse);
  96188. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  96189. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  96190. pParse->nTab = 2;
  96191. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  96192. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  96193. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  96194. sqlite3Select(pParse, pSelect, &dest);
  96195. sqlite3VdbeEndCoroutine(v, regYield);
  96196. sqlite3VdbeJumpHere(v, addrTop - 1);
  96197. if( pParse->nErr ) return;
  96198. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  96199. if( pSelTab==0 ) return;
  96200. assert( p->aCol==0 );
  96201. p->nCol = pSelTab->nCol;
  96202. p->aCol = pSelTab->aCol;
  96203. pSelTab->nCol = 0;
  96204. pSelTab->aCol = 0;
  96205. sqlite3DeleteTable(db, pSelTab);
  96206. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  96207. VdbeCoverage(v);
  96208. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  96209. sqlite3TableAffinity(v, p, 0);
  96210. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  96211. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  96212. sqlite3VdbeGoto(v, addrInsLoop);
  96213. sqlite3VdbeJumpHere(v, addrInsLoop);
  96214. sqlite3VdbeAddOp1(v, OP_Close, 1);
  96215. }
  96216. /* Compute the complete text of the CREATE statement */
  96217. if( pSelect ){
  96218. zStmt = createTableStmt(db, p);
  96219. }else{
  96220. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  96221. n = (int)(pEnd2->z - pParse->sNameToken.z);
  96222. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  96223. zStmt = sqlite3MPrintf(db,
  96224. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  96225. );
  96226. }
  96227. /* A slot for the record has already been allocated in the
  96228. ** SQLITE_MASTER table. We just need to update that slot with all
  96229. ** the information we've collected.
  96230. */
  96231. sqlite3NestedParse(pParse,
  96232. "UPDATE %Q.%s "
  96233. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  96234. "WHERE rowid=#%d",
  96235. db->aDb[iDb].zDbSName, MASTER_NAME,
  96236. zType,
  96237. p->zName,
  96238. p->zName,
  96239. pParse->regRoot,
  96240. zStmt,
  96241. pParse->regRowid
  96242. );
  96243. sqlite3DbFree(db, zStmt);
  96244. sqlite3ChangeCookie(pParse, iDb);
  96245. #ifndef SQLITE_OMIT_AUTOINCREMENT
  96246. /* Check to see if we need to create an sqlite_sequence table for
  96247. ** keeping track of autoincrement keys.
  96248. */
  96249. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  96250. Db *pDb = &db->aDb[iDb];
  96251. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96252. if( pDb->pSchema->pSeqTab==0 ){
  96253. sqlite3NestedParse(pParse,
  96254. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  96255. pDb->zDbSName
  96256. );
  96257. }
  96258. }
  96259. #endif
  96260. /* Reparse everything to update our internal data structures */
  96261. sqlite3VdbeAddParseSchemaOp(v, iDb,
  96262. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  96263. }
  96264. /* Add the table to the in-memory representation of the database.
  96265. */
  96266. if( db->init.busy ){
  96267. Table *pOld;
  96268. Schema *pSchema = p->pSchema;
  96269. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96270. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  96271. if( pOld ){
  96272. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  96273. sqlite3OomFault(db);
  96274. return;
  96275. }
  96276. pParse->pNewTable = 0;
  96277. db->mDbFlags |= DBFLAG_SchemaChange;
  96278. #ifndef SQLITE_OMIT_ALTERTABLE
  96279. if( !p->pSelect ){
  96280. const char *zName = (const char *)pParse->sNameToken.z;
  96281. int nName;
  96282. assert( !pSelect && pCons && pEnd );
  96283. if( pCons->z==0 ){
  96284. pCons = pEnd;
  96285. }
  96286. nName = (int)((const char *)pCons->z - zName);
  96287. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  96288. }
  96289. #endif
  96290. }
  96291. }
  96292. #ifndef SQLITE_OMIT_VIEW
  96293. /*
  96294. ** The parser calls this routine in order to create a new VIEW
  96295. */
  96296. SQLITE_PRIVATE void sqlite3CreateView(
  96297. Parse *pParse, /* The parsing context */
  96298. Token *pBegin, /* The CREATE token that begins the statement */
  96299. Token *pName1, /* The token that holds the name of the view */
  96300. Token *pName2, /* The token that holds the name of the view */
  96301. ExprList *pCNames, /* Optional list of view column names */
  96302. Select *pSelect, /* A SELECT statement that will become the new view */
  96303. int isTemp, /* TRUE for a TEMPORARY view */
  96304. int noErr /* Suppress error messages if VIEW already exists */
  96305. ){
  96306. Table *p;
  96307. int n;
  96308. const char *z;
  96309. Token sEnd;
  96310. DbFixer sFix;
  96311. Token *pName = 0;
  96312. int iDb;
  96313. sqlite3 *db = pParse->db;
  96314. if( pParse->nVar>0 ){
  96315. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  96316. goto create_view_fail;
  96317. }
  96318. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  96319. p = pParse->pNewTable;
  96320. if( p==0 || pParse->nErr ) goto create_view_fail;
  96321. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  96322. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  96323. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  96324. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  96325. /* Make a copy of the entire SELECT statement that defines the view.
  96326. ** This will force all the Expr.token.z values to be dynamically
  96327. ** allocated rather than point to the input string - which means that
  96328. ** they will persist after the current sqlite3_exec() call returns.
  96329. */
  96330. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  96331. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  96332. if( db->mallocFailed ) goto create_view_fail;
  96333. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  96334. ** the end.
  96335. */
  96336. sEnd = pParse->sLastToken;
  96337. assert( sEnd.z[0]!=0 );
  96338. if( sEnd.z[0]!=';' ){
  96339. sEnd.z += sEnd.n;
  96340. }
  96341. sEnd.n = 0;
  96342. n = (int)(sEnd.z - pBegin->z);
  96343. assert( n>0 );
  96344. z = pBegin->z;
  96345. while( sqlite3Isspace(z[n-1]) ){ n--; }
  96346. sEnd.z = &z[n-1];
  96347. sEnd.n = 1;
  96348. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  96349. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  96350. create_view_fail:
  96351. sqlite3SelectDelete(db, pSelect);
  96352. sqlite3ExprListDelete(db, pCNames);
  96353. return;
  96354. }
  96355. #endif /* SQLITE_OMIT_VIEW */
  96356. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  96357. /*
  96358. ** The Table structure pTable is really a VIEW. Fill in the names of
  96359. ** the columns of the view in the pTable structure. Return the number
  96360. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  96361. */
  96362. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  96363. Table *pSelTab; /* A fake table from which we get the result set */
  96364. Select *pSel; /* Copy of the SELECT that implements the view */
  96365. int nErr = 0; /* Number of errors encountered */
  96366. int n; /* Temporarily holds the number of cursors assigned */
  96367. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  96368. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96369. int rc;
  96370. #endif
  96371. #ifndef SQLITE_OMIT_AUTHORIZATION
  96372. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  96373. #endif
  96374. assert( pTable );
  96375. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96376. db->nSchemaLock++;
  96377. rc = sqlite3VtabCallConnect(pParse, pTable);
  96378. db->nSchemaLock--;
  96379. if( rc ){
  96380. return 1;
  96381. }
  96382. if( IsVirtual(pTable) ) return 0;
  96383. #endif
  96384. #ifndef SQLITE_OMIT_VIEW
  96385. /* A positive nCol means the columns names for this view are
  96386. ** already known.
  96387. */
  96388. if( pTable->nCol>0 ) return 0;
  96389. /* A negative nCol is a special marker meaning that we are currently
  96390. ** trying to compute the column names. If we enter this routine with
  96391. ** a negative nCol, it means two or more views form a loop, like this:
  96392. **
  96393. ** CREATE VIEW one AS SELECT * FROM two;
  96394. ** CREATE VIEW two AS SELECT * FROM one;
  96395. **
  96396. ** Actually, the error above is now caught prior to reaching this point.
  96397. ** But the following test is still important as it does come up
  96398. ** in the following:
  96399. **
  96400. ** CREATE TABLE main.ex1(a);
  96401. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  96402. ** SELECT * FROM temp.ex1;
  96403. */
  96404. if( pTable->nCol<0 ){
  96405. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  96406. return 1;
  96407. }
  96408. assert( pTable->nCol>=0 );
  96409. /* If we get this far, it means we need to compute the table names.
  96410. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  96411. ** "*" elements in the results set of the view and will assign cursors
  96412. ** to the elements of the FROM clause. But we do not want these changes
  96413. ** to be permanent. So the computation is done on a copy of the SELECT
  96414. ** statement that defines the view.
  96415. */
  96416. assert( pTable->pSelect );
  96417. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  96418. if( pSel ){
  96419. n = pParse->nTab;
  96420. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  96421. pTable->nCol = -1;
  96422. db->lookaside.bDisable++;
  96423. #ifndef SQLITE_OMIT_AUTHORIZATION
  96424. xAuth = db->xAuth;
  96425. db->xAuth = 0;
  96426. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  96427. db->xAuth = xAuth;
  96428. #else
  96429. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  96430. #endif
  96431. pParse->nTab = n;
  96432. if( pTable->pCheck ){
  96433. /* CREATE VIEW name(arglist) AS ...
  96434. ** The names of the columns in the table are taken from
  96435. ** arglist which is stored in pTable->pCheck. The pCheck field
  96436. ** normally holds CHECK constraints on an ordinary table, but for
  96437. ** a VIEW it holds the list of column names.
  96438. */
  96439. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  96440. &pTable->nCol, &pTable->aCol);
  96441. if( db->mallocFailed==0
  96442. && pParse->nErr==0
  96443. && pTable->nCol==pSel->pEList->nExpr
  96444. ){
  96445. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  96446. }
  96447. }else if( pSelTab ){
  96448. /* CREATE VIEW name AS... without an argument list. Construct
  96449. ** the column names from the SELECT statement that defines the view.
  96450. */
  96451. assert( pTable->aCol==0 );
  96452. pTable->nCol = pSelTab->nCol;
  96453. pTable->aCol = pSelTab->aCol;
  96454. pSelTab->nCol = 0;
  96455. pSelTab->aCol = 0;
  96456. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  96457. }else{
  96458. pTable->nCol = 0;
  96459. nErr++;
  96460. }
  96461. sqlite3DeleteTable(db, pSelTab);
  96462. sqlite3SelectDelete(db, pSel);
  96463. db->lookaside.bDisable--;
  96464. } else {
  96465. nErr++;
  96466. }
  96467. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  96468. #endif /* SQLITE_OMIT_VIEW */
  96469. return nErr;
  96470. }
  96471. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  96472. #ifndef SQLITE_OMIT_VIEW
  96473. /*
  96474. ** Clear the column names from every VIEW in database idx.
  96475. */
  96476. static void sqliteViewResetAll(sqlite3 *db, int idx){
  96477. HashElem *i;
  96478. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  96479. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  96480. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  96481. Table *pTab = sqliteHashData(i);
  96482. if( pTab->pSelect ){
  96483. sqlite3DeleteColumnNames(db, pTab);
  96484. pTab->aCol = 0;
  96485. pTab->nCol = 0;
  96486. }
  96487. }
  96488. DbClearProperty(db, idx, DB_UnresetViews);
  96489. }
  96490. #else
  96491. # define sqliteViewResetAll(A,B)
  96492. #endif /* SQLITE_OMIT_VIEW */
  96493. /*
  96494. ** This function is called by the VDBE to adjust the internal schema
  96495. ** used by SQLite when the btree layer moves a table root page. The
  96496. ** root-page of a table or index in database iDb has changed from iFrom
  96497. ** to iTo.
  96498. **
  96499. ** Ticket #1728: The symbol table might still contain information
  96500. ** on tables and/or indices that are the process of being deleted.
  96501. ** If you are unlucky, one of those deleted indices or tables might
  96502. ** have the same rootpage number as the real table or index that is
  96503. ** being moved. So we cannot stop searching after the first match
  96504. ** because the first match might be for one of the deleted indices
  96505. ** or tables and not the table/index that is actually being moved.
  96506. ** We must continue looping until all tables and indices with
  96507. ** rootpage==iFrom have been converted to have a rootpage of iTo
  96508. ** in order to be certain that we got the right one.
  96509. */
  96510. #ifndef SQLITE_OMIT_AUTOVACUUM
  96511. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  96512. HashElem *pElem;
  96513. Hash *pHash;
  96514. Db *pDb;
  96515. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96516. pDb = &db->aDb[iDb];
  96517. pHash = &pDb->pSchema->tblHash;
  96518. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  96519. Table *pTab = sqliteHashData(pElem);
  96520. if( pTab->tnum==iFrom ){
  96521. pTab->tnum = iTo;
  96522. }
  96523. }
  96524. pHash = &pDb->pSchema->idxHash;
  96525. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  96526. Index *pIdx = sqliteHashData(pElem);
  96527. if( pIdx->tnum==iFrom ){
  96528. pIdx->tnum = iTo;
  96529. }
  96530. }
  96531. }
  96532. #endif
  96533. /*
  96534. ** Write code to erase the table with root-page iTable from database iDb.
  96535. ** Also write code to modify the sqlite_master table and internal schema
  96536. ** if a root-page of another table is moved by the btree-layer whilst
  96537. ** erasing iTable (this can happen with an auto-vacuum database).
  96538. */
  96539. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  96540. Vdbe *v = sqlite3GetVdbe(pParse);
  96541. int r1 = sqlite3GetTempReg(pParse);
  96542. assert( iTable>1 );
  96543. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  96544. sqlite3MayAbort(pParse);
  96545. #ifndef SQLITE_OMIT_AUTOVACUUM
  96546. /* OP_Destroy stores an in integer r1. If this integer
  96547. ** is non-zero, then it is the root page number of a table moved to
  96548. ** location iTable. The following code modifies the sqlite_master table to
  96549. ** reflect this.
  96550. **
  96551. ** The "#NNN" in the SQL is a special constant that means whatever value
  96552. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  96553. ** token for additional information.
  96554. */
  96555. sqlite3NestedParse(pParse,
  96556. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  96557. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  96558. #endif
  96559. sqlite3ReleaseTempReg(pParse, r1);
  96560. }
  96561. /*
  96562. ** Write VDBE code to erase table pTab and all associated indices on disk.
  96563. ** Code to update the sqlite_master tables and internal schema definitions
  96564. ** in case a root-page belonging to another table is moved by the btree layer
  96565. ** is also added (this can happen with an auto-vacuum database).
  96566. */
  96567. static void destroyTable(Parse *pParse, Table *pTab){
  96568. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  96569. ** is not defined), then it is important to call OP_Destroy on the
  96570. ** table and index root-pages in order, starting with the numerically
  96571. ** largest root-page number. This guarantees that none of the root-pages
  96572. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  96573. ** following were coded:
  96574. **
  96575. ** OP_Destroy 4 0
  96576. ** ...
  96577. ** OP_Destroy 5 0
  96578. **
  96579. ** and root page 5 happened to be the largest root-page number in the
  96580. ** database, then root page 5 would be moved to page 4 by the
  96581. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  96582. ** a free-list page.
  96583. */
  96584. int iTab = pTab->tnum;
  96585. int iDestroyed = 0;
  96586. while( 1 ){
  96587. Index *pIdx;
  96588. int iLargest = 0;
  96589. if( iDestroyed==0 || iTab<iDestroyed ){
  96590. iLargest = iTab;
  96591. }
  96592. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96593. int iIdx = pIdx->tnum;
  96594. assert( pIdx->pSchema==pTab->pSchema );
  96595. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  96596. iLargest = iIdx;
  96597. }
  96598. }
  96599. if( iLargest==0 ){
  96600. return;
  96601. }else{
  96602. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96603. assert( iDb>=0 && iDb<pParse->db->nDb );
  96604. destroyRootPage(pParse, iLargest, iDb);
  96605. iDestroyed = iLargest;
  96606. }
  96607. }
  96608. }
  96609. /*
  96610. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  96611. ** after a DROP INDEX or DROP TABLE command.
  96612. */
  96613. static void sqlite3ClearStatTables(
  96614. Parse *pParse, /* The parsing context */
  96615. int iDb, /* The database number */
  96616. const char *zType, /* "idx" or "tbl" */
  96617. const char *zName /* Name of index or table */
  96618. ){
  96619. int i;
  96620. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  96621. for(i=1; i<=4; i++){
  96622. char zTab[24];
  96623. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  96624. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  96625. sqlite3NestedParse(pParse,
  96626. "DELETE FROM %Q.%s WHERE %s=%Q",
  96627. zDbName, zTab, zType, zName
  96628. );
  96629. }
  96630. }
  96631. }
  96632. /*
  96633. ** Generate code to drop a table.
  96634. */
  96635. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  96636. Vdbe *v;
  96637. sqlite3 *db = pParse->db;
  96638. Trigger *pTrigger;
  96639. Db *pDb = &db->aDb[iDb];
  96640. v = sqlite3GetVdbe(pParse);
  96641. assert( v!=0 );
  96642. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96643. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96644. if( IsVirtual(pTab) ){
  96645. sqlite3VdbeAddOp0(v, OP_VBegin);
  96646. }
  96647. #endif
  96648. /* Drop all triggers associated with the table being dropped. Code
  96649. ** is generated to remove entries from sqlite_master and/or
  96650. ** sqlite_temp_master if required.
  96651. */
  96652. pTrigger = sqlite3TriggerList(pParse, pTab);
  96653. while( pTrigger ){
  96654. assert( pTrigger->pSchema==pTab->pSchema ||
  96655. pTrigger->pSchema==db->aDb[1].pSchema );
  96656. sqlite3DropTriggerPtr(pParse, pTrigger);
  96657. pTrigger = pTrigger->pNext;
  96658. }
  96659. #ifndef SQLITE_OMIT_AUTOINCREMENT
  96660. /* Remove any entries of the sqlite_sequence table associated with
  96661. ** the table being dropped. This is done before the table is dropped
  96662. ** at the btree level, in case the sqlite_sequence table needs to
  96663. ** move as a result of the drop (can happen in auto-vacuum mode).
  96664. */
  96665. if( pTab->tabFlags & TF_Autoincrement ){
  96666. sqlite3NestedParse(pParse,
  96667. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  96668. pDb->zDbSName, pTab->zName
  96669. );
  96670. }
  96671. #endif
  96672. /* Drop all SQLITE_MASTER table and index entries that refer to the
  96673. ** table. The program name loops through the master table and deletes
  96674. ** every row that refers to a table of the same name as the one being
  96675. ** dropped. Triggers are handled separately because a trigger can be
  96676. ** created in the temp database that refers to a table in another
  96677. ** database.
  96678. */
  96679. sqlite3NestedParse(pParse,
  96680. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  96681. pDb->zDbSName, MASTER_NAME, pTab->zName);
  96682. if( !isView && !IsVirtual(pTab) ){
  96683. destroyTable(pParse, pTab);
  96684. }
  96685. /* Remove the table entry from SQLite's internal schema and modify
  96686. ** the schema cookie.
  96687. */
  96688. if( IsVirtual(pTab) ){
  96689. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  96690. }
  96691. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  96692. sqlite3ChangeCookie(pParse, iDb);
  96693. sqliteViewResetAll(db, iDb);
  96694. }
  96695. /*
  96696. ** This routine is called to do the work of a DROP TABLE statement.
  96697. ** pName is the name of the table to be dropped.
  96698. */
  96699. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  96700. Table *pTab;
  96701. Vdbe *v;
  96702. sqlite3 *db = pParse->db;
  96703. int iDb;
  96704. if( db->mallocFailed ){
  96705. goto exit_drop_table;
  96706. }
  96707. assert( pParse->nErr==0 );
  96708. assert( pName->nSrc==1 );
  96709. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  96710. if( noErr ) db->suppressErr++;
  96711. assert( isView==0 || isView==LOCATE_VIEW );
  96712. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  96713. if( noErr ) db->suppressErr--;
  96714. if( pTab==0 ){
  96715. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  96716. goto exit_drop_table;
  96717. }
  96718. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96719. assert( iDb>=0 && iDb<db->nDb );
  96720. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  96721. ** it is initialized.
  96722. */
  96723. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  96724. goto exit_drop_table;
  96725. }
  96726. #ifndef SQLITE_OMIT_AUTHORIZATION
  96727. {
  96728. int code;
  96729. const char *zTab = SCHEMA_TABLE(iDb);
  96730. const char *zDb = db->aDb[iDb].zDbSName;
  96731. const char *zArg2 = 0;
  96732. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  96733. goto exit_drop_table;
  96734. }
  96735. if( isView ){
  96736. if( !OMIT_TEMPDB && iDb==1 ){
  96737. code = SQLITE_DROP_TEMP_VIEW;
  96738. }else{
  96739. code = SQLITE_DROP_VIEW;
  96740. }
  96741. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96742. }else if( IsVirtual(pTab) ){
  96743. code = SQLITE_DROP_VTABLE;
  96744. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  96745. #endif
  96746. }else{
  96747. if( !OMIT_TEMPDB && iDb==1 ){
  96748. code = SQLITE_DROP_TEMP_TABLE;
  96749. }else{
  96750. code = SQLITE_DROP_TABLE;
  96751. }
  96752. }
  96753. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  96754. goto exit_drop_table;
  96755. }
  96756. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  96757. goto exit_drop_table;
  96758. }
  96759. }
  96760. #endif
  96761. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  96762. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  96763. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  96764. goto exit_drop_table;
  96765. }
  96766. #ifndef SQLITE_OMIT_VIEW
  96767. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  96768. ** on a table.
  96769. */
  96770. if( isView && pTab->pSelect==0 ){
  96771. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  96772. goto exit_drop_table;
  96773. }
  96774. if( !isView && pTab->pSelect ){
  96775. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  96776. goto exit_drop_table;
  96777. }
  96778. #endif
  96779. /* Generate code to remove the table from the master table
  96780. ** on disk.
  96781. */
  96782. v = sqlite3GetVdbe(pParse);
  96783. if( v ){
  96784. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96785. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  96786. sqlite3FkDropTable(pParse, pName, pTab);
  96787. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  96788. }
  96789. exit_drop_table:
  96790. sqlite3SrcListDelete(db, pName);
  96791. }
  96792. /*
  96793. ** This routine is called to create a new foreign key on the table
  96794. ** currently under construction. pFromCol determines which columns
  96795. ** in the current table point to the foreign key. If pFromCol==0 then
  96796. ** connect the key to the last column inserted. pTo is the name of
  96797. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  96798. ** of tables in the parent pTo table. flags contains all
  96799. ** information about the conflict resolution algorithms specified
  96800. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  96801. **
  96802. ** An FKey structure is created and added to the table currently
  96803. ** under construction in the pParse->pNewTable field.
  96804. **
  96805. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  96806. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  96807. */
  96808. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  96809. Parse *pParse, /* Parsing context */
  96810. ExprList *pFromCol, /* Columns in this table that point to other table */
  96811. Token *pTo, /* Name of the other table */
  96812. ExprList *pToCol, /* Columns in the other table */
  96813. int flags /* Conflict resolution algorithms. */
  96814. ){
  96815. sqlite3 *db = pParse->db;
  96816. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96817. FKey *pFKey = 0;
  96818. FKey *pNextTo;
  96819. Table *p = pParse->pNewTable;
  96820. int nByte;
  96821. int i;
  96822. int nCol;
  96823. char *z;
  96824. assert( pTo!=0 );
  96825. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  96826. if( pFromCol==0 ){
  96827. int iCol = p->nCol-1;
  96828. if( NEVER(iCol<0) ) goto fk_end;
  96829. if( pToCol && pToCol->nExpr!=1 ){
  96830. sqlite3ErrorMsg(pParse, "foreign key on %s"
  96831. " should reference only one column of table %T",
  96832. p->aCol[iCol].zName, pTo);
  96833. goto fk_end;
  96834. }
  96835. nCol = 1;
  96836. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  96837. sqlite3ErrorMsg(pParse,
  96838. "number of columns in foreign key does not match the number of "
  96839. "columns in the referenced table");
  96840. goto fk_end;
  96841. }else{
  96842. nCol = pFromCol->nExpr;
  96843. }
  96844. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  96845. if( pToCol ){
  96846. for(i=0; i<pToCol->nExpr; i++){
  96847. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  96848. }
  96849. }
  96850. pFKey = sqlite3DbMallocZero(db, nByte );
  96851. if( pFKey==0 ){
  96852. goto fk_end;
  96853. }
  96854. pFKey->pFrom = p;
  96855. pFKey->pNextFrom = p->pFKey;
  96856. z = (char*)&pFKey->aCol[nCol];
  96857. pFKey->zTo = z;
  96858. memcpy(z, pTo->z, pTo->n);
  96859. z[pTo->n] = 0;
  96860. sqlite3Dequote(z);
  96861. z += pTo->n+1;
  96862. pFKey->nCol = nCol;
  96863. if( pFromCol==0 ){
  96864. pFKey->aCol[0].iFrom = p->nCol-1;
  96865. }else{
  96866. for(i=0; i<nCol; i++){
  96867. int j;
  96868. for(j=0; j<p->nCol; j++){
  96869. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  96870. pFKey->aCol[i].iFrom = j;
  96871. break;
  96872. }
  96873. }
  96874. if( j>=p->nCol ){
  96875. sqlite3ErrorMsg(pParse,
  96876. "unknown column \"%s\" in foreign key definition",
  96877. pFromCol->a[i].zName);
  96878. goto fk_end;
  96879. }
  96880. }
  96881. }
  96882. if( pToCol ){
  96883. for(i=0; i<nCol; i++){
  96884. int n = sqlite3Strlen30(pToCol->a[i].zName);
  96885. pFKey->aCol[i].zCol = z;
  96886. memcpy(z, pToCol->a[i].zName, n);
  96887. z[n] = 0;
  96888. z += n+1;
  96889. }
  96890. }
  96891. pFKey->isDeferred = 0;
  96892. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  96893. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  96894. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  96895. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  96896. pFKey->zTo, (void *)pFKey
  96897. );
  96898. if( pNextTo==pFKey ){
  96899. sqlite3OomFault(db);
  96900. goto fk_end;
  96901. }
  96902. if( pNextTo ){
  96903. assert( pNextTo->pPrevTo==0 );
  96904. pFKey->pNextTo = pNextTo;
  96905. pNextTo->pPrevTo = pFKey;
  96906. }
  96907. /* Link the foreign key to the table as the last step.
  96908. */
  96909. p->pFKey = pFKey;
  96910. pFKey = 0;
  96911. fk_end:
  96912. sqlite3DbFree(db, pFKey);
  96913. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  96914. sqlite3ExprListDelete(db, pFromCol);
  96915. sqlite3ExprListDelete(db, pToCol);
  96916. }
  96917. /*
  96918. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  96919. ** clause is seen as part of a foreign key definition. The isDeferred
  96920. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  96921. ** The behavior of the most recently created foreign key is adjusted
  96922. ** accordingly.
  96923. */
  96924. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  96925. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96926. Table *pTab;
  96927. FKey *pFKey;
  96928. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  96929. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  96930. pFKey->isDeferred = (u8)isDeferred;
  96931. #endif
  96932. }
  96933. /*
  96934. ** Generate code that will erase and refill index *pIdx. This is
  96935. ** used to initialize a newly created index or to recompute the
  96936. ** content of an index in response to a REINDEX command.
  96937. **
  96938. ** if memRootPage is not negative, it means that the index is newly
  96939. ** created. The register specified by memRootPage contains the
  96940. ** root page number of the index. If memRootPage is negative, then
  96941. ** the index already exists and must be cleared before being refilled and
  96942. ** the root page number of the index is taken from pIndex->tnum.
  96943. */
  96944. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  96945. Table *pTab = pIndex->pTable; /* The table that is indexed */
  96946. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  96947. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  96948. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  96949. int addr1; /* Address of top of loop */
  96950. int addr2; /* Address to jump to for next iteration */
  96951. int tnum; /* Root page of index */
  96952. int iPartIdxLabel; /* Jump to this label to skip a row */
  96953. Vdbe *v; /* Generate code into this virtual machine */
  96954. KeyInfo *pKey; /* KeyInfo for index */
  96955. int regRecord; /* Register holding assembled index record */
  96956. sqlite3 *db = pParse->db; /* The database connection */
  96957. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  96958. #ifndef SQLITE_OMIT_AUTHORIZATION
  96959. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  96960. db->aDb[iDb].zDbSName ) ){
  96961. return;
  96962. }
  96963. #endif
  96964. /* Require a write-lock on the table to perform this operation */
  96965. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  96966. v = sqlite3GetVdbe(pParse);
  96967. if( v==0 ) return;
  96968. if( memRootPage>=0 ){
  96969. tnum = memRootPage;
  96970. }else{
  96971. tnum = pIndex->tnum;
  96972. }
  96973. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  96974. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  96975. /* Open the sorter cursor if we are to use one. */
  96976. iSorter = pParse->nTab++;
  96977. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  96978. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  96979. /* Open the table. Loop through all rows of the table, inserting index
  96980. ** records into the sorter. */
  96981. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  96982. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  96983. regRecord = sqlite3GetTempReg(pParse);
  96984. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  96985. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  96986. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  96987. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  96988. sqlite3VdbeJumpHere(v, addr1);
  96989. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  96990. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  96991. (char *)pKey, P4_KEYINFO);
  96992. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  96993. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  96994. if( IsUniqueIndex(pIndex) ){
  96995. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  96996. sqlite3VdbeGoto(v, j2);
  96997. addr2 = sqlite3VdbeCurrentAddr(v);
  96998. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  96999. pIndex->nKeyCol); VdbeCoverage(v);
  97000. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  97001. }else{
  97002. addr2 = sqlite3VdbeCurrentAddr(v);
  97003. }
  97004. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  97005. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  97006. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  97007. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  97008. sqlite3ReleaseTempReg(pParse, regRecord);
  97009. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  97010. sqlite3VdbeJumpHere(v, addr1);
  97011. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  97012. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  97013. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  97014. }
  97015. /*
  97016. ** Allocate heap space to hold an Index object with nCol columns.
  97017. **
  97018. ** Increase the allocation size to provide an extra nExtra bytes
  97019. ** of 8-byte aligned space after the Index object and return a
  97020. ** pointer to this extra space in *ppExtra.
  97021. */
  97022. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  97023. sqlite3 *db, /* Database connection */
  97024. i16 nCol, /* Total number of columns in the index */
  97025. int nExtra, /* Number of bytes of extra space to alloc */
  97026. char **ppExtra /* Pointer to the "extra" space */
  97027. ){
  97028. Index *p; /* Allocated index object */
  97029. int nByte; /* Bytes of space for Index object + arrays */
  97030. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  97031. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  97032. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  97033. sizeof(i16)*nCol + /* Index.aiColumn */
  97034. sizeof(u8)*nCol); /* Index.aSortOrder */
  97035. p = sqlite3DbMallocZero(db, nByte + nExtra);
  97036. if( p ){
  97037. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  97038. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  97039. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  97040. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  97041. p->aSortOrder = (u8*)pExtra;
  97042. p->nColumn = nCol;
  97043. p->nKeyCol = nCol - 1;
  97044. *ppExtra = ((char*)p) + nByte;
  97045. }
  97046. return p;
  97047. }
  97048. /*
  97049. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  97050. ** and pTblList is the name of the table that is to be indexed. Both will
  97051. ** be NULL for a primary key or an index that is created to satisfy a
  97052. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  97053. ** as the table to be indexed. pParse->pNewTable is a table that is
  97054. ** currently being constructed by a CREATE TABLE statement.
  97055. **
  97056. ** pList is a list of columns to be indexed. pList will be NULL if this
  97057. ** is a primary key or unique-constraint on the most recent column added
  97058. ** to the table currently under construction.
  97059. */
  97060. SQLITE_PRIVATE void sqlite3CreateIndex(
  97061. Parse *pParse, /* All information about this parse */
  97062. Token *pName1, /* First part of index name. May be NULL */
  97063. Token *pName2, /* Second part of index name. May be NULL */
  97064. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  97065. ExprList *pList, /* A list of columns to be indexed */
  97066. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  97067. Token *pStart, /* The CREATE token that begins this statement */
  97068. Expr *pPIWhere, /* WHERE clause for partial indices */
  97069. int sortOrder, /* Sort order of primary key when pList==NULL */
  97070. int ifNotExist, /* Omit error if index already exists */
  97071. u8 idxType /* The index type */
  97072. ){
  97073. Table *pTab = 0; /* Table to be indexed */
  97074. Index *pIndex = 0; /* The index to be created */
  97075. char *zName = 0; /* Name of the index */
  97076. int nName; /* Number of characters in zName */
  97077. int i, j;
  97078. DbFixer sFix; /* For assigning database names to pTable */
  97079. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  97080. sqlite3 *db = pParse->db;
  97081. Db *pDb; /* The specific table containing the indexed database */
  97082. int iDb; /* Index of the database that is being written */
  97083. Token *pName = 0; /* Unqualified name of the index to create */
  97084. struct ExprList_item *pListItem; /* For looping over pList */
  97085. int nExtra = 0; /* Space allocated for zExtra[] */
  97086. int nExtraCol; /* Number of extra columns needed */
  97087. char *zExtra = 0; /* Extra space after the Index object */
  97088. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  97089. if( db->mallocFailed || pParse->nErr>0 ){
  97090. goto exit_create_index;
  97091. }
  97092. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  97093. goto exit_create_index;
  97094. }
  97095. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97096. goto exit_create_index;
  97097. }
  97098. /*
  97099. ** Find the table that is to be indexed. Return early if not found.
  97100. */
  97101. if( pTblName!=0 ){
  97102. /* Use the two-part index name to determine the database
  97103. ** to search for the table. 'Fix' the table name to this db
  97104. ** before looking up the table.
  97105. */
  97106. assert( pName1 && pName2 );
  97107. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  97108. if( iDb<0 ) goto exit_create_index;
  97109. assert( pName && pName->z );
  97110. #ifndef SQLITE_OMIT_TEMPDB
  97111. /* If the index name was unqualified, check if the table
  97112. ** is a temp table. If so, set the database to 1. Do not do this
  97113. ** if initialising a database schema.
  97114. */
  97115. if( !db->init.busy ){
  97116. pTab = sqlite3SrcListLookup(pParse, pTblName);
  97117. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  97118. iDb = 1;
  97119. }
  97120. }
  97121. #endif
  97122. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  97123. if( sqlite3FixSrcList(&sFix, pTblName) ){
  97124. /* Because the parser constructs pTblName from a single identifier,
  97125. ** sqlite3FixSrcList can never fail. */
  97126. assert(0);
  97127. }
  97128. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  97129. assert( db->mallocFailed==0 || pTab==0 );
  97130. if( pTab==0 ) goto exit_create_index;
  97131. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  97132. sqlite3ErrorMsg(pParse,
  97133. "cannot create a TEMP index on non-TEMP table \"%s\"",
  97134. pTab->zName);
  97135. goto exit_create_index;
  97136. }
  97137. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  97138. }else{
  97139. assert( pName==0 );
  97140. assert( pStart==0 );
  97141. pTab = pParse->pNewTable;
  97142. if( !pTab ) goto exit_create_index;
  97143. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  97144. }
  97145. pDb = &db->aDb[iDb];
  97146. assert( pTab!=0 );
  97147. assert( pParse->nErr==0 );
  97148. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  97149. && db->init.busy==0
  97150. #if SQLITE_USER_AUTHENTICATION
  97151. && sqlite3UserAuthTable(pTab->zName)==0
  97152. #endif
  97153. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  97154. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  97155. goto exit_create_index;
  97156. }
  97157. #ifndef SQLITE_OMIT_VIEW
  97158. if( pTab->pSelect ){
  97159. sqlite3ErrorMsg(pParse, "views may not be indexed");
  97160. goto exit_create_index;
  97161. }
  97162. #endif
  97163. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97164. if( IsVirtual(pTab) ){
  97165. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  97166. goto exit_create_index;
  97167. }
  97168. #endif
  97169. /*
  97170. ** Find the name of the index. Make sure there is not already another
  97171. ** index or table with the same name.
  97172. **
  97173. ** Exception: If we are reading the names of permanent indices from the
  97174. ** sqlite_master table (because some other process changed the schema) and
  97175. ** one of the index names collides with the name of a temporary table or
  97176. ** index, then we will continue to process this index.
  97177. **
  97178. ** If pName==0 it means that we are
  97179. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  97180. ** own name.
  97181. */
  97182. if( pName ){
  97183. zName = sqlite3NameFromToken(db, pName);
  97184. if( zName==0 ) goto exit_create_index;
  97185. assert( pName->z!=0 );
  97186. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  97187. goto exit_create_index;
  97188. }
  97189. if( !db->init.busy ){
  97190. if( sqlite3FindTable(db, zName, 0)!=0 ){
  97191. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  97192. goto exit_create_index;
  97193. }
  97194. }
  97195. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  97196. if( !ifNotExist ){
  97197. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  97198. }else{
  97199. assert( !db->init.busy );
  97200. sqlite3CodeVerifySchema(pParse, iDb);
  97201. }
  97202. goto exit_create_index;
  97203. }
  97204. }else{
  97205. int n;
  97206. Index *pLoop;
  97207. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  97208. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  97209. if( zName==0 ){
  97210. goto exit_create_index;
  97211. }
  97212. /* Automatic index names generated from within sqlite3_declare_vtab()
  97213. ** must have names that are distinct from normal automatic index names.
  97214. ** The following statement converts "sqlite3_autoindex..." into
  97215. ** "sqlite3_butoindex..." in order to make the names distinct.
  97216. ** The "vtab_err.test" test demonstrates the need of this statement. */
  97217. if( IN_DECLARE_VTAB ) zName[7]++;
  97218. }
  97219. /* Check for authorization to create an index.
  97220. */
  97221. #ifndef SQLITE_OMIT_AUTHORIZATION
  97222. {
  97223. const char *zDb = pDb->zDbSName;
  97224. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  97225. goto exit_create_index;
  97226. }
  97227. i = SQLITE_CREATE_INDEX;
  97228. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  97229. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  97230. goto exit_create_index;
  97231. }
  97232. }
  97233. #endif
  97234. /* If pList==0, it means this routine was called to make a primary
  97235. ** key out of the last column added to the table under construction.
  97236. ** So create a fake list to simulate this.
  97237. */
  97238. if( pList==0 ){
  97239. Token prevCol;
  97240. sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
  97241. pList = sqlite3ExprListAppend(pParse, 0,
  97242. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  97243. if( pList==0 ) goto exit_create_index;
  97244. assert( pList->nExpr==1 );
  97245. sqlite3ExprListSetSortOrder(pList, sortOrder);
  97246. }else{
  97247. sqlite3ExprListCheckLength(pParse, pList, "index");
  97248. }
  97249. /* Figure out how many bytes of space are required to store explicitly
  97250. ** specified collation sequence names.
  97251. */
  97252. for(i=0; i<pList->nExpr; i++){
  97253. Expr *pExpr = pList->a[i].pExpr;
  97254. assert( pExpr!=0 );
  97255. if( pExpr->op==TK_COLLATE ){
  97256. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  97257. }
  97258. }
  97259. /*
  97260. ** Allocate the index structure.
  97261. */
  97262. nName = sqlite3Strlen30(zName);
  97263. nExtraCol = pPk ? pPk->nKeyCol : 1;
  97264. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  97265. nName + nExtra + 1, &zExtra);
  97266. if( db->mallocFailed ){
  97267. goto exit_create_index;
  97268. }
  97269. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  97270. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  97271. pIndex->zName = zExtra;
  97272. zExtra += nName + 1;
  97273. memcpy(pIndex->zName, zName, nName+1);
  97274. pIndex->pTable = pTab;
  97275. pIndex->onError = (u8)onError;
  97276. pIndex->uniqNotNull = onError!=OE_None;
  97277. pIndex->idxType = idxType;
  97278. pIndex->pSchema = db->aDb[iDb].pSchema;
  97279. pIndex->nKeyCol = pList->nExpr;
  97280. if( pPIWhere ){
  97281. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  97282. pIndex->pPartIdxWhere = pPIWhere;
  97283. pPIWhere = 0;
  97284. }
  97285. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97286. /* Check to see if we should honor DESC requests on index columns
  97287. */
  97288. if( pDb->pSchema->file_format>=4 ){
  97289. sortOrderMask = -1; /* Honor DESC */
  97290. }else{
  97291. sortOrderMask = 0; /* Ignore DESC */
  97292. }
  97293. /* Analyze the list of expressions that form the terms of the index and
  97294. ** report any errors. In the common case where the expression is exactly
  97295. ** a table column, store that column in aiColumn[]. For general expressions,
  97296. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  97297. **
  97298. ** TODO: Issue a warning if two or more columns of the index are identical.
  97299. ** TODO: Issue a warning if the table primary key is used as part of the
  97300. ** index key.
  97301. */
  97302. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  97303. Expr *pCExpr; /* The i-th index expression */
  97304. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  97305. const char *zColl; /* Collation sequence name */
  97306. sqlite3StringToId(pListItem->pExpr);
  97307. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  97308. if( pParse->nErr ) goto exit_create_index;
  97309. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  97310. if( pCExpr->op!=TK_COLUMN ){
  97311. if( pTab==pParse->pNewTable ){
  97312. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  97313. "UNIQUE constraints");
  97314. goto exit_create_index;
  97315. }
  97316. if( pIndex->aColExpr==0 ){
  97317. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  97318. pIndex->aColExpr = pCopy;
  97319. if( !db->mallocFailed ){
  97320. assert( pCopy!=0 );
  97321. pListItem = &pCopy->a[i];
  97322. }
  97323. }
  97324. j = XN_EXPR;
  97325. pIndex->aiColumn[i] = XN_EXPR;
  97326. pIndex->uniqNotNull = 0;
  97327. }else{
  97328. j = pCExpr->iColumn;
  97329. assert( j<=0x7fff );
  97330. if( j<0 ){
  97331. j = pTab->iPKey;
  97332. }else if( pTab->aCol[j].notNull==0 ){
  97333. pIndex->uniqNotNull = 0;
  97334. }
  97335. pIndex->aiColumn[i] = (i16)j;
  97336. }
  97337. zColl = 0;
  97338. if( pListItem->pExpr->op==TK_COLLATE ){
  97339. int nColl;
  97340. zColl = pListItem->pExpr->u.zToken;
  97341. nColl = sqlite3Strlen30(zColl) + 1;
  97342. assert( nExtra>=nColl );
  97343. memcpy(zExtra, zColl, nColl);
  97344. zColl = zExtra;
  97345. zExtra += nColl;
  97346. nExtra -= nColl;
  97347. }else if( j>=0 ){
  97348. zColl = pTab->aCol[j].zColl;
  97349. }
  97350. if( !zColl ) zColl = sqlite3StrBINARY;
  97351. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  97352. goto exit_create_index;
  97353. }
  97354. pIndex->azColl[i] = zColl;
  97355. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  97356. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  97357. }
  97358. /* Append the table key to the end of the index. For WITHOUT ROWID
  97359. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  97360. ** normal tables (when pPk==0) this will be the rowid.
  97361. */
  97362. if( pPk ){
  97363. for(j=0; j<pPk->nKeyCol; j++){
  97364. int x = pPk->aiColumn[j];
  97365. assert( x>=0 );
  97366. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  97367. pIndex->nColumn--;
  97368. }else{
  97369. pIndex->aiColumn[i] = x;
  97370. pIndex->azColl[i] = pPk->azColl[j];
  97371. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  97372. i++;
  97373. }
  97374. }
  97375. assert( i==pIndex->nColumn );
  97376. }else{
  97377. pIndex->aiColumn[i] = XN_ROWID;
  97378. pIndex->azColl[i] = sqlite3StrBINARY;
  97379. }
  97380. sqlite3DefaultRowEst(pIndex);
  97381. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  97382. /* If this index contains every column of its table, then mark
  97383. ** it as a covering index */
  97384. assert( HasRowid(pTab)
  97385. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  97386. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  97387. pIndex->isCovering = 1;
  97388. for(j=0; j<pTab->nCol; j++){
  97389. if( j==pTab->iPKey ) continue;
  97390. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  97391. pIndex->isCovering = 0;
  97392. break;
  97393. }
  97394. }
  97395. if( pTab==pParse->pNewTable ){
  97396. /* This routine has been called to create an automatic index as a
  97397. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  97398. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  97399. ** i.e. one of:
  97400. **
  97401. ** CREATE TABLE t(x PRIMARY KEY, y);
  97402. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  97403. **
  97404. ** Either way, check to see if the table already has such an index. If
  97405. ** so, don't bother creating this one. This only applies to
  97406. ** automatically created indices. Users can do as they wish with
  97407. ** explicit indices.
  97408. **
  97409. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  97410. ** (and thus suppressing the second one) even if they have different
  97411. ** sort orders.
  97412. **
  97413. ** If there are different collating sequences or if the columns of
  97414. ** the constraint occur in different orders, then the constraints are
  97415. ** considered distinct and both result in separate indices.
  97416. */
  97417. Index *pIdx;
  97418. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97419. int k;
  97420. assert( IsUniqueIndex(pIdx) );
  97421. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  97422. assert( IsUniqueIndex(pIndex) );
  97423. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  97424. for(k=0; k<pIdx->nKeyCol; k++){
  97425. const char *z1;
  97426. const char *z2;
  97427. assert( pIdx->aiColumn[k]>=0 );
  97428. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  97429. z1 = pIdx->azColl[k];
  97430. z2 = pIndex->azColl[k];
  97431. if( sqlite3StrICmp(z1, z2) ) break;
  97432. }
  97433. if( k==pIdx->nKeyCol ){
  97434. if( pIdx->onError!=pIndex->onError ){
  97435. /* This constraint creates the same index as a previous
  97436. ** constraint specified somewhere in the CREATE TABLE statement.
  97437. ** However the ON CONFLICT clauses are different. If both this
  97438. ** constraint and the previous equivalent constraint have explicit
  97439. ** ON CONFLICT clauses this is an error. Otherwise, use the
  97440. ** explicitly specified behavior for the index.
  97441. */
  97442. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  97443. sqlite3ErrorMsg(pParse,
  97444. "conflicting ON CONFLICT clauses specified", 0);
  97445. }
  97446. if( pIdx->onError==OE_Default ){
  97447. pIdx->onError = pIndex->onError;
  97448. }
  97449. }
  97450. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  97451. goto exit_create_index;
  97452. }
  97453. }
  97454. }
  97455. /* Link the new Index structure to its table and to the other
  97456. ** in-memory database structures.
  97457. */
  97458. assert( pParse->nErr==0 );
  97459. if( db->init.busy ){
  97460. Index *p;
  97461. assert( !IN_DECLARE_VTAB );
  97462. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  97463. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  97464. pIndex->zName, pIndex);
  97465. if( p ){
  97466. assert( p==pIndex ); /* Malloc must have failed */
  97467. sqlite3OomFault(db);
  97468. goto exit_create_index;
  97469. }
  97470. db->mDbFlags |= DBFLAG_SchemaChange;
  97471. if( pTblName!=0 ){
  97472. pIndex->tnum = db->init.newTnum;
  97473. }
  97474. }
  97475. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  97476. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  97477. ** emit code to allocate the index rootpage on disk and make an entry for
  97478. ** the index in the sqlite_master table and populate the index with
  97479. ** content. But, do not do this if we are simply reading the sqlite_master
  97480. ** table to parse the schema, or if this index is the PRIMARY KEY index
  97481. ** of a WITHOUT ROWID table.
  97482. **
  97483. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  97484. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  97485. ** has just been created, it contains no data and the index initialization
  97486. ** step can be skipped.
  97487. */
  97488. else if( HasRowid(pTab) || pTblName!=0 ){
  97489. Vdbe *v;
  97490. char *zStmt;
  97491. int iMem = ++pParse->nMem;
  97492. v = sqlite3GetVdbe(pParse);
  97493. if( v==0 ) goto exit_create_index;
  97494. sqlite3BeginWriteOperation(pParse, 1, iDb);
  97495. /* Create the rootpage for the index using CreateIndex. But before
  97496. ** doing so, code a Noop instruction and store its address in
  97497. ** Index.tnum. This is required in case this index is actually a
  97498. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  97499. ** that case the convertToWithoutRowidTable() routine will replace
  97500. ** the Noop with a Goto to jump over the VDBE code generated below. */
  97501. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  97502. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  97503. /* Gather the complete text of the CREATE INDEX statement into
  97504. ** the zStmt variable
  97505. */
  97506. if( pStart ){
  97507. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  97508. if( pName->z[n-1]==';' ) n--;
  97509. /* A named index with an explicit CREATE INDEX statement */
  97510. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  97511. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  97512. }else{
  97513. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  97514. /* zStmt = sqlite3MPrintf(""); */
  97515. zStmt = 0;
  97516. }
  97517. /* Add an entry in sqlite_master for this index
  97518. */
  97519. sqlite3NestedParse(pParse,
  97520. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  97521. db->aDb[iDb].zDbSName, MASTER_NAME,
  97522. pIndex->zName,
  97523. pTab->zName,
  97524. iMem,
  97525. zStmt
  97526. );
  97527. sqlite3DbFree(db, zStmt);
  97528. /* Fill the index with data and reparse the schema. Code an OP_Expire
  97529. ** to invalidate all pre-compiled statements.
  97530. */
  97531. if( pTblName ){
  97532. sqlite3RefillIndex(pParse, pIndex, iMem);
  97533. sqlite3ChangeCookie(pParse, iDb);
  97534. sqlite3VdbeAddParseSchemaOp(v, iDb,
  97535. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  97536. sqlite3VdbeAddOp0(v, OP_Expire);
  97537. }
  97538. sqlite3VdbeJumpHere(v, pIndex->tnum);
  97539. }
  97540. /* When adding an index to the list of indices for a table, make
  97541. ** sure all indices labeled OE_Replace come after all those labeled
  97542. ** OE_Ignore. This is necessary for the correct constraint check
  97543. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  97544. ** UPDATE and INSERT statements.
  97545. */
  97546. if( db->init.busy || pTblName==0 ){
  97547. if( onError!=OE_Replace || pTab->pIndex==0
  97548. || pTab->pIndex->onError==OE_Replace){
  97549. pIndex->pNext = pTab->pIndex;
  97550. pTab->pIndex = pIndex;
  97551. }else{
  97552. Index *pOther = pTab->pIndex;
  97553. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  97554. pOther = pOther->pNext;
  97555. }
  97556. pIndex->pNext = pOther->pNext;
  97557. pOther->pNext = pIndex;
  97558. }
  97559. pIndex = 0;
  97560. }
  97561. /* Clean up before exiting */
  97562. exit_create_index:
  97563. if( pIndex ) freeIndex(db, pIndex);
  97564. sqlite3ExprDelete(db, pPIWhere);
  97565. sqlite3ExprListDelete(db, pList);
  97566. sqlite3SrcListDelete(db, pTblName);
  97567. sqlite3DbFree(db, zName);
  97568. }
  97569. /*
  97570. ** Fill the Index.aiRowEst[] array with default information - information
  97571. ** to be used when we have not run the ANALYZE command.
  97572. **
  97573. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  97574. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  97575. ** number of rows in the table that match any particular value of the
  97576. ** first column of the index. aiRowEst[2] is an estimate of the number
  97577. ** of rows that match any particular combination of the first 2 columns
  97578. ** of the index. And so forth. It must always be the case that
  97579. *
  97580. ** aiRowEst[N]<=aiRowEst[N-1]
  97581. ** aiRowEst[N]>=1
  97582. **
  97583. ** Apart from that, we have little to go on besides intuition as to
  97584. ** how aiRowEst[] should be initialized. The numbers generated here
  97585. ** are based on typical values found in actual indices.
  97586. */
  97587. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  97588. /* 10, 9, 8, 7, 6 */
  97589. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  97590. LogEst *a = pIdx->aiRowLogEst;
  97591. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  97592. int i;
  97593. /* Indexes with default row estimates should not have stat1 data */
  97594. assert( !pIdx->hasStat1 );
  97595. /* Set the first entry (number of rows in the index) to the estimated
  97596. ** number of rows in the table, or half the number of rows in the table
  97597. ** for a partial index. But do not let the estimate drop below 10. */
  97598. a[0] = pIdx->pTable->nRowLogEst;
  97599. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  97600. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  97601. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  97602. ** 6 and each subsequent value (if any) is 5. */
  97603. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  97604. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  97605. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  97606. }
  97607. assert( 0==sqlite3LogEst(1) );
  97608. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  97609. }
  97610. /*
  97611. ** This routine will drop an existing named index. This routine
  97612. ** implements the DROP INDEX statement.
  97613. */
  97614. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  97615. Index *pIndex;
  97616. Vdbe *v;
  97617. sqlite3 *db = pParse->db;
  97618. int iDb;
  97619. assert( pParse->nErr==0 ); /* Never called with prior errors */
  97620. if( db->mallocFailed ){
  97621. goto exit_drop_index;
  97622. }
  97623. assert( pName->nSrc==1 );
  97624. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97625. goto exit_drop_index;
  97626. }
  97627. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  97628. if( pIndex==0 ){
  97629. if( !ifExists ){
  97630. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  97631. }else{
  97632. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  97633. }
  97634. pParse->checkSchema = 1;
  97635. goto exit_drop_index;
  97636. }
  97637. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  97638. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  97639. "or PRIMARY KEY constraint cannot be dropped", 0);
  97640. goto exit_drop_index;
  97641. }
  97642. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  97643. #ifndef SQLITE_OMIT_AUTHORIZATION
  97644. {
  97645. int code = SQLITE_DROP_INDEX;
  97646. Table *pTab = pIndex->pTable;
  97647. const char *zDb = db->aDb[iDb].zDbSName;
  97648. const char *zTab = SCHEMA_TABLE(iDb);
  97649. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  97650. goto exit_drop_index;
  97651. }
  97652. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  97653. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  97654. goto exit_drop_index;
  97655. }
  97656. }
  97657. #endif
  97658. /* Generate code to remove the index and from the master table */
  97659. v = sqlite3GetVdbe(pParse);
  97660. if( v ){
  97661. sqlite3BeginWriteOperation(pParse, 1, iDb);
  97662. sqlite3NestedParse(pParse,
  97663. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  97664. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  97665. );
  97666. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  97667. sqlite3ChangeCookie(pParse, iDb);
  97668. destroyRootPage(pParse, pIndex->tnum, iDb);
  97669. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  97670. }
  97671. exit_drop_index:
  97672. sqlite3SrcListDelete(db, pName);
  97673. }
  97674. /*
  97675. ** pArray is a pointer to an array of objects. Each object in the
  97676. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  97677. ** to extend the array so that there is space for a new object at the end.
  97678. **
  97679. ** When this function is called, *pnEntry contains the current size of
  97680. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  97681. ** in total).
  97682. **
  97683. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  97684. ** space allocated for the new object is zeroed, *pnEntry updated to
  97685. ** reflect the new size of the array and a pointer to the new allocation
  97686. ** returned. *pIdx is set to the index of the new array entry in this case.
  97687. **
  97688. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  97689. ** unchanged and a copy of pArray returned.
  97690. */
  97691. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  97692. sqlite3 *db, /* Connection to notify of malloc failures */
  97693. void *pArray, /* Array of objects. Might be reallocated */
  97694. int szEntry, /* Size of each object in the array */
  97695. int *pnEntry, /* Number of objects currently in use */
  97696. int *pIdx /* Write the index of a new slot here */
  97697. ){
  97698. char *z;
  97699. int n = *pnEntry;
  97700. if( (n & (n-1))==0 ){
  97701. int sz = (n==0) ? 1 : 2*n;
  97702. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  97703. if( pNew==0 ){
  97704. *pIdx = -1;
  97705. return pArray;
  97706. }
  97707. pArray = pNew;
  97708. }
  97709. z = (char*)pArray;
  97710. memset(&z[n * szEntry], 0, szEntry);
  97711. *pIdx = n;
  97712. ++*pnEntry;
  97713. return pArray;
  97714. }
  97715. /*
  97716. ** Append a new element to the given IdList. Create a new IdList if
  97717. ** need be.
  97718. **
  97719. ** A new IdList is returned, or NULL if malloc() fails.
  97720. */
  97721. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  97722. int i;
  97723. if( pList==0 ){
  97724. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  97725. if( pList==0 ) return 0;
  97726. }
  97727. pList->a = sqlite3ArrayAllocate(
  97728. db,
  97729. pList->a,
  97730. sizeof(pList->a[0]),
  97731. &pList->nId,
  97732. &i
  97733. );
  97734. if( i<0 ){
  97735. sqlite3IdListDelete(db, pList);
  97736. return 0;
  97737. }
  97738. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  97739. return pList;
  97740. }
  97741. /*
  97742. ** Delete an IdList.
  97743. */
  97744. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  97745. int i;
  97746. if( pList==0 ) return;
  97747. for(i=0; i<pList->nId; i++){
  97748. sqlite3DbFree(db, pList->a[i].zName);
  97749. }
  97750. sqlite3DbFree(db, pList->a);
  97751. sqlite3DbFreeNN(db, pList);
  97752. }
  97753. /*
  97754. ** Return the index in pList of the identifier named zId. Return -1
  97755. ** if not found.
  97756. */
  97757. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  97758. int i;
  97759. if( pList==0 ) return -1;
  97760. for(i=0; i<pList->nId; i++){
  97761. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  97762. }
  97763. return -1;
  97764. }
  97765. /*
  97766. ** Expand the space allocated for the given SrcList object by
  97767. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  97768. ** New slots are zeroed.
  97769. **
  97770. ** For example, suppose a SrcList initially contains two entries: A,B.
  97771. ** To append 3 new entries onto the end, do this:
  97772. **
  97773. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  97774. **
  97775. ** After the call above it would contain: A, B, nil, nil, nil.
  97776. ** If the iStart argument had been 1 instead of 2, then the result
  97777. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  97778. ** the iStart value would be 0. The result then would
  97779. ** be: nil, nil, nil, A, B.
  97780. **
  97781. ** If a memory allocation fails the SrcList is unchanged. The
  97782. ** db->mallocFailed flag will be set to true.
  97783. */
  97784. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  97785. sqlite3 *db, /* Database connection to notify of OOM errors */
  97786. SrcList *pSrc, /* The SrcList to be enlarged */
  97787. int nExtra, /* Number of new slots to add to pSrc->a[] */
  97788. int iStart /* Index in pSrc->a[] of first new slot */
  97789. ){
  97790. int i;
  97791. /* Sanity checking on calling parameters */
  97792. assert( iStart>=0 );
  97793. assert( nExtra>=1 );
  97794. assert( pSrc!=0 );
  97795. assert( iStart<=pSrc->nSrc );
  97796. /* Allocate additional space if needed */
  97797. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  97798. SrcList *pNew;
  97799. int nAlloc = pSrc->nSrc*2+nExtra;
  97800. int nGot;
  97801. pNew = sqlite3DbRealloc(db, pSrc,
  97802. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  97803. if( pNew==0 ){
  97804. assert( db->mallocFailed );
  97805. return pSrc;
  97806. }
  97807. pSrc = pNew;
  97808. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  97809. pSrc->nAlloc = nGot;
  97810. }
  97811. /* Move existing slots that come after the newly inserted slots
  97812. ** out of the way */
  97813. for(i=pSrc->nSrc-1; i>=iStart; i--){
  97814. pSrc->a[i+nExtra] = pSrc->a[i];
  97815. }
  97816. pSrc->nSrc += nExtra;
  97817. /* Zero the newly allocated slots */
  97818. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  97819. for(i=iStart; i<iStart+nExtra; i++){
  97820. pSrc->a[i].iCursor = -1;
  97821. }
  97822. /* Return a pointer to the enlarged SrcList */
  97823. return pSrc;
  97824. }
  97825. /*
  97826. ** Append a new table name to the given SrcList. Create a new SrcList if
  97827. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  97828. **
  97829. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  97830. ** SrcList might be the same as the SrcList that was input or it might be
  97831. ** a new one. If an OOM error does occurs, then the prior value of pList
  97832. ** that is input to this routine is automatically freed.
  97833. **
  97834. ** If pDatabase is not null, it means that the table has an optional
  97835. ** database name prefix. Like this: "database.table". The pDatabase
  97836. ** points to the table name and the pTable points to the database name.
  97837. ** The SrcList.a[].zName field is filled with the table name which might
  97838. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  97839. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  97840. ** or with NULL if no database is specified.
  97841. **
  97842. ** In other words, if call like this:
  97843. **
  97844. ** sqlite3SrcListAppend(D,A,B,0);
  97845. **
  97846. ** Then B is a table name and the database name is unspecified. If called
  97847. ** like this:
  97848. **
  97849. ** sqlite3SrcListAppend(D,A,B,C);
  97850. **
  97851. ** Then C is the table name and B is the database name. If C is defined
  97852. ** then so is B. In other words, we never have a case where:
  97853. **
  97854. ** sqlite3SrcListAppend(D,A,0,C);
  97855. **
  97856. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  97857. ** before being added to the SrcList.
  97858. */
  97859. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  97860. sqlite3 *db, /* Connection to notify of malloc failures */
  97861. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  97862. Token *pTable, /* Table to append */
  97863. Token *pDatabase /* Database of the table */
  97864. ){
  97865. struct SrcList_item *pItem;
  97866. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  97867. assert( db!=0 );
  97868. if( pList==0 ){
  97869. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  97870. if( pList==0 ) return 0;
  97871. pList->nAlloc = 1;
  97872. pList->nSrc = 1;
  97873. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  97874. pList->a[0].iCursor = -1;
  97875. }else{
  97876. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  97877. }
  97878. if( db->mallocFailed ){
  97879. sqlite3SrcListDelete(db, pList);
  97880. return 0;
  97881. }
  97882. pItem = &pList->a[pList->nSrc-1];
  97883. if( pDatabase && pDatabase->z==0 ){
  97884. pDatabase = 0;
  97885. }
  97886. if( pDatabase ){
  97887. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  97888. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  97889. }else{
  97890. pItem->zName = sqlite3NameFromToken(db, pTable);
  97891. pItem->zDatabase = 0;
  97892. }
  97893. return pList;
  97894. }
  97895. /*
  97896. ** Assign VdbeCursor index numbers to all tables in a SrcList
  97897. */
  97898. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  97899. int i;
  97900. struct SrcList_item *pItem;
  97901. assert(pList || pParse->db->mallocFailed );
  97902. if( pList ){
  97903. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  97904. if( pItem->iCursor>=0 ) break;
  97905. pItem->iCursor = pParse->nTab++;
  97906. if( pItem->pSelect ){
  97907. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  97908. }
  97909. }
  97910. }
  97911. }
  97912. /*
  97913. ** Delete an entire SrcList including all its substructure.
  97914. */
  97915. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  97916. int i;
  97917. struct SrcList_item *pItem;
  97918. if( pList==0 ) return;
  97919. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  97920. sqlite3DbFree(db, pItem->zDatabase);
  97921. sqlite3DbFree(db, pItem->zName);
  97922. sqlite3DbFree(db, pItem->zAlias);
  97923. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  97924. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  97925. sqlite3DeleteTable(db, pItem->pTab);
  97926. sqlite3SelectDelete(db, pItem->pSelect);
  97927. sqlite3ExprDelete(db, pItem->pOn);
  97928. sqlite3IdListDelete(db, pItem->pUsing);
  97929. }
  97930. sqlite3DbFreeNN(db, pList);
  97931. }
  97932. /*
  97933. ** This routine is called by the parser to add a new term to the
  97934. ** end of a growing FROM clause. The "p" parameter is the part of
  97935. ** the FROM clause that has already been constructed. "p" is NULL
  97936. ** if this is the first term of the FROM clause. pTable and pDatabase
  97937. ** are the name of the table and database named in the FROM clause term.
  97938. ** pDatabase is NULL if the database name qualifier is missing - the
  97939. ** usual case. If the term has an alias, then pAlias points to the
  97940. ** alias token. If the term is a subquery, then pSubquery is the
  97941. ** SELECT statement that the subquery encodes. The pTable and
  97942. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  97943. ** parameters are the content of the ON and USING clauses.
  97944. **
  97945. ** Return a new SrcList which encodes is the FROM with the new
  97946. ** term added.
  97947. */
  97948. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  97949. Parse *pParse, /* Parsing context */
  97950. SrcList *p, /* The left part of the FROM clause already seen */
  97951. Token *pTable, /* Name of the table to add to the FROM clause */
  97952. Token *pDatabase, /* Name of the database containing pTable */
  97953. Token *pAlias, /* The right-hand side of the AS subexpression */
  97954. Select *pSubquery, /* A subquery used in place of a table name */
  97955. Expr *pOn, /* The ON clause of a join */
  97956. IdList *pUsing /* The USING clause of a join */
  97957. ){
  97958. struct SrcList_item *pItem;
  97959. sqlite3 *db = pParse->db;
  97960. if( !p && (pOn || pUsing) ){
  97961. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  97962. (pOn ? "ON" : "USING")
  97963. );
  97964. goto append_from_error;
  97965. }
  97966. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  97967. if( p==0 || NEVER(p->nSrc==0) ){
  97968. goto append_from_error;
  97969. }
  97970. pItem = &p->a[p->nSrc-1];
  97971. assert( pAlias!=0 );
  97972. if( pAlias->n ){
  97973. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  97974. }
  97975. pItem->pSelect = pSubquery;
  97976. pItem->pOn = pOn;
  97977. pItem->pUsing = pUsing;
  97978. return p;
  97979. append_from_error:
  97980. assert( p==0 );
  97981. sqlite3ExprDelete(db, pOn);
  97982. sqlite3IdListDelete(db, pUsing);
  97983. sqlite3SelectDelete(db, pSubquery);
  97984. return 0;
  97985. }
  97986. /*
  97987. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  97988. ** element of the source-list passed as the second argument.
  97989. */
  97990. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  97991. assert( pIndexedBy!=0 );
  97992. if( p && pIndexedBy->n>0 ){
  97993. struct SrcList_item *pItem;
  97994. assert( p->nSrc>0 );
  97995. pItem = &p->a[p->nSrc-1];
  97996. assert( pItem->fg.notIndexed==0 );
  97997. assert( pItem->fg.isIndexedBy==0 );
  97998. assert( pItem->fg.isTabFunc==0 );
  97999. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  98000. /* A "NOT INDEXED" clause was supplied. See parse.y
  98001. ** construct "indexed_opt" for details. */
  98002. pItem->fg.notIndexed = 1;
  98003. }else{
  98004. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  98005. pItem->fg.isIndexedBy = 1;
  98006. }
  98007. }
  98008. }
  98009. /*
  98010. ** Add the list of function arguments to the SrcList entry for a
  98011. ** table-valued-function.
  98012. */
  98013. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  98014. if( p ){
  98015. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  98016. assert( pItem->fg.notIndexed==0 );
  98017. assert( pItem->fg.isIndexedBy==0 );
  98018. assert( pItem->fg.isTabFunc==0 );
  98019. pItem->u1.pFuncArg = pList;
  98020. pItem->fg.isTabFunc = 1;
  98021. }else{
  98022. sqlite3ExprListDelete(pParse->db, pList);
  98023. }
  98024. }
  98025. /*
  98026. ** When building up a FROM clause in the parser, the join operator
  98027. ** is initially attached to the left operand. But the code generator
  98028. ** expects the join operator to be on the right operand. This routine
  98029. ** Shifts all join operators from left to right for an entire FROM
  98030. ** clause.
  98031. **
  98032. ** Example: Suppose the join is like this:
  98033. **
  98034. ** A natural cross join B
  98035. **
  98036. ** The operator is "natural cross join". The A and B operands are stored
  98037. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  98038. ** operator with A. This routine shifts that operator over to B.
  98039. */
  98040. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  98041. if( p ){
  98042. int i;
  98043. for(i=p->nSrc-1; i>0; i--){
  98044. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  98045. }
  98046. p->a[0].fg.jointype = 0;
  98047. }
  98048. }
  98049. /*
  98050. ** Generate VDBE code for a BEGIN statement.
  98051. */
  98052. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  98053. sqlite3 *db;
  98054. Vdbe *v;
  98055. int i;
  98056. assert( pParse!=0 );
  98057. db = pParse->db;
  98058. assert( db!=0 );
  98059. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  98060. return;
  98061. }
  98062. v = sqlite3GetVdbe(pParse);
  98063. if( !v ) return;
  98064. if( type!=TK_DEFERRED ){
  98065. for(i=0; i<db->nDb; i++){
  98066. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  98067. sqlite3VdbeUsesBtree(v, i);
  98068. }
  98069. }
  98070. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  98071. }
  98072. /*
  98073. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  98074. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  98075. ** code is generated for a COMMIT.
  98076. */
  98077. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  98078. Vdbe *v;
  98079. int isRollback;
  98080. assert( pParse!=0 );
  98081. assert( pParse->db!=0 );
  98082. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  98083. isRollback = eType==TK_ROLLBACK;
  98084. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  98085. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  98086. return;
  98087. }
  98088. v = sqlite3GetVdbe(pParse);
  98089. if( v ){
  98090. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  98091. }
  98092. }
  98093. /*
  98094. ** This function is called by the parser when it parses a command to create,
  98095. ** release or rollback an SQL savepoint.
  98096. */
  98097. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  98098. char *zName = sqlite3NameFromToken(pParse->db, pName);
  98099. if( zName ){
  98100. Vdbe *v = sqlite3GetVdbe(pParse);
  98101. #ifndef SQLITE_OMIT_AUTHORIZATION
  98102. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  98103. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  98104. #endif
  98105. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  98106. sqlite3DbFree(pParse->db, zName);
  98107. return;
  98108. }
  98109. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  98110. }
  98111. }
  98112. /*
  98113. ** Make sure the TEMP database is open and available for use. Return
  98114. ** the number of errors. Leave any error messages in the pParse structure.
  98115. */
  98116. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  98117. sqlite3 *db = pParse->db;
  98118. if( db->aDb[1].pBt==0 && !pParse->explain ){
  98119. int rc;
  98120. Btree *pBt;
  98121. static const int flags =
  98122. SQLITE_OPEN_READWRITE |
  98123. SQLITE_OPEN_CREATE |
  98124. SQLITE_OPEN_EXCLUSIVE |
  98125. SQLITE_OPEN_DELETEONCLOSE |
  98126. SQLITE_OPEN_TEMP_DB;
  98127. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  98128. if( rc!=SQLITE_OK ){
  98129. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  98130. "file for storing temporary tables");
  98131. pParse->rc = rc;
  98132. return 1;
  98133. }
  98134. db->aDb[1].pBt = pBt;
  98135. assert( db->aDb[1].pSchema );
  98136. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  98137. sqlite3OomFault(db);
  98138. return 1;
  98139. }
  98140. }
  98141. return 0;
  98142. }
  98143. /*
  98144. ** Record the fact that the schema cookie will need to be verified
  98145. ** for database iDb. The code to actually verify the schema cookie
  98146. ** will occur at the end of the top-level VDBE and will be generated
  98147. ** later, by sqlite3FinishCoding().
  98148. */
  98149. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  98150. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  98151. assert( iDb>=0 && iDb<pParse->db->nDb );
  98152. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  98153. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  98154. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  98155. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  98156. DbMaskSet(pToplevel->cookieMask, iDb);
  98157. if( !OMIT_TEMPDB && iDb==1 ){
  98158. sqlite3OpenTempDatabase(pToplevel);
  98159. }
  98160. }
  98161. }
  98162. /*
  98163. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  98164. ** attached database. Otherwise, invoke it for the database named zDb only.
  98165. */
  98166. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  98167. sqlite3 *db = pParse->db;
  98168. int i;
  98169. for(i=0; i<db->nDb; i++){
  98170. Db *pDb = &db->aDb[i];
  98171. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  98172. sqlite3CodeVerifySchema(pParse, i);
  98173. }
  98174. }
  98175. }
  98176. /*
  98177. ** Generate VDBE code that prepares for doing an operation that
  98178. ** might change the database.
  98179. **
  98180. ** This routine starts a new transaction if we are not already within
  98181. ** a transaction. If we are already within a transaction, then a checkpoint
  98182. ** is set if the setStatement parameter is true. A checkpoint should
  98183. ** be set for operations that might fail (due to a constraint) part of
  98184. ** the way through and which will need to undo some writes without having to
  98185. ** rollback the whole transaction. For operations where all constraints
  98186. ** can be checked before any changes are made to the database, it is never
  98187. ** necessary to undo a write and the checkpoint should not be set.
  98188. */
  98189. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  98190. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  98191. sqlite3CodeVerifySchema(pParse, iDb);
  98192. DbMaskSet(pToplevel->writeMask, iDb);
  98193. pToplevel->isMultiWrite |= setStatement;
  98194. }
  98195. /*
  98196. ** Indicate that the statement currently under construction might write
  98197. ** more than one entry (example: deleting one row then inserting another,
  98198. ** inserting multiple rows in a table, or inserting a row and index entries.)
  98199. ** If an abort occurs after some of these writes have completed, then it will
  98200. ** be necessary to undo the completed writes.
  98201. */
  98202. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  98203. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  98204. pToplevel->isMultiWrite = 1;
  98205. }
  98206. /*
  98207. ** The code generator calls this routine if is discovers that it is
  98208. ** possible to abort a statement prior to completion. In order to
  98209. ** perform this abort without corrupting the database, we need to make
  98210. ** sure that the statement is protected by a statement transaction.
  98211. **
  98212. ** Technically, we only need to set the mayAbort flag if the
  98213. ** isMultiWrite flag was previously set. There is a time dependency
  98214. ** such that the abort must occur after the multiwrite. This makes
  98215. ** some statements involving the REPLACE conflict resolution algorithm
  98216. ** go a little faster. But taking advantage of this time dependency
  98217. ** makes it more difficult to prove that the code is correct (in
  98218. ** particular, it prevents us from writing an effective
  98219. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  98220. ** to take the safe route and skip the optimization.
  98221. */
  98222. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  98223. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  98224. pToplevel->mayAbort = 1;
  98225. }
  98226. /*
  98227. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  98228. ** error. The onError parameter determines which (if any) of the statement
  98229. ** and/or current transaction is rolled back.
  98230. */
  98231. SQLITE_PRIVATE void sqlite3HaltConstraint(
  98232. Parse *pParse, /* Parsing context */
  98233. int errCode, /* extended error code */
  98234. int onError, /* Constraint type */
  98235. char *p4, /* Error message */
  98236. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  98237. u8 p5Errmsg /* P5_ErrMsg type */
  98238. ){
  98239. Vdbe *v = sqlite3GetVdbe(pParse);
  98240. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  98241. if( onError==OE_Abort ){
  98242. sqlite3MayAbort(pParse);
  98243. }
  98244. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  98245. sqlite3VdbeChangeP5(v, p5Errmsg);
  98246. }
  98247. /*
  98248. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  98249. */
  98250. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  98251. Parse *pParse, /* Parsing context */
  98252. int onError, /* Constraint type */
  98253. Index *pIdx /* The index that triggers the constraint */
  98254. ){
  98255. char *zErr;
  98256. int j;
  98257. StrAccum errMsg;
  98258. Table *pTab = pIdx->pTable;
  98259. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  98260. if( pIdx->aColExpr ){
  98261. sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
  98262. }else{
  98263. for(j=0; j<pIdx->nKeyCol; j++){
  98264. char *zCol;
  98265. assert( pIdx->aiColumn[j]>=0 );
  98266. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  98267. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  98268. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  98269. sqlite3StrAccumAppend(&errMsg, ".", 1);
  98270. sqlite3StrAccumAppendAll(&errMsg, zCol);
  98271. }
  98272. }
  98273. zErr = sqlite3StrAccumFinish(&errMsg);
  98274. sqlite3HaltConstraint(pParse,
  98275. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  98276. : SQLITE_CONSTRAINT_UNIQUE,
  98277. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  98278. }
  98279. /*
  98280. ** Code an OP_Halt due to non-unique rowid.
  98281. */
  98282. SQLITE_PRIVATE void sqlite3RowidConstraint(
  98283. Parse *pParse, /* Parsing context */
  98284. int onError, /* Conflict resolution algorithm */
  98285. Table *pTab /* The table with the non-unique rowid */
  98286. ){
  98287. char *zMsg;
  98288. int rc;
  98289. if( pTab->iPKey>=0 ){
  98290. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  98291. pTab->aCol[pTab->iPKey].zName);
  98292. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  98293. }else{
  98294. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  98295. rc = SQLITE_CONSTRAINT_ROWID;
  98296. }
  98297. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  98298. P5_ConstraintUnique);
  98299. }
  98300. /*
  98301. ** Check to see if pIndex uses the collating sequence pColl. Return
  98302. ** true if it does and false if it does not.
  98303. */
  98304. #ifndef SQLITE_OMIT_REINDEX
  98305. static int collationMatch(const char *zColl, Index *pIndex){
  98306. int i;
  98307. assert( zColl!=0 );
  98308. for(i=0; i<pIndex->nColumn; i++){
  98309. const char *z = pIndex->azColl[i];
  98310. assert( z!=0 || pIndex->aiColumn[i]<0 );
  98311. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  98312. return 1;
  98313. }
  98314. }
  98315. return 0;
  98316. }
  98317. #endif
  98318. /*
  98319. ** Recompute all indices of pTab that use the collating sequence pColl.
  98320. ** If pColl==0 then recompute all indices of pTab.
  98321. */
  98322. #ifndef SQLITE_OMIT_REINDEX
  98323. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  98324. Index *pIndex; /* An index associated with pTab */
  98325. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  98326. if( zColl==0 || collationMatch(zColl, pIndex) ){
  98327. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  98328. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98329. sqlite3RefillIndex(pParse, pIndex, -1);
  98330. }
  98331. }
  98332. }
  98333. #endif
  98334. /*
  98335. ** Recompute all indices of all tables in all databases where the
  98336. ** indices use the collating sequence pColl. If pColl==0 then recompute
  98337. ** all indices everywhere.
  98338. */
  98339. #ifndef SQLITE_OMIT_REINDEX
  98340. static void reindexDatabases(Parse *pParse, char const *zColl){
  98341. Db *pDb; /* A single database */
  98342. int iDb; /* The database index number */
  98343. sqlite3 *db = pParse->db; /* The database connection */
  98344. HashElem *k; /* For looping over tables in pDb */
  98345. Table *pTab; /* A table in the database */
  98346. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  98347. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  98348. assert( pDb!=0 );
  98349. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  98350. pTab = (Table*)sqliteHashData(k);
  98351. reindexTable(pParse, pTab, zColl);
  98352. }
  98353. }
  98354. }
  98355. #endif
  98356. /*
  98357. ** Generate code for the REINDEX command.
  98358. **
  98359. ** REINDEX -- 1
  98360. ** REINDEX <collation> -- 2
  98361. ** REINDEX ?<database>.?<tablename> -- 3
  98362. ** REINDEX ?<database>.?<indexname> -- 4
  98363. **
  98364. ** Form 1 causes all indices in all attached databases to be rebuilt.
  98365. ** Form 2 rebuilds all indices in all databases that use the named
  98366. ** collating function. Forms 3 and 4 rebuild the named index or all
  98367. ** indices associated with the named table.
  98368. */
  98369. #ifndef SQLITE_OMIT_REINDEX
  98370. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  98371. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  98372. char *z; /* Name of a table or index */
  98373. const char *zDb; /* Name of the database */
  98374. Table *pTab; /* A table in the database */
  98375. Index *pIndex; /* An index associated with pTab */
  98376. int iDb; /* The database index number */
  98377. sqlite3 *db = pParse->db; /* The database connection */
  98378. Token *pObjName; /* Name of the table or index to be reindexed */
  98379. /* Read the database schema. If an error occurs, leave an error message
  98380. ** and code in pParse and return NULL. */
  98381. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  98382. return;
  98383. }
  98384. if( pName1==0 ){
  98385. reindexDatabases(pParse, 0);
  98386. return;
  98387. }else if( NEVER(pName2==0) || pName2->z==0 ){
  98388. char *zColl;
  98389. assert( pName1->z );
  98390. zColl = sqlite3NameFromToken(pParse->db, pName1);
  98391. if( !zColl ) return;
  98392. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  98393. if( pColl ){
  98394. reindexDatabases(pParse, zColl);
  98395. sqlite3DbFree(db, zColl);
  98396. return;
  98397. }
  98398. sqlite3DbFree(db, zColl);
  98399. }
  98400. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  98401. if( iDb<0 ) return;
  98402. z = sqlite3NameFromToken(db, pObjName);
  98403. if( z==0 ) return;
  98404. zDb = db->aDb[iDb].zDbSName;
  98405. pTab = sqlite3FindTable(db, z, zDb);
  98406. if( pTab ){
  98407. reindexTable(pParse, pTab, 0);
  98408. sqlite3DbFree(db, z);
  98409. return;
  98410. }
  98411. pIndex = sqlite3FindIndex(db, z, zDb);
  98412. sqlite3DbFree(db, z);
  98413. if( pIndex ){
  98414. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98415. sqlite3RefillIndex(pParse, pIndex, -1);
  98416. return;
  98417. }
  98418. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  98419. }
  98420. #endif
  98421. /*
  98422. ** Return a KeyInfo structure that is appropriate for the given Index.
  98423. **
  98424. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  98425. ** when it has finished using it.
  98426. */
  98427. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  98428. int i;
  98429. int nCol = pIdx->nColumn;
  98430. int nKey = pIdx->nKeyCol;
  98431. KeyInfo *pKey;
  98432. if( pParse->nErr ) return 0;
  98433. if( pIdx->uniqNotNull ){
  98434. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  98435. }else{
  98436. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  98437. }
  98438. if( pKey ){
  98439. assert( sqlite3KeyInfoIsWriteable(pKey) );
  98440. for(i=0; i<nCol; i++){
  98441. const char *zColl = pIdx->azColl[i];
  98442. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  98443. sqlite3LocateCollSeq(pParse, zColl);
  98444. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  98445. }
  98446. if( pParse->nErr ){
  98447. sqlite3KeyInfoUnref(pKey);
  98448. pKey = 0;
  98449. }
  98450. }
  98451. return pKey;
  98452. }
  98453. #ifndef SQLITE_OMIT_CTE
  98454. /*
  98455. ** This routine is invoked once per CTE by the parser while parsing a
  98456. ** WITH clause.
  98457. */
  98458. SQLITE_PRIVATE With *sqlite3WithAdd(
  98459. Parse *pParse, /* Parsing context */
  98460. With *pWith, /* Existing WITH clause, or NULL */
  98461. Token *pName, /* Name of the common-table */
  98462. ExprList *pArglist, /* Optional column name list for the table */
  98463. Select *pQuery /* Query used to initialize the table */
  98464. ){
  98465. sqlite3 *db = pParse->db;
  98466. With *pNew;
  98467. char *zName;
  98468. /* Check that the CTE name is unique within this WITH clause. If
  98469. ** not, store an error in the Parse structure. */
  98470. zName = sqlite3NameFromToken(pParse->db, pName);
  98471. if( zName && pWith ){
  98472. int i;
  98473. for(i=0; i<pWith->nCte; i++){
  98474. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  98475. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  98476. }
  98477. }
  98478. }
  98479. if( pWith ){
  98480. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  98481. pNew = sqlite3DbRealloc(db, pWith, nByte);
  98482. }else{
  98483. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  98484. }
  98485. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  98486. if( db->mallocFailed ){
  98487. sqlite3ExprListDelete(db, pArglist);
  98488. sqlite3SelectDelete(db, pQuery);
  98489. sqlite3DbFree(db, zName);
  98490. pNew = pWith;
  98491. }else{
  98492. pNew->a[pNew->nCte].pSelect = pQuery;
  98493. pNew->a[pNew->nCte].pCols = pArglist;
  98494. pNew->a[pNew->nCte].zName = zName;
  98495. pNew->a[pNew->nCte].zCteErr = 0;
  98496. pNew->nCte++;
  98497. }
  98498. return pNew;
  98499. }
  98500. /*
  98501. ** Free the contents of the With object passed as the second argument.
  98502. */
  98503. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  98504. if( pWith ){
  98505. int i;
  98506. for(i=0; i<pWith->nCte; i++){
  98507. struct Cte *pCte = &pWith->a[i];
  98508. sqlite3ExprListDelete(db, pCte->pCols);
  98509. sqlite3SelectDelete(db, pCte->pSelect);
  98510. sqlite3DbFree(db, pCte->zName);
  98511. }
  98512. sqlite3DbFree(db, pWith);
  98513. }
  98514. }
  98515. #endif /* !defined(SQLITE_OMIT_CTE) */
  98516. /************** End of build.c ***********************************************/
  98517. /************** Begin file callback.c ****************************************/
  98518. /*
  98519. ** 2005 May 23
  98520. **
  98521. ** The author disclaims copyright to this source code. In place of
  98522. ** a legal notice, here is a blessing:
  98523. **
  98524. ** May you do good and not evil.
  98525. ** May you find forgiveness for yourself and forgive others.
  98526. ** May you share freely, never taking more than you give.
  98527. **
  98528. *************************************************************************
  98529. **
  98530. ** This file contains functions used to access the internal hash tables
  98531. ** of user defined functions and collation sequences.
  98532. */
  98533. /* #include "sqliteInt.h" */
  98534. /*
  98535. ** Invoke the 'collation needed' callback to request a collation sequence
  98536. ** in the encoding enc of name zName, length nName.
  98537. */
  98538. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  98539. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  98540. if( db->xCollNeeded ){
  98541. char *zExternal = sqlite3DbStrDup(db, zName);
  98542. if( !zExternal ) return;
  98543. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  98544. sqlite3DbFree(db, zExternal);
  98545. }
  98546. #ifndef SQLITE_OMIT_UTF16
  98547. if( db->xCollNeeded16 ){
  98548. char const *zExternal;
  98549. sqlite3_value *pTmp = sqlite3ValueNew(db);
  98550. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  98551. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  98552. if( zExternal ){
  98553. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  98554. }
  98555. sqlite3ValueFree(pTmp);
  98556. }
  98557. #endif
  98558. }
  98559. /*
  98560. ** This routine is called if the collation factory fails to deliver a
  98561. ** collation function in the best encoding but there may be other versions
  98562. ** of this collation function (for other text encodings) available. Use one
  98563. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  98564. ** possible.
  98565. */
  98566. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  98567. CollSeq *pColl2;
  98568. char *z = pColl->zName;
  98569. int i;
  98570. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  98571. for(i=0; i<3; i++){
  98572. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  98573. if( pColl2->xCmp!=0 ){
  98574. memcpy(pColl, pColl2, sizeof(CollSeq));
  98575. pColl->xDel = 0; /* Do not copy the destructor */
  98576. return SQLITE_OK;
  98577. }
  98578. }
  98579. return SQLITE_ERROR;
  98580. }
  98581. /*
  98582. ** This function is responsible for invoking the collation factory callback
  98583. ** or substituting a collation sequence of a different encoding when the
  98584. ** requested collation sequence is not available in the desired encoding.
  98585. **
  98586. ** If it is not NULL, then pColl must point to the database native encoding
  98587. ** collation sequence with name zName, length nName.
  98588. **
  98589. ** The return value is either the collation sequence to be used in database
  98590. ** db for collation type name zName, length nName, or NULL, if no collation
  98591. ** sequence can be found. If no collation is found, leave an error message.
  98592. **
  98593. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  98594. */
  98595. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  98596. Parse *pParse, /* Parsing context */
  98597. u8 enc, /* The desired encoding for the collating sequence */
  98598. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  98599. const char *zName /* Collating sequence name */
  98600. ){
  98601. CollSeq *p;
  98602. sqlite3 *db = pParse->db;
  98603. p = pColl;
  98604. if( !p ){
  98605. p = sqlite3FindCollSeq(db, enc, zName, 0);
  98606. }
  98607. if( !p || !p->xCmp ){
  98608. /* No collation sequence of this type for this encoding is registered.
  98609. ** Call the collation factory to see if it can supply us with one.
  98610. */
  98611. callCollNeeded(db, enc, zName);
  98612. p = sqlite3FindCollSeq(db, enc, zName, 0);
  98613. }
  98614. if( p && !p->xCmp && synthCollSeq(db, p) ){
  98615. p = 0;
  98616. }
  98617. assert( !p || p->xCmp );
  98618. if( p==0 ){
  98619. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  98620. }
  98621. return p;
  98622. }
  98623. /*
  98624. ** This routine is called on a collation sequence before it is used to
  98625. ** check that it is defined. An undefined collation sequence exists when
  98626. ** a database is loaded that contains references to collation sequences
  98627. ** that have not been defined by sqlite3_create_collation() etc.
  98628. **
  98629. ** If required, this routine calls the 'collation needed' callback to
  98630. ** request a definition of the collating sequence. If this doesn't work,
  98631. ** an equivalent collating sequence that uses a text encoding different
  98632. ** from the main database is substituted, if one is available.
  98633. */
  98634. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  98635. if( pColl && pColl->xCmp==0 ){
  98636. const char *zName = pColl->zName;
  98637. sqlite3 *db = pParse->db;
  98638. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  98639. if( !p ){
  98640. return SQLITE_ERROR;
  98641. }
  98642. assert( p==pColl );
  98643. }
  98644. return SQLITE_OK;
  98645. }
  98646. /*
  98647. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  98648. ** specified by zName and nName is not found and parameter 'create' is
  98649. ** true, then create a new entry. Otherwise return NULL.
  98650. **
  98651. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  98652. ** array of three CollSeq structures. The first is the collation sequence
  98653. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  98654. **
  98655. ** Stored immediately after the three collation sequences is a copy of
  98656. ** the collation sequence name. A pointer to this string is stored in
  98657. ** each collation sequence structure.
  98658. */
  98659. static CollSeq *findCollSeqEntry(
  98660. sqlite3 *db, /* Database connection */
  98661. const char *zName, /* Name of the collating sequence */
  98662. int create /* Create a new entry if true */
  98663. ){
  98664. CollSeq *pColl;
  98665. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  98666. if( 0==pColl && create ){
  98667. int nName = sqlite3Strlen30(zName) + 1;
  98668. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  98669. if( pColl ){
  98670. CollSeq *pDel = 0;
  98671. pColl[0].zName = (char*)&pColl[3];
  98672. pColl[0].enc = SQLITE_UTF8;
  98673. pColl[1].zName = (char*)&pColl[3];
  98674. pColl[1].enc = SQLITE_UTF16LE;
  98675. pColl[2].zName = (char*)&pColl[3];
  98676. pColl[2].enc = SQLITE_UTF16BE;
  98677. memcpy(pColl[0].zName, zName, nName);
  98678. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  98679. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  98680. ** return the pColl pointer to be deleted (because it wasn't added
  98681. ** to the hash table).
  98682. */
  98683. assert( pDel==0 || pDel==pColl );
  98684. if( pDel!=0 ){
  98685. sqlite3OomFault(db);
  98686. sqlite3DbFree(db, pDel);
  98687. pColl = 0;
  98688. }
  98689. }
  98690. }
  98691. return pColl;
  98692. }
  98693. /*
  98694. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  98695. ** Return the CollSeq* pointer for the collation sequence named zName
  98696. ** for the encoding 'enc' from the database 'db'.
  98697. **
  98698. ** If the entry specified is not found and 'create' is true, then create a
  98699. ** new entry. Otherwise return NULL.
  98700. **
  98701. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  98702. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  98703. ** if necessary and generates an error message if the collating sequence
  98704. ** cannot be found.
  98705. **
  98706. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  98707. */
  98708. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  98709. sqlite3 *db,
  98710. u8 enc,
  98711. const char *zName,
  98712. int create
  98713. ){
  98714. CollSeq *pColl;
  98715. if( zName ){
  98716. pColl = findCollSeqEntry(db, zName, create);
  98717. }else{
  98718. pColl = db->pDfltColl;
  98719. }
  98720. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  98721. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  98722. if( pColl ) pColl += enc-1;
  98723. return pColl;
  98724. }
  98725. /* During the search for the best function definition, this procedure
  98726. ** is called to test how well the function passed as the first argument
  98727. ** matches the request for a function with nArg arguments in a system
  98728. ** that uses encoding enc. The value returned indicates how well the
  98729. ** request is matched. A higher value indicates a better match.
  98730. **
  98731. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  98732. ** is also -1. In other words, we are searching for a function that
  98733. ** takes a variable number of arguments.
  98734. **
  98735. ** If nArg is -2 that means that we are searching for any function
  98736. ** regardless of the number of arguments it uses, so return a positive
  98737. ** match score for any
  98738. **
  98739. ** The returned value is always between 0 and 6, as follows:
  98740. **
  98741. ** 0: Not a match.
  98742. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  98743. ** 2: UTF16 byte order change required and function takes any number of args.
  98744. ** 3: encoding matches and function takes any number of arguments
  98745. ** 4: UTF8/16 conversion required - argument count matches exactly
  98746. ** 5: UTF16 byte order conversion required - argument count matches exactly
  98747. ** 6: Perfect match: encoding and argument count match exactly.
  98748. **
  98749. ** If nArg==(-2) then any function with a non-null xSFunc is
  98750. ** a perfect match and any function with xSFunc NULL is
  98751. ** a non-match.
  98752. */
  98753. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  98754. static int matchQuality(
  98755. FuncDef *p, /* The function we are evaluating for match quality */
  98756. int nArg, /* Desired number of arguments. (-1)==any */
  98757. u8 enc /* Desired text encoding */
  98758. ){
  98759. int match;
  98760. /* nArg of -2 is a special case */
  98761. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  98762. /* Wrong number of arguments means "no match" */
  98763. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  98764. /* Give a better score to a function with a specific number of arguments
  98765. ** than to function that accepts any number of arguments. */
  98766. if( p->nArg==nArg ){
  98767. match = 4;
  98768. }else{
  98769. match = 1;
  98770. }
  98771. /* Bonus points if the text encoding matches */
  98772. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  98773. match += 2; /* Exact encoding match */
  98774. }else if( (enc & p->funcFlags & 2)!=0 ){
  98775. match += 1; /* Both are UTF16, but with different byte orders */
  98776. }
  98777. return match;
  98778. }
  98779. /*
  98780. ** Search a FuncDefHash for a function with the given name. Return
  98781. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  98782. */
  98783. static FuncDef *functionSearch(
  98784. int h, /* Hash of the name */
  98785. const char *zFunc /* Name of function */
  98786. ){
  98787. FuncDef *p;
  98788. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  98789. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  98790. return p;
  98791. }
  98792. }
  98793. return 0;
  98794. }
  98795. /*
  98796. ** Insert a new FuncDef into a FuncDefHash hash table.
  98797. */
  98798. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  98799. FuncDef *aDef, /* List of global functions to be inserted */
  98800. int nDef /* Length of the apDef[] list */
  98801. ){
  98802. int i;
  98803. for(i=0; i<nDef; i++){
  98804. FuncDef *pOther;
  98805. const char *zName = aDef[i].zName;
  98806. int nName = sqlite3Strlen30(zName);
  98807. int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
  98808. assert( zName[0]>='a' && zName[0]<='z' );
  98809. pOther = functionSearch(h, zName);
  98810. if( pOther ){
  98811. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  98812. aDef[i].pNext = pOther->pNext;
  98813. pOther->pNext = &aDef[i];
  98814. }else{
  98815. aDef[i].pNext = 0;
  98816. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  98817. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  98818. }
  98819. }
  98820. }
  98821. /*
  98822. ** Locate a user function given a name, a number of arguments and a flag
  98823. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  98824. ** pointer to the FuncDef structure that defines that function, or return
  98825. ** NULL if the function does not exist.
  98826. **
  98827. ** If the createFlag argument is true, then a new (blank) FuncDef
  98828. ** structure is created and liked into the "db" structure if a
  98829. ** no matching function previously existed.
  98830. **
  98831. ** If nArg is -2, then the first valid function found is returned. A
  98832. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  98833. ** case is used to see if zName is a valid function name for some number
  98834. ** of arguments. If nArg is -2, then createFlag must be 0.
  98835. **
  98836. ** If createFlag is false, then a function with the required name and
  98837. ** number of arguments may be returned even if the eTextRep flag does not
  98838. ** match that requested.
  98839. */
  98840. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  98841. sqlite3 *db, /* An open database */
  98842. const char *zName, /* Name of the function. zero-terminated */
  98843. int nArg, /* Number of arguments. -1 means any number */
  98844. u8 enc, /* Preferred text encoding */
  98845. u8 createFlag /* Create new entry if true and does not otherwise exist */
  98846. ){
  98847. FuncDef *p; /* Iterator variable */
  98848. FuncDef *pBest = 0; /* Best match found so far */
  98849. int bestScore = 0; /* Score of best match */
  98850. int h; /* Hash value */
  98851. int nName; /* Length of the name */
  98852. assert( nArg>=(-2) );
  98853. assert( nArg>=(-1) || createFlag==0 );
  98854. nName = sqlite3Strlen30(zName);
  98855. /* First search for a match amongst the application-defined functions.
  98856. */
  98857. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  98858. while( p ){
  98859. int score = matchQuality(p, nArg, enc);
  98860. if( score>bestScore ){
  98861. pBest = p;
  98862. bestScore = score;
  98863. }
  98864. p = p->pNext;
  98865. }
  98866. /* If no match is found, search the built-in functions.
  98867. **
  98868. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  98869. ** functions even if a prior app-defined function was found. And give
  98870. ** priority to built-in functions.
  98871. **
  98872. ** Except, if createFlag is true, that means that we are trying to
  98873. ** install a new function. Whatever FuncDef structure is returned it will
  98874. ** have fields overwritten with new information appropriate for the
  98875. ** new function. But the FuncDefs for built-in functions are read-only.
  98876. ** So we must not search for built-ins when creating a new function.
  98877. */
  98878. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  98879. bestScore = 0;
  98880. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  98881. p = functionSearch(h, zName);
  98882. while( p ){
  98883. int score = matchQuality(p, nArg, enc);
  98884. if( score>bestScore ){
  98885. pBest = p;
  98886. bestScore = score;
  98887. }
  98888. p = p->pNext;
  98889. }
  98890. }
  98891. /* If the createFlag parameter is true and the search did not reveal an
  98892. ** exact match for the name, number of arguments and encoding, then add a
  98893. ** new entry to the hash table and return it.
  98894. */
  98895. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  98896. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  98897. FuncDef *pOther;
  98898. pBest->zName = (const char*)&pBest[1];
  98899. pBest->nArg = (u16)nArg;
  98900. pBest->funcFlags = enc;
  98901. memcpy((char*)&pBest[1], zName, nName+1);
  98902. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  98903. if( pOther==pBest ){
  98904. sqlite3DbFree(db, pBest);
  98905. sqlite3OomFault(db);
  98906. return 0;
  98907. }else{
  98908. pBest->pNext = pOther;
  98909. }
  98910. }
  98911. if( pBest && (pBest->xSFunc || createFlag) ){
  98912. return pBest;
  98913. }
  98914. return 0;
  98915. }
  98916. /*
  98917. ** Free all resources held by the schema structure. The void* argument points
  98918. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  98919. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  98920. ** of the schema hash tables).
  98921. **
  98922. ** The Schema.cache_size variable is not cleared.
  98923. */
  98924. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  98925. Hash temp1;
  98926. Hash temp2;
  98927. HashElem *pElem;
  98928. Schema *pSchema = (Schema *)p;
  98929. temp1 = pSchema->tblHash;
  98930. temp2 = pSchema->trigHash;
  98931. sqlite3HashInit(&pSchema->trigHash);
  98932. sqlite3HashClear(&pSchema->idxHash);
  98933. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  98934. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  98935. }
  98936. sqlite3HashClear(&temp2);
  98937. sqlite3HashInit(&pSchema->tblHash);
  98938. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  98939. Table *pTab = sqliteHashData(pElem);
  98940. sqlite3DeleteTable(0, pTab);
  98941. }
  98942. sqlite3HashClear(&temp1);
  98943. sqlite3HashClear(&pSchema->fkeyHash);
  98944. pSchema->pSeqTab = 0;
  98945. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  98946. pSchema->iGeneration++;
  98947. }
  98948. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  98949. }
  98950. /*
  98951. ** Find and return the schema associated with a BTree. Create
  98952. ** a new one if necessary.
  98953. */
  98954. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  98955. Schema * p;
  98956. if( pBt ){
  98957. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  98958. }else{
  98959. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  98960. }
  98961. if( !p ){
  98962. sqlite3OomFault(db);
  98963. }else if ( 0==p->file_format ){
  98964. sqlite3HashInit(&p->tblHash);
  98965. sqlite3HashInit(&p->idxHash);
  98966. sqlite3HashInit(&p->trigHash);
  98967. sqlite3HashInit(&p->fkeyHash);
  98968. p->enc = SQLITE_UTF8;
  98969. }
  98970. return p;
  98971. }
  98972. /************** End of callback.c ********************************************/
  98973. /************** Begin file delete.c ******************************************/
  98974. /*
  98975. ** 2001 September 15
  98976. **
  98977. ** The author disclaims copyright to this source code. In place of
  98978. ** a legal notice, here is a blessing:
  98979. **
  98980. ** May you do good and not evil.
  98981. ** May you find forgiveness for yourself and forgive others.
  98982. ** May you share freely, never taking more than you give.
  98983. **
  98984. *************************************************************************
  98985. ** This file contains C code routines that are called by the parser
  98986. ** in order to generate code for DELETE FROM statements.
  98987. */
  98988. /* #include "sqliteInt.h" */
  98989. /*
  98990. ** While a SrcList can in general represent multiple tables and subqueries
  98991. ** (as in the FROM clause of a SELECT statement) in this case it contains
  98992. ** the name of a single table, as one might find in an INSERT, DELETE,
  98993. ** or UPDATE statement. Look up that table in the symbol table and
  98994. ** return a pointer. Set an error message and return NULL if the table
  98995. ** name is not found or if any other error occurs.
  98996. **
  98997. ** The following fields are initialized appropriate in pSrc:
  98998. **
  98999. ** pSrc->a[0].pTab Pointer to the Table object
  99000. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  99001. **
  99002. */
  99003. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  99004. struct SrcList_item *pItem = pSrc->a;
  99005. Table *pTab;
  99006. assert( pItem && pSrc->nSrc==1 );
  99007. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  99008. sqlite3DeleteTable(pParse->db, pItem->pTab);
  99009. pItem->pTab = pTab;
  99010. if( pTab ){
  99011. pTab->nTabRef++;
  99012. }
  99013. if( sqlite3IndexedByLookup(pParse, pItem) ){
  99014. pTab = 0;
  99015. }
  99016. return pTab;
  99017. }
  99018. /*
  99019. ** Check to make sure the given table is writable. If it is not
  99020. ** writable, generate an error message and return 1. If it is
  99021. ** writable return 0;
  99022. */
  99023. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  99024. /* A table is not writable under the following circumstances:
  99025. **
  99026. ** 1) It is a virtual table and no implementation of the xUpdate method
  99027. ** has been provided, or
  99028. ** 2) It is a system table (i.e. sqlite_master), this call is not
  99029. ** part of a nested parse and writable_schema pragma has not
  99030. ** been specified.
  99031. **
  99032. ** In either case leave an error message in pParse and return non-zero.
  99033. */
  99034. if( ( IsVirtual(pTab)
  99035. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  99036. || ( (pTab->tabFlags & TF_Readonly)!=0
  99037. && (pParse->db->flags & SQLITE_WriteSchema)==0
  99038. && pParse->nested==0 )
  99039. ){
  99040. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  99041. return 1;
  99042. }
  99043. #ifndef SQLITE_OMIT_VIEW
  99044. if( !viewOk && pTab->pSelect ){
  99045. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  99046. return 1;
  99047. }
  99048. #endif
  99049. return 0;
  99050. }
  99051. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  99052. /*
  99053. ** Evaluate a view and store its result in an ephemeral table. The
  99054. ** pWhere argument is an optional WHERE clause that restricts the
  99055. ** set of rows in the view that are to be added to the ephemeral table.
  99056. */
  99057. SQLITE_PRIVATE void sqlite3MaterializeView(
  99058. Parse *pParse, /* Parsing context */
  99059. Table *pView, /* View definition */
  99060. Expr *pWhere, /* Optional WHERE clause to be added */
  99061. int iCur /* Cursor number for ephemeral table */
  99062. ){
  99063. SelectDest dest;
  99064. Select *pSel;
  99065. SrcList *pFrom;
  99066. sqlite3 *db = pParse->db;
  99067. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  99068. pWhere = sqlite3ExprDup(db, pWhere, 0);
  99069. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  99070. if( pFrom ){
  99071. assert( pFrom->nSrc==1 );
  99072. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  99073. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  99074. assert( pFrom->a[0].pOn==0 );
  99075. assert( pFrom->a[0].pUsing==0 );
  99076. }
  99077. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
  99078. SF_IncludeHidden, 0, 0);
  99079. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  99080. sqlite3Select(pParse, pSel, &dest);
  99081. sqlite3SelectDelete(db, pSel);
  99082. }
  99083. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  99084. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  99085. /*
  99086. ** Generate an expression tree to implement the WHERE, ORDER BY,
  99087. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  99088. **
  99089. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  99090. ** \__________________________/
  99091. ** pLimitWhere (pInClause)
  99092. */
  99093. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  99094. Parse *pParse, /* The parser context */
  99095. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  99096. Expr *pWhere, /* The WHERE clause. May be null */
  99097. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  99098. Expr *pLimit, /* The LIMIT clause. May be null */
  99099. Expr *pOffset, /* The OFFSET clause. May be null */
  99100. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  99101. ){
  99102. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  99103. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  99104. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  99105. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  99106. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  99107. Select *pSelect = NULL; /* Complete SELECT tree */
  99108. /* Check that there isn't an ORDER BY without a LIMIT clause.
  99109. */
  99110. if( pOrderBy && (pLimit == 0) ) {
  99111. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  99112. goto limit_where_cleanup;
  99113. }
  99114. /* We only need to generate a select expression if there
  99115. ** is a limit/offset term to enforce.
  99116. */
  99117. if( pLimit == 0 ) {
  99118. /* if pLimit is null, pOffset will always be null as well. */
  99119. assert( pOffset == 0 );
  99120. return pWhere;
  99121. }
  99122. /* Generate a select expression tree to enforce the limit/offset
  99123. ** term for the DELETE or UPDATE statement. For example:
  99124. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  99125. ** becomes:
  99126. ** DELETE FROM table_a WHERE rowid IN (
  99127. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  99128. ** );
  99129. */
  99130. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  99131. if( pSelectRowid == 0 ) goto limit_where_cleanup;
  99132. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  99133. if( pEList == 0 ) goto limit_where_cleanup;
  99134. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  99135. ** and the SELECT subtree. */
  99136. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  99137. if( pSelectSrc == 0 ) {
  99138. sqlite3ExprListDelete(pParse->db, pEList);
  99139. goto limit_where_cleanup;
  99140. }
  99141. /* generate the SELECT expression tree. */
  99142. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  99143. pOrderBy,0,pLimit,pOffset);
  99144. if( pSelect == 0 ) return 0;
  99145. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  99146. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  99147. pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
  99148. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  99149. return pInClause;
  99150. limit_where_cleanup:
  99151. sqlite3ExprDelete(pParse->db, pWhere);
  99152. sqlite3ExprListDelete(pParse->db, pOrderBy);
  99153. sqlite3ExprDelete(pParse->db, pLimit);
  99154. sqlite3ExprDelete(pParse->db, pOffset);
  99155. return 0;
  99156. }
  99157. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  99158. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  99159. /*
  99160. ** Generate code for a DELETE FROM statement.
  99161. **
  99162. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  99163. ** \________/ \________________/
  99164. ** pTabList pWhere
  99165. */
  99166. SQLITE_PRIVATE void sqlite3DeleteFrom(
  99167. Parse *pParse, /* The parser context */
  99168. SrcList *pTabList, /* The table from which we should delete things */
  99169. Expr *pWhere /* The WHERE clause. May be null */
  99170. ){
  99171. Vdbe *v; /* The virtual database engine */
  99172. Table *pTab; /* The table from which records will be deleted */
  99173. int i; /* Loop counter */
  99174. WhereInfo *pWInfo; /* Information about the WHERE clause */
  99175. Index *pIdx; /* For looping over indices of the table */
  99176. int iTabCur; /* Cursor number for the table */
  99177. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  99178. int iIdxCur = 0; /* Cursor number of the first index */
  99179. int nIdx; /* Number of indices */
  99180. sqlite3 *db; /* Main database structure */
  99181. AuthContext sContext; /* Authorization context */
  99182. NameContext sNC; /* Name context to resolve expressions in */
  99183. int iDb; /* Database number */
  99184. int memCnt = -1; /* Memory cell used for change counting */
  99185. int rcauth; /* Value returned by authorization callback */
  99186. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  99187. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  99188. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  99189. Index *pPk; /* The PRIMARY KEY index on the table */
  99190. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  99191. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  99192. int iKey; /* Memory cell holding key of row to be deleted */
  99193. i16 nKey; /* Number of memory cells in the row key */
  99194. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  99195. int iRowSet = 0; /* Register for rowset of rows to delete */
  99196. int addrBypass = 0; /* Address of jump over the delete logic */
  99197. int addrLoop = 0; /* Top of the delete loop */
  99198. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  99199. int bComplex; /* True if there are triggers or FKs or
  99200. ** subqueries in the WHERE clause */
  99201. #ifndef SQLITE_OMIT_TRIGGER
  99202. int isView; /* True if attempting to delete from a view */
  99203. Trigger *pTrigger; /* List of table triggers, if required */
  99204. #endif
  99205. memset(&sContext, 0, sizeof(sContext));
  99206. db = pParse->db;
  99207. if( pParse->nErr || db->mallocFailed ){
  99208. goto delete_from_cleanup;
  99209. }
  99210. assert( pTabList->nSrc==1 );
  99211. /* Locate the table which we want to delete. This table has to be
  99212. ** put in an SrcList structure because some of the subroutines we
  99213. ** will be calling are designed to work with multiple tables and expect
  99214. ** an SrcList* parameter instead of just a Table* parameter.
  99215. */
  99216. pTab = sqlite3SrcListLookup(pParse, pTabList);
  99217. if( pTab==0 ) goto delete_from_cleanup;
  99218. /* Figure out if we have any triggers and if the table being
  99219. ** deleted from is a view
  99220. */
  99221. #ifndef SQLITE_OMIT_TRIGGER
  99222. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  99223. isView = pTab->pSelect!=0;
  99224. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  99225. #else
  99226. # define pTrigger 0
  99227. # define isView 0
  99228. #endif
  99229. #ifdef SQLITE_OMIT_VIEW
  99230. # undef isView
  99231. # define isView 0
  99232. #endif
  99233. /* If pTab is really a view, make sure it has been initialized.
  99234. */
  99235. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  99236. goto delete_from_cleanup;
  99237. }
  99238. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  99239. goto delete_from_cleanup;
  99240. }
  99241. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99242. assert( iDb<db->nDb );
  99243. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  99244. db->aDb[iDb].zDbSName);
  99245. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  99246. if( rcauth==SQLITE_DENY ){
  99247. goto delete_from_cleanup;
  99248. }
  99249. assert(!isView || pTrigger);
  99250. /* Assign cursor numbers to the table and all its indices.
  99251. */
  99252. assert( pTabList->nSrc==1 );
  99253. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  99254. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  99255. pParse->nTab++;
  99256. }
  99257. /* Start the view context
  99258. */
  99259. if( isView ){
  99260. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  99261. }
  99262. /* Begin generating code.
  99263. */
  99264. v = sqlite3GetVdbe(pParse);
  99265. if( v==0 ){
  99266. goto delete_from_cleanup;
  99267. }
  99268. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  99269. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99270. /* If we are trying to delete from a view, realize that view into
  99271. ** an ephemeral table.
  99272. */
  99273. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  99274. if( isView ){
  99275. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  99276. iDataCur = iIdxCur = iTabCur;
  99277. }
  99278. #endif
  99279. /* Resolve the column names in the WHERE clause.
  99280. */
  99281. memset(&sNC, 0, sizeof(sNC));
  99282. sNC.pParse = pParse;
  99283. sNC.pSrcList = pTabList;
  99284. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  99285. goto delete_from_cleanup;
  99286. }
  99287. /* Initialize the counter of the number of rows deleted, if
  99288. ** we are counting rows.
  99289. */
  99290. if( db->flags & SQLITE_CountRows ){
  99291. memCnt = ++pParse->nMem;
  99292. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  99293. }
  99294. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  99295. /* Special case: A DELETE without a WHERE clause deletes everything.
  99296. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  99297. ** this optimization caused the row change count (the value returned by
  99298. ** API function sqlite3_count_changes) to be set incorrectly.
  99299. **
  99300. ** The "rcauth==SQLITE_OK" terms is the
  99301. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  99302. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  99303. ** the truncate optimization is disabled and all rows are deleted
  99304. ** individually.
  99305. */
  99306. if( rcauth==SQLITE_OK
  99307. && pWhere==0
  99308. && !bComplex
  99309. && !IsVirtual(pTab)
  99310. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  99311. && db->xPreUpdateCallback==0
  99312. #endif
  99313. ){
  99314. assert( !isView );
  99315. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  99316. if( HasRowid(pTab) ){
  99317. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  99318. pTab->zName, P4_STATIC);
  99319. }
  99320. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99321. assert( pIdx->pSchema==pTab->pSchema );
  99322. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  99323. }
  99324. }else
  99325. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  99326. {
  99327. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  99328. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  99329. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  99330. if( HasRowid(pTab) ){
  99331. /* For a rowid table, initialize the RowSet to an empty set */
  99332. pPk = 0;
  99333. nPk = 1;
  99334. iRowSet = ++pParse->nMem;
  99335. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  99336. }else{
  99337. /* For a WITHOUT ROWID table, create an ephemeral table used to
  99338. ** hold all primary keys for rows to be deleted. */
  99339. pPk = sqlite3PrimaryKeyIndex(pTab);
  99340. assert( pPk!=0 );
  99341. nPk = pPk->nKeyCol;
  99342. iPk = pParse->nMem+1;
  99343. pParse->nMem += nPk;
  99344. iEphCur = pParse->nTab++;
  99345. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  99346. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  99347. }
  99348. /* Construct a query to find the rowid or primary key for every row
  99349. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  99350. ** to indicate the strategy used to implement this delete:
  99351. **
  99352. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  99353. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  99354. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  99355. */
  99356. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  99357. if( pWInfo==0 ) goto delete_from_cleanup;
  99358. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  99359. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  99360. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  99361. /* Keep track of the number of rows to be deleted */
  99362. if( db->flags & SQLITE_CountRows ){
  99363. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  99364. }
  99365. /* Extract the rowid or primary key for the current row */
  99366. if( pPk ){
  99367. for(i=0; i<nPk; i++){
  99368. assert( pPk->aiColumn[i]>=0 );
  99369. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  99370. pPk->aiColumn[i], iPk+i);
  99371. }
  99372. iKey = iPk;
  99373. }else{
  99374. iKey = pParse->nMem + 1;
  99375. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  99376. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  99377. }
  99378. if( eOnePass!=ONEPASS_OFF ){
  99379. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  99380. ** one, so just keep it in its register(s) and fall through to the
  99381. ** delete code. */
  99382. nKey = nPk; /* OP_Found will use an unpacked key */
  99383. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  99384. if( aToOpen==0 ){
  99385. sqlite3WhereEnd(pWInfo);
  99386. goto delete_from_cleanup;
  99387. }
  99388. memset(aToOpen, 1, nIdx+1);
  99389. aToOpen[nIdx+1] = 0;
  99390. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  99391. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  99392. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  99393. }else{
  99394. if( pPk ){
  99395. /* Add the PK key for this row to the temporary table */
  99396. iKey = ++pParse->nMem;
  99397. nKey = 0; /* Zero tells OP_Found to use a composite key */
  99398. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  99399. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  99400. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  99401. }else{
  99402. /* Add the rowid of the row to be deleted to the RowSet */
  99403. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  99404. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  99405. }
  99406. }
  99407. /* If this DELETE cannot use the ONEPASS strategy, this is the
  99408. ** end of the WHERE loop */
  99409. if( eOnePass!=ONEPASS_OFF ){
  99410. addrBypass = sqlite3VdbeMakeLabel(v);
  99411. }else{
  99412. sqlite3WhereEnd(pWInfo);
  99413. }
  99414. /* Unless this is a view, open cursors for the table we are
  99415. ** deleting from and all its indices. If this is a view, then the
  99416. ** only effect this statement has is to fire the INSTEAD OF
  99417. ** triggers.
  99418. */
  99419. if( !isView ){
  99420. int iAddrOnce = 0;
  99421. if( eOnePass==ONEPASS_MULTI ){
  99422. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  99423. }
  99424. testcase( IsVirtual(pTab) );
  99425. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  99426. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  99427. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  99428. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  99429. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  99430. }
  99431. /* Set up a loop over the rowids/primary-keys that were found in the
  99432. ** where-clause loop above.
  99433. */
  99434. if( eOnePass!=ONEPASS_OFF ){
  99435. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  99436. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  99437. assert( pPk!=0 || pTab->pSelect!=0 );
  99438. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  99439. VdbeCoverage(v);
  99440. }
  99441. }else if( pPk ){
  99442. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  99443. if( IsVirtual(pTab) ){
  99444. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  99445. }else{
  99446. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  99447. }
  99448. assert( nKey==0 ); /* OP_Found will use a composite key */
  99449. }else{
  99450. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  99451. VdbeCoverage(v);
  99452. assert( nKey==1 );
  99453. }
  99454. /* Delete the row */
  99455. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99456. if( IsVirtual(pTab) ){
  99457. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  99458. sqlite3VtabMakeWritable(pParse, pTab);
  99459. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  99460. sqlite3VdbeChangeP5(v, OE_Abort);
  99461. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  99462. sqlite3MayAbort(pParse);
  99463. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  99464. pParse->isMultiWrite = 0;
  99465. }
  99466. }else
  99467. #endif
  99468. {
  99469. int count = (pParse->nested==0); /* True to count changes */
  99470. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  99471. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  99472. }
  99473. /* End of the loop over all rowids/primary-keys. */
  99474. if( eOnePass!=ONEPASS_OFF ){
  99475. sqlite3VdbeResolveLabel(v, addrBypass);
  99476. sqlite3WhereEnd(pWInfo);
  99477. }else if( pPk ){
  99478. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  99479. sqlite3VdbeJumpHere(v, addrLoop);
  99480. }else{
  99481. sqlite3VdbeGoto(v, addrLoop);
  99482. sqlite3VdbeJumpHere(v, addrLoop);
  99483. }
  99484. } /* End non-truncate path */
  99485. /* Update the sqlite_sequence table by storing the content of the
  99486. ** maximum rowid counter values recorded while inserting into
  99487. ** autoincrement tables.
  99488. */
  99489. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  99490. sqlite3AutoincrementEnd(pParse);
  99491. }
  99492. /* Return the number of rows that were deleted. If this routine is
  99493. ** generating code because of a call to sqlite3NestedParse(), do not
  99494. ** invoke the callback function.
  99495. */
  99496. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  99497. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  99498. sqlite3VdbeSetNumCols(v, 1);
  99499. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  99500. }
  99501. delete_from_cleanup:
  99502. sqlite3AuthContextPop(&sContext);
  99503. sqlite3SrcListDelete(db, pTabList);
  99504. sqlite3ExprDelete(db, pWhere);
  99505. sqlite3DbFree(db, aToOpen);
  99506. return;
  99507. }
  99508. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  99509. ** they may interfere with compilation of other functions in this file
  99510. ** (or in another file, if this file becomes part of the amalgamation). */
  99511. #ifdef isView
  99512. #undef isView
  99513. #endif
  99514. #ifdef pTrigger
  99515. #undef pTrigger
  99516. #endif
  99517. /*
  99518. ** This routine generates VDBE code that causes a single row of a
  99519. ** single table to be deleted. Both the original table entry and
  99520. ** all indices are removed.
  99521. **
  99522. ** Preconditions:
  99523. **
  99524. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  99525. ** store for the table. (This will be either the table itself,
  99526. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  99527. ** of a WITHOUT ROWID table.)
  99528. **
  99529. ** 2. Read/write cursors for all indices of pTab must be open as
  99530. ** cursor number iIdxCur+i for the i-th index.
  99531. **
  99532. ** 3. The primary key for the row to be deleted must be stored in a
  99533. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  99534. ** that a search record formed from OP_MakeRecord is contained in the
  99535. ** single memory location iPk.
  99536. **
  99537. ** eMode:
  99538. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  99539. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  99540. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  99541. ** then this function must seek iDataCur to the entry identified by iPk
  99542. ** and nPk before reading from it.
  99543. **
  99544. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  99545. ** of a ONEPASS delete that affects multiple rows. In this case, if
  99546. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  99547. ** iDataCur, then its position should be preserved following the delete
  99548. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  99549. ** position of iDataCur should be preserved instead.
  99550. **
  99551. ** iIdxNoSeek:
  99552. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  99553. ** then it identifies an index cursor (from within array of cursors
  99554. ** starting at iIdxCur) that already points to the index entry to be deleted.
  99555. ** Except, this optimization is disabled if there are BEFORE triggers since
  99556. ** the trigger body might have moved the cursor.
  99557. */
  99558. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  99559. Parse *pParse, /* Parsing context */
  99560. Table *pTab, /* Table containing the row to be deleted */
  99561. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  99562. int iDataCur, /* Cursor from which column data is extracted */
  99563. int iIdxCur, /* First index cursor */
  99564. int iPk, /* First memory cell containing the PRIMARY KEY */
  99565. i16 nPk, /* Number of PRIMARY KEY memory cells */
  99566. u8 count, /* If non-zero, increment the row change counter */
  99567. u8 onconf, /* Default ON CONFLICT policy for triggers */
  99568. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  99569. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  99570. ){
  99571. Vdbe *v = pParse->pVdbe; /* Vdbe */
  99572. int iOld = 0; /* First register in OLD.* array */
  99573. int iLabel; /* Label resolved to end of generated code */
  99574. u8 opSeek; /* Seek opcode */
  99575. /* Vdbe is guaranteed to have been allocated by this stage. */
  99576. assert( v );
  99577. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  99578. iDataCur, iIdxCur, iPk, (int)nPk));
  99579. /* Seek cursor iCur to the row to delete. If this row no longer exists
  99580. ** (this can happen if a trigger program has already deleted it), do
  99581. ** not attempt to delete it or fire any DELETE triggers. */
  99582. iLabel = sqlite3VdbeMakeLabel(v);
  99583. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  99584. if( eMode==ONEPASS_OFF ){
  99585. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  99586. VdbeCoverageIf(v, opSeek==OP_NotExists);
  99587. VdbeCoverageIf(v, opSeek==OP_NotFound);
  99588. }
  99589. /* If there are any triggers to fire, allocate a range of registers to
  99590. ** use for the old.* references in the triggers. */
  99591. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  99592. u32 mask; /* Mask of OLD.* columns in use */
  99593. int iCol; /* Iterator used while populating OLD.* */
  99594. int addrStart; /* Start of BEFORE trigger programs */
  99595. /* TODO: Could use temporary registers here. Also could attempt to
  99596. ** avoid copying the contents of the rowid register. */
  99597. mask = sqlite3TriggerColmask(
  99598. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  99599. );
  99600. mask |= sqlite3FkOldmask(pParse, pTab);
  99601. iOld = pParse->nMem+1;
  99602. pParse->nMem += (1 + pTab->nCol);
  99603. /* Populate the OLD.* pseudo-table register array. These values will be
  99604. ** used by any BEFORE and AFTER triggers that exist. */
  99605. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  99606. for(iCol=0; iCol<pTab->nCol; iCol++){
  99607. testcase( mask!=0xffffffff && iCol==31 );
  99608. testcase( mask!=0xffffffff && iCol==32 );
  99609. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  99610. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  99611. }
  99612. }
  99613. /* Invoke BEFORE DELETE trigger programs. */
  99614. addrStart = sqlite3VdbeCurrentAddr(v);
  99615. sqlite3CodeRowTrigger(pParse, pTrigger,
  99616. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  99617. );
  99618. /* If any BEFORE triggers were coded, then seek the cursor to the
  99619. ** row to be deleted again. It may be that the BEFORE triggers moved
  99620. ** the cursor or already deleted the row that the cursor was
  99621. ** pointing to.
  99622. **
  99623. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  99624. ** may have moved that cursor.
  99625. */
  99626. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  99627. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  99628. VdbeCoverageIf(v, opSeek==OP_NotExists);
  99629. VdbeCoverageIf(v, opSeek==OP_NotFound);
  99630. testcase( iIdxNoSeek>=0 );
  99631. iIdxNoSeek = -1;
  99632. }
  99633. /* Do FK processing. This call checks that any FK constraints that
  99634. ** refer to this table (i.e. constraints attached to other tables)
  99635. ** are not violated by deleting this row. */
  99636. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  99637. }
  99638. /* Delete the index and table entries. Skip this step if pTab is really
  99639. ** a view (in which case the only effect of the DELETE statement is to
  99640. ** fire the INSTEAD OF triggers).
  99641. **
  99642. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  99643. ** invoke the update-hook. The pre-update-hook, on the other hand should
  99644. ** be invoked unless table pTab is a system table. The difference is that
  99645. ** the update-hook is not invoked for rows removed by REPLACE, but the
  99646. ** pre-update-hook is.
  99647. */
  99648. if( pTab->pSelect==0 ){
  99649. u8 p5 = 0;
  99650. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  99651. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  99652. if( pParse->nested==0 ){
  99653. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  99654. }
  99655. if( eMode!=ONEPASS_OFF ){
  99656. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  99657. }
  99658. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  99659. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  99660. }
  99661. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  99662. sqlite3VdbeChangeP5(v, p5);
  99663. }
  99664. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  99665. ** handle rows (possibly in other tables) that refer via a foreign key
  99666. ** to the row just deleted. */
  99667. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  99668. /* Invoke AFTER DELETE trigger programs. */
  99669. sqlite3CodeRowTrigger(pParse, pTrigger,
  99670. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  99671. );
  99672. /* Jump here if the row had already been deleted before any BEFORE
  99673. ** trigger programs were invoked. Or if a trigger program throws a
  99674. ** RAISE(IGNORE) exception. */
  99675. sqlite3VdbeResolveLabel(v, iLabel);
  99676. VdbeModuleComment((v, "END: GenRowDel()"));
  99677. }
  99678. /*
  99679. ** This routine generates VDBE code that causes the deletion of all
  99680. ** index entries associated with a single row of a single table, pTab
  99681. **
  99682. ** Preconditions:
  99683. **
  99684. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  99685. ** btree for the table pTab. (This will be either the table itself
  99686. ** for rowid tables or to the primary key index for WITHOUT ROWID
  99687. ** tables.)
  99688. **
  99689. ** 2. Read/write cursors for all indices of pTab must be open as
  99690. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  99691. ** index is the 0-th index.)
  99692. **
  99693. ** 3. The "iDataCur" cursor must be already be positioned on the row
  99694. ** that is to be deleted.
  99695. */
  99696. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  99697. Parse *pParse, /* Parsing and code generating context */
  99698. Table *pTab, /* Table containing the row to be deleted */
  99699. int iDataCur, /* Cursor of table holding data. */
  99700. int iIdxCur, /* First index cursor */
  99701. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  99702. int iIdxNoSeek /* Do not delete from this cursor */
  99703. ){
  99704. int i; /* Index loop counter */
  99705. int r1 = -1; /* Register holding an index key */
  99706. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  99707. Index *pIdx; /* Current index */
  99708. Index *pPrior = 0; /* Prior index */
  99709. Vdbe *v; /* The prepared statement under construction */
  99710. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  99711. v = pParse->pVdbe;
  99712. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  99713. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  99714. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  99715. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  99716. if( pIdx==pPk ) continue;
  99717. if( iIdxCur+i==iIdxNoSeek ) continue;
  99718. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  99719. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  99720. &iPartIdxLabel, pPrior, r1);
  99721. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  99722. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  99723. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  99724. pPrior = pIdx;
  99725. }
  99726. }
  99727. /*
  99728. ** Generate code that will assemble an index key and stores it in register
  99729. ** regOut. The key with be for index pIdx which is an index on pTab.
  99730. ** iCur is the index of a cursor open on the pTab table and pointing to
  99731. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  99732. ** iCur must be the cursor of the PRIMARY KEY index.
  99733. **
  99734. ** Return a register number which is the first in a block of
  99735. ** registers that holds the elements of the index key. The
  99736. ** block of registers has already been deallocated by the time
  99737. ** this routine returns.
  99738. **
  99739. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  99740. ** to that label if pIdx is a partial index that should be skipped.
  99741. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  99742. ** A partial index should be skipped if its WHERE clause evaluates
  99743. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  99744. ** will be set to zero which is an empty label that is ignored by
  99745. ** sqlite3ResolvePartIdxLabel().
  99746. **
  99747. ** The pPrior and regPrior parameters are used to implement a cache to
  99748. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  99749. ** a pointer to a different index for which an index key has just been
  99750. ** computed into register regPrior. If the current pIdx index is generating
  99751. ** its key into the same sequence of registers and if pPrior and pIdx share
  99752. ** a column in common, then the register corresponding to that column already
  99753. ** holds the correct value and the loading of that register is skipped.
  99754. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  99755. ** on a table with multiple indices, and especially with the ROWID or
  99756. ** PRIMARY KEY columns of the index.
  99757. */
  99758. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  99759. Parse *pParse, /* Parsing context */
  99760. Index *pIdx, /* The index for which to generate a key */
  99761. int iDataCur, /* Cursor number from which to take column data */
  99762. int regOut, /* Put the new key into this register if not 0 */
  99763. int prefixOnly, /* Compute only a unique prefix of the key */
  99764. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  99765. Index *pPrior, /* Previously generated index key */
  99766. int regPrior /* Register holding previous generated key */
  99767. ){
  99768. Vdbe *v = pParse->pVdbe;
  99769. int j;
  99770. int regBase;
  99771. int nCol;
  99772. if( piPartIdxLabel ){
  99773. if( pIdx->pPartIdxWhere ){
  99774. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  99775. pParse->iSelfTab = iDataCur + 1;
  99776. sqlite3ExprCachePush(pParse);
  99777. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  99778. SQLITE_JUMPIFNULL);
  99779. pParse->iSelfTab = 0;
  99780. }else{
  99781. *piPartIdxLabel = 0;
  99782. }
  99783. }
  99784. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  99785. regBase = sqlite3GetTempRange(pParse, nCol);
  99786. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  99787. for(j=0; j<nCol; j++){
  99788. if( pPrior
  99789. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  99790. && pPrior->aiColumn[j]!=XN_EXPR
  99791. ){
  99792. /* This column was already computed by the previous index */
  99793. continue;
  99794. }
  99795. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  99796. /* If the column affinity is REAL but the number is an integer, then it
  99797. ** might be stored in the table as an integer (using a compact
  99798. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  99799. ** But we are getting ready to store this value back into an index, where
  99800. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  99801. ** opcode if it is present */
  99802. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  99803. }
  99804. if( regOut ){
  99805. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  99806. if( pIdx->pTable->pSelect ){
  99807. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  99808. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  99809. }
  99810. }
  99811. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  99812. return regBase;
  99813. }
  99814. /*
  99815. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  99816. ** because it was a partial index, then this routine should be called to
  99817. ** resolve that label.
  99818. */
  99819. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  99820. if( iLabel ){
  99821. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  99822. sqlite3ExprCachePop(pParse);
  99823. }
  99824. }
  99825. /************** End of delete.c **********************************************/
  99826. /************** Begin file func.c ********************************************/
  99827. /*
  99828. ** 2002 February 23
  99829. **
  99830. ** The author disclaims copyright to this source code. In place of
  99831. ** a legal notice, here is a blessing:
  99832. **
  99833. ** May you do good and not evil.
  99834. ** May you find forgiveness for yourself and forgive others.
  99835. ** May you share freely, never taking more than you give.
  99836. **
  99837. *************************************************************************
  99838. ** This file contains the C-language implementations for many of the SQL
  99839. ** functions of SQLite. (Some function, and in particular the date and
  99840. ** time functions, are implemented separately.)
  99841. */
  99842. /* #include "sqliteInt.h" */
  99843. /* #include <stdlib.h> */
  99844. /* #include <assert.h> */
  99845. /* #include "vdbeInt.h" */
  99846. /*
  99847. ** Return the collating function associated with a function.
  99848. */
  99849. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  99850. VdbeOp *pOp;
  99851. assert( context->pVdbe!=0 );
  99852. pOp = &context->pVdbe->aOp[context->iOp-1];
  99853. assert( pOp->opcode==OP_CollSeq );
  99854. assert( pOp->p4type==P4_COLLSEQ );
  99855. return pOp->p4.pColl;
  99856. }
  99857. /*
  99858. ** Indicate that the accumulator load should be skipped on this
  99859. ** iteration of the aggregate loop.
  99860. */
  99861. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  99862. context->skipFlag = 1;
  99863. }
  99864. /*
  99865. ** Implementation of the non-aggregate min() and max() functions
  99866. */
  99867. static void minmaxFunc(
  99868. sqlite3_context *context,
  99869. int argc,
  99870. sqlite3_value **argv
  99871. ){
  99872. int i;
  99873. int mask; /* 0 for min() or 0xffffffff for max() */
  99874. int iBest;
  99875. CollSeq *pColl;
  99876. assert( argc>1 );
  99877. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  99878. pColl = sqlite3GetFuncCollSeq(context);
  99879. assert( pColl );
  99880. assert( mask==-1 || mask==0 );
  99881. iBest = 0;
  99882. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  99883. for(i=1; i<argc; i++){
  99884. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  99885. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  99886. testcase( mask==0 );
  99887. iBest = i;
  99888. }
  99889. }
  99890. sqlite3_result_value(context, argv[iBest]);
  99891. }
  99892. /*
  99893. ** Return the type of the argument.
  99894. */
  99895. static void typeofFunc(
  99896. sqlite3_context *context,
  99897. int NotUsed,
  99898. sqlite3_value **argv
  99899. ){
  99900. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  99901. int i = sqlite3_value_type(argv[0]) - 1;
  99902. UNUSED_PARAMETER(NotUsed);
  99903. assert( i>=0 && i<ArraySize(azType) );
  99904. assert( SQLITE_INTEGER==1 );
  99905. assert( SQLITE_FLOAT==2 );
  99906. assert( SQLITE_TEXT==3 );
  99907. assert( SQLITE_BLOB==4 );
  99908. assert( SQLITE_NULL==5 );
  99909. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  99910. ** the datatype code for the initial datatype of the sqlite3_value object
  99911. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  99912. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  99913. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  99914. }
  99915. /*
  99916. ** Implementation of the length() function
  99917. */
  99918. static void lengthFunc(
  99919. sqlite3_context *context,
  99920. int argc,
  99921. sqlite3_value **argv
  99922. ){
  99923. int len;
  99924. assert( argc==1 );
  99925. UNUSED_PARAMETER(argc);
  99926. switch( sqlite3_value_type(argv[0]) ){
  99927. case SQLITE_BLOB:
  99928. case SQLITE_INTEGER:
  99929. case SQLITE_FLOAT: {
  99930. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  99931. break;
  99932. }
  99933. case SQLITE_TEXT: {
  99934. const unsigned char *z = sqlite3_value_text(argv[0]);
  99935. if( z==0 ) return;
  99936. len = 0;
  99937. while( *z ){
  99938. len++;
  99939. SQLITE_SKIP_UTF8(z);
  99940. }
  99941. sqlite3_result_int(context, len);
  99942. break;
  99943. }
  99944. default: {
  99945. sqlite3_result_null(context);
  99946. break;
  99947. }
  99948. }
  99949. }
  99950. /*
  99951. ** Implementation of the abs() function.
  99952. **
  99953. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  99954. ** the numeric argument X.
  99955. */
  99956. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99957. assert( argc==1 );
  99958. UNUSED_PARAMETER(argc);
  99959. switch( sqlite3_value_type(argv[0]) ){
  99960. case SQLITE_INTEGER: {
  99961. i64 iVal = sqlite3_value_int64(argv[0]);
  99962. if( iVal<0 ){
  99963. if( iVal==SMALLEST_INT64 ){
  99964. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  99965. ** then abs(X) throws an integer overflow error since there is no
  99966. ** equivalent positive 64-bit two complement value. */
  99967. sqlite3_result_error(context, "integer overflow", -1);
  99968. return;
  99969. }
  99970. iVal = -iVal;
  99971. }
  99972. sqlite3_result_int64(context, iVal);
  99973. break;
  99974. }
  99975. case SQLITE_NULL: {
  99976. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  99977. sqlite3_result_null(context);
  99978. break;
  99979. }
  99980. default: {
  99981. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  99982. ** something that can be converted into a number, we have:
  99983. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  99984. ** that cannot be converted to a numeric value.
  99985. */
  99986. double rVal = sqlite3_value_double(argv[0]);
  99987. if( rVal<0 ) rVal = -rVal;
  99988. sqlite3_result_double(context, rVal);
  99989. break;
  99990. }
  99991. }
  99992. }
  99993. /*
  99994. ** Implementation of the instr() function.
  99995. **
  99996. ** instr(haystack,needle) finds the first occurrence of needle
  99997. ** in haystack and returns the number of previous characters plus 1,
  99998. ** or 0 if needle does not occur within haystack.
  99999. **
  100000. ** If both haystack and needle are BLOBs, then the result is one more than
  100001. ** the number of bytes in haystack prior to the first occurrence of needle,
  100002. ** or 0 if needle never occurs in haystack.
  100003. */
  100004. static void instrFunc(
  100005. sqlite3_context *context,
  100006. int argc,
  100007. sqlite3_value **argv
  100008. ){
  100009. const unsigned char *zHaystack;
  100010. const unsigned char *zNeedle;
  100011. int nHaystack;
  100012. int nNeedle;
  100013. int typeHaystack, typeNeedle;
  100014. int N = 1;
  100015. int isText;
  100016. UNUSED_PARAMETER(argc);
  100017. typeHaystack = sqlite3_value_type(argv[0]);
  100018. typeNeedle = sqlite3_value_type(argv[1]);
  100019. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  100020. nHaystack = sqlite3_value_bytes(argv[0]);
  100021. nNeedle = sqlite3_value_bytes(argv[1]);
  100022. if( nNeedle>0 ){
  100023. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  100024. zHaystack = sqlite3_value_blob(argv[0]);
  100025. zNeedle = sqlite3_value_blob(argv[1]);
  100026. isText = 0;
  100027. }else{
  100028. zHaystack = sqlite3_value_text(argv[0]);
  100029. zNeedle = sqlite3_value_text(argv[1]);
  100030. isText = 1;
  100031. }
  100032. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  100033. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  100034. N++;
  100035. do{
  100036. nHaystack--;
  100037. zHaystack++;
  100038. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  100039. }
  100040. if( nNeedle>nHaystack ) N = 0;
  100041. }
  100042. sqlite3_result_int(context, N);
  100043. }
  100044. /*
  100045. ** Implementation of the printf() function.
  100046. */
  100047. static void printfFunc(
  100048. sqlite3_context *context,
  100049. int argc,
  100050. sqlite3_value **argv
  100051. ){
  100052. PrintfArguments x;
  100053. StrAccum str;
  100054. const char *zFormat;
  100055. int n;
  100056. sqlite3 *db = sqlite3_context_db_handle(context);
  100057. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  100058. x.nArg = argc-1;
  100059. x.nUsed = 0;
  100060. x.apArg = argv+1;
  100061. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  100062. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  100063. sqlite3XPrintf(&str, zFormat, &x);
  100064. n = str.nChar;
  100065. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  100066. SQLITE_DYNAMIC);
  100067. }
  100068. }
  100069. /*
  100070. ** Implementation of the substr() function.
  100071. **
  100072. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  100073. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  100074. ** of x. If x is text, then we actually count UTF-8 characters.
  100075. ** If x is a blob, then we count bytes.
  100076. **
  100077. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  100078. **
  100079. ** If p2 is negative, return the p2 characters preceding p1.
  100080. */
  100081. static void substrFunc(
  100082. sqlite3_context *context,
  100083. int argc,
  100084. sqlite3_value **argv
  100085. ){
  100086. const unsigned char *z;
  100087. const unsigned char *z2;
  100088. int len;
  100089. int p0type;
  100090. i64 p1, p2;
  100091. int negP2 = 0;
  100092. assert( argc==3 || argc==2 );
  100093. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  100094. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  100095. ){
  100096. return;
  100097. }
  100098. p0type = sqlite3_value_type(argv[0]);
  100099. p1 = sqlite3_value_int(argv[1]);
  100100. if( p0type==SQLITE_BLOB ){
  100101. len = sqlite3_value_bytes(argv[0]);
  100102. z = sqlite3_value_blob(argv[0]);
  100103. if( z==0 ) return;
  100104. assert( len==sqlite3_value_bytes(argv[0]) );
  100105. }else{
  100106. z = sqlite3_value_text(argv[0]);
  100107. if( z==0 ) return;
  100108. len = 0;
  100109. if( p1<0 ){
  100110. for(z2=z; *z2; len++){
  100111. SQLITE_SKIP_UTF8(z2);
  100112. }
  100113. }
  100114. }
  100115. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  100116. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  100117. ** as substr(X,1,N) - it returns the first N characters of X. This
  100118. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  100119. ** from 2009-02-02 for compatibility of applications that exploited the
  100120. ** old buggy behavior. */
  100121. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  100122. #endif
  100123. if( argc==3 ){
  100124. p2 = sqlite3_value_int(argv[2]);
  100125. if( p2<0 ){
  100126. p2 = -p2;
  100127. negP2 = 1;
  100128. }
  100129. }else{
  100130. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  100131. }
  100132. if( p1<0 ){
  100133. p1 += len;
  100134. if( p1<0 ){
  100135. p2 += p1;
  100136. if( p2<0 ) p2 = 0;
  100137. p1 = 0;
  100138. }
  100139. }else if( p1>0 ){
  100140. p1--;
  100141. }else if( p2>0 ){
  100142. p2--;
  100143. }
  100144. if( negP2 ){
  100145. p1 -= p2;
  100146. if( p1<0 ){
  100147. p2 += p1;
  100148. p1 = 0;
  100149. }
  100150. }
  100151. assert( p1>=0 && p2>=0 );
  100152. if( p0type!=SQLITE_BLOB ){
  100153. while( *z && p1 ){
  100154. SQLITE_SKIP_UTF8(z);
  100155. p1--;
  100156. }
  100157. for(z2=z; *z2 && p2; p2--){
  100158. SQLITE_SKIP_UTF8(z2);
  100159. }
  100160. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  100161. SQLITE_UTF8);
  100162. }else{
  100163. if( p1+p2>len ){
  100164. p2 = len-p1;
  100165. if( p2<0 ) p2 = 0;
  100166. }
  100167. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  100168. }
  100169. }
  100170. /*
  100171. ** Implementation of the round() function
  100172. */
  100173. #ifndef SQLITE_OMIT_FLOATING_POINT
  100174. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  100175. int n = 0;
  100176. double r;
  100177. char *zBuf;
  100178. assert( argc==1 || argc==2 );
  100179. if( argc==2 ){
  100180. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  100181. n = sqlite3_value_int(argv[1]);
  100182. if( n>30 ) n = 30;
  100183. if( n<0 ) n = 0;
  100184. }
  100185. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  100186. r = sqlite3_value_double(argv[0]);
  100187. /* If Y==0 and X will fit in a 64-bit int,
  100188. ** handle the rounding directly,
  100189. ** otherwise use printf.
  100190. */
  100191. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  100192. r = (double)((sqlite_int64)(r+0.5));
  100193. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  100194. r = -(double)((sqlite_int64)((-r)+0.5));
  100195. }else{
  100196. zBuf = sqlite3_mprintf("%.*f",n,r);
  100197. if( zBuf==0 ){
  100198. sqlite3_result_error_nomem(context);
  100199. return;
  100200. }
  100201. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  100202. sqlite3_free(zBuf);
  100203. }
  100204. sqlite3_result_double(context, r);
  100205. }
  100206. #endif
  100207. /*
  100208. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  100209. ** allocation fails, call sqlite3_result_error_nomem() to notify
  100210. ** the database handle that malloc() has failed and return NULL.
  100211. ** If nByte is larger than the maximum string or blob length, then
  100212. ** raise an SQLITE_TOOBIG exception and return NULL.
  100213. */
  100214. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  100215. char *z;
  100216. sqlite3 *db = sqlite3_context_db_handle(context);
  100217. assert( nByte>0 );
  100218. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  100219. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  100220. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  100221. sqlite3_result_error_toobig(context);
  100222. z = 0;
  100223. }else{
  100224. z = sqlite3Malloc(nByte);
  100225. if( !z ){
  100226. sqlite3_result_error_nomem(context);
  100227. }
  100228. }
  100229. return z;
  100230. }
  100231. /*
  100232. ** Implementation of the upper() and lower() SQL functions.
  100233. */
  100234. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  100235. char *z1;
  100236. const char *z2;
  100237. int i, n;
  100238. UNUSED_PARAMETER(argc);
  100239. z2 = (char*)sqlite3_value_text(argv[0]);
  100240. n = sqlite3_value_bytes(argv[0]);
  100241. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  100242. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  100243. if( z2 ){
  100244. z1 = contextMalloc(context, ((i64)n)+1);
  100245. if( z1 ){
  100246. for(i=0; i<n; i++){
  100247. z1[i] = (char)sqlite3Toupper(z2[i]);
  100248. }
  100249. sqlite3_result_text(context, z1, n, sqlite3_free);
  100250. }
  100251. }
  100252. }
  100253. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  100254. char *z1;
  100255. const char *z2;
  100256. int i, n;
  100257. UNUSED_PARAMETER(argc);
  100258. z2 = (char*)sqlite3_value_text(argv[0]);
  100259. n = sqlite3_value_bytes(argv[0]);
  100260. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  100261. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  100262. if( z2 ){
  100263. z1 = contextMalloc(context, ((i64)n)+1);
  100264. if( z1 ){
  100265. for(i=0; i<n; i++){
  100266. z1[i] = sqlite3Tolower(z2[i]);
  100267. }
  100268. sqlite3_result_text(context, z1, n, sqlite3_free);
  100269. }
  100270. }
  100271. }
  100272. /*
  100273. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  100274. ** as VDBE code so that unused argument values do not have to be computed.
  100275. ** However, we still need some kind of function implementation for this
  100276. ** routines in the function table. The noopFunc macro provides this.
  100277. ** noopFunc will never be called so it doesn't matter what the implementation
  100278. ** is. We might as well use the "version()" function as a substitute.
  100279. */
  100280. #define noopFunc versionFunc /* Substitute function - never called */
  100281. /*
  100282. ** Implementation of random(). Return a random integer.
  100283. */
  100284. static void randomFunc(
  100285. sqlite3_context *context,
  100286. int NotUsed,
  100287. sqlite3_value **NotUsed2
  100288. ){
  100289. sqlite_int64 r;
  100290. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100291. sqlite3_randomness(sizeof(r), &r);
  100292. if( r<0 ){
  100293. /* We need to prevent a random number of 0x8000000000000000
  100294. ** (or -9223372036854775808) since when you do abs() of that
  100295. ** number of you get the same value back again. To do this
  100296. ** in a way that is testable, mask the sign bit off of negative
  100297. ** values, resulting in a positive value. Then take the
  100298. ** 2s complement of that positive value. The end result can
  100299. ** therefore be no less than -9223372036854775807.
  100300. */
  100301. r = -(r & LARGEST_INT64);
  100302. }
  100303. sqlite3_result_int64(context, r);
  100304. }
  100305. /*
  100306. ** Implementation of randomblob(N). Return a random blob
  100307. ** that is N bytes long.
  100308. */
  100309. static void randomBlob(
  100310. sqlite3_context *context,
  100311. int argc,
  100312. sqlite3_value **argv
  100313. ){
  100314. int n;
  100315. unsigned char *p;
  100316. assert( argc==1 );
  100317. UNUSED_PARAMETER(argc);
  100318. n = sqlite3_value_int(argv[0]);
  100319. if( n<1 ){
  100320. n = 1;
  100321. }
  100322. p = contextMalloc(context, n);
  100323. if( p ){
  100324. sqlite3_randomness(n, p);
  100325. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  100326. }
  100327. }
  100328. /*
  100329. ** Implementation of the last_insert_rowid() SQL function. The return
  100330. ** value is the same as the sqlite3_last_insert_rowid() API function.
  100331. */
  100332. static void last_insert_rowid(
  100333. sqlite3_context *context,
  100334. int NotUsed,
  100335. sqlite3_value **NotUsed2
  100336. ){
  100337. sqlite3 *db = sqlite3_context_db_handle(context);
  100338. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100339. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  100340. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  100341. ** function. */
  100342. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  100343. }
  100344. /*
  100345. ** Implementation of the changes() SQL function.
  100346. **
  100347. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  100348. ** around the sqlite3_changes() C/C++ function and hence follows the same
  100349. ** rules for counting changes.
  100350. */
  100351. static void changes(
  100352. sqlite3_context *context,
  100353. int NotUsed,
  100354. sqlite3_value **NotUsed2
  100355. ){
  100356. sqlite3 *db = sqlite3_context_db_handle(context);
  100357. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100358. sqlite3_result_int(context, sqlite3_changes(db));
  100359. }
  100360. /*
  100361. ** Implementation of the total_changes() SQL function. The return value is
  100362. ** the same as the sqlite3_total_changes() API function.
  100363. */
  100364. static void total_changes(
  100365. sqlite3_context *context,
  100366. int NotUsed,
  100367. sqlite3_value **NotUsed2
  100368. ){
  100369. sqlite3 *db = sqlite3_context_db_handle(context);
  100370. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100371. /* IMP: R-52756-41993 This function is a wrapper around the
  100372. ** sqlite3_total_changes() C/C++ interface. */
  100373. sqlite3_result_int(context, sqlite3_total_changes(db));
  100374. }
  100375. /*
  100376. ** A structure defining how to do GLOB-style comparisons.
  100377. */
  100378. struct compareInfo {
  100379. u8 matchAll; /* "*" or "%" */
  100380. u8 matchOne; /* "?" or "_" */
  100381. u8 matchSet; /* "[" or 0 */
  100382. u8 noCase; /* true to ignore case differences */
  100383. };
  100384. /*
  100385. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  100386. ** character is exactly one byte in size. Also, provde the Utf8Read()
  100387. ** macro for fast reading of the next character in the common case where
  100388. ** the next character is ASCII.
  100389. */
  100390. #if defined(SQLITE_EBCDIC)
  100391. # define sqlite3Utf8Read(A) (*((*A)++))
  100392. # define Utf8Read(A) (*(A++))
  100393. #else
  100394. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  100395. #endif
  100396. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  100397. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  100398. ** case. Thus 'a' LIKE 'A' would be true. */
  100399. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  100400. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  100401. ** is case sensitive causing 'a' LIKE 'A' to be false */
  100402. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  100403. /*
  100404. ** Possible error returns from patternMatch()
  100405. */
  100406. #define SQLITE_MATCH 0
  100407. #define SQLITE_NOMATCH 1
  100408. #define SQLITE_NOWILDCARDMATCH 2
  100409. /*
  100410. ** Compare two UTF-8 strings for equality where the first string is
  100411. ** a GLOB or LIKE expression. Return values:
  100412. **
  100413. ** SQLITE_MATCH: Match
  100414. ** SQLITE_NOMATCH: No match
  100415. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  100416. **
  100417. ** Globbing rules:
  100418. **
  100419. ** '*' Matches any sequence of zero or more characters.
  100420. **
  100421. ** '?' Matches exactly one character.
  100422. **
  100423. ** [...] Matches one character from the enclosed list of
  100424. ** characters.
  100425. **
  100426. ** [^...] Matches one character not in the enclosed list.
  100427. **
  100428. ** With the [...] and [^...] matching, a ']' character can be included
  100429. ** in the list by making it the first character after '[' or '^'. A
  100430. ** range of characters can be specified using '-'. Example:
  100431. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  100432. ** it the last character in the list.
  100433. **
  100434. ** Like matching rules:
  100435. **
  100436. ** '%' Matches any sequence of zero or more characters
  100437. **
  100438. *** '_' Matches any one character
  100439. **
  100440. ** Ec Where E is the "esc" character and c is any other
  100441. ** character, including '%', '_', and esc, match exactly c.
  100442. **
  100443. ** The comments within this routine usually assume glob matching.
  100444. **
  100445. ** This routine is usually quick, but can be N**2 in the worst case.
  100446. */
  100447. static int patternCompare(
  100448. const u8 *zPattern, /* The glob pattern */
  100449. const u8 *zString, /* The string to compare against the glob */
  100450. const struct compareInfo *pInfo, /* Information about how to do the compare */
  100451. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  100452. ){
  100453. u32 c, c2; /* Next pattern and input string chars */
  100454. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  100455. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  100456. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  100457. const u8 *zEscaped = 0; /* One past the last escaped input char */
  100458. while( (c = Utf8Read(zPattern))!=0 ){
  100459. if( c==matchAll ){ /* Match "*" */
  100460. /* Skip over multiple "*" characters in the pattern. If there
  100461. ** are also "?" characters, skip those as well, but consume a
  100462. ** single character of the input string for each "?" skipped */
  100463. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  100464. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  100465. return SQLITE_NOWILDCARDMATCH;
  100466. }
  100467. }
  100468. if( c==0 ){
  100469. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  100470. }else if( c==matchOther ){
  100471. if( pInfo->matchSet==0 ){
  100472. c = sqlite3Utf8Read(&zPattern);
  100473. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  100474. }else{
  100475. /* "[...]" immediately follows the "*". We have to do a slow
  100476. ** recursive search in this case, but it is an unusual case. */
  100477. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  100478. while( *zString ){
  100479. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  100480. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  100481. SQLITE_SKIP_UTF8(zString);
  100482. }
  100483. return SQLITE_NOWILDCARDMATCH;
  100484. }
  100485. }
  100486. /* At this point variable c contains the first character of the
  100487. ** pattern string past the "*". Search in the input string for the
  100488. ** first matching character and recursively continue the match from
  100489. ** that point.
  100490. **
  100491. ** For a case-insensitive search, set variable cx to be the same as
  100492. ** c but in the other case and search the input string for either
  100493. ** c or cx.
  100494. */
  100495. if( c<=0x80 ){
  100496. u32 cx;
  100497. int bMatch;
  100498. if( noCase ){
  100499. cx = sqlite3Toupper(c);
  100500. c = sqlite3Tolower(c);
  100501. }else{
  100502. cx = c;
  100503. }
  100504. while( (c2 = *(zString++))!=0 ){
  100505. if( c2!=c && c2!=cx ) continue;
  100506. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  100507. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  100508. }
  100509. }else{
  100510. int bMatch;
  100511. while( (c2 = Utf8Read(zString))!=0 ){
  100512. if( c2!=c ) continue;
  100513. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  100514. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  100515. }
  100516. }
  100517. return SQLITE_NOWILDCARDMATCH;
  100518. }
  100519. if( c==matchOther ){
  100520. if( pInfo->matchSet==0 ){
  100521. c = sqlite3Utf8Read(&zPattern);
  100522. if( c==0 ) return SQLITE_NOMATCH;
  100523. zEscaped = zPattern;
  100524. }else{
  100525. u32 prior_c = 0;
  100526. int seen = 0;
  100527. int invert = 0;
  100528. c = sqlite3Utf8Read(&zString);
  100529. if( c==0 ) return SQLITE_NOMATCH;
  100530. c2 = sqlite3Utf8Read(&zPattern);
  100531. if( c2=='^' ){
  100532. invert = 1;
  100533. c2 = sqlite3Utf8Read(&zPattern);
  100534. }
  100535. if( c2==']' ){
  100536. if( c==']' ) seen = 1;
  100537. c2 = sqlite3Utf8Read(&zPattern);
  100538. }
  100539. while( c2 && c2!=']' ){
  100540. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  100541. c2 = sqlite3Utf8Read(&zPattern);
  100542. if( c>=prior_c && c<=c2 ) seen = 1;
  100543. prior_c = 0;
  100544. }else{
  100545. if( c==c2 ){
  100546. seen = 1;
  100547. }
  100548. prior_c = c2;
  100549. }
  100550. c2 = sqlite3Utf8Read(&zPattern);
  100551. }
  100552. if( c2==0 || (seen ^ invert)==0 ){
  100553. return SQLITE_NOMATCH;
  100554. }
  100555. continue;
  100556. }
  100557. }
  100558. c2 = Utf8Read(zString);
  100559. if( c==c2 ) continue;
  100560. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  100561. continue;
  100562. }
  100563. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  100564. return SQLITE_NOMATCH;
  100565. }
  100566. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  100567. }
  100568. /*
  100569. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  100570. ** non-zero if there is no match.
  100571. */
  100572. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  100573. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  100574. }
  100575. /*
  100576. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  100577. ** a miss - like strcmp().
  100578. */
  100579. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  100580. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  100581. }
  100582. /*
  100583. ** Count the number of times that the LIKE operator (or GLOB which is
  100584. ** just a variation of LIKE) gets called. This is used for testing
  100585. ** only.
  100586. */
  100587. #ifdef SQLITE_TEST
  100588. SQLITE_API int sqlite3_like_count = 0;
  100589. #endif
  100590. /*
  100591. ** Implementation of the like() SQL function. This function implements
  100592. ** the build-in LIKE operator. The first argument to the function is the
  100593. ** pattern and the second argument is the string. So, the SQL statements:
  100594. **
  100595. ** A LIKE B
  100596. **
  100597. ** is implemented as like(B,A).
  100598. **
  100599. ** This same function (with a different compareInfo structure) computes
  100600. ** the GLOB operator.
  100601. */
  100602. static void likeFunc(
  100603. sqlite3_context *context,
  100604. int argc,
  100605. sqlite3_value **argv
  100606. ){
  100607. const unsigned char *zA, *zB;
  100608. u32 escape;
  100609. int nPat;
  100610. sqlite3 *db = sqlite3_context_db_handle(context);
  100611. struct compareInfo *pInfo = sqlite3_user_data(context);
  100612. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  100613. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  100614. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  100615. ){
  100616. #ifdef SQLITE_TEST
  100617. sqlite3_like_count++;
  100618. #endif
  100619. sqlite3_result_int(context, 0);
  100620. return;
  100621. }
  100622. #endif
  100623. zB = sqlite3_value_text(argv[0]);
  100624. zA = sqlite3_value_text(argv[1]);
  100625. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  100626. ** of deep recursion and N*N behavior in patternCompare().
  100627. */
  100628. nPat = sqlite3_value_bytes(argv[0]);
  100629. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  100630. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  100631. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  100632. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  100633. return;
  100634. }
  100635. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  100636. if( argc==3 ){
  100637. /* The escape character string must consist of a single UTF-8 character.
  100638. ** Otherwise, return an error.
  100639. */
  100640. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  100641. if( zEsc==0 ) return;
  100642. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  100643. sqlite3_result_error(context,
  100644. "ESCAPE expression must be a single character", -1);
  100645. return;
  100646. }
  100647. escape = sqlite3Utf8Read(&zEsc);
  100648. }else{
  100649. escape = pInfo->matchSet;
  100650. }
  100651. if( zA && zB ){
  100652. #ifdef SQLITE_TEST
  100653. sqlite3_like_count++;
  100654. #endif
  100655. sqlite3_result_int(context,
  100656. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  100657. }
  100658. }
  100659. /*
  100660. ** Implementation of the NULLIF(x,y) function. The result is the first
  100661. ** argument if the arguments are different. The result is NULL if the
  100662. ** arguments are equal to each other.
  100663. */
  100664. static void nullifFunc(
  100665. sqlite3_context *context,
  100666. int NotUsed,
  100667. sqlite3_value **argv
  100668. ){
  100669. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  100670. UNUSED_PARAMETER(NotUsed);
  100671. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  100672. sqlite3_result_value(context, argv[0]);
  100673. }
  100674. }
  100675. /*
  100676. ** Implementation of the sqlite_version() function. The result is the version
  100677. ** of the SQLite library that is running.
  100678. */
  100679. static void versionFunc(
  100680. sqlite3_context *context,
  100681. int NotUsed,
  100682. sqlite3_value **NotUsed2
  100683. ){
  100684. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100685. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  100686. ** sqlite3_libversion() C-interface. */
  100687. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  100688. }
  100689. /*
  100690. ** Implementation of the sqlite_source_id() function. The result is a string
  100691. ** that identifies the particular version of the source code used to build
  100692. ** SQLite.
  100693. */
  100694. static void sourceidFunc(
  100695. sqlite3_context *context,
  100696. int NotUsed,
  100697. sqlite3_value **NotUsed2
  100698. ){
  100699. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  100700. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  100701. ** sqlite3_sourceid() C interface. */
  100702. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  100703. }
  100704. /*
  100705. ** Implementation of the sqlite_log() function. This is a wrapper around
  100706. ** sqlite3_log(). The return value is NULL. The function exists purely for
  100707. ** its side-effects.
  100708. */
  100709. static void errlogFunc(
  100710. sqlite3_context *context,
  100711. int argc,
  100712. sqlite3_value **argv
  100713. ){
  100714. UNUSED_PARAMETER(argc);
  100715. UNUSED_PARAMETER(context);
  100716. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  100717. }
  100718. /*
  100719. ** Implementation of the sqlite_compileoption_used() function.
  100720. ** The result is an integer that identifies if the compiler option
  100721. ** was used to build SQLite.
  100722. */
  100723. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  100724. static void compileoptionusedFunc(
  100725. sqlite3_context *context,
  100726. int argc,
  100727. sqlite3_value **argv
  100728. ){
  100729. const char *zOptName;
  100730. assert( argc==1 );
  100731. UNUSED_PARAMETER(argc);
  100732. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  100733. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  100734. ** function.
  100735. */
  100736. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  100737. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  100738. }
  100739. }
  100740. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  100741. /*
  100742. ** Implementation of the sqlite_compileoption_get() function.
  100743. ** The result is a string that identifies the compiler options
  100744. ** used to build SQLite.
  100745. */
  100746. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  100747. static void compileoptiongetFunc(
  100748. sqlite3_context *context,
  100749. int argc,
  100750. sqlite3_value **argv
  100751. ){
  100752. int n;
  100753. assert( argc==1 );
  100754. UNUSED_PARAMETER(argc);
  100755. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  100756. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  100757. */
  100758. n = sqlite3_value_int(argv[0]);
  100759. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  100760. }
  100761. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  100762. /* Array for converting from half-bytes (nybbles) into ASCII hex
  100763. ** digits. */
  100764. static const char hexdigits[] = {
  100765. '0', '1', '2', '3', '4', '5', '6', '7',
  100766. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  100767. };
  100768. /*
  100769. ** Implementation of the QUOTE() function. This function takes a single
  100770. ** argument. If the argument is numeric, the return value is the same as
  100771. ** the argument. If the argument is NULL, the return value is the string
  100772. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  100773. ** single-quote escapes.
  100774. */
  100775. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  100776. assert( argc==1 );
  100777. UNUSED_PARAMETER(argc);
  100778. switch( sqlite3_value_type(argv[0]) ){
  100779. case SQLITE_FLOAT: {
  100780. double r1, r2;
  100781. char zBuf[50];
  100782. r1 = sqlite3_value_double(argv[0]);
  100783. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  100784. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  100785. if( r1!=r2 ){
  100786. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  100787. }
  100788. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  100789. break;
  100790. }
  100791. case SQLITE_INTEGER: {
  100792. sqlite3_result_value(context, argv[0]);
  100793. break;
  100794. }
  100795. case SQLITE_BLOB: {
  100796. char *zText = 0;
  100797. char const *zBlob = sqlite3_value_blob(argv[0]);
  100798. int nBlob = sqlite3_value_bytes(argv[0]);
  100799. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  100800. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  100801. if( zText ){
  100802. int i;
  100803. for(i=0; i<nBlob; i++){
  100804. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  100805. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  100806. }
  100807. zText[(nBlob*2)+2] = '\'';
  100808. zText[(nBlob*2)+3] = '\0';
  100809. zText[0] = 'X';
  100810. zText[1] = '\'';
  100811. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  100812. sqlite3_free(zText);
  100813. }
  100814. break;
  100815. }
  100816. case SQLITE_TEXT: {
  100817. int i,j;
  100818. u64 n;
  100819. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  100820. char *z;
  100821. if( zArg==0 ) return;
  100822. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  100823. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  100824. if( z ){
  100825. z[0] = '\'';
  100826. for(i=0, j=1; zArg[i]; i++){
  100827. z[j++] = zArg[i];
  100828. if( zArg[i]=='\'' ){
  100829. z[j++] = '\'';
  100830. }
  100831. }
  100832. z[j++] = '\'';
  100833. z[j] = 0;
  100834. sqlite3_result_text(context, z, j, sqlite3_free);
  100835. }
  100836. break;
  100837. }
  100838. default: {
  100839. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  100840. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  100841. break;
  100842. }
  100843. }
  100844. }
  100845. /*
  100846. ** The unicode() function. Return the integer unicode code-point value
  100847. ** for the first character of the input string.
  100848. */
  100849. static void unicodeFunc(
  100850. sqlite3_context *context,
  100851. int argc,
  100852. sqlite3_value **argv
  100853. ){
  100854. const unsigned char *z = sqlite3_value_text(argv[0]);
  100855. (void)argc;
  100856. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  100857. }
  100858. /*
  100859. ** The char() function takes zero or more arguments, each of which is
  100860. ** an integer. It constructs a string where each character of the string
  100861. ** is the unicode character for the corresponding integer argument.
  100862. */
  100863. static void charFunc(
  100864. sqlite3_context *context,
  100865. int argc,
  100866. sqlite3_value **argv
  100867. ){
  100868. unsigned char *z, *zOut;
  100869. int i;
  100870. zOut = z = sqlite3_malloc64( argc*4+1 );
  100871. if( z==0 ){
  100872. sqlite3_result_error_nomem(context);
  100873. return;
  100874. }
  100875. for(i=0; i<argc; i++){
  100876. sqlite3_int64 x;
  100877. unsigned c;
  100878. x = sqlite3_value_int64(argv[i]);
  100879. if( x<0 || x>0x10ffff ) x = 0xfffd;
  100880. c = (unsigned)(x & 0x1fffff);
  100881. if( c<0x00080 ){
  100882. *zOut++ = (u8)(c&0xFF);
  100883. }else if( c<0x00800 ){
  100884. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  100885. *zOut++ = 0x80 + (u8)(c & 0x3F);
  100886. }else if( c<0x10000 ){
  100887. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  100888. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  100889. *zOut++ = 0x80 + (u8)(c & 0x3F);
  100890. }else{
  100891. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  100892. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  100893. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  100894. *zOut++ = 0x80 + (u8)(c & 0x3F);
  100895. } \
  100896. }
  100897. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  100898. }
  100899. /*
  100900. ** The hex() function. Interpret the argument as a blob. Return
  100901. ** a hexadecimal rendering as text.
  100902. */
  100903. static void hexFunc(
  100904. sqlite3_context *context,
  100905. int argc,
  100906. sqlite3_value **argv
  100907. ){
  100908. int i, n;
  100909. const unsigned char *pBlob;
  100910. char *zHex, *z;
  100911. assert( argc==1 );
  100912. UNUSED_PARAMETER(argc);
  100913. pBlob = sqlite3_value_blob(argv[0]);
  100914. n = sqlite3_value_bytes(argv[0]);
  100915. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  100916. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  100917. if( zHex ){
  100918. for(i=0; i<n; i++, pBlob++){
  100919. unsigned char c = *pBlob;
  100920. *(z++) = hexdigits[(c>>4)&0xf];
  100921. *(z++) = hexdigits[c&0xf];
  100922. }
  100923. *z = 0;
  100924. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  100925. }
  100926. }
  100927. /*
  100928. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  100929. */
  100930. static void zeroblobFunc(
  100931. sqlite3_context *context,
  100932. int argc,
  100933. sqlite3_value **argv
  100934. ){
  100935. i64 n;
  100936. int rc;
  100937. assert( argc==1 );
  100938. UNUSED_PARAMETER(argc);
  100939. n = sqlite3_value_int64(argv[0]);
  100940. if( n<0 ) n = 0;
  100941. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  100942. if( rc ){
  100943. sqlite3_result_error_code(context, rc);
  100944. }
  100945. }
  100946. /*
  100947. ** The replace() function. Three arguments are all strings: call
  100948. ** them A, B, and C. The result is also a string which is derived
  100949. ** from A by replacing every occurrence of B with C. The match
  100950. ** must be exact. Collating sequences are not used.
  100951. */
  100952. static void replaceFunc(
  100953. sqlite3_context *context,
  100954. int argc,
  100955. sqlite3_value **argv
  100956. ){
  100957. const unsigned char *zStr; /* The input string A */
  100958. const unsigned char *zPattern; /* The pattern string B */
  100959. const unsigned char *zRep; /* The replacement string C */
  100960. unsigned char *zOut; /* The output */
  100961. int nStr; /* Size of zStr */
  100962. int nPattern; /* Size of zPattern */
  100963. int nRep; /* Size of zRep */
  100964. i64 nOut; /* Maximum size of zOut */
  100965. int loopLimit; /* Last zStr[] that might match zPattern[] */
  100966. int i, j; /* Loop counters */
  100967. assert( argc==3 );
  100968. UNUSED_PARAMETER(argc);
  100969. zStr = sqlite3_value_text(argv[0]);
  100970. if( zStr==0 ) return;
  100971. nStr = sqlite3_value_bytes(argv[0]);
  100972. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  100973. zPattern = sqlite3_value_text(argv[1]);
  100974. if( zPattern==0 ){
  100975. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  100976. || sqlite3_context_db_handle(context)->mallocFailed );
  100977. return;
  100978. }
  100979. if( zPattern[0]==0 ){
  100980. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  100981. sqlite3_result_value(context, argv[0]);
  100982. return;
  100983. }
  100984. nPattern = sqlite3_value_bytes(argv[1]);
  100985. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  100986. zRep = sqlite3_value_text(argv[2]);
  100987. if( zRep==0 ) return;
  100988. nRep = sqlite3_value_bytes(argv[2]);
  100989. assert( zRep==sqlite3_value_text(argv[2]) );
  100990. nOut = nStr + 1;
  100991. assert( nOut<SQLITE_MAX_LENGTH );
  100992. zOut = contextMalloc(context, (i64)nOut);
  100993. if( zOut==0 ){
  100994. return;
  100995. }
  100996. loopLimit = nStr - nPattern;
  100997. for(i=j=0; i<=loopLimit; i++){
  100998. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  100999. zOut[j++] = zStr[i];
  101000. }else{
  101001. u8 *zOld;
  101002. sqlite3 *db = sqlite3_context_db_handle(context);
  101003. nOut += nRep - nPattern;
  101004. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  101005. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  101006. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  101007. sqlite3_result_error_toobig(context);
  101008. sqlite3_free(zOut);
  101009. return;
  101010. }
  101011. zOld = zOut;
  101012. zOut = sqlite3_realloc64(zOut, (int)nOut);
  101013. if( zOut==0 ){
  101014. sqlite3_result_error_nomem(context);
  101015. sqlite3_free(zOld);
  101016. return;
  101017. }
  101018. memcpy(&zOut[j], zRep, nRep);
  101019. j += nRep;
  101020. i += nPattern-1;
  101021. }
  101022. }
  101023. assert( j+nStr-i+1==nOut );
  101024. memcpy(&zOut[j], &zStr[i], nStr-i);
  101025. j += nStr - i;
  101026. assert( j<=nOut );
  101027. zOut[j] = 0;
  101028. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  101029. }
  101030. /*
  101031. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  101032. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  101033. */
  101034. static void trimFunc(
  101035. sqlite3_context *context,
  101036. int argc,
  101037. sqlite3_value **argv
  101038. ){
  101039. const unsigned char *zIn; /* Input string */
  101040. const unsigned char *zCharSet; /* Set of characters to trim */
  101041. int nIn; /* Number of bytes in input */
  101042. int flags; /* 1: trimleft 2: trimright 3: trim */
  101043. int i; /* Loop counter */
  101044. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  101045. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  101046. int nChar; /* Number of characters in zCharSet */
  101047. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  101048. return;
  101049. }
  101050. zIn = sqlite3_value_text(argv[0]);
  101051. if( zIn==0 ) return;
  101052. nIn = sqlite3_value_bytes(argv[0]);
  101053. assert( zIn==sqlite3_value_text(argv[0]) );
  101054. if( argc==1 ){
  101055. static const unsigned char lenOne[] = { 1 };
  101056. static unsigned char * const azOne[] = { (u8*)" " };
  101057. nChar = 1;
  101058. aLen = (u8*)lenOne;
  101059. azChar = (unsigned char **)azOne;
  101060. zCharSet = 0;
  101061. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  101062. return;
  101063. }else{
  101064. const unsigned char *z;
  101065. for(z=zCharSet, nChar=0; *z; nChar++){
  101066. SQLITE_SKIP_UTF8(z);
  101067. }
  101068. if( nChar>0 ){
  101069. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  101070. if( azChar==0 ){
  101071. return;
  101072. }
  101073. aLen = (unsigned char*)&azChar[nChar];
  101074. for(z=zCharSet, nChar=0; *z; nChar++){
  101075. azChar[nChar] = (unsigned char *)z;
  101076. SQLITE_SKIP_UTF8(z);
  101077. aLen[nChar] = (u8)(z - azChar[nChar]);
  101078. }
  101079. }
  101080. }
  101081. if( nChar>0 ){
  101082. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  101083. if( flags & 1 ){
  101084. while( nIn>0 ){
  101085. int len = 0;
  101086. for(i=0; i<nChar; i++){
  101087. len = aLen[i];
  101088. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  101089. }
  101090. if( i>=nChar ) break;
  101091. zIn += len;
  101092. nIn -= len;
  101093. }
  101094. }
  101095. if( flags & 2 ){
  101096. while( nIn>0 ){
  101097. int len = 0;
  101098. for(i=0; i<nChar; i++){
  101099. len = aLen[i];
  101100. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  101101. }
  101102. if( i>=nChar ) break;
  101103. nIn -= len;
  101104. }
  101105. }
  101106. if( zCharSet ){
  101107. sqlite3_free(azChar);
  101108. }
  101109. }
  101110. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  101111. }
  101112. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  101113. /*
  101114. ** The "unknown" function is automatically substituted in place of
  101115. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  101116. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  101117. ** When the "sqlite3" command-line shell is built using this functionality,
  101118. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  101119. ** involving application-defined functions to be examined in a generic
  101120. ** sqlite3 shell.
  101121. */
  101122. static void unknownFunc(
  101123. sqlite3_context *context,
  101124. int argc,
  101125. sqlite3_value **argv
  101126. ){
  101127. /* no-op */
  101128. }
  101129. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  101130. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  101131. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  101132. ** when SQLite is built.
  101133. */
  101134. #ifdef SQLITE_SOUNDEX
  101135. /*
  101136. ** Compute the soundex encoding of a word.
  101137. **
  101138. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  101139. ** soundex encoding of the string X.
  101140. */
  101141. static void soundexFunc(
  101142. sqlite3_context *context,
  101143. int argc,
  101144. sqlite3_value **argv
  101145. ){
  101146. char zResult[8];
  101147. const u8 *zIn;
  101148. int i, j;
  101149. static const unsigned char iCode[] = {
  101150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  101151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  101152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  101153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  101154. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  101155. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  101156. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  101157. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  101158. };
  101159. assert( argc==1 );
  101160. zIn = (u8*)sqlite3_value_text(argv[0]);
  101161. if( zIn==0 ) zIn = (u8*)"";
  101162. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  101163. if( zIn[i] ){
  101164. u8 prevcode = iCode[zIn[i]&0x7f];
  101165. zResult[0] = sqlite3Toupper(zIn[i]);
  101166. for(j=1; j<4 && zIn[i]; i++){
  101167. int code = iCode[zIn[i]&0x7f];
  101168. if( code>0 ){
  101169. if( code!=prevcode ){
  101170. prevcode = code;
  101171. zResult[j++] = code + '0';
  101172. }
  101173. }else{
  101174. prevcode = 0;
  101175. }
  101176. }
  101177. while( j<4 ){
  101178. zResult[j++] = '0';
  101179. }
  101180. zResult[j] = 0;
  101181. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  101182. }else{
  101183. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  101184. ** is NULL or contains no ASCII alphabetic characters. */
  101185. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  101186. }
  101187. }
  101188. #endif /* SQLITE_SOUNDEX */
  101189. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  101190. /*
  101191. ** A function that loads a shared-library extension then returns NULL.
  101192. */
  101193. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  101194. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  101195. const char *zProc;
  101196. sqlite3 *db = sqlite3_context_db_handle(context);
  101197. char *zErrMsg = 0;
  101198. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  101199. ** flag is set. See the sqlite3_enable_load_extension() API.
  101200. */
  101201. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  101202. sqlite3_result_error(context, "not authorized", -1);
  101203. return;
  101204. }
  101205. if( argc==2 ){
  101206. zProc = (const char *)sqlite3_value_text(argv[1]);
  101207. }else{
  101208. zProc = 0;
  101209. }
  101210. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  101211. sqlite3_result_error(context, zErrMsg, -1);
  101212. sqlite3_free(zErrMsg);
  101213. }
  101214. }
  101215. #endif
  101216. /*
  101217. ** An instance of the following structure holds the context of a
  101218. ** sum() or avg() aggregate computation.
  101219. */
  101220. typedef struct SumCtx SumCtx;
  101221. struct SumCtx {
  101222. double rSum; /* Floating point sum */
  101223. i64 iSum; /* Integer sum */
  101224. i64 cnt; /* Number of elements summed */
  101225. u8 overflow; /* True if integer overflow seen */
  101226. u8 approx; /* True if non-integer value was input to the sum */
  101227. };
  101228. /*
  101229. ** Routines used to compute the sum, average, and total.
  101230. **
  101231. ** The SUM() function follows the (broken) SQL standard which means
  101232. ** that it returns NULL if it sums over no inputs. TOTAL returns
  101233. ** 0.0 in that case. In addition, TOTAL always returns a float where
  101234. ** SUM might return an integer if it never encounters a floating point
  101235. ** value. TOTAL never fails, but SUM might through an exception if
  101236. ** it overflows an integer.
  101237. */
  101238. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  101239. SumCtx *p;
  101240. int type;
  101241. assert( argc==1 );
  101242. UNUSED_PARAMETER(argc);
  101243. p = sqlite3_aggregate_context(context, sizeof(*p));
  101244. type = sqlite3_value_numeric_type(argv[0]);
  101245. if( p && type!=SQLITE_NULL ){
  101246. p->cnt++;
  101247. if( type==SQLITE_INTEGER ){
  101248. i64 v = sqlite3_value_int64(argv[0]);
  101249. p->rSum += v;
  101250. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  101251. p->overflow = 1;
  101252. }
  101253. }else{
  101254. p->rSum += sqlite3_value_double(argv[0]);
  101255. p->approx = 1;
  101256. }
  101257. }
  101258. }
  101259. static void sumFinalize(sqlite3_context *context){
  101260. SumCtx *p;
  101261. p = sqlite3_aggregate_context(context, 0);
  101262. if( p && p->cnt>0 ){
  101263. if( p->overflow ){
  101264. sqlite3_result_error(context,"integer overflow",-1);
  101265. }else if( p->approx ){
  101266. sqlite3_result_double(context, p->rSum);
  101267. }else{
  101268. sqlite3_result_int64(context, p->iSum);
  101269. }
  101270. }
  101271. }
  101272. static void avgFinalize(sqlite3_context *context){
  101273. SumCtx *p;
  101274. p = sqlite3_aggregate_context(context, 0);
  101275. if( p && p->cnt>0 ){
  101276. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  101277. }
  101278. }
  101279. static void totalFinalize(sqlite3_context *context){
  101280. SumCtx *p;
  101281. p = sqlite3_aggregate_context(context, 0);
  101282. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  101283. sqlite3_result_double(context, p ? p->rSum : (double)0);
  101284. }
  101285. /*
  101286. ** The following structure keeps track of state information for the
  101287. ** count() aggregate function.
  101288. */
  101289. typedef struct CountCtx CountCtx;
  101290. struct CountCtx {
  101291. i64 n;
  101292. };
  101293. /*
  101294. ** Routines to implement the count() aggregate function.
  101295. */
  101296. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  101297. CountCtx *p;
  101298. p = sqlite3_aggregate_context(context, sizeof(*p));
  101299. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  101300. p->n++;
  101301. }
  101302. #ifndef SQLITE_OMIT_DEPRECATED
  101303. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  101304. ** sure it still operates correctly, verify that its count agrees with our
  101305. ** internal count when using count(*) and when the total count can be
  101306. ** expressed as a 32-bit integer. */
  101307. assert( argc==1 || p==0 || p->n>0x7fffffff
  101308. || p->n==sqlite3_aggregate_count(context) );
  101309. #endif
  101310. }
  101311. static void countFinalize(sqlite3_context *context){
  101312. CountCtx *p;
  101313. p = sqlite3_aggregate_context(context, 0);
  101314. sqlite3_result_int64(context, p ? p->n : 0);
  101315. }
  101316. /*
  101317. ** Routines to implement min() and max() aggregate functions.
  101318. */
  101319. static void minmaxStep(
  101320. sqlite3_context *context,
  101321. int NotUsed,
  101322. sqlite3_value **argv
  101323. ){
  101324. Mem *pArg = (Mem *)argv[0];
  101325. Mem *pBest;
  101326. UNUSED_PARAMETER(NotUsed);
  101327. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  101328. if( !pBest ) return;
  101329. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  101330. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  101331. }else if( pBest->flags ){
  101332. int max;
  101333. int cmp;
  101334. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  101335. /* This step function is used for both the min() and max() aggregates,
  101336. ** the only difference between the two being that the sense of the
  101337. ** comparison is inverted. For the max() aggregate, the
  101338. ** sqlite3_user_data() function returns (void *)-1. For min() it
  101339. ** returns (void *)db, where db is the sqlite3* database pointer.
  101340. ** Therefore the next statement sets variable 'max' to 1 for the max()
  101341. ** aggregate, or 0 for min().
  101342. */
  101343. max = sqlite3_user_data(context)!=0;
  101344. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  101345. if( (max && cmp<0) || (!max && cmp>0) ){
  101346. sqlite3VdbeMemCopy(pBest, pArg);
  101347. }else{
  101348. sqlite3SkipAccumulatorLoad(context);
  101349. }
  101350. }else{
  101351. pBest->db = sqlite3_context_db_handle(context);
  101352. sqlite3VdbeMemCopy(pBest, pArg);
  101353. }
  101354. }
  101355. static void minMaxFinalize(sqlite3_context *context){
  101356. sqlite3_value *pRes;
  101357. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  101358. if( pRes ){
  101359. if( pRes->flags ){
  101360. sqlite3_result_value(context, pRes);
  101361. }
  101362. sqlite3VdbeMemRelease(pRes);
  101363. }
  101364. }
  101365. /*
  101366. ** group_concat(EXPR, ?SEPARATOR?)
  101367. */
  101368. static void groupConcatStep(
  101369. sqlite3_context *context,
  101370. int argc,
  101371. sqlite3_value **argv
  101372. ){
  101373. const char *zVal;
  101374. StrAccum *pAccum;
  101375. const char *zSep;
  101376. int nVal, nSep;
  101377. assert( argc==1 || argc==2 );
  101378. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  101379. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  101380. if( pAccum ){
  101381. sqlite3 *db = sqlite3_context_db_handle(context);
  101382. int firstTerm = pAccum->mxAlloc==0;
  101383. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  101384. if( !firstTerm ){
  101385. if( argc==2 ){
  101386. zSep = (char*)sqlite3_value_text(argv[1]);
  101387. nSep = sqlite3_value_bytes(argv[1]);
  101388. }else{
  101389. zSep = ",";
  101390. nSep = 1;
  101391. }
  101392. if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  101393. }
  101394. zVal = (char*)sqlite3_value_text(argv[0]);
  101395. nVal = sqlite3_value_bytes(argv[0]);
  101396. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  101397. }
  101398. }
  101399. static void groupConcatFinalize(sqlite3_context *context){
  101400. StrAccum *pAccum;
  101401. pAccum = sqlite3_aggregate_context(context, 0);
  101402. if( pAccum ){
  101403. if( pAccum->accError==STRACCUM_TOOBIG ){
  101404. sqlite3_result_error_toobig(context);
  101405. }else if( pAccum->accError==STRACCUM_NOMEM ){
  101406. sqlite3_result_error_nomem(context);
  101407. }else{
  101408. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  101409. sqlite3_free);
  101410. }
  101411. }
  101412. }
  101413. /*
  101414. ** This routine does per-connection function registration. Most
  101415. ** of the built-in functions above are part of the global function set.
  101416. ** This routine only deals with those that are not global.
  101417. */
  101418. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  101419. int rc = sqlite3_overload_function(db, "MATCH", 2);
  101420. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  101421. if( rc==SQLITE_NOMEM ){
  101422. sqlite3OomFault(db);
  101423. }
  101424. }
  101425. /*
  101426. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  101427. */
  101428. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  101429. FuncDef *pDef;
  101430. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  101431. if( ALWAYS(pDef) ){
  101432. pDef->funcFlags |= flagVal;
  101433. }
  101434. }
  101435. /*
  101436. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  101437. ** parameter determines whether or not the LIKE operator is case
  101438. ** sensitive. GLOB is always case sensitive.
  101439. */
  101440. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  101441. struct compareInfo *pInfo;
  101442. if( caseSensitive ){
  101443. pInfo = (struct compareInfo*)&likeInfoAlt;
  101444. }else{
  101445. pInfo = (struct compareInfo*)&likeInfoNorm;
  101446. }
  101447. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  101448. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  101449. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  101450. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  101451. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  101452. setLikeOptFlag(db, "like",
  101453. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  101454. }
  101455. /*
  101456. ** pExpr points to an expression which implements a function. If
  101457. ** it is appropriate to apply the LIKE optimization to that function
  101458. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  101459. ** escape character and then return TRUE. If the function is not a
  101460. ** LIKE-style function then return FALSE.
  101461. **
  101462. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  101463. ** operator if c is a string literal that is exactly one byte in length.
  101464. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  101465. ** no ESCAPE clause.
  101466. **
  101467. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  101468. ** the function (default for LIKE). If the function makes the distinction
  101469. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  101470. ** false.
  101471. */
  101472. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  101473. FuncDef *pDef;
  101474. int nExpr;
  101475. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  101476. return 0;
  101477. }
  101478. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  101479. nExpr = pExpr->x.pList->nExpr;
  101480. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  101481. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  101482. return 0;
  101483. }
  101484. if( nExpr<3 ){
  101485. aWc[3] = 0;
  101486. }else{
  101487. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  101488. char *zEscape;
  101489. if( pEscape->op!=TK_STRING ) return 0;
  101490. zEscape = pEscape->u.zToken;
  101491. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  101492. aWc[3] = zEscape[0];
  101493. }
  101494. /* The memcpy() statement assumes that the wildcard characters are
  101495. ** the first three statements in the compareInfo structure. The
  101496. ** asserts() that follow verify that assumption
  101497. */
  101498. memcpy(aWc, pDef->pUserData, 3);
  101499. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  101500. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  101501. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  101502. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  101503. return 1;
  101504. }
  101505. /*
  101506. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  101507. ** to the global function hash table. This occurs at start-time (as
  101508. ** a consequence of calling sqlite3_initialize()).
  101509. **
  101510. ** After this routine runs
  101511. */
  101512. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  101513. /*
  101514. ** The following array holds FuncDef structures for all of the functions
  101515. ** defined in this file.
  101516. **
  101517. ** The array cannot be constant since changes are made to the
  101518. ** FuncDef.pHash elements at start-time. The elements of this array
  101519. ** are read-only after initialization is complete.
  101520. **
  101521. ** For peak efficiency, put the most frequently used function last.
  101522. */
  101523. static FuncDef aBuiltinFunc[] = {
  101524. #ifdef SQLITE_SOUNDEX
  101525. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  101526. #endif
  101527. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  101528. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  101529. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  101530. #endif
  101531. #if SQLITE_USER_AUTHENTICATION
  101532. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  101533. #endif
  101534. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  101535. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  101536. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  101537. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  101538. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  101539. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  101540. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  101541. #ifdef SQLITE_DEBUG
  101542. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  101543. #endif
  101544. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  101545. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  101546. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  101547. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  101548. FUNCTION(trim, 1, 3, 0, trimFunc ),
  101549. FUNCTION(trim, 2, 3, 0, trimFunc ),
  101550. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  101551. FUNCTION(min, 0, 0, 1, 0 ),
  101552. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  101553. SQLITE_FUNC_MINMAX ),
  101554. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  101555. FUNCTION(max, 0, 1, 1, 0 ),
  101556. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  101557. SQLITE_FUNC_MINMAX ),
  101558. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  101559. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  101560. FUNCTION(instr, 2, 0, 0, instrFunc ),
  101561. FUNCTION(printf, -1, 0, 0, printfFunc ),
  101562. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  101563. FUNCTION(char, -1, 0, 0, charFunc ),
  101564. FUNCTION(abs, 1, 0, 0, absFunc ),
  101565. #ifndef SQLITE_OMIT_FLOATING_POINT
  101566. FUNCTION(round, 1, 0, 0, roundFunc ),
  101567. FUNCTION(round, 2, 0, 0, roundFunc ),
  101568. #endif
  101569. FUNCTION(upper, 1, 0, 0, upperFunc ),
  101570. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  101571. FUNCTION(hex, 1, 0, 0, hexFunc ),
  101572. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  101573. VFUNCTION(random, 0, 0, 0, randomFunc ),
  101574. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  101575. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  101576. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  101577. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  101578. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  101579. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  101580. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  101581. VFUNCTION(changes, 0, 0, 0, changes ),
  101582. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  101583. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  101584. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  101585. FUNCTION(substr, 2, 0, 0, substrFunc ),
  101586. FUNCTION(substr, 3, 0, 0, substrFunc ),
  101587. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  101588. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  101589. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  101590. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  101591. SQLITE_FUNC_COUNT ),
  101592. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  101593. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  101594. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  101595. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  101596. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  101597. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  101598. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  101599. #else
  101600. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  101601. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  101602. #endif
  101603. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  101604. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  101605. #endif
  101606. FUNCTION(coalesce, 1, 0, 0, 0 ),
  101607. FUNCTION(coalesce, 0, 0, 0, 0 ),
  101608. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  101609. };
  101610. #ifndef SQLITE_OMIT_ALTERTABLE
  101611. sqlite3AlterFunctions();
  101612. #endif
  101613. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  101614. sqlite3AnalyzeFunctions();
  101615. #endif
  101616. sqlite3RegisterDateTimeFunctions();
  101617. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  101618. #if 0 /* Enable to print out how the built-in functions are hashed */
  101619. {
  101620. int i;
  101621. FuncDef *p;
  101622. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  101623. printf("FUNC-HASH %02d:", i);
  101624. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  101625. int n = sqlite3Strlen30(p->zName);
  101626. int h = p->zName[0] + n;
  101627. printf(" %s(%d)", p->zName, h);
  101628. }
  101629. printf("\n");
  101630. }
  101631. }
  101632. #endif
  101633. }
  101634. /************** End of func.c ************************************************/
  101635. /************** Begin file fkey.c ********************************************/
  101636. /*
  101637. **
  101638. ** The author disclaims copyright to this source code. In place of
  101639. ** a legal notice, here is a blessing:
  101640. **
  101641. ** May you do good and not evil.
  101642. ** May you find forgiveness for yourself and forgive others.
  101643. ** May you share freely, never taking more than you give.
  101644. **
  101645. *************************************************************************
  101646. ** This file contains code used by the compiler to add foreign key
  101647. ** support to compiled SQL statements.
  101648. */
  101649. /* #include "sqliteInt.h" */
  101650. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101651. #ifndef SQLITE_OMIT_TRIGGER
  101652. /*
  101653. ** Deferred and Immediate FKs
  101654. ** --------------------------
  101655. **
  101656. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  101657. ** If an immediate foreign key constraint is violated,
  101658. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  101659. ** statement transaction rolled back. If a
  101660. ** deferred foreign key constraint is violated, no action is taken
  101661. ** immediately. However if the application attempts to commit the
  101662. ** transaction before fixing the constraint violation, the attempt fails.
  101663. **
  101664. ** Deferred constraints are implemented using a simple counter associated
  101665. ** with the database handle. The counter is set to zero each time a
  101666. ** database transaction is opened. Each time a statement is executed
  101667. ** that causes a foreign key violation, the counter is incremented. Each
  101668. ** time a statement is executed that removes an existing violation from
  101669. ** the database, the counter is decremented. When the transaction is
  101670. ** committed, the commit fails if the current value of the counter is
  101671. ** greater than zero. This scheme has two big drawbacks:
  101672. **
  101673. ** * When a commit fails due to a deferred foreign key constraint,
  101674. ** there is no way to tell which foreign constraint is not satisfied,
  101675. ** or which row it is not satisfied for.
  101676. **
  101677. ** * If the database contains foreign key violations when the
  101678. ** transaction is opened, this may cause the mechanism to malfunction.
  101679. **
  101680. ** Despite these problems, this approach is adopted as it seems simpler
  101681. ** than the alternatives.
  101682. **
  101683. ** INSERT operations:
  101684. **
  101685. ** I.1) For each FK for which the table is the child table, search
  101686. ** the parent table for a match. If none is found increment the
  101687. ** constraint counter.
  101688. **
  101689. ** I.2) For each FK for which the table is the parent table,
  101690. ** search the child table for rows that correspond to the new
  101691. ** row in the parent table. Decrement the counter for each row
  101692. ** found (as the constraint is now satisfied).
  101693. **
  101694. ** DELETE operations:
  101695. **
  101696. ** D.1) For each FK for which the table is the child table,
  101697. ** search the parent table for a row that corresponds to the
  101698. ** deleted row in the child table. If such a row is not found,
  101699. ** decrement the counter.
  101700. **
  101701. ** D.2) For each FK for which the table is the parent table, search
  101702. ** the child table for rows that correspond to the deleted row
  101703. ** in the parent table. For each found increment the counter.
  101704. **
  101705. ** UPDATE operations:
  101706. **
  101707. ** An UPDATE command requires that all 4 steps above are taken, but only
  101708. ** for FK constraints for which the affected columns are actually
  101709. ** modified (values must be compared at runtime).
  101710. **
  101711. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  101712. ** This simplifies the implementation a bit.
  101713. **
  101714. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  101715. ** resolution is considered to delete rows before the new row is inserted.
  101716. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  101717. ** is thrown, even if the FK constraint would be satisfied after the new
  101718. ** row is inserted.
  101719. **
  101720. ** Immediate constraints are usually handled similarly. The only difference
  101721. ** is that the counter used is stored as part of each individual statement
  101722. ** object (struct Vdbe). If, after the statement has run, its immediate
  101723. ** constraint counter is greater than zero,
  101724. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  101725. ** and the statement transaction is rolled back. An exception is an INSERT
  101726. ** statement that inserts a single row only (no triggers). In this case,
  101727. ** instead of using a counter, an exception is thrown immediately if the
  101728. ** INSERT violates a foreign key constraint. This is necessary as such
  101729. ** an INSERT does not open a statement transaction.
  101730. **
  101731. ** TODO: How should dropping a table be handled? How should renaming a
  101732. ** table be handled?
  101733. **
  101734. **
  101735. ** Query API Notes
  101736. ** ---------------
  101737. **
  101738. ** Before coding an UPDATE or DELETE row operation, the code-generator
  101739. ** for those two operations needs to know whether or not the operation
  101740. ** requires any FK processing and, if so, which columns of the original
  101741. ** row are required by the FK processing VDBE code (i.e. if FKs were
  101742. ** implemented using triggers, which of the old.* columns would be
  101743. ** accessed). No information is required by the code-generator before
  101744. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  101745. ** generation code to query for this information are:
  101746. **
  101747. ** sqlite3FkRequired() - Test to see if FK processing is required.
  101748. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  101749. **
  101750. **
  101751. ** Externally accessible module functions
  101752. ** --------------------------------------
  101753. **
  101754. ** sqlite3FkCheck() - Check for foreign key violations.
  101755. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  101756. ** sqlite3FkDelete() - Delete an FKey structure.
  101757. */
  101758. /*
  101759. ** VDBE Calling Convention
  101760. ** -----------------------
  101761. **
  101762. ** Example:
  101763. **
  101764. ** For the following INSERT statement:
  101765. **
  101766. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  101767. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  101768. **
  101769. ** Register (x): 2 (type integer)
  101770. ** Register (x+1): 1 (type integer)
  101771. ** Register (x+2): NULL (type NULL)
  101772. ** Register (x+3): 3.1 (type real)
  101773. */
  101774. /*
  101775. ** A foreign key constraint requires that the key columns in the parent
  101776. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  101777. ** Given that pParent is the parent table for foreign key constraint pFKey,
  101778. ** search the schema for a unique index on the parent key columns.
  101779. **
  101780. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  101781. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  101782. ** is set to point to the unique index.
  101783. **
  101784. ** If the parent key consists of a single column (the foreign key constraint
  101785. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  101786. ** Otherwise, it is set to point to an allocated array of size N, where
  101787. ** N is the number of columns in the parent key. The first element of the
  101788. ** array is the index of the child table column that is mapped by the FK
  101789. ** constraint to the parent table column stored in the left-most column
  101790. ** of index *ppIdx. The second element of the array is the index of the
  101791. ** child table column that corresponds to the second left-most column of
  101792. ** *ppIdx, and so on.
  101793. **
  101794. ** If the required index cannot be found, either because:
  101795. **
  101796. ** 1) The named parent key columns do not exist, or
  101797. **
  101798. ** 2) The named parent key columns do exist, but are not subject to a
  101799. ** UNIQUE or PRIMARY KEY constraint, or
  101800. **
  101801. ** 3) No parent key columns were provided explicitly as part of the
  101802. ** foreign key definition, and the parent table does not have a
  101803. ** PRIMARY KEY, or
  101804. **
  101805. ** 4) No parent key columns were provided explicitly as part of the
  101806. ** foreign key definition, and the PRIMARY KEY of the parent table
  101807. ** consists of a different number of columns to the child key in
  101808. ** the child table.
  101809. **
  101810. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  101811. ** into pParse. If an OOM error occurs, non-zero is returned and the
  101812. ** pParse->db->mallocFailed flag is set.
  101813. */
  101814. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  101815. Parse *pParse, /* Parse context to store any error in */
  101816. Table *pParent, /* Parent table of FK constraint pFKey */
  101817. FKey *pFKey, /* Foreign key to find index for */
  101818. Index **ppIdx, /* OUT: Unique index on parent table */
  101819. int **paiCol /* OUT: Map of index columns in pFKey */
  101820. ){
  101821. Index *pIdx = 0; /* Value to return via *ppIdx */
  101822. int *aiCol = 0; /* Value to return via *paiCol */
  101823. int nCol = pFKey->nCol; /* Number of columns in parent key */
  101824. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  101825. /* The caller is responsible for zeroing output parameters. */
  101826. assert( ppIdx && *ppIdx==0 );
  101827. assert( !paiCol || *paiCol==0 );
  101828. assert( pParse );
  101829. /* If this is a non-composite (single column) foreign key, check if it
  101830. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  101831. ** and *paiCol set to zero and return early.
  101832. **
  101833. ** Otherwise, for a composite foreign key (more than one column), allocate
  101834. ** space for the aiCol array (returned via output parameter *paiCol).
  101835. ** Non-composite foreign keys do not require the aiCol array.
  101836. */
  101837. if( nCol==1 ){
  101838. /* The FK maps to the IPK if any of the following are true:
  101839. **
  101840. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  101841. ** mapped to the primary key of table pParent, or
  101842. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  101843. ** PRIMARY KEY.
  101844. */
  101845. if( pParent->iPKey>=0 ){
  101846. if( !zKey ) return 0;
  101847. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  101848. }
  101849. }else if( paiCol ){
  101850. assert( nCol>1 );
  101851. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  101852. if( !aiCol ) return 1;
  101853. *paiCol = aiCol;
  101854. }
  101855. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  101856. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  101857. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  101858. ** of columns. If each indexed column corresponds to a foreign key
  101859. ** column of pFKey, then this index is a winner. */
  101860. if( zKey==0 ){
  101861. /* If zKey is NULL, then this foreign key is implicitly mapped to
  101862. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  101863. ** identified by the test. */
  101864. if( IsPrimaryKeyIndex(pIdx) ){
  101865. if( aiCol ){
  101866. int i;
  101867. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  101868. }
  101869. break;
  101870. }
  101871. }else{
  101872. /* If zKey is non-NULL, then this foreign key was declared to
  101873. ** map to an explicit list of columns in table pParent. Check if this
  101874. ** index matches those columns. Also, check that the index uses
  101875. ** the default collation sequences for each column. */
  101876. int i, j;
  101877. for(i=0; i<nCol; i++){
  101878. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  101879. const char *zDfltColl; /* Def. collation for column */
  101880. char *zIdxCol; /* Name of indexed column */
  101881. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  101882. /* If the index uses a collation sequence that is different from
  101883. ** the default collation sequence for the column, this index is
  101884. ** unusable. Bail out early in this case. */
  101885. zDfltColl = pParent->aCol[iCol].zColl;
  101886. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  101887. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  101888. zIdxCol = pParent->aCol[iCol].zName;
  101889. for(j=0; j<nCol; j++){
  101890. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  101891. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  101892. break;
  101893. }
  101894. }
  101895. if( j==nCol ) break;
  101896. }
  101897. if( i==nCol ) break; /* pIdx is usable */
  101898. }
  101899. }
  101900. }
  101901. if( !pIdx ){
  101902. if( !pParse->disableTriggers ){
  101903. sqlite3ErrorMsg(pParse,
  101904. "foreign key mismatch - \"%w\" referencing \"%w\"",
  101905. pFKey->pFrom->zName, pFKey->zTo);
  101906. }
  101907. sqlite3DbFree(pParse->db, aiCol);
  101908. return 1;
  101909. }
  101910. *ppIdx = pIdx;
  101911. return 0;
  101912. }
  101913. /*
  101914. ** This function is called when a row is inserted into or deleted from the
  101915. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  101916. ** on the child table of pFKey, this function is invoked twice for each row
  101917. ** affected - once to "delete" the old row, and then again to "insert" the
  101918. ** new row.
  101919. **
  101920. ** Each time it is called, this function generates VDBE code to locate the
  101921. ** row in the parent table that corresponds to the row being inserted into
  101922. ** or deleted from the child table. If the parent row can be found, no
  101923. ** special action is taken. Otherwise, if the parent row can *not* be
  101924. ** found in the parent table:
  101925. **
  101926. ** Operation | FK type | Action taken
  101927. ** --------------------------------------------------------------------------
  101928. ** INSERT immediate Increment the "immediate constraint counter".
  101929. **
  101930. ** DELETE immediate Decrement the "immediate constraint counter".
  101931. **
  101932. ** INSERT deferred Increment the "deferred constraint counter".
  101933. **
  101934. ** DELETE deferred Decrement the "deferred constraint counter".
  101935. **
  101936. ** These operations are identified in the comment at the top of this file
  101937. ** (fkey.c) as "I.1" and "D.1".
  101938. */
  101939. static void fkLookupParent(
  101940. Parse *pParse, /* Parse context */
  101941. int iDb, /* Index of database housing pTab */
  101942. Table *pTab, /* Parent table of FK pFKey */
  101943. Index *pIdx, /* Unique index on parent key columns in pTab */
  101944. FKey *pFKey, /* Foreign key constraint */
  101945. int *aiCol, /* Map from parent key columns to child table columns */
  101946. int regData, /* Address of array containing child table row */
  101947. int nIncr, /* Increment constraint counter by this */
  101948. int isIgnore /* If true, pretend pTab contains all NULL values */
  101949. ){
  101950. int i; /* Iterator variable */
  101951. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  101952. int iCur = pParse->nTab - 1; /* Cursor number to use */
  101953. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  101954. /* If nIncr is less than zero, then check at runtime if there are any
  101955. ** outstanding constraints to resolve. If there are not, there is no need
  101956. ** to check if deleting this row resolves any outstanding violations.
  101957. **
  101958. ** Check if any of the key columns in the child table row are NULL. If
  101959. ** any are, then the constraint is considered satisfied. No need to
  101960. ** search for a matching row in the parent table. */
  101961. if( nIncr<0 ){
  101962. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  101963. VdbeCoverage(v);
  101964. }
  101965. for(i=0; i<pFKey->nCol; i++){
  101966. int iReg = aiCol[i] + regData + 1;
  101967. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  101968. }
  101969. if( isIgnore==0 ){
  101970. if( pIdx==0 ){
  101971. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  101972. ** column of the parent table (table pTab). */
  101973. int iMustBeInt; /* Address of MustBeInt instruction */
  101974. int regTemp = sqlite3GetTempReg(pParse);
  101975. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  101976. ** apply the affinity of the parent key). If this fails, then there
  101977. ** is no matching parent key. Before using MustBeInt, make a copy of
  101978. ** the value. Otherwise, the value inserted into the child key column
  101979. ** will have INTEGER affinity applied to it, which may not be correct. */
  101980. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  101981. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  101982. VdbeCoverage(v);
  101983. /* If the parent table is the same as the child table, and we are about
  101984. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  101985. ** then check if the row being inserted matches itself. If so, do not
  101986. ** increment the constraint-counter. */
  101987. if( pTab==pFKey->pFrom && nIncr==1 ){
  101988. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  101989. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  101990. }
  101991. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  101992. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  101993. sqlite3VdbeGoto(v, iOk);
  101994. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  101995. sqlite3VdbeJumpHere(v, iMustBeInt);
  101996. sqlite3ReleaseTempReg(pParse, regTemp);
  101997. }else{
  101998. int nCol = pFKey->nCol;
  101999. int regTemp = sqlite3GetTempRange(pParse, nCol);
  102000. int regRec = sqlite3GetTempReg(pParse);
  102001. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  102002. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  102003. for(i=0; i<nCol; i++){
  102004. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  102005. }
  102006. /* If the parent table is the same as the child table, and we are about
  102007. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  102008. ** then check if the row being inserted matches itself. If so, do not
  102009. ** increment the constraint-counter.
  102010. **
  102011. ** If any of the parent-key values are NULL, then the row cannot match
  102012. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  102013. ** of the parent-key values are NULL (at this point it is known that
  102014. ** none of the child key values are).
  102015. */
  102016. if( pTab==pFKey->pFrom && nIncr==1 ){
  102017. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  102018. for(i=0; i<nCol; i++){
  102019. int iChild = aiCol[i]+1+regData;
  102020. int iParent = pIdx->aiColumn[i]+1+regData;
  102021. assert( pIdx->aiColumn[i]>=0 );
  102022. assert( aiCol[i]!=pTab->iPKey );
  102023. if( pIdx->aiColumn[i]==pTab->iPKey ){
  102024. /* The parent key is a composite key that includes the IPK column */
  102025. iParent = regData;
  102026. }
  102027. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  102028. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  102029. }
  102030. sqlite3VdbeGoto(v, iOk);
  102031. }
  102032. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  102033. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  102034. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  102035. sqlite3ReleaseTempReg(pParse, regRec);
  102036. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  102037. }
  102038. }
  102039. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  102040. && !pParse->pToplevel
  102041. && !pParse->isMultiWrite
  102042. ){
  102043. /* Special case: If this is an INSERT statement that will insert exactly
  102044. ** one row into the table, raise a constraint immediately instead of
  102045. ** incrementing a counter. This is necessary as the VM code is being
  102046. ** generated for will not open a statement transaction. */
  102047. assert( nIncr==1 );
  102048. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  102049. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  102050. }else{
  102051. if( nIncr>0 && pFKey->isDeferred==0 ){
  102052. sqlite3MayAbort(pParse);
  102053. }
  102054. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  102055. }
  102056. sqlite3VdbeResolveLabel(v, iOk);
  102057. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  102058. }
  102059. /*
  102060. ** Return an Expr object that refers to a memory register corresponding
  102061. ** to column iCol of table pTab.
  102062. **
  102063. ** regBase is the first of an array of register that contains the data
  102064. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  102065. ** column. regBase+2 holds the second column, and so forth.
  102066. */
  102067. static Expr *exprTableRegister(
  102068. Parse *pParse, /* Parsing and code generating context */
  102069. Table *pTab, /* The table whose content is at r[regBase]... */
  102070. int regBase, /* Contents of table pTab */
  102071. i16 iCol /* Which column of pTab is desired */
  102072. ){
  102073. Expr *pExpr;
  102074. Column *pCol;
  102075. const char *zColl;
  102076. sqlite3 *db = pParse->db;
  102077. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  102078. if( pExpr ){
  102079. if( iCol>=0 && iCol!=pTab->iPKey ){
  102080. pCol = &pTab->aCol[iCol];
  102081. pExpr->iTable = regBase + iCol + 1;
  102082. pExpr->affinity = pCol->affinity;
  102083. zColl = pCol->zColl;
  102084. if( zColl==0 ) zColl = db->pDfltColl->zName;
  102085. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  102086. }else{
  102087. pExpr->iTable = regBase;
  102088. pExpr->affinity = SQLITE_AFF_INTEGER;
  102089. }
  102090. }
  102091. return pExpr;
  102092. }
  102093. /*
  102094. ** Return an Expr object that refers to column iCol of table pTab which
  102095. ** has cursor iCur.
  102096. */
  102097. static Expr *exprTableColumn(
  102098. sqlite3 *db, /* The database connection */
  102099. Table *pTab, /* The table whose column is desired */
  102100. int iCursor, /* The open cursor on the table */
  102101. i16 iCol /* The column that is wanted */
  102102. ){
  102103. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  102104. if( pExpr ){
  102105. pExpr->pTab = pTab;
  102106. pExpr->iTable = iCursor;
  102107. pExpr->iColumn = iCol;
  102108. }
  102109. return pExpr;
  102110. }
  102111. /*
  102112. ** This function is called to generate code executed when a row is deleted
  102113. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  102114. ** deferred, when a row is inserted into the same table. When generating
  102115. ** code for an SQL UPDATE operation, this function may be called twice -
  102116. ** once to "delete" the old row and once to "insert" the new row.
  102117. **
  102118. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  102119. ** the number of FK violations in the db) or +1 when deleting one (as this
  102120. ** may increase the number of FK constraint problems).
  102121. **
  102122. ** The code generated by this function scans through the rows in the child
  102123. ** table that correspond to the parent table row being deleted or inserted.
  102124. ** For each child row found, one of the following actions is taken:
  102125. **
  102126. ** Operation | FK type | Action taken
  102127. ** --------------------------------------------------------------------------
  102128. ** DELETE immediate Increment the "immediate constraint counter".
  102129. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  102130. ** throw a "FOREIGN KEY constraint failed" exception.
  102131. **
  102132. ** INSERT immediate Decrement the "immediate constraint counter".
  102133. **
  102134. ** DELETE deferred Increment the "deferred constraint counter".
  102135. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  102136. ** throw a "FOREIGN KEY constraint failed" exception.
  102137. **
  102138. ** INSERT deferred Decrement the "deferred constraint counter".
  102139. **
  102140. ** These operations are identified in the comment at the top of this file
  102141. ** (fkey.c) as "I.2" and "D.2".
  102142. */
  102143. static void fkScanChildren(
  102144. Parse *pParse, /* Parse context */
  102145. SrcList *pSrc, /* The child table to be scanned */
  102146. Table *pTab, /* The parent table */
  102147. Index *pIdx, /* Index on parent covering the foreign key */
  102148. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  102149. int *aiCol, /* Map from pIdx cols to child table cols */
  102150. int regData, /* Parent row data starts here */
  102151. int nIncr /* Amount to increment deferred counter by */
  102152. ){
  102153. sqlite3 *db = pParse->db; /* Database handle */
  102154. int i; /* Iterator variable */
  102155. Expr *pWhere = 0; /* WHERE clause to scan with */
  102156. NameContext sNameContext; /* Context used to resolve WHERE clause */
  102157. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  102158. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  102159. Vdbe *v = sqlite3GetVdbe(pParse);
  102160. assert( pIdx==0 || pIdx->pTable==pTab );
  102161. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  102162. assert( pIdx!=0 || pFKey->nCol==1 );
  102163. assert( pIdx!=0 || HasRowid(pTab) );
  102164. if( nIncr<0 ){
  102165. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  102166. VdbeCoverage(v);
  102167. }
  102168. /* Create an Expr object representing an SQL expression like:
  102169. **
  102170. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  102171. **
  102172. ** The collation sequence used for the comparison should be that of
  102173. ** the parent key columns. The affinity of the parent key column should
  102174. ** be applied to each child key value before the comparison takes place.
  102175. */
  102176. for(i=0; i<pFKey->nCol; i++){
  102177. Expr *pLeft; /* Value from parent table row */
  102178. Expr *pRight; /* Column ref to child table */
  102179. Expr *pEq; /* Expression (pLeft = pRight) */
  102180. i16 iCol; /* Index of column in child table */
  102181. const char *zCol; /* Name of column in child table */
  102182. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  102183. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  102184. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  102185. assert( iCol>=0 );
  102186. zCol = pFKey->pFrom->aCol[iCol].zName;
  102187. pRight = sqlite3Expr(db, TK_ID, zCol);
  102188. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  102189. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  102190. }
  102191. /* If the child table is the same as the parent table, then add terms
  102192. ** to the WHERE clause that prevent this entry from being scanned.
  102193. ** The added WHERE clause terms are like this:
  102194. **
  102195. ** $current_rowid!=rowid
  102196. ** NOT( $current_a==a AND $current_b==b AND ... )
  102197. **
  102198. ** The first form is used for rowid tables. The second form is used
  102199. ** for WITHOUT ROWID tables. In the second form, the primary key is
  102200. ** (a,b,...)
  102201. */
  102202. if( pTab==pFKey->pFrom && nIncr>0 ){
  102203. Expr *pNe; /* Expression (pLeft != pRight) */
  102204. Expr *pLeft; /* Value from parent table row */
  102205. Expr *pRight; /* Column ref to child table */
  102206. if( HasRowid(pTab) ){
  102207. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  102208. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  102209. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  102210. }else{
  102211. Expr *pEq, *pAll = 0;
  102212. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  102213. assert( pIdx!=0 );
  102214. for(i=0; i<pPk->nKeyCol; i++){
  102215. i16 iCol = pIdx->aiColumn[i];
  102216. assert( iCol>=0 );
  102217. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  102218. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  102219. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  102220. pAll = sqlite3ExprAnd(db, pAll, pEq);
  102221. }
  102222. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  102223. }
  102224. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  102225. }
  102226. /* Resolve the references in the WHERE clause. */
  102227. memset(&sNameContext, 0, sizeof(NameContext));
  102228. sNameContext.pSrcList = pSrc;
  102229. sNameContext.pParse = pParse;
  102230. sqlite3ResolveExprNames(&sNameContext, pWhere);
  102231. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  102232. ** clause. For each row found, increment either the deferred or immediate
  102233. ** foreign key constraint counter. */
  102234. if( pParse->nErr==0 ){
  102235. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  102236. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  102237. if( pWInfo ){
  102238. sqlite3WhereEnd(pWInfo);
  102239. }
  102240. }
  102241. /* Clean up the WHERE clause constructed above. */
  102242. sqlite3ExprDelete(db, pWhere);
  102243. if( iFkIfZero ){
  102244. sqlite3VdbeJumpHere(v, iFkIfZero);
  102245. }
  102246. }
  102247. /*
  102248. ** This function returns a linked list of FKey objects (connected by
  102249. ** FKey.pNextTo) holding all children of table pTab. For example,
  102250. ** given the following schema:
  102251. **
  102252. ** CREATE TABLE t1(a PRIMARY KEY);
  102253. ** CREATE TABLE t2(b REFERENCES t1(a);
  102254. **
  102255. ** Calling this function with table "t1" as an argument returns a pointer
  102256. ** to the FKey structure representing the foreign key constraint on table
  102257. ** "t2". Calling this function with "t2" as the argument would return a
  102258. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  102259. ** table).
  102260. */
  102261. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  102262. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  102263. }
  102264. /*
  102265. ** The second argument is a Trigger structure allocated by the
  102266. ** fkActionTrigger() routine. This function deletes the Trigger structure
  102267. ** and all of its sub-components.
  102268. **
  102269. ** The Trigger structure or any of its sub-components may be allocated from
  102270. ** the lookaside buffer belonging to database handle dbMem.
  102271. */
  102272. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  102273. if( p ){
  102274. TriggerStep *pStep = p->step_list;
  102275. sqlite3ExprDelete(dbMem, pStep->pWhere);
  102276. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  102277. sqlite3SelectDelete(dbMem, pStep->pSelect);
  102278. sqlite3ExprDelete(dbMem, p->pWhen);
  102279. sqlite3DbFree(dbMem, p);
  102280. }
  102281. }
  102282. /*
  102283. ** This function is called to generate code that runs when table pTab is
  102284. ** being dropped from the database. The SrcList passed as the second argument
  102285. ** to this function contains a single entry guaranteed to resolve to
  102286. ** table pTab.
  102287. **
  102288. ** Normally, no code is required. However, if either
  102289. **
  102290. ** (a) The table is the parent table of a FK constraint, or
  102291. ** (b) The table is the child table of a deferred FK constraint and it is
  102292. ** determined at runtime that there are outstanding deferred FK
  102293. ** constraint violations in the database,
  102294. **
  102295. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  102296. ** the table from the database. Triggers are disabled while running this
  102297. ** DELETE, but foreign key actions are not.
  102298. */
  102299. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  102300. sqlite3 *db = pParse->db;
  102301. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  102302. int iSkip = 0;
  102303. Vdbe *v = sqlite3GetVdbe(pParse);
  102304. assert( v ); /* VDBE has already been allocated */
  102305. if( sqlite3FkReferences(pTab)==0 ){
  102306. /* Search for a deferred foreign key constraint for which this table
  102307. ** is the child table. If one cannot be found, return without
  102308. ** generating any VDBE code. If one can be found, then jump over
  102309. ** the entire DELETE if there are no outstanding deferred constraints
  102310. ** when this statement is run. */
  102311. FKey *p;
  102312. for(p=pTab->pFKey; p; p=p->pNextFrom){
  102313. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  102314. }
  102315. if( !p ) return;
  102316. iSkip = sqlite3VdbeMakeLabel(v);
  102317. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  102318. }
  102319. pParse->disableTriggers = 1;
  102320. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  102321. pParse->disableTriggers = 0;
  102322. /* If the DELETE has generated immediate foreign key constraint
  102323. ** violations, halt the VDBE and return an error at this point, before
  102324. ** any modifications to the schema are made. This is because statement
  102325. ** transactions are not able to rollback schema changes.
  102326. **
  102327. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  102328. ** the statement transaction will not be rolled back even if FK
  102329. ** constraints are violated.
  102330. */
  102331. if( (db->flags & SQLITE_DeferFKs)==0 ){
  102332. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  102333. VdbeCoverage(v);
  102334. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  102335. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  102336. }
  102337. if( iSkip ){
  102338. sqlite3VdbeResolveLabel(v, iSkip);
  102339. }
  102340. }
  102341. }
  102342. /*
  102343. ** The second argument points to an FKey object representing a foreign key
  102344. ** for which pTab is the child table. An UPDATE statement against pTab
  102345. ** is currently being processed. For each column of the table that is
  102346. ** actually updated, the corresponding element in the aChange[] array
  102347. ** is zero or greater (if a column is unmodified the corresponding element
  102348. ** is set to -1). If the rowid column is modified by the UPDATE statement
  102349. ** the bChngRowid argument is non-zero.
  102350. **
  102351. ** This function returns true if any of the columns that are part of the
  102352. ** child key for FK constraint *p are modified.
  102353. */
  102354. static int fkChildIsModified(
  102355. Table *pTab, /* Table being updated */
  102356. FKey *p, /* Foreign key for which pTab is the child */
  102357. int *aChange, /* Array indicating modified columns */
  102358. int bChngRowid /* True if rowid is modified by this update */
  102359. ){
  102360. int i;
  102361. for(i=0; i<p->nCol; i++){
  102362. int iChildKey = p->aCol[i].iFrom;
  102363. if( aChange[iChildKey]>=0 ) return 1;
  102364. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  102365. }
  102366. return 0;
  102367. }
  102368. /*
  102369. ** The second argument points to an FKey object representing a foreign key
  102370. ** for which pTab is the parent table. An UPDATE statement against pTab
  102371. ** is currently being processed. For each column of the table that is
  102372. ** actually updated, the corresponding element in the aChange[] array
  102373. ** is zero or greater (if a column is unmodified the corresponding element
  102374. ** is set to -1). If the rowid column is modified by the UPDATE statement
  102375. ** the bChngRowid argument is non-zero.
  102376. **
  102377. ** This function returns true if any of the columns that are part of the
  102378. ** parent key for FK constraint *p are modified.
  102379. */
  102380. static int fkParentIsModified(
  102381. Table *pTab,
  102382. FKey *p,
  102383. int *aChange,
  102384. int bChngRowid
  102385. ){
  102386. int i;
  102387. for(i=0; i<p->nCol; i++){
  102388. char *zKey = p->aCol[i].zCol;
  102389. int iKey;
  102390. for(iKey=0; iKey<pTab->nCol; iKey++){
  102391. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  102392. Column *pCol = &pTab->aCol[iKey];
  102393. if( zKey ){
  102394. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  102395. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  102396. return 1;
  102397. }
  102398. }
  102399. }
  102400. }
  102401. return 0;
  102402. }
  102403. /*
  102404. ** Return true if the parser passed as the first argument is being
  102405. ** used to code a trigger that is really a "SET NULL" action belonging
  102406. ** to trigger pFKey.
  102407. */
  102408. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  102409. Parse *pTop = sqlite3ParseToplevel(pParse);
  102410. if( pTop->pTriggerPrg ){
  102411. Trigger *p = pTop->pTriggerPrg->pTrigger;
  102412. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  102413. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  102414. ){
  102415. return 1;
  102416. }
  102417. }
  102418. return 0;
  102419. }
  102420. /*
  102421. ** This function is called when inserting, deleting or updating a row of
  102422. ** table pTab to generate VDBE code to perform foreign key constraint
  102423. ** processing for the operation.
  102424. **
  102425. ** For a DELETE operation, parameter regOld is passed the index of the
  102426. ** first register in an array of (pTab->nCol+1) registers containing the
  102427. ** rowid of the row being deleted, followed by each of the column values
  102428. ** of the row being deleted, from left to right. Parameter regNew is passed
  102429. ** zero in this case.
  102430. **
  102431. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  102432. ** first register of an array of (pTab->nCol+1) registers containing the new
  102433. ** row data.
  102434. **
  102435. ** For an UPDATE operation, this function is called twice. Once before
  102436. ** the original record is deleted from the table using the calling convention
  102437. ** described for DELETE. Then again after the original record is deleted
  102438. ** but before the new record is inserted using the INSERT convention.
  102439. */
  102440. SQLITE_PRIVATE void sqlite3FkCheck(
  102441. Parse *pParse, /* Parse context */
  102442. Table *pTab, /* Row is being deleted from this table */
  102443. int regOld, /* Previous row data is stored here */
  102444. int regNew, /* New row data is stored here */
  102445. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  102446. int bChngRowid /* True if rowid is UPDATEd */
  102447. ){
  102448. sqlite3 *db = pParse->db; /* Database handle */
  102449. FKey *pFKey; /* Used to iterate through FKs */
  102450. int iDb; /* Index of database containing pTab */
  102451. const char *zDb; /* Name of database containing pTab */
  102452. int isIgnoreErrors = pParse->disableTriggers;
  102453. /* Exactly one of regOld and regNew should be non-zero. */
  102454. assert( (regOld==0)!=(regNew==0) );
  102455. /* If foreign-keys are disabled, this function is a no-op. */
  102456. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  102457. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102458. zDb = db->aDb[iDb].zDbSName;
  102459. /* Loop through all the foreign key constraints for which pTab is the
  102460. ** child table (the table that the foreign key definition is part of). */
  102461. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  102462. Table *pTo; /* Parent table of foreign key pFKey */
  102463. Index *pIdx = 0; /* Index on key columns in pTo */
  102464. int *aiFree = 0;
  102465. int *aiCol;
  102466. int iCol;
  102467. int i;
  102468. int bIgnore = 0;
  102469. if( aChange
  102470. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  102471. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  102472. ){
  102473. continue;
  102474. }
  102475. /* Find the parent table of this foreign key. Also find a unique index
  102476. ** on the parent key columns in the parent table. If either of these
  102477. ** schema items cannot be located, set an error in pParse and return
  102478. ** early. */
  102479. if( pParse->disableTriggers ){
  102480. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  102481. }else{
  102482. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  102483. }
  102484. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  102485. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  102486. if( !isIgnoreErrors || db->mallocFailed ) return;
  102487. if( pTo==0 ){
  102488. /* If isIgnoreErrors is true, then a table is being dropped. In this
  102489. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  102490. ** before actually dropping it in order to check FK constraints.
  102491. ** If the parent table of an FK constraint on the current table is
  102492. ** missing, behave as if it is empty. i.e. decrement the relevant
  102493. ** FK counter for each row of the current table with non-NULL keys.
  102494. */
  102495. Vdbe *v = sqlite3GetVdbe(pParse);
  102496. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  102497. for(i=0; i<pFKey->nCol; i++){
  102498. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  102499. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  102500. }
  102501. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  102502. }
  102503. continue;
  102504. }
  102505. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  102506. if( aiFree ){
  102507. aiCol = aiFree;
  102508. }else{
  102509. iCol = pFKey->aCol[0].iFrom;
  102510. aiCol = &iCol;
  102511. }
  102512. for(i=0; i<pFKey->nCol; i++){
  102513. if( aiCol[i]==pTab->iPKey ){
  102514. aiCol[i] = -1;
  102515. }
  102516. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  102517. #ifndef SQLITE_OMIT_AUTHORIZATION
  102518. /* Request permission to read the parent key columns. If the
  102519. ** authorization callback returns SQLITE_IGNORE, behave as if any
  102520. ** values read from the parent table are NULL. */
  102521. if( db->xAuth ){
  102522. int rcauth;
  102523. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  102524. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  102525. bIgnore = (rcauth==SQLITE_IGNORE);
  102526. }
  102527. #endif
  102528. }
  102529. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  102530. ** a cursor to use to search the unique index on the parent key columns
  102531. ** in the parent table. */
  102532. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  102533. pParse->nTab++;
  102534. if( regOld!=0 ){
  102535. /* A row is being removed from the child table. Search for the parent.
  102536. ** If the parent does not exist, removing the child row resolves an
  102537. ** outstanding foreign key constraint violation. */
  102538. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  102539. }
  102540. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  102541. /* A row is being added to the child table. If a parent row cannot
  102542. ** be found, adding the child row has violated the FK constraint.
  102543. **
  102544. ** If this operation is being performed as part of a trigger program
  102545. ** that is actually a "SET NULL" action belonging to this very
  102546. ** foreign key, then omit this scan altogether. As all child key
  102547. ** values are guaranteed to be NULL, it is not possible for adding
  102548. ** this row to cause an FK violation. */
  102549. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  102550. }
  102551. sqlite3DbFree(db, aiFree);
  102552. }
  102553. /* Loop through all the foreign key constraints that refer to this table.
  102554. ** (the "child" constraints) */
  102555. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  102556. Index *pIdx = 0; /* Foreign key index for pFKey */
  102557. SrcList *pSrc;
  102558. int *aiCol = 0;
  102559. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  102560. continue;
  102561. }
  102562. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  102563. && !pParse->pToplevel && !pParse->isMultiWrite
  102564. ){
  102565. assert( regOld==0 && regNew!=0 );
  102566. /* Inserting a single row into a parent table cannot cause (or fix)
  102567. ** an immediate foreign key violation. So do nothing in this case. */
  102568. continue;
  102569. }
  102570. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  102571. if( !isIgnoreErrors || db->mallocFailed ) return;
  102572. continue;
  102573. }
  102574. assert( aiCol || pFKey->nCol==1 );
  102575. /* Create a SrcList structure containing the child table. We need the
  102576. ** child table as a SrcList for sqlite3WhereBegin() */
  102577. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  102578. if( pSrc ){
  102579. struct SrcList_item *pItem = pSrc->a;
  102580. pItem->pTab = pFKey->pFrom;
  102581. pItem->zName = pFKey->pFrom->zName;
  102582. pItem->pTab->nTabRef++;
  102583. pItem->iCursor = pParse->nTab++;
  102584. if( regNew!=0 ){
  102585. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  102586. }
  102587. if( regOld!=0 ){
  102588. int eAction = pFKey->aAction[aChange!=0];
  102589. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  102590. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  102591. ** action applies, then any foreign key violations caused by
  102592. ** removing the parent key will be rectified by the action trigger.
  102593. ** So do not set the "may-abort" flag in this case.
  102594. **
  102595. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  102596. ** may-abort flag will eventually be set on this statement anyway
  102597. ** (when this function is called as part of processing the UPDATE
  102598. ** within the action trigger).
  102599. **
  102600. ** Note 2: At first glance it may seem like SQLite could simply omit
  102601. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  102602. ** applies. The trouble starts if the CASCADE or SET NULL action
  102603. ** trigger causes other triggers or action rules attached to the
  102604. ** child table to fire. In these cases the fk constraint counters
  102605. ** might be set incorrectly if any OP_FkCounter related scans are
  102606. ** omitted. */
  102607. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  102608. sqlite3MayAbort(pParse);
  102609. }
  102610. }
  102611. pItem->zName = 0;
  102612. sqlite3SrcListDelete(db, pSrc);
  102613. }
  102614. sqlite3DbFree(db, aiCol);
  102615. }
  102616. }
  102617. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  102618. /*
  102619. ** This function is called before generating code to update or delete a
  102620. ** row contained in table pTab.
  102621. */
  102622. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  102623. Parse *pParse, /* Parse context */
  102624. Table *pTab /* Table being modified */
  102625. ){
  102626. u32 mask = 0;
  102627. if( pParse->db->flags&SQLITE_ForeignKeys ){
  102628. FKey *p;
  102629. int i;
  102630. for(p=pTab->pFKey; p; p=p->pNextFrom){
  102631. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  102632. }
  102633. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  102634. Index *pIdx = 0;
  102635. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  102636. if( pIdx ){
  102637. for(i=0; i<pIdx->nKeyCol; i++){
  102638. assert( pIdx->aiColumn[i]>=0 );
  102639. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  102640. }
  102641. }
  102642. }
  102643. }
  102644. return mask;
  102645. }
  102646. /*
  102647. ** This function is called before generating code to update or delete a
  102648. ** row contained in table pTab. If the operation is a DELETE, then
  102649. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  102650. ** to an array of size N, where N is the number of columns in table pTab.
  102651. ** If the i'th column is not modified by the UPDATE, then the corresponding
  102652. ** entry in the aChange[] array is set to -1. If the column is modified,
  102653. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  102654. ** UPDATE statement modifies the rowid fields of the table.
  102655. **
  102656. ** If any foreign key processing will be required, this function returns
  102657. ** non-zero. If there is no foreign key related processing, this function
  102658. ** returns zero.
  102659. **
  102660. ** For an UPDATE, this function returns 2 if:
  102661. **
  102662. ** * There are any FKs for which pTab is the child and the parent table, or
  102663. ** * the UPDATE modifies one or more parent keys for which the action is
  102664. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  102665. **
  102666. ** Or, assuming some other foreign key processing is required, 1.
  102667. */
  102668. SQLITE_PRIVATE int sqlite3FkRequired(
  102669. Parse *pParse, /* Parse context */
  102670. Table *pTab, /* Table being modified */
  102671. int *aChange, /* Non-NULL for UPDATE operations */
  102672. int chngRowid /* True for UPDATE that affects rowid */
  102673. ){
  102674. int eRet = 0;
  102675. if( pParse->db->flags&SQLITE_ForeignKeys ){
  102676. if( !aChange ){
  102677. /* A DELETE operation. Foreign key processing is required if the
  102678. ** table in question is either the child or parent table for any
  102679. ** foreign key constraint. */
  102680. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  102681. }else{
  102682. /* This is an UPDATE. Foreign key processing is only required if the
  102683. ** operation modifies one or more child or parent key columns. */
  102684. FKey *p;
  102685. /* Check if any child key columns are being modified. */
  102686. for(p=pTab->pFKey; p; p=p->pNextFrom){
  102687. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  102688. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  102689. eRet = 1;
  102690. }
  102691. }
  102692. /* Check if any parent key columns are being modified. */
  102693. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  102694. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  102695. if( p->aAction[1]!=OE_None ) return 2;
  102696. eRet = 1;
  102697. }
  102698. }
  102699. }
  102700. }
  102701. return eRet;
  102702. }
  102703. /*
  102704. ** This function is called when an UPDATE or DELETE operation is being
  102705. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  102706. ** If the current operation is an UPDATE, then the pChanges parameter is
  102707. ** passed a pointer to the list of columns being modified. If it is a
  102708. ** DELETE, pChanges is passed a NULL pointer.
  102709. **
  102710. ** It returns a pointer to a Trigger structure containing a trigger
  102711. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  102712. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  102713. ** returned (these actions require no special handling by the triggers
  102714. ** sub-system, code for them is created by fkScanChildren()).
  102715. **
  102716. ** For example, if pFKey is the foreign key and pTab is table "p" in
  102717. ** the following schema:
  102718. **
  102719. ** CREATE TABLE p(pk PRIMARY KEY);
  102720. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  102721. **
  102722. ** then the returned trigger structure is equivalent to:
  102723. **
  102724. ** CREATE TRIGGER ... DELETE ON p BEGIN
  102725. ** DELETE FROM c WHERE ck = old.pk;
  102726. ** END;
  102727. **
  102728. ** The returned pointer is cached as part of the foreign key object. It
  102729. ** is eventually freed along with the rest of the foreign key object by
  102730. ** sqlite3FkDelete().
  102731. */
  102732. static Trigger *fkActionTrigger(
  102733. Parse *pParse, /* Parse context */
  102734. Table *pTab, /* Table being updated or deleted from */
  102735. FKey *pFKey, /* Foreign key to get action for */
  102736. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  102737. ){
  102738. sqlite3 *db = pParse->db; /* Database handle */
  102739. int action; /* One of OE_None, OE_Cascade etc. */
  102740. Trigger *pTrigger; /* Trigger definition to return */
  102741. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  102742. action = pFKey->aAction[iAction];
  102743. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  102744. return 0;
  102745. }
  102746. pTrigger = pFKey->apTrigger[iAction];
  102747. if( action!=OE_None && !pTrigger ){
  102748. char const *zFrom; /* Name of child table */
  102749. int nFrom; /* Length in bytes of zFrom */
  102750. Index *pIdx = 0; /* Parent key index for this FK */
  102751. int *aiCol = 0; /* child table cols -> parent key cols */
  102752. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  102753. Expr *pWhere = 0; /* WHERE clause of trigger step */
  102754. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  102755. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  102756. int i; /* Iterator variable */
  102757. Expr *pWhen = 0; /* WHEN clause for the trigger */
  102758. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  102759. assert( aiCol || pFKey->nCol==1 );
  102760. for(i=0; i<pFKey->nCol; i++){
  102761. Token tOld = { "old", 3 }; /* Literal "old" token */
  102762. Token tNew = { "new", 3 }; /* Literal "new" token */
  102763. Token tFromCol; /* Name of column in child table */
  102764. Token tToCol; /* Name of column in parent table */
  102765. int iFromCol; /* Idx of column in child table */
  102766. Expr *pEq; /* tFromCol = OLD.tToCol */
  102767. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  102768. assert( iFromCol>=0 );
  102769. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  102770. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  102771. sqlite3TokenInit(&tToCol,
  102772. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  102773. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  102774. /* Create the expression "OLD.zToCol = zFromCol". It is important
  102775. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  102776. ** that the affinity and collation sequence associated with the
  102777. ** parent table are used for the comparison. */
  102778. pEq = sqlite3PExpr(pParse, TK_EQ,
  102779. sqlite3PExpr(pParse, TK_DOT,
  102780. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  102781. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  102782. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  102783. );
  102784. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  102785. /* For ON UPDATE, construct the next term of the WHEN clause.
  102786. ** The final WHEN clause will be like this:
  102787. **
  102788. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  102789. */
  102790. if( pChanges ){
  102791. pEq = sqlite3PExpr(pParse, TK_IS,
  102792. sqlite3PExpr(pParse, TK_DOT,
  102793. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  102794. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  102795. sqlite3PExpr(pParse, TK_DOT,
  102796. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  102797. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  102798. );
  102799. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  102800. }
  102801. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  102802. Expr *pNew;
  102803. if( action==OE_Cascade ){
  102804. pNew = sqlite3PExpr(pParse, TK_DOT,
  102805. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  102806. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  102807. }else if( action==OE_SetDflt ){
  102808. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  102809. if( pDflt ){
  102810. pNew = sqlite3ExprDup(db, pDflt, 0);
  102811. }else{
  102812. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  102813. }
  102814. }else{
  102815. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  102816. }
  102817. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  102818. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  102819. }
  102820. }
  102821. sqlite3DbFree(db, aiCol);
  102822. zFrom = pFKey->pFrom->zName;
  102823. nFrom = sqlite3Strlen30(zFrom);
  102824. if( action==OE_Restrict ){
  102825. Token tFrom;
  102826. Expr *pRaise;
  102827. tFrom.z = zFrom;
  102828. tFrom.n = nFrom;
  102829. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  102830. if( pRaise ){
  102831. pRaise->affinity = OE_Abort;
  102832. }
  102833. pSelect = sqlite3SelectNew(pParse,
  102834. sqlite3ExprListAppend(pParse, 0, pRaise),
  102835. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  102836. pWhere,
  102837. 0, 0, 0, 0, 0, 0
  102838. );
  102839. pWhere = 0;
  102840. }
  102841. /* Disable lookaside memory allocation */
  102842. db->lookaside.bDisable++;
  102843. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  102844. sizeof(Trigger) + /* struct Trigger */
  102845. sizeof(TriggerStep) + /* Single step in trigger program */
  102846. nFrom + 1 /* Space for pStep->zTarget */
  102847. );
  102848. if( pTrigger ){
  102849. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  102850. pStep->zTarget = (char *)&pStep[1];
  102851. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  102852. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  102853. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  102854. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  102855. if( pWhen ){
  102856. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  102857. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  102858. }
  102859. }
  102860. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  102861. db->lookaside.bDisable--;
  102862. sqlite3ExprDelete(db, pWhere);
  102863. sqlite3ExprDelete(db, pWhen);
  102864. sqlite3ExprListDelete(db, pList);
  102865. sqlite3SelectDelete(db, pSelect);
  102866. if( db->mallocFailed==1 ){
  102867. fkTriggerDelete(db, pTrigger);
  102868. return 0;
  102869. }
  102870. assert( pStep!=0 );
  102871. switch( action ){
  102872. case OE_Restrict:
  102873. pStep->op = TK_SELECT;
  102874. break;
  102875. case OE_Cascade:
  102876. if( !pChanges ){
  102877. pStep->op = TK_DELETE;
  102878. break;
  102879. }
  102880. default:
  102881. pStep->op = TK_UPDATE;
  102882. }
  102883. pStep->pTrig = pTrigger;
  102884. pTrigger->pSchema = pTab->pSchema;
  102885. pTrigger->pTabSchema = pTab->pSchema;
  102886. pFKey->apTrigger[iAction] = pTrigger;
  102887. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  102888. }
  102889. return pTrigger;
  102890. }
  102891. /*
  102892. ** This function is called when deleting or updating a row to implement
  102893. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  102894. */
  102895. SQLITE_PRIVATE void sqlite3FkActions(
  102896. Parse *pParse, /* Parse context */
  102897. Table *pTab, /* Table being updated or deleted from */
  102898. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  102899. int regOld, /* Address of array containing old row */
  102900. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  102901. int bChngRowid /* True if rowid is UPDATEd */
  102902. ){
  102903. /* If foreign-key support is enabled, iterate through all FKs that
  102904. ** refer to table pTab. If there is an action associated with the FK
  102905. ** for this operation (either update or delete), invoke the associated
  102906. ** trigger sub-program. */
  102907. if( pParse->db->flags&SQLITE_ForeignKeys ){
  102908. FKey *pFKey; /* Iterator variable */
  102909. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  102910. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  102911. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  102912. if( pAct ){
  102913. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  102914. }
  102915. }
  102916. }
  102917. }
  102918. }
  102919. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  102920. /*
  102921. ** Free all memory associated with foreign key definitions attached to
  102922. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  102923. ** hash table.
  102924. */
  102925. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  102926. FKey *pFKey; /* Iterator variable */
  102927. FKey *pNext; /* Copy of pFKey->pNextFrom */
  102928. assert( db==0 || IsVirtual(pTab)
  102929. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  102930. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  102931. /* Remove the FK from the fkeyHash hash table. */
  102932. if( !db || db->pnBytesFreed==0 ){
  102933. if( pFKey->pPrevTo ){
  102934. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  102935. }else{
  102936. void *p = (void *)pFKey->pNextTo;
  102937. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  102938. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  102939. }
  102940. if( pFKey->pNextTo ){
  102941. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  102942. }
  102943. }
  102944. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  102945. ** classified as either immediate or deferred.
  102946. */
  102947. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  102948. /* Delete any triggers created to implement actions for this FK. */
  102949. #ifndef SQLITE_OMIT_TRIGGER
  102950. fkTriggerDelete(db, pFKey->apTrigger[0]);
  102951. fkTriggerDelete(db, pFKey->apTrigger[1]);
  102952. #endif
  102953. pNext = pFKey->pNextFrom;
  102954. sqlite3DbFree(db, pFKey);
  102955. }
  102956. }
  102957. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  102958. /************** End of fkey.c ************************************************/
  102959. /************** Begin file insert.c ******************************************/
  102960. /*
  102961. ** 2001 September 15
  102962. **
  102963. ** The author disclaims copyright to this source code. In place of
  102964. ** a legal notice, here is a blessing:
  102965. **
  102966. ** May you do good and not evil.
  102967. ** May you find forgiveness for yourself and forgive others.
  102968. ** May you share freely, never taking more than you give.
  102969. **
  102970. *************************************************************************
  102971. ** This file contains C code routines that are called by the parser
  102972. ** to handle INSERT statements in SQLite.
  102973. */
  102974. /* #include "sqliteInt.h" */
  102975. /*
  102976. ** Generate code that will
  102977. **
  102978. ** (1) acquire a lock for table pTab then
  102979. ** (2) open pTab as cursor iCur.
  102980. **
  102981. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  102982. ** for that table that is actually opened.
  102983. */
  102984. SQLITE_PRIVATE void sqlite3OpenTable(
  102985. Parse *pParse, /* Generate code into this VDBE */
  102986. int iCur, /* The cursor number of the table */
  102987. int iDb, /* The database index in sqlite3.aDb[] */
  102988. Table *pTab, /* The table to be opened */
  102989. int opcode /* OP_OpenRead or OP_OpenWrite */
  102990. ){
  102991. Vdbe *v;
  102992. assert( !IsVirtual(pTab) );
  102993. v = sqlite3GetVdbe(pParse);
  102994. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  102995. sqlite3TableLock(pParse, iDb, pTab->tnum,
  102996. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  102997. if( HasRowid(pTab) ){
  102998. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  102999. VdbeComment((v, "%s", pTab->zName));
  103000. }else{
  103001. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  103002. assert( pPk!=0 );
  103003. assert( pPk->tnum==pTab->tnum );
  103004. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  103005. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  103006. VdbeComment((v, "%s", pTab->zName));
  103007. }
  103008. }
  103009. /*
  103010. ** Return a pointer to the column affinity string associated with index
  103011. ** pIdx. A column affinity string has one character for each column in
  103012. ** the table, according to the affinity of the column:
  103013. **
  103014. ** Character Column affinity
  103015. ** ------------------------------
  103016. ** 'A' BLOB
  103017. ** 'B' TEXT
  103018. ** 'C' NUMERIC
  103019. ** 'D' INTEGER
  103020. ** 'F' REAL
  103021. **
  103022. ** An extra 'D' is appended to the end of the string to cover the
  103023. ** rowid that appears as the last column in every index.
  103024. **
  103025. ** Memory for the buffer containing the column index affinity string
  103026. ** is managed along with the rest of the Index structure. It will be
  103027. ** released when sqlite3DeleteIndex() is called.
  103028. */
  103029. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  103030. if( !pIdx->zColAff ){
  103031. /* The first time a column affinity string for a particular index is
  103032. ** required, it is allocated and populated here. It is then stored as
  103033. ** a member of the Index structure for subsequent use.
  103034. **
  103035. ** The column affinity string will eventually be deleted by
  103036. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  103037. ** up.
  103038. */
  103039. int n;
  103040. Table *pTab = pIdx->pTable;
  103041. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  103042. if( !pIdx->zColAff ){
  103043. sqlite3OomFault(db);
  103044. return 0;
  103045. }
  103046. for(n=0; n<pIdx->nColumn; n++){
  103047. i16 x = pIdx->aiColumn[n];
  103048. if( x>=0 ){
  103049. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  103050. }else if( x==XN_ROWID ){
  103051. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  103052. }else{
  103053. char aff;
  103054. assert( x==XN_EXPR );
  103055. assert( pIdx->aColExpr!=0 );
  103056. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  103057. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  103058. pIdx->zColAff[n] = aff;
  103059. }
  103060. }
  103061. pIdx->zColAff[n] = 0;
  103062. }
  103063. return pIdx->zColAff;
  103064. }
  103065. /*
  103066. ** Compute the affinity string for table pTab, if it has not already been
  103067. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  103068. **
  103069. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  103070. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  103071. ** for register iReg and following. Or if affinities exists and iReg==0,
  103072. ** then just set the P4 operand of the previous opcode (which should be
  103073. ** an OP_MakeRecord) to the affinity string.
  103074. **
  103075. ** A column affinity string has one character per column:
  103076. **
  103077. ** Character Column affinity
  103078. ** ------------------------------
  103079. ** 'A' BLOB
  103080. ** 'B' TEXT
  103081. ** 'C' NUMERIC
  103082. ** 'D' INTEGER
  103083. ** 'E' REAL
  103084. */
  103085. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  103086. int i;
  103087. char *zColAff = pTab->zColAff;
  103088. if( zColAff==0 ){
  103089. sqlite3 *db = sqlite3VdbeDb(v);
  103090. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  103091. if( !zColAff ){
  103092. sqlite3OomFault(db);
  103093. return;
  103094. }
  103095. for(i=0; i<pTab->nCol; i++){
  103096. zColAff[i] = pTab->aCol[i].affinity;
  103097. }
  103098. do{
  103099. zColAff[i--] = 0;
  103100. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  103101. pTab->zColAff = zColAff;
  103102. }
  103103. i = sqlite3Strlen30(zColAff);
  103104. if( i ){
  103105. if( iReg ){
  103106. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  103107. }else{
  103108. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  103109. }
  103110. }
  103111. }
  103112. /*
  103113. ** Return non-zero if the table pTab in database iDb or any of its indices
  103114. ** have been opened at any point in the VDBE program. This is used to see if
  103115. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  103116. ** run without using a temporary table for the results of the SELECT.
  103117. */
  103118. static int readsTable(Parse *p, int iDb, Table *pTab){
  103119. Vdbe *v = sqlite3GetVdbe(p);
  103120. int i;
  103121. int iEnd = sqlite3VdbeCurrentAddr(v);
  103122. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103123. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  103124. #endif
  103125. for(i=1; i<iEnd; i++){
  103126. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  103127. assert( pOp!=0 );
  103128. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  103129. Index *pIndex;
  103130. int tnum = pOp->p2;
  103131. if( tnum==pTab->tnum ){
  103132. return 1;
  103133. }
  103134. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  103135. if( tnum==pIndex->tnum ){
  103136. return 1;
  103137. }
  103138. }
  103139. }
  103140. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103141. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  103142. assert( pOp->p4.pVtab!=0 );
  103143. assert( pOp->p4type==P4_VTAB );
  103144. return 1;
  103145. }
  103146. #endif
  103147. }
  103148. return 0;
  103149. }
  103150. #ifndef SQLITE_OMIT_AUTOINCREMENT
  103151. /*
  103152. ** Locate or create an AutoincInfo structure associated with table pTab
  103153. ** which is in database iDb. Return the register number for the register
  103154. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  103155. ** table. (Also return zero when doing a VACUUM since we do not want to
  103156. ** update the AUTOINCREMENT counters during a VACUUM.)
  103157. **
  103158. ** There is at most one AutoincInfo structure per table even if the
  103159. ** same table is autoincremented multiple times due to inserts within
  103160. ** triggers. A new AutoincInfo structure is created if this is the
  103161. ** first use of table pTab. On 2nd and subsequent uses, the original
  103162. ** AutoincInfo structure is used.
  103163. **
  103164. ** Three memory locations are allocated:
  103165. **
  103166. ** (1) Register to hold the name of the pTab table.
  103167. ** (2) Register to hold the maximum ROWID of pTab.
  103168. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  103169. **
  103170. ** The 2nd register is the one that is returned. That is all the
  103171. ** insert routine needs to know about.
  103172. */
  103173. static int autoIncBegin(
  103174. Parse *pParse, /* Parsing context */
  103175. int iDb, /* Index of the database holding pTab */
  103176. Table *pTab /* The table we are writing to */
  103177. ){
  103178. int memId = 0; /* Register holding maximum rowid */
  103179. if( (pTab->tabFlags & TF_Autoincrement)!=0
  103180. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  103181. ){
  103182. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103183. AutoincInfo *pInfo;
  103184. pInfo = pToplevel->pAinc;
  103185. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  103186. if( pInfo==0 ){
  103187. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  103188. if( pInfo==0 ) return 0;
  103189. pInfo->pNext = pToplevel->pAinc;
  103190. pToplevel->pAinc = pInfo;
  103191. pInfo->pTab = pTab;
  103192. pInfo->iDb = iDb;
  103193. pToplevel->nMem++; /* Register to hold name of table */
  103194. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  103195. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  103196. }
  103197. memId = pInfo->regCtr;
  103198. }
  103199. return memId;
  103200. }
  103201. /*
  103202. ** This routine generates code that will initialize all of the
  103203. ** register used by the autoincrement tracker.
  103204. */
  103205. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  103206. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  103207. sqlite3 *db = pParse->db; /* The database connection */
  103208. Db *pDb; /* Database only autoinc table */
  103209. int memId; /* Register holding max rowid */
  103210. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  103211. /* This routine is never called during trigger-generation. It is
  103212. ** only called from the top-level */
  103213. assert( pParse->pTriggerTab==0 );
  103214. assert( sqlite3IsToplevel(pParse) );
  103215. assert( v ); /* We failed long ago if this is not so */
  103216. for(p = pParse->pAinc; p; p = p->pNext){
  103217. static const int iLn = VDBE_OFFSET_LINENO(2);
  103218. static const VdbeOpList autoInc[] = {
  103219. /* 0 */ {OP_Null, 0, 0, 0},
  103220. /* 1 */ {OP_Rewind, 0, 9, 0},
  103221. /* 2 */ {OP_Column, 0, 0, 0},
  103222. /* 3 */ {OP_Ne, 0, 7, 0},
  103223. /* 4 */ {OP_Rowid, 0, 0, 0},
  103224. /* 5 */ {OP_Column, 0, 1, 0},
  103225. /* 6 */ {OP_Goto, 0, 9, 0},
  103226. /* 7 */ {OP_Next, 0, 2, 0},
  103227. /* 8 */ {OP_Integer, 0, 0, 0},
  103228. /* 9 */ {OP_Close, 0, 0, 0}
  103229. };
  103230. VdbeOp *aOp;
  103231. pDb = &db->aDb[p->iDb];
  103232. memId = p->regCtr;
  103233. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  103234. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  103235. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  103236. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  103237. if( aOp==0 ) break;
  103238. aOp[0].p2 = memId;
  103239. aOp[0].p3 = memId+1;
  103240. aOp[2].p3 = memId;
  103241. aOp[3].p1 = memId-1;
  103242. aOp[3].p3 = memId;
  103243. aOp[3].p5 = SQLITE_JUMPIFNULL;
  103244. aOp[4].p2 = memId+1;
  103245. aOp[5].p3 = memId;
  103246. aOp[8].p2 = memId;
  103247. }
  103248. }
  103249. /*
  103250. ** Update the maximum rowid for an autoincrement calculation.
  103251. **
  103252. ** This routine should be called when the regRowid register holds a
  103253. ** new rowid that is about to be inserted. If that new rowid is
  103254. ** larger than the maximum rowid in the memId memory cell, then the
  103255. ** memory cell is updated.
  103256. */
  103257. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  103258. if( memId>0 ){
  103259. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  103260. }
  103261. }
  103262. /*
  103263. ** This routine generates the code needed to write autoincrement
  103264. ** maximum rowid values back into the sqlite_sequence register.
  103265. ** Every statement that might do an INSERT into an autoincrement
  103266. ** table (either directly or through triggers) needs to call this
  103267. ** routine just before the "exit" code.
  103268. */
  103269. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  103270. AutoincInfo *p;
  103271. Vdbe *v = pParse->pVdbe;
  103272. sqlite3 *db = pParse->db;
  103273. assert( v );
  103274. for(p = pParse->pAinc; p; p = p->pNext){
  103275. static const int iLn = VDBE_OFFSET_LINENO(2);
  103276. static const VdbeOpList autoIncEnd[] = {
  103277. /* 0 */ {OP_NotNull, 0, 2, 0},
  103278. /* 1 */ {OP_NewRowid, 0, 0, 0},
  103279. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  103280. /* 3 */ {OP_Insert, 0, 0, 0},
  103281. /* 4 */ {OP_Close, 0, 0, 0}
  103282. };
  103283. VdbeOp *aOp;
  103284. Db *pDb = &db->aDb[p->iDb];
  103285. int iRec;
  103286. int memId = p->regCtr;
  103287. iRec = sqlite3GetTempReg(pParse);
  103288. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  103289. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  103290. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  103291. if( aOp==0 ) break;
  103292. aOp[0].p1 = memId+1;
  103293. aOp[1].p2 = memId+1;
  103294. aOp[2].p1 = memId-1;
  103295. aOp[2].p3 = iRec;
  103296. aOp[3].p2 = iRec;
  103297. aOp[3].p3 = memId+1;
  103298. aOp[3].p5 = OPFLAG_APPEND;
  103299. sqlite3ReleaseTempReg(pParse, iRec);
  103300. }
  103301. }
  103302. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  103303. if( pParse->pAinc ) autoIncrementEnd(pParse);
  103304. }
  103305. #else
  103306. /*
  103307. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  103308. ** above are all no-ops
  103309. */
  103310. # define autoIncBegin(A,B,C) (0)
  103311. # define autoIncStep(A,B,C)
  103312. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  103313. /* Forward declaration */
  103314. static int xferOptimization(
  103315. Parse *pParse, /* Parser context */
  103316. Table *pDest, /* The table we are inserting into */
  103317. Select *pSelect, /* A SELECT statement to use as the data source */
  103318. int onError, /* How to handle constraint errors */
  103319. int iDbDest /* The database of pDest */
  103320. );
  103321. /*
  103322. ** This routine is called to handle SQL of the following forms:
  103323. **
  103324. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  103325. ** insert into TABLE (IDLIST) select
  103326. ** insert into TABLE (IDLIST) default values
  103327. **
  103328. ** The IDLIST following the table name is always optional. If omitted,
  103329. ** then a list of all (non-hidden) columns for the table is substituted.
  103330. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  103331. ** is omitted.
  103332. **
  103333. ** For the pSelect parameter holds the values to be inserted for the
  103334. ** first two forms shown above. A VALUES clause is really just short-hand
  103335. ** for a SELECT statement that omits the FROM clause and everything else
  103336. ** that follows. If the pSelect parameter is NULL, that means that the
  103337. ** DEFAULT VALUES form of the INSERT statement is intended.
  103338. **
  103339. ** The code generated follows one of four templates. For a simple
  103340. ** insert with data coming from a single-row VALUES clause, the code executes
  103341. ** once straight down through. Pseudo-code follows (we call this
  103342. ** the "1st template"):
  103343. **
  103344. ** open write cursor to <table> and its indices
  103345. ** put VALUES clause expressions into registers
  103346. ** write the resulting record into <table>
  103347. ** cleanup
  103348. **
  103349. ** The three remaining templates assume the statement is of the form
  103350. **
  103351. ** INSERT INTO <table> SELECT ...
  103352. **
  103353. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  103354. ** in other words if the SELECT pulls all columns from a single table
  103355. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  103356. ** if <table2> and <table1> are distinct tables but have identical
  103357. ** schemas, including all the same indices, then a special optimization
  103358. ** is invoked that copies raw records from <table2> over to <table1>.
  103359. ** See the xferOptimization() function for the implementation of this
  103360. ** template. This is the 2nd template.
  103361. **
  103362. ** open a write cursor to <table>
  103363. ** open read cursor on <table2>
  103364. ** transfer all records in <table2> over to <table>
  103365. ** close cursors
  103366. ** foreach index on <table>
  103367. ** open a write cursor on the <table> index
  103368. ** open a read cursor on the corresponding <table2> index
  103369. ** transfer all records from the read to the write cursors
  103370. ** close cursors
  103371. ** end foreach
  103372. **
  103373. ** The 3rd template is for when the second template does not apply
  103374. ** and the SELECT clause does not read from <table> at any time.
  103375. ** The generated code follows this template:
  103376. **
  103377. ** X <- A
  103378. ** goto B
  103379. ** A: setup for the SELECT
  103380. ** loop over the rows in the SELECT
  103381. ** load values into registers R..R+n
  103382. ** yield X
  103383. ** end loop
  103384. ** cleanup after the SELECT
  103385. ** end-coroutine X
  103386. ** B: open write cursor to <table> and its indices
  103387. ** C: yield X, at EOF goto D
  103388. ** insert the select result into <table> from R..R+n
  103389. ** goto C
  103390. ** D: cleanup
  103391. **
  103392. ** The 4th template is used if the insert statement takes its
  103393. ** values from a SELECT but the data is being inserted into a table
  103394. ** that is also read as part of the SELECT. In the third form,
  103395. ** we have to use an intermediate table to store the results of
  103396. ** the select. The template is like this:
  103397. **
  103398. ** X <- A
  103399. ** goto B
  103400. ** A: setup for the SELECT
  103401. ** loop over the tables in the SELECT
  103402. ** load value into register R..R+n
  103403. ** yield X
  103404. ** end loop
  103405. ** cleanup after the SELECT
  103406. ** end co-routine R
  103407. ** B: open temp table
  103408. ** L: yield X, at EOF goto M
  103409. ** insert row from R..R+n into temp table
  103410. ** goto L
  103411. ** M: open write cursor to <table> and its indices
  103412. ** rewind temp table
  103413. ** C: loop over rows of intermediate table
  103414. ** transfer values form intermediate table into <table>
  103415. ** end loop
  103416. ** D: cleanup
  103417. */
  103418. SQLITE_PRIVATE void sqlite3Insert(
  103419. Parse *pParse, /* Parser context */
  103420. SrcList *pTabList, /* Name of table into which we are inserting */
  103421. Select *pSelect, /* A SELECT statement to use as the data source */
  103422. IdList *pColumn, /* Column names corresponding to IDLIST. */
  103423. int onError /* How to handle constraint errors */
  103424. ){
  103425. sqlite3 *db; /* The main database structure */
  103426. Table *pTab; /* The table to insert into. aka TABLE */
  103427. int i, j; /* Loop counters */
  103428. Vdbe *v; /* Generate code into this virtual machine */
  103429. Index *pIdx; /* For looping over indices of the table */
  103430. int nColumn; /* Number of columns in the data */
  103431. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  103432. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  103433. int iIdxCur = 0; /* First index cursor */
  103434. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  103435. int endOfLoop; /* Label for the end of the insertion loop */
  103436. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  103437. int addrInsTop = 0; /* Jump to label "D" */
  103438. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  103439. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  103440. int iDb; /* Index of database holding TABLE */
  103441. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  103442. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  103443. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  103444. u8 bIdListInOrder; /* True if IDLIST is in table order */
  103445. ExprList *pList = 0; /* List of VALUES() to be inserted */
  103446. /* Register allocations */
  103447. int regFromSelect = 0;/* Base register for data coming from SELECT */
  103448. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  103449. int regRowCount = 0; /* Memory cell used for the row counter */
  103450. int regIns; /* Block of regs holding rowid+data being inserted */
  103451. int regRowid; /* registers holding insert rowid */
  103452. int regData; /* register holding first column to insert */
  103453. int *aRegIdx = 0; /* One register allocated to each index */
  103454. #ifndef SQLITE_OMIT_TRIGGER
  103455. int isView; /* True if attempting to insert into a view */
  103456. Trigger *pTrigger; /* List of triggers on pTab, if required */
  103457. int tmask; /* Mask of trigger times */
  103458. #endif
  103459. db = pParse->db;
  103460. if( pParse->nErr || db->mallocFailed ){
  103461. goto insert_cleanup;
  103462. }
  103463. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  103464. /* If the Select object is really just a simple VALUES() list with a
  103465. ** single row (the common case) then keep that one row of values
  103466. ** and discard the other (unused) parts of the pSelect object
  103467. */
  103468. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  103469. pList = pSelect->pEList;
  103470. pSelect->pEList = 0;
  103471. sqlite3SelectDelete(db, pSelect);
  103472. pSelect = 0;
  103473. }
  103474. /* Locate the table into which we will be inserting new information.
  103475. */
  103476. assert( pTabList->nSrc==1 );
  103477. pTab = sqlite3SrcListLookup(pParse, pTabList);
  103478. if( pTab==0 ){
  103479. goto insert_cleanup;
  103480. }
  103481. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103482. assert( iDb<db->nDb );
  103483. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  103484. db->aDb[iDb].zDbSName) ){
  103485. goto insert_cleanup;
  103486. }
  103487. withoutRowid = !HasRowid(pTab);
  103488. /* Figure out if we have any triggers and if the table being
  103489. ** inserted into is a view
  103490. */
  103491. #ifndef SQLITE_OMIT_TRIGGER
  103492. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  103493. isView = pTab->pSelect!=0;
  103494. #else
  103495. # define pTrigger 0
  103496. # define tmask 0
  103497. # define isView 0
  103498. #endif
  103499. #ifdef SQLITE_OMIT_VIEW
  103500. # undef isView
  103501. # define isView 0
  103502. #endif
  103503. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  103504. /* If pTab is really a view, make sure it has been initialized.
  103505. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  103506. */
  103507. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  103508. goto insert_cleanup;
  103509. }
  103510. /* Cannot insert into a read-only table.
  103511. */
  103512. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  103513. goto insert_cleanup;
  103514. }
  103515. /* Allocate a VDBE
  103516. */
  103517. v = sqlite3GetVdbe(pParse);
  103518. if( v==0 ) goto insert_cleanup;
  103519. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  103520. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  103521. #ifndef SQLITE_OMIT_XFER_OPT
  103522. /* If the statement is of the form
  103523. **
  103524. ** INSERT INTO <table1> SELECT * FROM <table2>;
  103525. **
  103526. ** Then special optimizations can be applied that make the transfer
  103527. ** very fast and which reduce fragmentation of indices.
  103528. **
  103529. ** This is the 2nd template.
  103530. */
  103531. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  103532. assert( !pTrigger );
  103533. assert( pList==0 );
  103534. goto insert_end;
  103535. }
  103536. #endif /* SQLITE_OMIT_XFER_OPT */
  103537. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  103538. ** sqlite_sequence table and store it in memory cell regAutoinc.
  103539. */
  103540. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  103541. /* Allocate registers for holding the rowid of the new row,
  103542. ** the content of the new row, and the assembled row record.
  103543. */
  103544. regRowid = regIns = pParse->nMem+1;
  103545. pParse->nMem += pTab->nCol + 1;
  103546. if( IsVirtual(pTab) ){
  103547. regRowid++;
  103548. pParse->nMem++;
  103549. }
  103550. regData = regRowid+1;
  103551. /* If the INSERT statement included an IDLIST term, then make sure
  103552. ** all elements of the IDLIST really are columns of the table and
  103553. ** remember the column indices.
  103554. **
  103555. ** If the table has an INTEGER PRIMARY KEY column and that column
  103556. ** is named in the IDLIST, then record in the ipkColumn variable
  103557. ** the index into IDLIST of the primary key column. ipkColumn is
  103558. ** the index of the primary key as it appears in IDLIST, not as
  103559. ** is appears in the original table. (The index of the INTEGER
  103560. ** PRIMARY KEY in the original table is pTab->iPKey.)
  103561. */
  103562. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  103563. if( pColumn ){
  103564. for(i=0; i<pColumn->nId; i++){
  103565. pColumn->a[i].idx = -1;
  103566. }
  103567. for(i=0; i<pColumn->nId; i++){
  103568. for(j=0; j<pTab->nCol; j++){
  103569. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  103570. pColumn->a[i].idx = j;
  103571. if( i!=j ) bIdListInOrder = 0;
  103572. if( j==pTab->iPKey ){
  103573. ipkColumn = i; assert( !withoutRowid );
  103574. }
  103575. break;
  103576. }
  103577. }
  103578. if( j>=pTab->nCol ){
  103579. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  103580. ipkColumn = i;
  103581. bIdListInOrder = 0;
  103582. }else{
  103583. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  103584. pTabList, 0, pColumn->a[i].zName);
  103585. pParse->checkSchema = 1;
  103586. goto insert_cleanup;
  103587. }
  103588. }
  103589. }
  103590. }
  103591. /* Figure out how many columns of data are supplied. If the data
  103592. ** is coming from a SELECT statement, then generate a co-routine that
  103593. ** produces a single row of the SELECT on each invocation. The
  103594. ** co-routine is the common header to the 3rd and 4th templates.
  103595. */
  103596. if( pSelect ){
  103597. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  103598. ** Generate a co-routine to run the SELECT. */
  103599. int regYield; /* Register holding co-routine entry-point */
  103600. int addrTop; /* Top of the co-routine */
  103601. int rc; /* Result code */
  103602. regYield = ++pParse->nMem;
  103603. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  103604. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  103605. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  103606. dest.iSdst = bIdListInOrder ? regData : 0;
  103607. dest.nSdst = pTab->nCol;
  103608. rc = sqlite3Select(pParse, pSelect, &dest);
  103609. regFromSelect = dest.iSdst;
  103610. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  103611. sqlite3VdbeEndCoroutine(v, regYield);
  103612. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  103613. assert( pSelect->pEList );
  103614. nColumn = pSelect->pEList->nExpr;
  103615. /* Set useTempTable to TRUE if the result of the SELECT statement
  103616. ** should be written into a temporary table (template 4). Set to
  103617. ** FALSE if each output row of the SELECT can be written directly into
  103618. ** the destination table (template 3).
  103619. **
  103620. ** A temp table must be used if the table being updated is also one
  103621. ** of the tables being read by the SELECT statement. Also use a
  103622. ** temp table in the case of row triggers.
  103623. */
  103624. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  103625. useTempTable = 1;
  103626. }
  103627. if( useTempTable ){
  103628. /* Invoke the coroutine to extract information from the SELECT
  103629. ** and add it to a transient table srcTab. The code generated
  103630. ** here is from the 4th template:
  103631. **
  103632. ** B: open temp table
  103633. ** L: yield X, goto M at EOF
  103634. ** insert row from R..R+n into temp table
  103635. ** goto L
  103636. ** M: ...
  103637. */
  103638. int regRec; /* Register to hold packed record */
  103639. int regTempRowid; /* Register to hold temp table ROWID */
  103640. int addrL; /* Label "L" */
  103641. srcTab = pParse->nTab++;
  103642. regRec = sqlite3GetTempReg(pParse);
  103643. regTempRowid = sqlite3GetTempReg(pParse);
  103644. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  103645. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  103646. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  103647. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  103648. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  103649. sqlite3VdbeGoto(v, addrL);
  103650. sqlite3VdbeJumpHere(v, addrL);
  103651. sqlite3ReleaseTempReg(pParse, regRec);
  103652. sqlite3ReleaseTempReg(pParse, regTempRowid);
  103653. }
  103654. }else{
  103655. /* This is the case if the data for the INSERT is coming from a
  103656. ** single-row VALUES clause
  103657. */
  103658. NameContext sNC;
  103659. memset(&sNC, 0, sizeof(sNC));
  103660. sNC.pParse = pParse;
  103661. srcTab = -1;
  103662. assert( useTempTable==0 );
  103663. if( pList ){
  103664. nColumn = pList->nExpr;
  103665. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  103666. goto insert_cleanup;
  103667. }
  103668. }else{
  103669. nColumn = 0;
  103670. }
  103671. }
  103672. /* If there is no IDLIST term but the table has an integer primary
  103673. ** key, the set the ipkColumn variable to the integer primary key
  103674. ** column index in the original table definition.
  103675. */
  103676. if( pColumn==0 && nColumn>0 ){
  103677. ipkColumn = pTab->iPKey;
  103678. }
  103679. /* Make sure the number of columns in the source data matches the number
  103680. ** of columns to be inserted into the table.
  103681. */
  103682. for(i=0; i<pTab->nCol; i++){
  103683. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  103684. }
  103685. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  103686. sqlite3ErrorMsg(pParse,
  103687. "table %S has %d columns but %d values were supplied",
  103688. pTabList, 0, pTab->nCol-nHidden, nColumn);
  103689. goto insert_cleanup;
  103690. }
  103691. if( pColumn!=0 && nColumn!=pColumn->nId ){
  103692. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  103693. goto insert_cleanup;
  103694. }
  103695. /* Initialize the count of rows to be inserted
  103696. */
  103697. if( db->flags & SQLITE_CountRows ){
  103698. regRowCount = ++pParse->nMem;
  103699. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  103700. }
  103701. /* If this is not a view, open the table and and all indices */
  103702. if( !isView ){
  103703. int nIdx;
  103704. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  103705. &iDataCur, &iIdxCur);
  103706. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  103707. if( aRegIdx==0 ){
  103708. goto insert_cleanup;
  103709. }
  103710. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  103711. assert( pIdx );
  103712. aRegIdx[i] = ++pParse->nMem;
  103713. pParse->nMem += pIdx->nColumn;
  103714. }
  103715. }
  103716. /* This is the top of the main insertion loop */
  103717. if( useTempTable ){
  103718. /* This block codes the top of loop only. The complete loop is the
  103719. ** following pseudocode (template 4):
  103720. **
  103721. ** rewind temp table, if empty goto D
  103722. ** C: loop over rows of intermediate table
  103723. ** transfer values form intermediate table into <table>
  103724. ** end loop
  103725. ** D: ...
  103726. */
  103727. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  103728. addrCont = sqlite3VdbeCurrentAddr(v);
  103729. }else if( pSelect ){
  103730. /* This block codes the top of loop only. The complete loop is the
  103731. ** following pseudocode (template 3):
  103732. **
  103733. ** C: yield X, at EOF goto D
  103734. ** insert the select result into <table> from R..R+n
  103735. ** goto C
  103736. ** D: ...
  103737. */
  103738. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  103739. VdbeCoverage(v);
  103740. }
  103741. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  103742. */
  103743. endOfLoop = sqlite3VdbeMakeLabel(v);
  103744. if( tmask & TRIGGER_BEFORE ){
  103745. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  103746. /* build the NEW.* reference row. Note that if there is an INTEGER
  103747. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  103748. ** translated into a unique ID for the row. But on a BEFORE trigger,
  103749. ** we do not know what the unique ID will be (because the insert has
  103750. ** not happened yet) so we substitute a rowid of -1
  103751. */
  103752. if( ipkColumn<0 ){
  103753. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  103754. }else{
  103755. int addr1;
  103756. assert( !withoutRowid );
  103757. if( useTempTable ){
  103758. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  103759. }else{
  103760. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  103761. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  103762. }
  103763. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  103764. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  103765. sqlite3VdbeJumpHere(v, addr1);
  103766. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  103767. }
  103768. /* Cannot have triggers on a virtual table. If it were possible,
  103769. ** this block would have to account for hidden column.
  103770. */
  103771. assert( !IsVirtual(pTab) );
  103772. /* Create the new column data
  103773. */
  103774. for(i=j=0; i<pTab->nCol; i++){
  103775. if( pColumn ){
  103776. for(j=0; j<pColumn->nId; j++){
  103777. if( pColumn->a[j].idx==i ) break;
  103778. }
  103779. }
  103780. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  103781. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  103782. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  103783. }else if( useTempTable ){
  103784. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  103785. }else{
  103786. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  103787. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  103788. }
  103789. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  103790. }
  103791. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  103792. ** do not attempt any conversions before assembling the record.
  103793. ** If this is a real table, attempt conversions as required by the
  103794. ** table column affinities.
  103795. */
  103796. if( !isView ){
  103797. sqlite3TableAffinity(v, pTab, regCols+1);
  103798. }
  103799. /* Fire BEFORE or INSTEAD OF triggers */
  103800. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  103801. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  103802. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  103803. }
  103804. /* Compute the content of the next row to insert into a range of
  103805. ** registers beginning at regIns.
  103806. */
  103807. if( !isView ){
  103808. if( IsVirtual(pTab) ){
  103809. /* The row that the VUpdate opcode will delete: none */
  103810. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  103811. }
  103812. if( ipkColumn>=0 ){
  103813. if( useTempTable ){
  103814. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  103815. }else if( pSelect ){
  103816. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  103817. }else{
  103818. VdbeOp *pOp;
  103819. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  103820. pOp = sqlite3VdbeGetOp(v, -1);
  103821. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  103822. appendFlag = 1;
  103823. pOp->opcode = OP_NewRowid;
  103824. pOp->p1 = iDataCur;
  103825. pOp->p2 = regRowid;
  103826. pOp->p3 = regAutoinc;
  103827. }
  103828. }
  103829. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  103830. ** to generate a unique primary key value.
  103831. */
  103832. if( !appendFlag ){
  103833. int addr1;
  103834. if( !IsVirtual(pTab) ){
  103835. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  103836. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  103837. sqlite3VdbeJumpHere(v, addr1);
  103838. }else{
  103839. addr1 = sqlite3VdbeCurrentAddr(v);
  103840. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  103841. }
  103842. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  103843. }
  103844. }else if( IsVirtual(pTab) || withoutRowid ){
  103845. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  103846. }else{
  103847. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  103848. appendFlag = 1;
  103849. }
  103850. autoIncStep(pParse, regAutoinc, regRowid);
  103851. /* Compute data for all columns of the new entry, beginning
  103852. ** with the first column.
  103853. */
  103854. nHidden = 0;
  103855. for(i=0; i<pTab->nCol; i++){
  103856. int iRegStore = regRowid+1+i;
  103857. if( i==pTab->iPKey ){
  103858. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  103859. ** Whenever this column is read, the rowid will be substituted
  103860. ** in its place. Hence, fill this column with a NULL to avoid
  103861. ** taking up data space with information that will never be used.
  103862. ** As there may be shallow copies of this value, make it a soft-NULL */
  103863. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  103864. continue;
  103865. }
  103866. if( pColumn==0 ){
  103867. if( IsHiddenColumn(&pTab->aCol[i]) ){
  103868. j = -1;
  103869. nHidden++;
  103870. }else{
  103871. j = i - nHidden;
  103872. }
  103873. }else{
  103874. for(j=0; j<pColumn->nId; j++){
  103875. if( pColumn->a[j].idx==i ) break;
  103876. }
  103877. }
  103878. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  103879. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  103880. }else if( useTempTable ){
  103881. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  103882. }else if( pSelect ){
  103883. if( regFromSelect!=regData ){
  103884. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  103885. }
  103886. }else{
  103887. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  103888. }
  103889. }
  103890. /* Generate code to check constraints and generate index keys and
  103891. ** do the insertion.
  103892. */
  103893. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103894. if( IsVirtual(pTab) ){
  103895. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  103896. sqlite3VtabMakeWritable(pParse, pTab);
  103897. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  103898. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  103899. sqlite3MayAbort(pParse);
  103900. }else
  103901. #endif
  103902. {
  103903. int isReplace; /* Set to true if constraints may cause a replace */
  103904. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  103905. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  103906. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  103907. );
  103908. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  103909. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  103910. ** constraints or (b) there are no triggers and this table is not a
  103911. ** parent table in a foreign key constraint. It is safe to set the
  103912. ** flag in the second case as if any REPLACE constraint is hit, an
  103913. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  103914. ** cursor that is disturbed. And these instructions both clear the
  103915. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  103916. ** functionality. */
  103917. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  103918. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  103919. ));
  103920. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  103921. regIns, aRegIdx, 0, appendFlag, bUseSeek
  103922. );
  103923. }
  103924. }
  103925. /* Update the count of rows that are inserted
  103926. */
  103927. if( (db->flags & SQLITE_CountRows)!=0 ){
  103928. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  103929. }
  103930. if( pTrigger ){
  103931. /* Code AFTER triggers */
  103932. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  103933. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  103934. }
  103935. /* The bottom of the main insertion loop, if the data source
  103936. ** is a SELECT statement.
  103937. */
  103938. sqlite3VdbeResolveLabel(v, endOfLoop);
  103939. if( useTempTable ){
  103940. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  103941. sqlite3VdbeJumpHere(v, addrInsTop);
  103942. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  103943. }else if( pSelect ){
  103944. sqlite3VdbeGoto(v, addrCont);
  103945. sqlite3VdbeJumpHere(v, addrInsTop);
  103946. }
  103947. insert_end:
  103948. /* Update the sqlite_sequence table by storing the content of the
  103949. ** maximum rowid counter values recorded while inserting into
  103950. ** autoincrement tables.
  103951. */
  103952. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  103953. sqlite3AutoincrementEnd(pParse);
  103954. }
  103955. /*
  103956. ** Return the number of rows inserted. If this routine is
  103957. ** generating code because of a call to sqlite3NestedParse(), do not
  103958. ** invoke the callback function.
  103959. */
  103960. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  103961. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  103962. sqlite3VdbeSetNumCols(v, 1);
  103963. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  103964. }
  103965. insert_cleanup:
  103966. sqlite3SrcListDelete(db, pTabList);
  103967. sqlite3ExprListDelete(db, pList);
  103968. sqlite3SelectDelete(db, pSelect);
  103969. sqlite3IdListDelete(db, pColumn);
  103970. sqlite3DbFree(db, aRegIdx);
  103971. }
  103972. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  103973. ** they may interfere with compilation of other functions in this file
  103974. ** (or in another file, if this file becomes part of the amalgamation). */
  103975. #ifdef isView
  103976. #undef isView
  103977. #endif
  103978. #ifdef pTrigger
  103979. #undef pTrigger
  103980. #endif
  103981. #ifdef tmask
  103982. #undef tmask
  103983. #endif
  103984. /*
  103985. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  103986. */
  103987. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  103988. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  103989. /* This is the Walker callback from checkConstraintUnchanged(). Set
  103990. ** bit 0x01 of pWalker->eCode if
  103991. ** pWalker->eCode to 0 if this expression node references any of the
  103992. ** columns that are being modifed by an UPDATE statement.
  103993. */
  103994. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  103995. if( pExpr->op==TK_COLUMN ){
  103996. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  103997. if( pExpr->iColumn>=0 ){
  103998. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  103999. pWalker->eCode |= CKCNSTRNT_COLUMN;
  104000. }
  104001. }else{
  104002. pWalker->eCode |= CKCNSTRNT_ROWID;
  104003. }
  104004. }
  104005. return WRC_Continue;
  104006. }
  104007. /*
  104008. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  104009. ** only columns that are modified by the UPDATE are those for which
  104010. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  104011. **
  104012. ** Return true if CHECK constraint pExpr does not use any of the
  104013. ** changing columns (or the rowid if it is changing). In other words,
  104014. ** return true if this CHECK constraint can be skipped when validating
  104015. ** the new row in the UPDATE statement.
  104016. */
  104017. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  104018. Walker w;
  104019. memset(&w, 0, sizeof(w));
  104020. w.eCode = 0;
  104021. w.xExprCallback = checkConstraintExprNode;
  104022. w.u.aiCol = aiChng;
  104023. sqlite3WalkExpr(&w, pExpr);
  104024. if( !chngRowid ){
  104025. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  104026. w.eCode &= ~CKCNSTRNT_ROWID;
  104027. }
  104028. testcase( w.eCode==0 );
  104029. testcase( w.eCode==CKCNSTRNT_COLUMN );
  104030. testcase( w.eCode==CKCNSTRNT_ROWID );
  104031. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  104032. return !w.eCode;
  104033. }
  104034. /*
  104035. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  104036. ** on table pTab.
  104037. **
  104038. ** The regNewData parameter is the first register in a range that contains
  104039. ** the data to be inserted or the data after the update. There will be
  104040. ** pTab->nCol+1 registers in this range. The first register (the one
  104041. ** that regNewData points to) will contain the new rowid, or NULL in the
  104042. ** case of a WITHOUT ROWID table. The second register in the range will
  104043. ** contain the content of the first table column. The third register will
  104044. ** contain the content of the second table column. And so forth.
  104045. **
  104046. ** The regOldData parameter is similar to regNewData except that it contains
  104047. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  104048. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  104049. ** checking regOldData for zero.
  104050. **
  104051. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  104052. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  104053. ** might be modified by the UPDATE. If pkChng is false, then the key of
  104054. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  104055. **
  104056. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  104057. ** was explicitly specified as part of the INSERT statement. If pkChng
  104058. ** is zero, it means that the either rowid is computed automatically or
  104059. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  104060. ** pkChng will only be true if the INSERT statement provides an integer
  104061. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  104062. **
  104063. ** The code generated by this routine will store new index entries into
  104064. ** registers identified by aRegIdx[]. No index entry is created for
  104065. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  104066. ** the same as the order of indices on the linked list of indices
  104067. ** at pTab->pIndex.
  104068. **
  104069. ** The caller must have already opened writeable cursors on the main
  104070. ** table and all applicable indices (that is to say, all indices for which
  104071. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  104072. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  104073. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  104074. ** for the first index in the pTab->pIndex list. Cursors for other indices
  104075. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  104076. **
  104077. ** This routine also generates code to check constraints. NOT NULL,
  104078. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  104079. ** then the appropriate action is performed. There are five possible
  104080. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  104081. **
  104082. ** Constraint type Action What Happens
  104083. ** --------------- ---------- ----------------------------------------
  104084. ** any ROLLBACK The current transaction is rolled back and
  104085. ** sqlite3_step() returns immediately with a
  104086. ** return code of SQLITE_CONSTRAINT.
  104087. **
  104088. ** any ABORT Back out changes from the current command
  104089. ** only (do not do a complete rollback) then
  104090. ** cause sqlite3_step() to return immediately
  104091. ** with SQLITE_CONSTRAINT.
  104092. **
  104093. ** any FAIL Sqlite3_step() returns immediately with a
  104094. ** return code of SQLITE_CONSTRAINT. The
  104095. ** transaction is not rolled back and any
  104096. ** changes to prior rows are retained.
  104097. **
  104098. ** any IGNORE The attempt in insert or update the current
  104099. ** row is skipped, without throwing an error.
  104100. ** Processing continues with the next row.
  104101. ** (There is an immediate jump to ignoreDest.)
  104102. **
  104103. ** NOT NULL REPLACE The NULL value is replace by the default
  104104. ** value for that column. If the default value
  104105. ** is NULL, the action is the same as ABORT.
  104106. **
  104107. ** UNIQUE REPLACE The other row that conflicts with the row
  104108. ** being inserted is removed.
  104109. **
  104110. ** CHECK REPLACE Illegal. The results in an exception.
  104111. **
  104112. ** Which action to take is determined by the overrideError parameter.
  104113. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  104114. ** is used. Or if pParse->onError==OE_Default then the onError value
  104115. ** for the constraint is used.
  104116. */
  104117. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  104118. Parse *pParse, /* The parser context */
  104119. Table *pTab, /* The table being inserted or updated */
  104120. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  104121. int iDataCur, /* Canonical data cursor (main table or PK index) */
  104122. int iIdxCur, /* First index cursor */
  104123. int regNewData, /* First register in a range holding values to insert */
  104124. int regOldData, /* Previous content. 0 for INSERTs */
  104125. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  104126. u8 overrideError, /* Override onError to this if not OE_Default */
  104127. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  104128. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  104129. int *aiChng /* column i is unchanged if aiChng[i]<0 */
  104130. ){
  104131. Vdbe *v; /* VDBE under constrution */
  104132. Index *pIdx; /* Pointer to one of the indices */
  104133. Index *pPk = 0; /* The PRIMARY KEY index */
  104134. sqlite3 *db; /* Database connection */
  104135. int i; /* loop counter */
  104136. int ix; /* Index loop counter */
  104137. int nCol; /* Number of columns */
  104138. int onError; /* Conflict resolution strategy */
  104139. int addr1; /* Address of jump instruction */
  104140. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  104141. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  104142. int ipkTop = 0; /* Top of the rowid change constraint check */
  104143. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  104144. u8 isUpdate; /* True if this is an UPDATE operation */
  104145. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  104146. isUpdate = regOldData!=0;
  104147. db = pParse->db;
  104148. v = sqlite3GetVdbe(pParse);
  104149. assert( v!=0 );
  104150. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  104151. nCol = pTab->nCol;
  104152. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  104153. ** normal rowid tables. nPkField is the number of key fields in the
  104154. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  104155. ** number of fields in the true primary key of the table. */
  104156. if( HasRowid(pTab) ){
  104157. pPk = 0;
  104158. nPkField = 1;
  104159. }else{
  104160. pPk = sqlite3PrimaryKeyIndex(pTab);
  104161. nPkField = pPk->nKeyCol;
  104162. }
  104163. /* Record that this module has started */
  104164. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  104165. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  104166. /* Test all NOT NULL constraints.
  104167. */
  104168. for(i=0; i<nCol; i++){
  104169. if( i==pTab->iPKey ){
  104170. continue; /* ROWID is never NULL */
  104171. }
  104172. if( aiChng && aiChng[i]<0 ){
  104173. /* Don't bother checking for NOT NULL on columns that do not change */
  104174. continue;
  104175. }
  104176. onError = pTab->aCol[i].notNull;
  104177. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  104178. if( overrideError!=OE_Default ){
  104179. onError = overrideError;
  104180. }else if( onError==OE_Default ){
  104181. onError = OE_Abort;
  104182. }
  104183. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  104184. onError = OE_Abort;
  104185. }
  104186. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  104187. || onError==OE_Ignore || onError==OE_Replace );
  104188. switch( onError ){
  104189. case OE_Abort:
  104190. sqlite3MayAbort(pParse);
  104191. /* Fall through */
  104192. case OE_Rollback:
  104193. case OE_Fail: {
  104194. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  104195. pTab->aCol[i].zName);
  104196. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  104197. regNewData+1+i);
  104198. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  104199. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  104200. VdbeCoverage(v);
  104201. break;
  104202. }
  104203. case OE_Ignore: {
  104204. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  104205. VdbeCoverage(v);
  104206. break;
  104207. }
  104208. default: {
  104209. assert( onError==OE_Replace );
  104210. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  104211. VdbeCoverage(v);
  104212. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  104213. sqlite3VdbeJumpHere(v, addr1);
  104214. break;
  104215. }
  104216. }
  104217. }
  104218. /* Test all CHECK constraints
  104219. */
  104220. #ifndef SQLITE_OMIT_CHECK
  104221. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  104222. ExprList *pCheck = pTab->pCheck;
  104223. pParse->iSelfTab = -(regNewData+1);
  104224. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  104225. for(i=0; i<pCheck->nExpr; i++){
  104226. int allOk;
  104227. Expr *pExpr = pCheck->a[i].pExpr;
  104228. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  104229. allOk = sqlite3VdbeMakeLabel(v);
  104230. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  104231. if( onError==OE_Ignore ){
  104232. sqlite3VdbeGoto(v, ignoreDest);
  104233. }else{
  104234. char *zName = pCheck->a[i].zName;
  104235. if( zName==0 ) zName = pTab->zName;
  104236. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  104237. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  104238. onError, zName, P4_TRANSIENT,
  104239. P5_ConstraintCheck);
  104240. }
  104241. sqlite3VdbeResolveLabel(v, allOk);
  104242. }
  104243. pParse->iSelfTab = 0;
  104244. }
  104245. #endif /* !defined(SQLITE_OMIT_CHECK) */
  104246. /* If rowid is changing, make sure the new rowid does not previously
  104247. ** exist in the table.
  104248. */
  104249. if( pkChng && pPk==0 ){
  104250. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  104251. /* Figure out what action to take in case of a rowid collision */
  104252. onError = pTab->keyConf;
  104253. if( overrideError!=OE_Default ){
  104254. onError = overrideError;
  104255. }else if( onError==OE_Default ){
  104256. onError = OE_Abort;
  104257. }
  104258. if( isUpdate ){
  104259. /* pkChng!=0 does not mean that the rowid has changed, only that
  104260. ** it might have changed. Skip the conflict logic below if the rowid
  104261. ** is unchanged. */
  104262. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  104263. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  104264. VdbeCoverage(v);
  104265. }
  104266. /* If the response to a rowid conflict is REPLACE but the response
  104267. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  104268. ** to defer the running of the rowid conflict checking until after
  104269. ** the UNIQUE constraints have run.
  104270. */
  104271. if( onError==OE_Replace && overrideError!=OE_Replace ){
  104272. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104273. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  104274. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  104275. break;
  104276. }
  104277. }
  104278. }
  104279. /* Check to see if the new rowid already exists in the table. Skip
  104280. ** the following conflict logic if it does not. */
  104281. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  104282. VdbeCoverage(v);
  104283. /* Generate code that deals with a rowid collision */
  104284. switch( onError ){
  104285. default: {
  104286. onError = OE_Abort;
  104287. /* Fall thru into the next case */
  104288. }
  104289. case OE_Rollback:
  104290. case OE_Abort:
  104291. case OE_Fail: {
  104292. sqlite3RowidConstraint(pParse, onError, pTab);
  104293. break;
  104294. }
  104295. case OE_Replace: {
  104296. /* If there are DELETE triggers on this table and the
  104297. ** recursive-triggers flag is set, call GenerateRowDelete() to
  104298. ** remove the conflicting row from the table. This will fire
  104299. ** the triggers and remove both the table and index b-tree entries.
  104300. **
  104301. ** Otherwise, if there are no triggers or the recursive-triggers
  104302. ** flag is not set, but the table has one or more indexes, call
  104303. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  104304. ** only. The table b-tree entry will be replaced by the new entry
  104305. ** when it is inserted.
  104306. **
  104307. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  104308. ** also invoke MultiWrite() to indicate that this VDBE may require
  104309. ** statement rollback (if the statement is aborted after the delete
  104310. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  104311. ** but being more selective here allows statements like:
  104312. **
  104313. ** REPLACE INTO t(rowid) VALUES($newrowid)
  104314. **
  104315. ** to run without a statement journal if there are no indexes on the
  104316. ** table.
  104317. */
  104318. Trigger *pTrigger = 0;
  104319. if( db->flags&SQLITE_RecTriggers ){
  104320. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  104321. }
  104322. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  104323. sqlite3MultiWrite(pParse);
  104324. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  104325. regNewData, 1, 0, OE_Replace, 1, -1);
  104326. }else{
  104327. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  104328. if( HasRowid(pTab) ){
  104329. /* This OP_Delete opcode fires the pre-update-hook only. It does
  104330. ** not modify the b-tree. It is more efficient to let the coming
  104331. ** OP_Insert replace the existing entry than it is to delete the
  104332. ** existing entry and then insert a new one. */
  104333. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  104334. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  104335. }
  104336. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  104337. if( pTab->pIndex ){
  104338. sqlite3MultiWrite(pParse);
  104339. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  104340. }
  104341. }
  104342. seenReplace = 1;
  104343. break;
  104344. }
  104345. case OE_Ignore: {
  104346. /*assert( seenReplace==0 );*/
  104347. sqlite3VdbeGoto(v, ignoreDest);
  104348. break;
  104349. }
  104350. }
  104351. sqlite3VdbeResolveLabel(v, addrRowidOk);
  104352. if( ipkTop ){
  104353. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  104354. sqlite3VdbeJumpHere(v, ipkTop);
  104355. }
  104356. }
  104357. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  104358. ** index and making sure that duplicate entries do not already exist.
  104359. ** Compute the revised record entries for indices as we go.
  104360. **
  104361. ** This loop also handles the case of the PRIMARY KEY index for a
  104362. ** WITHOUT ROWID table.
  104363. */
  104364. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  104365. int regIdx; /* Range of registers hold conent for pIdx */
  104366. int regR; /* Range of registers holding conflicting PK */
  104367. int iThisCur; /* Cursor for this UNIQUE index */
  104368. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  104369. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  104370. if( bAffinityDone==0 ){
  104371. sqlite3TableAffinity(v, pTab, regNewData+1);
  104372. bAffinityDone = 1;
  104373. }
  104374. iThisCur = iIdxCur+ix;
  104375. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  104376. /* Skip partial indices for which the WHERE clause is not true */
  104377. if( pIdx->pPartIdxWhere ){
  104378. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  104379. pParse->iSelfTab = -(regNewData+1);
  104380. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  104381. SQLITE_JUMPIFNULL);
  104382. pParse->iSelfTab = 0;
  104383. }
  104384. /* Create a record for this index entry as it should appear after
  104385. ** the insert or update. Store that record in the aRegIdx[ix] register
  104386. */
  104387. regIdx = aRegIdx[ix]+1;
  104388. for(i=0; i<pIdx->nColumn; i++){
  104389. int iField = pIdx->aiColumn[i];
  104390. int x;
  104391. if( iField==XN_EXPR ){
  104392. pParse->iSelfTab = -(regNewData+1);
  104393. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  104394. pParse->iSelfTab = 0;
  104395. VdbeComment((v, "%s column %d", pIdx->zName, i));
  104396. }else{
  104397. if( iField==XN_ROWID || iField==pTab->iPKey ){
  104398. x = regNewData;
  104399. }else{
  104400. x = iField + regNewData + 1;
  104401. }
  104402. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  104403. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  104404. }
  104405. }
  104406. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  104407. VdbeComment((v, "for %s", pIdx->zName));
  104408. #ifdef SQLITE_ENABLE_NULL_TRIM
  104409. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  104410. #endif
  104411. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  104412. ** of a WITHOUT ROWID table and there has been no change the
  104413. ** primary key, then no collision is possible. The collision detection
  104414. ** logic below can all be skipped. */
  104415. if( isUpdate && pPk==pIdx && pkChng==0 ){
  104416. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  104417. continue;
  104418. }
  104419. /* Find out what action to take in case there is a uniqueness conflict */
  104420. onError = pIdx->onError;
  104421. if( onError==OE_None ){
  104422. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  104423. continue; /* pIdx is not a UNIQUE index */
  104424. }
  104425. if( overrideError!=OE_Default ){
  104426. onError = overrideError;
  104427. }else if( onError==OE_Default ){
  104428. onError = OE_Abort;
  104429. }
  104430. /* Collision detection may be omitted if all of the following are true:
  104431. ** (1) The conflict resolution algorithm is REPLACE
  104432. ** (2) The table is a WITHOUT ROWID table
  104433. ** (3) There are no secondary indexes on the table
  104434. ** (4) No delete triggers need to be fired if there is a conflict
  104435. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  104436. */
  104437. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  104438. && pPk==pIdx /* Condition 2 */
  104439. && onError==OE_Replace /* Condition 1 */
  104440. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  104441. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  104442. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  104443. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  104444. ){
  104445. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  104446. continue;
  104447. }
  104448. /* Check to see if the new index entry will be unique */
  104449. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  104450. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  104451. /* Generate code to handle collisions */
  104452. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  104453. if( isUpdate || onError==OE_Replace ){
  104454. if( HasRowid(pTab) ){
  104455. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  104456. /* Conflict only if the rowid of the existing index entry
  104457. ** is different from old-rowid */
  104458. if( isUpdate ){
  104459. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  104460. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  104461. VdbeCoverage(v);
  104462. }
  104463. }else{
  104464. int x;
  104465. /* Extract the PRIMARY KEY from the end of the index entry and
  104466. ** store it in registers regR..regR+nPk-1 */
  104467. if( pIdx!=pPk ){
  104468. for(i=0; i<pPk->nKeyCol; i++){
  104469. assert( pPk->aiColumn[i]>=0 );
  104470. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  104471. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  104472. VdbeComment((v, "%s.%s", pTab->zName,
  104473. pTab->aCol[pPk->aiColumn[i]].zName));
  104474. }
  104475. }
  104476. if( isUpdate ){
  104477. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  104478. ** table, only conflict if the new PRIMARY KEY values are actually
  104479. ** different from the old.
  104480. **
  104481. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  104482. ** of the matched index row are different from the original PRIMARY
  104483. ** KEY values of this row before the update. */
  104484. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  104485. int op = OP_Ne;
  104486. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  104487. for(i=0; i<pPk->nKeyCol; i++){
  104488. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  104489. x = pPk->aiColumn[i];
  104490. assert( x>=0 );
  104491. if( i==(pPk->nKeyCol-1) ){
  104492. addrJump = addrUniqueOk;
  104493. op = OP_Eq;
  104494. }
  104495. sqlite3VdbeAddOp4(v, op,
  104496. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  104497. );
  104498. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  104499. VdbeCoverageIf(v, op==OP_Eq);
  104500. VdbeCoverageIf(v, op==OP_Ne);
  104501. }
  104502. }
  104503. }
  104504. }
  104505. /* Generate code that executes if the new index entry is not unique */
  104506. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  104507. || onError==OE_Ignore || onError==OE_Replace );
  104508. switch( onError ){
  104509. case OE_Rollback:
  104510. case OE_Abort:
  104511. case OE_Fail: {
  104512. sqlite3UniqueConstraint(pParse, onError, pIdx);
  104513. break;
  104514. }
  104515. case OE_Ignore: {
  104516. sqlite3VdbeGoto(v, ignoreDest);
  104517. break;
  104518. }
  104519. default: {
  104520. Trigger *pTrigger = 0;
  104521. assert( onError==OE_Replace );
  104522. sqlite3MultiWrite(pParse);
  104523. if( db->flags&SQLITE_RecTriggers ){
  104524. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  104525. }
  104526. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  104527. regR, nPkField, 0, OE_Replace,
  104528. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  104529. seenReplace = 1;
  104530. break;
  104531. }
  104532. }
  104533. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  104534. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  104535. }
  104536. if( ipkTop ){
  104537. sqlite3VdbeGoto(v, ipkTop+1);
  104538. sqlite3VdbeJumpHere(v, ipkBottom);
  104539. }
  104540. *pbMayReplace = seenReplace;
  104541. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  104542. }
  104543. #ifdef SQLITE_ENABLE_NULL_TRIM
  104544. /*
  104545. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  104546. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  104547. **
  104548. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  104549. */
  104550. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  104551. u16 i;
  104552. /* Records with omitted columns are only allowed for schema format
  104553. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  104554. if( pTab->pSchema->file_format<2 ) return;
  104555. for(i=pTab->nCol-1; i>0; i--){
  104556. if( pTab->aCol[i].pDflt!=0 ) break;
  104557. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  104558. }
  104559. sqlite3VdbeChangeP5(v, i+1);
  104560. }
  104561. #endif
  104562. /*
  104563. ** This routine generates code to finish the INSERT or UPDATE operation
  104564. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  104565. ** A consecutive range of registers starting at regNewData contains the
  104566. ** rowid and the content to be inserted.
  104567. **
  104568. ** The arguments to this routine should be the same as the first six
  104569. ** arguments to sqlite3GenerateConstraintChecks.
  104570. */
  104571. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  104572. Parse *pParse, /* The parser context */
  104573. Table *pTab, /* the table into which we are inserting */
  104574. int iDataCur, /* Cursor of the canonical data source */
  104575. int iIdxCur, /* First index cursor */
  104576. int regNewData, /* Range of content */
  104577. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  104578. int update_flags, /* True for UPDATE, False for INSERT */
  104579. int appendBias, /* True if this is likely to be an append */
  104580. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  104581. ){
  104582. Vdbe *v; /* Prepared statements under construction */
  104583. Index *pIdx; /* An index being inserted or updated */
  104584. u8 pik_flags; /* flag values passed to the btree insert */
  104585. int regData; /* Content registers (after the rowid) */
  104586. int regRec; /* Register holding assembled record for the table */
  104587. int i; /* Loop counter */
  104588. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  104589. assert( update_flags==0
  104590. || update_flags==OPFLAG_ISUPDATE
  104591. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  104592. );
  104593. v = sqlite3GetVdbe(pParse);
  104594. assert( v!=0 );
  104595. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  104596. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  104597. if( aRegIdx[i]==0 ) continue;
  104598. bAffinityDone = 1;
  104599. if( pIdx->pPartIdxWhere ){
  104600. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  104601. VdbeCoverage(v);
  104602. }
  104603. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  104604. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  104605. assert( pParse->nested==0 );
  104606. pik_flags |= OPFLAG_NCHANGE;
  104607. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  104608. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  104609. if( update_flags==0 ){
  104610. sqlite3VdbeAddOp4(v, OP_InsertInt,
  104611. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  104612. );
  104613. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  104614. }
  104615. #endif
  104616. }
  104617. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  104618. aRegIdx[i]+1,
  104619. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  104620. sqlite3VdbeChangeP5(v, pik_flags);
  104621. }
  104622. if( !HasRowid(pTab) ) return;
  104623. regData = regNewData + 1;
  104624. regRec = sqlite3GetTempReg(pParse);
  104625. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  104626. sqlite3SetMakeRecordP5(v, pTab);
  104627. if( !bAffinityDone ){
  104628. sqlite3TableAffinity(v, pTab, 0);
  104629. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  104630. }
  104631. if( pParse->nested ){
  104632. pik_flags = 0;
  104633. }else{
  104634. pik_flags = OPFLAG_NCHANGE;
  104635. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  104636. }
  104637. if( appendBias ){
  104638. pik_flags |= OPFLAG_APPEND;
  104639. }
  104640. if( useSeekResult ){
  104641. pik_flags |= OPFLAG_USESEEKRESULT;
  104642. }
  104643. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  104644. if( !pParse->nested ){
  104645. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  104646. }
  104647. sqlite3VdbeChangeP5(v, pik_flags);
  104648. }
  104649. /*
  104650. ** Allocate cursors for the pTab table and all its indices and generate
  104651. ** code to open and initialized those cursors.
  104652. **
  104653. ** The cursor for the object that contains the complete data (normally
  104654. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  104655. ** ROWID table) is returned in *piDataCur. The first index cursor is
  104656. ** returned in *piIdxCur. The number of indices is returned.
  104657. **
  104658. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  104659. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  104660. ** If iBase is negative, then allocate the next available cursor.
  104661. **
  104662. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  104663. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  104664. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  104665. ** pTab->pIndex list.
  104666. **
  104667. ** If pTab is a virtual table, then this routine is a no-op and the
  104668. ** *piDataCur and *piIdxCur values are left uninitialized.
  104669. */
  104670. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  104671. Parse *pParse, /* Parsing context */
  104672. Table *pTab, /* Table to be opened */
  104673. int op, /* OP_OpenRead or OP_OpenWrite */
  104674. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  104675. int iBase, /* Use this for the table cursor, if there is one */
  104676. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  104677. int *piDataCur, /* Write the database source cursor number here */
  104678. int *piIdxCur /* Write the first index cursor number here */
  104679. ){
  104680. int i;
  104681. int iDb;
  104682. int iDataCur;
  104683. Index *pIdx;
  104684. Vdbe *v;
  104685. assert( op==OP_OpenRead || op==OP_OpenWrite );
  104686. assert( op==OP_OpenWrite || p5==0 );
  104687. if( IsVirtual(pTab) ){
  104688. /* This routine is a no-op for virtual tables. Leave the output
  104689. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  104690. ** can detect if they are used by mistake in the caller. */
  104691. return 0;
  104692. }
  104693. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  104694. v = sqlite3GetVdbe(pParse);
  104695. assert( v!=0 );
  104696. if( iBase<0 ) iBase = pParse->nTab;
  104697. iDataCur = iBase++;
  104698. if( piDataCur ) *piDataCur = iDataCur;
  104699. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  104700. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  104701. }else{
  104702. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  104703. }
  104704. if( piIdxCur ) *piIdxCur = iBase;
  104705. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  104706. int iIdxCur = iBase++;
  104707. assert( pIdx->pSchema==pTab->pSchema );
  104708. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  104709. if( piDataCur ) *piDataCur = iIdxCur;
  104710. p5 = 0;
  104711. }
  104712. if( aToOpen==0 || aToOpen[i+1] ){
  104713. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  104714. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  104715. sqlite3VdbeChangeP5(v, p5);
  104716. VdbeComment((v, "%s", pIdx->zName));
  104717. }
  104718. }
  104719. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  104720. return i;
  104721. }
  104722. #ifdef SQLITE_TEST
  104723. /*
  104724. ** The following global variable is incremented whenever the
  104725. ** transfer optimization is used. This is used for testing
  104726. ** purposes only - to make sure the transfer optimization really
  104727. ** is happening when it is supposed to.
  104728. */
  104729. SQLITE_API int sqlite3_xferopt_count;
  104730. #endif /* SQLITE_TEST */
  104731. #ifndef SQLITE_OMIT_XFER_OPT
  104732. /*
  104733. ** Check to see if index pSrc is compatible as a source of data
  104734. ** for index pDest in an insert transfer optimization. The rules
  104735. ** for a compatible index:
  104736. **
  104737. ** * The index is over the same set of columns
  104738. ** * The same DESC and ASC markings occurs on all columns
  104739. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  104740. ** * The same collating sequence on each column
  104741. ** * The index has the exact same WHERE clause
  104742. */
  104743. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  104744. int i;
  104745. assert( pDest && pSrc );
  104746. assert( pDest->pTable!=pSrc->pTable );
  104747. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  104748. return 0; /* Different number of columns */
  104749. }
  104750. if( pDest->onError!=pSrc->onError ){
  104751. return 0; /* Different conflict resolution strategies */
  104752. }
  104753. for(i=0; i<pSrc->nKeyCol; i++){
  104754. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  104755. return 0; /* Different columns indexed */
  104756. }
  104757. if( pSrc->aiColumn[i]==XN_EXPR ){
  104758. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  104759. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  104760. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  104761. return 0; /* Different expressions in the index */
  104762. }
  104763. }
  104764. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  104765. return 0; /* Different sort orders */
  104766. }
  104767. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  104768. return 0; /* Different collating sequences */
  104769. }
  104770. }
  104771. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  104772. return 0; /* Different WHERE clauses */
  104773. }
  104774. /* If no test above fails then the indices must be compatible */
  104775. return 1;
  104776. }
  104777. /*
  104778. ** Attempt the transfer optimization on INSERTs of the form
  104779. **
  104780. ** INSERT INTO tab1 SELECT * FROM tab2;
  104781. **
  104782. ** The xfer optimization transfers raw records from tab2 over to tab1.
  104783. ** Columns are not decoded and reassembled, which greatly improves
  104784. ** performance. Raw index records are transferred in the same way.
  104785. **
  104786. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  104787. ** There are lots of rules for determining compatibility - see comments
  104788. ** embedded in the code for details.
  104789. **
  104790. ** This routine returns TRUE if the optimization is guaranteed to be used.
  104791. ** Sometimes the xfer optimization will only work if the destination table
  104792. ** is empty - a factor that can only be determined at run-time. In that
  104793. ** case, this routine generates code for the xfer optimization but also
  104794. ** does a test to see if the destination table is empty and jumps over the
  104795. ** xfer optimization code if the test fails. In that case, this routine
  104796. ** returns FALSE so that the caller will know to go ahead and generate
  104797. ** an unoptimized transfer. This routine also returns FALSE if there
  104798. ** is no chance that the xfer optimization can be applied.
  104799. **
  104800. ** This optimization is particularly useful at making VACUUM run faster.
  104801. */
  104802. static int xferOptimization(
  104803. Parse *pParse, /* Parser context */
  104804. Table *pDest, /* The table we are inserting into */
  104805. Select *pSelect, /* A SELECT statement to use as the data source */
  104806. int onError, /* How to handle constraint errors */
  104807. int iDbDest /* The database of pDest */
  104808. ){
  104809. sqlite3 *db = pParse->db;
  104810. ExprList *pEList; /* The result set of the SELECT */
  104811. Table *pSrc; /* The table in the FROM clause of SELECT */
  104812. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  104813. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  104814. int i; /* Loop counter */
  104815. int iDbSrc; /* The database of pSrc */
  104816. int iSrc, iDest; /* Cursors from source and destination */
  104817. int addr1, addr2; /* Loop addresses */
  104818. int emptyDestTest = 0; /* Address of test for empty pDest */
  104819. int emptySrcTest = 0; /* Address of test for empty pSrc */
  104820. Vdbe *v; /* The VDBE we are building */
  104821. int regAutoinc; /* Memory register used by AUTOINC */
  104822. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  104823. int regData, regRowid; /* Registers holding data and rowid */
  104824. if( pSelect==0 ){
  104825. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  104826. }
  104827. if( pParse->pWith || pSelect->pWith ){
  104828. /* Do not attempt to process this query if there are an WITH clauses
  104829. ** attached to it. Proceeding may generate a false "no such table: xxx"
  104830. ** error if pSelect reads from a CTE named "xxx". */
  104831. return 0;
  104832. }
  104833. if( sqlite3TriggerList(pParse, pDest) ){
  104834. return 0; /* tab1 must not have triggers */
  104835. }
  104836. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104837. if( IsVirtual(pDest) ){
  104838. return 0; /* tab1 must not be a virtual table */
  104839. }
  104840. #endif
  104841. if( onError==OE_Default ){
  104842. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  104843. if( onError==OE_Default ) onError = OE_Abort;
  104844. }
  104845. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  104846. if( pSelect->pSrc->nSrc!=1 ){
  104847. return 0; /* FROM clause must have exactly one term */
  104848. }
  104849. if( pSelect->pSrc->a[0].pSelect ){
  104850. return 0; /* FROM clause cannot contain a subquery */
  104851. }
  104852. if( pSelect->pWhere ){
  104853. return 0; /* SELECT may not have a WHERE clause */
  104854. }
  104855. if( pSelect->pOrderBy ){
  104856. return 0; /* SELECT may not have an ORDER BY clause */
  104857. }
  104858. /* Do not need to test for a HAVING clause. If HAVING is present but
  104859. ** there is no ORDER BY, we will get an error. */
  104860. if( pSelect->pGroupBy ){
  104861. return 0; /* SELECT may not have a GROUP BY clause */
  104862. }
  104863. if( pSelect->pLimit ){
  104864. return 0; /* SELECT may not have a LIMIT clause */
  104865. }
  104866. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  104867. if( pSelect->pPrior ){
  104868. return 0; /* SELECT may not be a compound query */
  104869. }
  104870. if( pSelect->selFlags & SF_Distinct ){
  104871. return 0; /* SELECT may not be DISTINCT */
  104872. }
  104873. pEList = pSelect->pEList;
  104874. assert( pEList!=0 );
  104875. if( pEList->nExpr!=1 ){
  104876. return 0; /* The result set must have exactly one column */
  104877. }
  104878. assert( pEList->a[0].pExpr );
  104879. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  104880. return 0; /* The result set must be the special operator "*" */
  104881. }
  104882. /* At this point we have established that the statement is of the
  104883. ** correct syntactic form to participate in this optimization. Now
  104884. ** we have to check the semantics.
  104885. */
  104886. pItem = pSelect->pSrc->a;
  104887. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  104888. if( pSrc==0 ){
  104889. return 0; /* FROM clause does not contain a real table */
  104890. }
  104891. if( pSrc==pDest ){
  104892. return 0; /* tab1 and tab2 may not be the same table */
  104893. }
  104894. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  104895. return 0; /* source and destination must both be WITHOUT ROWID or not */
  104896. }
  104897. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104898. if( IsVirtual(pSrc) ){
  104899. return 0; /* tab2 must not be a virtual table */
  104900. }
  104901. #endif
  104902. if( pSrc->pSelect ){
  104903. return 0; /* tab2 may not be a view */
  104904. }
  104905. if( pDest->nCol!=pSrc->nCol ){
  104906. return 0; /* Number of columns must be the same in tab1 and tab2 */
  104907. }
  104908. if( pDest->iPKey!=pSrc->iPKey ){
  104909. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  104910. }
  104911. for(i=0; i<pDest->nCol; i++){
  104912. Column *pDestCol = &pDest->aCol[i];
  104913. Column *pSrcCol = &pSrc->aCol[i];
  104914. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  104915. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  104916. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  104917. ){
  104918. return 0; /* Neither table may have __hidden__ columns */
  104919. }
  104920. #endif
  104921. if( pDestCol->affinity!=pSrcCol->affinity ){
  104922. return 0; /* Affinity must be the same on all columns */
  104923. }
  104924. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  104925. return 0; /* Collating sequence must be the same on all columns */
  104926. }
  104927. if( pDestCol->notNull && !pSrcCol->notNull ){
  104928. return 0; /* tab2 must be NOT NULL if tab1 is */
  104929. }
  104930. /* Default values for second and subsequent columns need to match. */
  104931. if( i>0 ){
  104932. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  104933. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  104934. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  104935. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  104936. pSrcCol->pDflt->u.zToken)!=0)
  104937. ){
  104938. return 0; /* Default values must be the same for all columns */
  104939. }
  104940. }
  104941. }
  104942. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  104943. if( IsUniqueIndex(pDestIdx) ){
  104944. destHasUniqueIdx = 1;
  104945. }
  104946. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  104947. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  104948. }
  104949. if( pSrcIdx==0 ){
  104950. return 0; /* pDestIdx has no corresponding index in pSrc */
  104951. }
  104952. }
  104953. #ifndef SQLITE_OMIT_CHECK
  104954. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  104955. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  104956. }
  104957. #endif
  104958. #ifndef SQLITE_OMIT_FOREIGN_KEY
  104959. /* Disallow the transfer optimization if the destination table constains
  104960. ** any foreign key constraints. This is more restrictive than necessary.
  104961. ** But the main beneficiary of the transfer optimization is the VACUUM
  104962. ** command, and the VACUUM command disables foreign key constraints. So
  104963. ** the extra complication to make this rule less restrictive is probably
  104964. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  104965. */
  104966. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  104967. return 0;
  104968. }
  104969. #endif
  104970. if( (db->flags & SQLITE_CountRows)!=0 ){
  104971. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  104972. }
  104973. /* If we get this far, it means that the xfer optimization is at
  104974. ** least a possibility, though it might only work if the destination
  104975. ** table (tab1) is initially empty.
  104976. */
  104977. #ifdef SQLITE_TEST
  104978. sqlite3_xferopt_count++;
  104979. #endif
  104980. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  104981. v = sqlite3GetVdbe(pParse);
  104982. sqlite3CodeVerifySchema(pParse, iDbSrc);
  104983. iSrc = pParse->nTab++;
  104984. iDest = pParse->nTab++;
  104985. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  104986. regData = sqlite3GetTempReg(pParse);
  104987. regRowid = sqlite3GetTempReg(pParse);
  104988. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  104989. assert( HasRowid(pDest) || destHasUniqueIdx );
  104990. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  104991. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  104992. || destHasUniqueIdx /* (2) */
  104993. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  104994. )){
  104995. /* In some circumstances, we are able to run the xfer optimization
  104996. ** only if the destination table is initially empty. Unless the
  104997. ** DBFLAG_Vacuum flag is set, this block generates code to make
  104998. ** that determination. If DBFLAG_Vacuum is set, then the destination
  104999. ** table is always empty.
  105000. **
  105001. ** Conditions under which the destination must be empty:
  105002. **
  105003. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  105004. ** (If the destination is not initially empty, the rowid fields
  105005. ** of index entries might need to change.)
  105006. **
  105007. ** (2) The destination has a unique index. (The xfer optimization
  105008. ** is unable to test uniqueness.)
  105009. **
  105010. ** (3) onError is something other than OE_Abort and OE_Rollback.
  105011. */
  105012. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  105013. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  105014. sqlite3VdbeJumpHere(v, addr1);
  105015. }
  105016. if( HasRowid(pSrc) ){
  105017. u8 insFlags;
  105018. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  105019. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  105020. if( pDest->iPKey>=0 ){
  105021. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  105022. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  105023. VdbeCoverage(v);
  105024. sqlite3RowidConstraint(pParse, onError, pDest);
  105025. sqlite3VdbeJumpHere(v, addr2);
  105026. autoIncStep(pParse, regAutoinc, regRowid);
  105027. }else if( pDest->pIndex==0 ){
  105028. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  105029. }else{
  105030. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  105031. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  105032. }
  105033. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  105034. if( db->mDbFlags & DBFLAG_Vacuum ){
  105035. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  105036. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  105037. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  105038. }else{
  105039. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  105040. }
  105041. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  105042. (char*)pDest, P4_TABLE);
  105043. sqlite3VdbeChangeP5(v, insFlags);
  105044. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  105045. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  105046. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  105047. }else{
  105048. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  105049. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  105050. }
  105051. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  105052. u8 idxInsFlags = 0;
  105053. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  105054. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  105055. }
  105056. assert( pSrcIdx );
  105057. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  105058. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  105059. VdbeComment((v, "%s", pSrcIdx->zName));
  105060. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  105061. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  105062. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  105063. VdbeComment((v, "%s", pDestIdx->zName));
  105064. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  105065. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  105066. if( db->mDbFlags & DBFLAG_Vacuum ){
  105067. /* This INSERT command is part of a VACUUM operation, which guarantees
  105068. ** that the destination table is empty. If all indexed columns use
  105069. ** collation sequence BINARY, then it can also be assumed that the
  105070. ** index will be populated by inserting keys in strictly sorted
  105071. ** order. In this case, instead of seeking within the b-tree as part
  105072. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  105073. ** OP_IdxInsert to seek to the point within the b-tree where each key
  105074. ** should be inserted. This is faster.
  105075. **
  105076. ** If any of the indexed columns use a collation sequence other than
  105077. ** BINARY, this optimization is disabled. This is because the user
  105078. ** might change the definition of a collation sequence and then run
  105079. ** a VACUUM command. In that case keys may not be written in strictly
  105080. ** sorted order. */
  105081. for(i=0; i<pSrcIdx->nColumn; i++){
  105082. const char *zColl = pSrcIdx->azColl[i];
  105083. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  105084. }
  105085. if( i==pSrcIdx->nColumn ){
  105086. idxInsFlags = OPFLAG_USESEEKRESULT;
  105087. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  105088. }
  105089. }
  105090. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  105091. idxInsFlags |= OPFLAG_NCHANGE;
  105092. }
  105093. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  105094. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  105095. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  105096. sqlite3VdbeJumpHere(v, addr1);
  105097. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  105098. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  105099. }
  105100. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  105101. sqlite3ReleaseTempReg(pParse, regRowid);
  105102. sqlite3ReleaseTempReg(pParse, regData);
  105103. if( emptyDestTest ){
  105104. sqlite3AutoincrementEnd(pParse);
  105105. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  105106. sqlite3VdbeJumpHere(v, emptyDestTest);
  105107. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  105108. return 0;
  105109. }else{
  105110. return 1;
  105111. }
  105112. }
  105113. #endif /* SQLITE_OMIT_XFER_OPT */
  105114. /************** End of insert.c **********************************************/
  105115. /************** Begin file legacy.c ******************************************/
  105116. /*
  105117. ** 2001 September 15
  105118. **
  105119. ** The author disclaims copyright to this source code. In place of
  105120. ** a legal notice, here is a blessing:
  105121. **
  105122. ** May you do good and not evil.
  105123. ** May you find forgiveness for yourself and forgive others.
  105124. ** May you share freely, never taking more than you give.
  105125. **
  105126. *************************************************************************
  105127. ** Main file for the SQLite library. The routines in this file
  105128. ** implement the programmer interface to the library. Routines in
  105129. ** other files are for internal use by SQLite and should not be
  105130. ** accessed by users of the library.
  105131. */
  105132. /* #include "sqliteInt.h" */
  105133. /*
  105134. ** Execute SQL code. Return one of the SQLITE_ success/failure
  105135. ** codes. Also write an error message into memory obtained from
  105136. ** malloc() and make *pzErrMsg point to that message.
  105137. **
  105138. ** If the SQL is a query, then for each row in the query result
  105139. ** the xCallback() function is called. pArg becomes the first
  105140. ** argument to xCallback(). If xCallback=NULL then no callback
  105141. ** is invoked, even for queries.
  105142. */
  105143. SQLITE_API int sqlite3_exec(
  105144. sqlite3 *db, /* The database on which the SQL executes */
  105145. const char *zSql, /* The SQL to be executed */
  105146. sqlite3_callback xCallback, /* Invoke this callback routine */
  105147. void *pArg, /* First argument to xCallback() */
  105148. char **pzErrMsg /* Write error messages here */
  105149. ){
  105150. int rc = SQLITE_OK; /* Return code */
  105151. const char *zLeftover; /* Tail of unprocessed SQL */
  105152. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  105153. char **azCols = 0; /* Names of result columns */
  105154. int callbackIsInit; /* True if callback data is initialized */
  105155. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  105156. if( zSql==0 ) zSql = "";
  105157. sqlite3_mutex_enter(db->mutex);
  105158. sqlite3Error(db, SQLITE_OK);
  105159. while( rc==SQLITE_OK && zSql[0] ){
  105160. int nCol;
  105161. char **azVals = 0;
  105162. pStmt = 0;
  105163. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  105164. assert( rc==SQLITE_OK || pStmt==0 );
  105165. if( rc!=SQLITE_OK ){
  105166. continue;
  105167. }
  105168. if( !pStmt ){
  105169. /* this happens for a comment or white-space */
  105170. zSql = zLeftover;
  105171. continue;
  105172. }
  105173. callbackIsInit = 0;
  105174. nCol = sqlite3_column_count(pStmt);
  105175. while( 1 ){
  105176. int i;
  105177. rc = sqlite3_step(pStmt);
  105178. /* Invoke the callback function if required */
  105179. if( xCallback && (SQLITE_ROW==rc ||
  105180. (SQLITE_DONE==rc && !callbackIsInit
  105181. && db->flags&SQLITE_NullCallback)) ){
  105182. if( !callbackIsInit ){
  105183. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  105184. if( azCols==0 ){
  105185. goto exec_out;
  105186. }
  105187. for(i=0; i<nCol; i++){
  105188. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  105189. /* sqlite3VdbeSetColName() installs column names as UTF8
  105190. ** strings so there is no way for sqlite3_column_name() to fail. */
  105191. assert( azCols[i]!=0 );
  105192. }
  105193. callbackIsInit = 1;
  105194. }
  105195. if( rc==SQLITE_ROW ){
  105196. azVals = &azCols[nCol];
  105197. for(i=0; i<nCol; i++){
  105198. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  105199. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  105200. sqlite3OomFault(db);
  105201. goto exec_out;
  105202. }
  105203. }
  105204. azVals[i] = 0;
  105205. }
  105206. if( xCallback(pArg, nCol, azVals, azCols) ){
  105207. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  105208. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  105209. ** return SQLITE_ABORT. */
  105210. rc = SQLITE_ABORT;
  105211. sqlite3VdbeFinalize((Vdbe *)pStmt);
  105212. pStmt = 0;
  105213. sqlite3Error(db, SQLITE_ABORT);
  105214. goto exec_out;
  105215. }
  105216. }
  105217. if( rc!=SQLITE_ROW ){
  105218. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  105219. pStmt = 0;
  105220. zSql = zLeftover;
  105221. while( sqlite3Isspace(zSql[0]) ) zSql++;
  105222. break;
  105223. }
  105224. }
  105225. sqlite3DbFree(db, azCols);
  105226. azCols = 0;
  105227. }
  105228. exec_out:
  105229. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  105230. sqlite3DbFree(db, azCols);
  105231. rc = sqlite3ApiExit(db, rc);
  105232. if( rc!=SQLITE_OK && pzErrMsg ){
  105233. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  105234. if( *pzErrMsg==0 ){
  105235. rc = SQLITE_NOMEM_BKPT;
  105236. sqlite3Error(db, SQLITE_NOMEM);
  105237. }
  105238. }else if( pzErrMsg ){
  105239. *pzErrMsg = 0;
  105240. }
  105241. assert( (rc&db->errMask)==rc );
  105242. sqlite3_mutex_leave(db->mutex);
  105243. return rc;
  105244. }
  105245. /************** End of legacy.c **********************************************/
  105246. /************** Begin file loadext.c *****************************************/
  105247. /*
  105248. ** 2006 June 7
  105249. **
  105250. ** The author disclaims copyright to this source code. In place of
  105251. ** a legal notice, here is a blessing:
  105252. **
  105253. ** May you do good and not evil.
  105254. ** May you find forgiveness for yourself and forgive others.
  105255. ** May you share freely, never taking more than you give.
  105256. **
  105257. *************************************************************************
  105258. ** This file contains code used to dynamically load extensions into
  105259. ** the SQLite library.
  105260. */
  105261. #ifndef SQLITE_CORE
  105262. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  105263. #endif
  105264. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  105265. /************** Begin file sqlite3ext.h **************************************/
  105266. /*
  105267. ** 2006 June 7
  105268. **
  105269. ** The author disclaims copyright to this source code. In place of
  105270. ** a legal notice, here is a blessing:
  105271. **
  105272. ** May you do good and not evil.
  105273. ** May you find forgiveness for yourself and forgive others.
  105274. ** May you share freely, never taking more than you give.
  105275. **
  105276. *************************************************************************
  105277. ** This header file defines the SQLite interface for use by
  105278. ** shared libraries that want to be imported as extensions into
  105279. ** an SQLite instance. Shared libraries that intend to be loaded
  105280. ** as extensions by SQLite should #include this file instead of
  105281. ** sqlite3.h.
  105282. */
  105283. #ifndef SQLITE3EXT_H
  105284. #define SQLITE3EXT_H
  105285. /* #include "sqlite3.h" */
  105286. /*
  105287. ** The following structure holds pointers to all of the SQLite API
  105288. ** routines.
  105289. **
  105290. ** WARNING: In order to maintain backwards compatibility, add new
  105291. ** interfaces to the end of this structure only. If you insert new
  105292. ** interfaces in the middle of this structure, then older different
  105293. ** versions of SQLite will not be able to load each other's shared
  105294. ** libraries!
  105295. */
  105296. struct sqlite3_api_routines {
  105297. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  105298. int (*aggregate_count)(sqlite3_context*);
  105299. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  105300. int (*bind_double)(sqlite3_stmt*,int,double);
  105301. int (*bind_int)(sqlite3_stmt*,int,int);
  105302. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  105303. int (*bind_null)(sqlite3_stmt*,int);
  105304. int (*bind_parameter_count)(sqlite3_stmt*);
  105305. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  105306. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  105307. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  105308. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  105309. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  105310. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  105311. int (*busy_timeout)(sqlite3*,int ms);
  105312. int (*changes)(sqlite3*);
  105313. int (*close)(sqlite3*);
  105314. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  105315. int eTextRep,const char*));
  105316. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  105317. int eTextRep,const void*));
  105318. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  105319. int (*column_bytes)(sqlite3_stmt*,int iCol);
  105320. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  105321. int (*column_count)(sqlite3_stmt*pStmt);
  105322. const char * (*column_database_name)(sqlite3_stmt*,int);
  105323. const void * (*column_database_name16)(sqlite3_stmt*,int);
  105324. const char * (*column_decltype)(sqlite3_stmt*,int i);
  105325. const void * (*column_decltype16)(sqlite3_stmt*,int);
  105326. double (*column_double)(sqlite3_stmt*,int iCol);
  105327. int (*column_int)(sqlite3_stmt*,int iCol);
  105328. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  105329. const char * (*column_name)(sqlite3_stmt*,int);
  105330. const void * (*column_name16)(sqlite3_stmt*,int);
  105331. const char * (*column_origin_name)(sqlite3_stmt*,int);
  105332. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  105333. const char * (*column_table_name)(sqlite3_stmt*,int);
  105334. const void * (*column_table_name16)(sqlite3_stmt*,int);
  105335. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  105336. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  105337. int (*column_type)(sqlite3_stmt*,int iCol);
  105338. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  105339. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  105340. int (*complete)(const char*sql);
  105341. int (*complete16)(const void*sql);
  105342. int (*create_collation)(sqlite3*,const char*,int,void*,
  105343. int(*)(void*,int,const void*,int,const void*));
  105344. int (*create_collation16)(sqlite3*,const void*,int,void*,
  105345. int(*)(void*,int,const void*,int,const void*));
  105346. int (*create_function)(sqlite3*,const char*,int,int,void*,
  105347. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  105348. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  105349. void (*xFinal)(sqlite3_context*));
  105350. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  105351. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  105352. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  105353. void (*xFinal)(sqlite3_context*));
  105354. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  105355. int (*data_count)(sqlite3_stmt*pStmt);
  105356. sqlite3 * (*db_handle)(sqlite3_stmt*);
  105357. int (*declare_vtab)(sqlite3*,const char*);
  105358. int (*enable_shared_cache)(int);
  105359. int (*errcode)(sqlite3*db);
  105360. const char * (*errmsg)(sqlite3*);
  105361. const void * (*errmsg16)(sqlite3*);
  105362. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  105363. int (*expired)(sqlite3_stmt*);
  105364. int (*finalize)(sqlite3_stmt*pStmt);
  105365. void (*free)(void*);
  105366. void (*free_table)(char**result);
  105367. int (*get_autocommit)(sqlite3*);
  105368. void * (*get_auxdata)(sqlite3_context*,int);
  105369. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  105370. int (*global_recover)(void);
  105371. void (*interruptx)(sqlite3*);
  105372. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  105373. const char * (*libversion)(void);
  105374. int (*libversion_number)(void);
  105375. void *(*malloc)(int);
  105376. char * (*mprintf)(const char*,...);
  105377. int (*open)(const char*,sqlite3**);
  105378. int (*open16)(const void*,sqlite3**);
  105379. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  105380. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  105381. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  105382. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  105383. void *(*realloc)(void*,int);
  105384. int (*reset)(sqlite3_stmt*pStmt);
  105385. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  105386. void (*result_double)(sqlite3_context*,double);
  105387. void (*result_error)(sqlite3_context*,const char*,int);
  105388. void (*result_error16)(sqlite3_context*,const void*,int);
  105389. void (*result_int)(sqlite3_context*,int);
  105390. void (*result_int64)(sqlite3_context*,sqlite_int64);
  105391. void (*result_null)(sqlite3_context*);
  105392. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  105393. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  105394. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  105395. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  105396. void (*result_value)(sqlite3_context*,sqlite3_value*);
  105397. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  105398. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  105399. const char*,const char*),void*);
  105400. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  105401. char * (*xsnprintf)(int,char*,const char*,...);
  105402. int (*step)(sqlite3_stmt*);
  105403. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  105404. char const**,char const**,int*,int*,int*);
  105405. void (*thread_cleanup)(void);
  105406. int (*total_changes)(sqlite3*);
  105407. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  105408. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  105409. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  105410. sqlite_int64),void*);
  105411. void * (*user_data)(sqlite3_context*);
  105412. const void * (*value_blob)(sqlite3_value*);
  105413. int (*value_bytes)(sqlite3_value*);
  105414. int (*value_bytes16)(sqlite3_value*);
  105415. double (*value_double)(sqlite3_value*);
  105416. int (*value_int)(sqlite3_value*);
  105417. sqlite_int64 (*value_int64)(sqlite3_value*);
  105418. int (*value_numeric_type)(sqlite3_value*);
  105419. const unsigned char * (*value_text)(sqlite3_value*);
  105420. const void * (*value_text16)(sqlite3_value*);
  105421. const void * (*value_text16be)(sqlite3_value*);
  105422. const void * (*value_text16le)(sqlite3_value*);
  105423. int (*value_type)(sqlite3_value*);
  105424. char *(*vmprintf)(const char*,va_list);
  105425. /* Added ??? */
  105426. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  105427. /* Added by 3.3.13 */
  105428. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  105429. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  105430. int (*clear_bindings)(sqlite3_stmt*);
  105431. /* Added by 3.4.1 */
  105432. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  105433. void (*xDestroy)(void *));
  105434. /* Added by 3.5.0 */
  105435. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  105436. int (*blob_bytes)(sqlite3_blob*);
  105437. int (*blob_close)(sqlite3_blob*);
  105438. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  105439. int,sqlite3_blob**);
  105440. int (*blob_read)(sqlite3_blob*,void*,int,int);
  105441. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  105442. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  105443. int(*)(void*,int,const void*,int,const void*),
  105444. void(*)(void*));
  105445. int (*file_control)(sqlite3*,const char*,int,void*);
  105446. sqlite3_int64 (*memory_highwater)(int);
  105447. sqlite3_int64 (*memory_used)(void);
  105448. sqlite3_mutex *(*mutex_alloc)(int);
  105449. void (*mutex_enter)(sqlite3_mutex*);
  105450. void (*mutex_free)(sqlite3_mutex*);
  105451. void (*mutex_leave)(sqlite3_mutex*);
  105452. int (*mutex_try)(sqlite3_mutex*);
  105453. int (*open_v2)(const char*,sqlite3**,int,const char*);
  105454. int (*release_memory)(int);
  105455. void (*result_error_nomem)(sqlite3_context*);
  105456. void (*result_error_toobig)(sqlite3_context*);
  105457. int (*sleep)(int);
  105458. void (*soft_heap_limit)(int);
  105459. sqlite3_vfs *(*vfs_find)(const char*);
  105460. int (*vfs_register)(sqlite3_vfs*,int);
  105461. int (*vfs_unregister)(sqlite3_vfs*);
  105462. int (*xthreadsafe)(void);
  105463. void (*result_zeroblob)(sqlite3_context*,int);
  105464. void (*result_error_code)(sqlite3_context*,int);
  105465. int (*test_control)(int, ...);
  105466. void (*randomness)(int,void*);
  105467. sqlite3 *(*context_db_handle)(sqlite3_context*);
  105468. int (*extended_result_codes)(sqlite3*,int);
  105469. int (*limit)(sqlite3*,int,int);
  105470. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  105471. const char *(*sql)(sqlite3_stmt*);
  105472. int (*status)(int,int*,int*,int);
  105473. int (*backup_finish)(sqlite3_backup*);
  105474. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  105475. int (*backup_pagecount)(sqlite3_backup*);
  105476. int (*backup_remaining)(sqlite3_backup*);
  105477. int (*backup_step)(sqlite3_backup*,int);
  105478. const char *(*compileoption_get)(int);
  105479. int (*compileoption_used)(const char*);
  105480. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  105481. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  105482. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  105483. void (*xFinal)(sqlite3_context*),
  105484. void(*xDestroy)(void*));
  105485. int (*db_config)(sqlite3*,int,...);
  105486. sqlite3_mutex *(*db_mutex)(sqlite3*);
  105487. int (*db_status)(sqlite3*,int,int*,int*,int);
  105488. int (*extended_errcode)(sqlite3*);
  105489. void (*log)(int,const char*,...);
  105490. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  105491. const char *(*sourceid)(void);
  105492. int (*stmt_status)(sqlite3_stmt*,int,int);
  105493. int (*strnicmp)(const char*,const char*,int);
  105494. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  105495. int (*wal_autocheckpoint)(sqlite3*,int);
  105496. int (*wal_checkpoint)(sqlite3*,const char*);
  105497. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  105498. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  105499. int (*vtab_config)(sqlite3*,int op,...);
  105500. int (*vtab_on_conflict)(sqlite3*);
  105501. /* Version 3.7.16 and later */
  105502. int (*close_v2)(sqlite3*);
  105503. const char *(*db_filename)(sqlite3*,const char*);
  105504. int (*db_readonly)(sqlite3*,const char*);
  105505. int (*db_release_memory)(sqlite3*);
  105506. const char *(*errstr)(int);
  105507. int (*stmt_busy)(sqlite3_stmt*);
  105508. int (*stmt_readonly)(sqlite3_stmt*);
  105509. int (*stricmp)(const char*,const char*);
  105510. int (*uri_boolean)(const char*,const char*,int);
  105511. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  105512. const char *(*uri_parameter)(const char*,const char*);
  105513. char *(*xvsnprintf)(int,char*,const char*,va_list);
  105514. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  105515. /* Version 3.8.7 and later */
  105516. int (*auto_extension)(void(*)(void));
  105517. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  105518. void(*)(void*));
  105519. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  105520. void(*)(void*),unsigned char);
  105521. int (*cancel_auto_extension)(void(*)(void));
  105522. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  105523. void *(*malloc64)(sqlite3_uint64);
  105524. sqlite3_uint64 (*msize)(void*);
  105525. void *(*realloc64)(void*,sqlite3_uint64);
  105526. void (*reset_auto_extension)(void);
  105527. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  105528. void(*)(void*));
  105529. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  105530. void(*)(void*), unsigned char);
  105531. int (*strglob)(const char*,const char*);
  105532. /* Version 3.8.11 and later */
  105533. sqlite3_value *(*value_dup)(const sqlite3_value*);
  105534. void (*value_free)(sqlite3_value*);
  105535. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  105536. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  105537. /* Version 3.9.0 and later */
  105538. unsigned int (*value_subtype)(sqlite3_value*);
  105539. void (*result_subtype)(sqlite3_context*,unsigned int);
  105540. /* Version 3.10.0 and later */
  105541. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  105542. int (*strlike)(const char*,const char*,unsigned int);
  105543. int (*db_cacheflush)(sqlite3*);
  105544. /* Version 3.12.0 and later */
  105545. int (*system_errno)(sqlite3*);
  105546. /* Version 3.14.0 and later */
  105547. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  105548. char *(*expanded_sql)(sqlite3_stmt*);
  105549. /* Version 3.18.0 and later */
  105550. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  105551. /* Version 3.20.0 and later */
  105552. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  105553. sqlite3_stmt**,const char**);
  105554. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  105555. sqlite3_stmt**,const void**);
  105556. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  105557. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  105558. void *(*value_pointer)(sqlite3_value*,const char*);
  105559. };
  105560. /*
  105561. ** This is the function signature used for all extension entry points. It
  105562. ** is also defined in the file "loadext.c".
  105563. */
  105564. typedef int (*sqlite3_loadext_entry)(
  105565. sqlite3 *db, /* Handle to the database. */
  105566. char **pzErrMsg, /* Used to set error string on failure. */
  105567. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  105568. );
  105569. /*
  105570. ** The following macros redefine the API routines so that they are
  105571. ** redirected through the global sqlite3_api structure.
  105572. **
  105573. ** This header file is also used by the loadext.c source file
  105574. ** (part of the main SQLite library - not an extension) so that
  105575. ** it can get access to the sqlite3_api_routines structure
  105576. ** definition. But the main library does not want to redefine
  105577. ** the API. So the redefinition macros are only valid if the
  105578. ** SQLITE_CORE macros is undefined.
  105579. */
  105580. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  105581. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  105582. #ifndef SQLITE_OMIT_DEPRECATED
  105583. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  105584. #endif
  105585. #define sqlite3_bind_blob sqlite3_api->bind_blob
  105586. #define sqlite3_bind_double sqlite3_api->bind_double
  105587. #define sqlite3_bind_int sqlite3_api->bind_int
  105588. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  105589. #define sqlite3_bind_null sqlite3_api->bind_null
  105590. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  105591. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  105592. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  105593. #define sqlite3_bind_text sqlite3_api->bind_text
  105594. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  105595. #define sqlite3_bind_value sqlite3_api->bind_value
  105596. #define sqlite3_busy_handler sqlite3_api->busy_handler
  105597. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  105598. #define sqlite3_changes sqlite3_api->changes
  105599. #define sqlite3_close sqlite3_api->close
  105600. #define sqlite3_collation_needed sqlite3_api->collation_needed
  105601. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  105602. #define sqlite3_column_blob sqlite3_api->column_blob
  105603. #define sqlite3_column_bytes sqlite3_api->column_bytes
  105604. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  105605. #define sqlite3_column_count sqlite3_api->column_count
  105606. #define sqlite3_column_database_name sqlite3_api->column_database_name
  105607. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  105608. #define sqlite3_column_decltype sqlite3_api->column_decltype
  105609. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  105610. #define sqlite3_column_double sqlite3_api->column_double
  105611. #define sqlite3_column_int sqlite3_api->column_int
  105612. #define sqlite3_column_int64 sqlite3_api->column_int64
  105613. #define sqlite3_column_name sqlite3_api->column_name
  105614. #define sqlite3_column_name16 sqlite3_api->column_name16
  105615. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  105616. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  105617. #define sqlite3_column_table_name sqlite3_api->column_table_name
  105618. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  105619. #define sqlite3_column_text sqlite3_api->column_text
  105620. #define sqlite3_column_text16 sqlite3_api->column_text16
  105621. #define sqlite3_column_type sqlite3_api->column_type
  105622. #define sqlite3_column_value sqlite3_api->column_value
  105623. #define sqlite3_commit_hook sqlite3_api->commit_hook
  105624. #define sqlite3_complete sqlite3_api->complete
  105625. #define sqlite3_complete16 sqlite3_api->complete16
  105626. #define sqlite3_create_collation sqlite3_api->create_collation
  105627. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  105628. #define sqlite3_create_function sqlite3_api->create_function
  105629. #define sqlite3_create_function16 sqlite3_api->create_function16
  105630. #define sqlite3_create_module sqlite3_api->create_module
  105631. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  105632. #define sqlite3_data_count sqlite3_api->data_count
  105633. #define sqlite3_db_handle sqlite3_api->db_handle
  105634. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  105635. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  105636. #define sqlite3_errcode sqlite3_api->errcode
  105637. #define sqlite3_errmsg sqlite3_api->errmsg
  105638. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  105639. #define sqlite3_exec sqlite3_api->exec
  105640. #ifndef SQLITE_OMIT_DEPRECATED
  105641. #define sqlite3_expired sqlite3_api->expired
  105642. #endif
  105643. #define sqlite3_finalize sqlite3_api->finalize
  105644. #define sqlite3_free sqlite3_api->free
  105645. #define sqlite3_free_table sqlite3_api->free_table
  105646. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  105647. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  105648. #define sqlite3_get_table sqlite3_api->get_table
  105649. #ifndef SQLITE_OMIT_DEPRECATED
  105650. #define sqlite3_global_recover sqlite3_api->global_recover
  105651. #endif
  105652. #define sqlite3_interrupt sqlite3_api->interruptx
  105653. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  105654. #define sqlite3_libversion sqlite3_api->libversion
  105655. #define sqlite3_libversion_number sqlite3_api->libversion_number
  105656. #define sqlite3_malloc sqlite3_api->malloc
  105657. #define sqlite3_mprintf sqlite3_api->mprintf
  105658. #define sqlite3_open sqlite3_api->open
  105659. #define sqlite3_open16 sqlite3_api->open16
  105660. #define sqlite3_prepare sqlite3_api->prepare
  105661. #define sqlite3_prepare16 sqlite3_api->prepare16
  105662. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  105663. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  105664. #define sqlite3_profile sqlite3_api->profile
  105665. #define sqlite3_progress_handler sqlite3_api->progress_handler
  105666. #define sqlite3_realloc sqlite3_api->realloc
  105667. #define sqlite3_reset sqlite3_api->reset
  105668. #define sqlite3_result_blob sqlite3_api->result_blob
  105669. #define sqlite3_result_double sqlite3_api->result_double
  105670. #define sqlite3_result_error sqlite3_api->result_error
  105671. #define sqlite3_result_error16 sqlite3_api->result_error16
  105672. #define sqlite3_result_int sqlite3_api->result_int
  105673. #define sqlite3_result_int64 sqlite3_api->result_int64
  105674. #define sqlite3_result_null sqlite3_api->result_null
  105675. #define sqlite3_result_text sqlite3_api->result_text
  105676. #define sqlite3_result_text16 sqlite3_api->result_text16
  105677. #define sqlite3_result_text16be sqlite3_api->result_text16be
  105678. #define sqlite3_result_text16le sqlite3_api->result_text16le
  105679. #define sqlite3_result_value sqlite3_api->result_value
  105680. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  105681. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  105682. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  105683. #define sqlite3_snprintf sqlite3_api->xsnprintf
  105684. #define sqlite3_step sqlite3_api->step
  105685. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  105686. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  105687. #define sqlite3_total_changes sqlite3_api->total_changes
  105688. #define sqlite3_trace sqlite3_api->trace
  105689. #ifndef SQLITE_OMIT_DEPRECATED
  105690. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  105691. #endif
  105692. #define sqlite3_update_hook sqlite3_api->update_hook
  105693. #define sqlite3_user_data sqlite3_api->user_data
  105694. #define sqlite3_value_blob sqlite3_api->value_blob
  105695. #define sqlite3_value_bytes sqlite3_api->value_bytes
  105696. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  105697. #define sqlite3_value_double sqlite3_api->value_double
  105698. #define sqlite3_value_int sqlite3_api->value_int
  105699. #define sqlite3_value_int64 sqlite3_api->value_int64
  105700. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  105701. #define sqlite3_value_text sqlite3_api->value_text
  105702. #define sqlite3_value_text16 sqlite3_api->value_text16
  105703. #define sqlite3_value_text16be sqlite3_api->value_text16be
  105704. #define sqlite3_value_text16le sqlite3_api->value_text16le
  105705. #define sqlite3_value_type sqlite3_api->value_type
  105706. #define sqlite3_vmprintf sqlite3_api->vmprintf
  105707. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  105708. #define sqlite3_overload_function sqlite3_api->overload_function
  105709. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  105710. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  105711. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  105712. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  105713. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  105714. #define sqlite3_blob_close sqlite3_api->blob_close
  105715. #define sqlite3_blob_open sqlite3_api->blob_open
  105716. #define sqlite3_blob_read sqlite3_api->blob_read
  105717. #define sqlite3_blob_write sqlite3_api->blob_write
  105718. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  105719. #define sqlite3_file_control sqlite3_api->file_control
  105720. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  105721. #define sqlite3_memory_used sqlite3_api->memory_used
  105722. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  105723. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  105724. #define sqlite3_mutex_free sqlite3_api->mutex_free
  105725. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  105726. #define sqlite3_mutex_try sqlite3_api->mutex_try
  105727. #define sqlite3_open_v2 sqlite3_api->open_v2
  105728. #define sqlite3_release_memory sqlite3_api->release_memory
  105729. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  105730. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  105731. #define sqlite3_sleep sqlite3_api->sleep
  105732. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  105733. #define sqlite3_vfs_find sqlite3_api->vfs_find
  105734. #define sqlite3_vfs_register sqlite3_api->vfs_register
  105735. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  105736. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  105737. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  105738. #define sqlite3_result_error_code sqlite3_api->result_error_code
  105739. #define sqlite3_test_control sqlite3_api->test_control
  105740. #define sqlite3_randomness sqlite3_api->randomness
  105741. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  105742. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  105743. #define sqlite3_limit sqlite3_api->limit
  105744. #define sqlite3_next_stmt sqlite3_api->next_stmt
  105745. #define sqlite3_sql sqlite3_api->sql
  105746. #define sqlite3_status sqlite3_api->status
  105747. #define sqlite3_backup_finish sqlite3_api->backup_finish
  105748. #define sqlite3_backup_init sqlite3_api->backup_init
  105749. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  105750. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  105751. #define sqlite3_backup_step sqlite3_api->backup_step
  105752. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  105753. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  105754. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  105755. #define sqlite3_db_config sqlite3_api->db_config
  105756. #define sqlite3_db_mutex sqlite3_api->db_mutex
  105757. #define sqlite3_db_status sqlite3_api->db_status
  105758. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  105759. #define sqlite3_log sqlite3_api->log
  105760. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  105761. #define sqlite3_sourceid sqlite3_api->sourceid
  105762. #define sqlite3_stmt_status sqlite3_api->stmt_status
  105763. #define sqlite3_strnicmp sqlite3_api->strnicmp
  105764. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  105765. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  105766. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  105767. #define sqlite3_wal_hook sqlite3_api->wal_hook
  105768. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  105769. #define sqlite3_vtab_config sqlite3_api->vtab_config
  105770. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  105771. /* Version 3.7.16 and later */
  105772. #define sqlite3_close_v2 sqlite3_api->close_v2
  105773. #define sqlite3_db_filename sqlite3_api->db_filename
  105774. #define sqlite3_db_readonly sqlite3_api->db_readonly
  105775. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  105776. #define sqlite3_errstr sqlite3_api->errstr
  105777. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  105778. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  105779. #define sqlite3_stricmp sqlite3_api->stricmp
  105780. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  105781. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  105782. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  105783. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  105784. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  105785. /* Version 3.8.7 and later */
  105786. #define sqlite3_auto_extension sqlite3_api->auto_extension
  105787. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  105788. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  105789. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  105790. #define sqlite3_load_extension sqlite3_api->load_extension
  105791. #define sqlite3_malloc64 sqlite3_api->malloc64
  105792. #define sqlite3_msize sqlite3_api->msize
  105793. #define sqlite3_realloc64 sqlite3_api->realloc64
  105794. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  105795. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  105796. #define sqlite3_result_text64 sqlite3_api->result_text64
  105797. #define sqlite3_strglob sqlite3_api->strglob
  105798. /* Version 3.8.11 and later */
  105799. #define sqlite3_value_dup sqlite3_api->value_dup
  105800. #define sqlite3_value_free sqlite3_api->value_free
  105801. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  105802. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  105803. /* Version 3.9.0 and later */
  105804. #define sqlite3_value_subtype sqlite3_api->value_subtype
  105805. #define sqlite3_result_subtype sqlite3_api->result_subtype
  105806. /* Version 3.10.0 and later */
  105807. #define sqlite3_status64 sqlite3_api->status64
  105808. #define sqlite3_strlike sqlite3_api->strlike
  105809. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  105810. /* Version 3.12.0 and later */
  105811. #define sqlite3_system_errno sqlite3_api->system_errno
  105812. /* Version 3.14.0 and later */
  105813. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  105814. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  105815. /* Version 3.18.0 and later */
  105816. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  105817. /* Version 3.20.0 and later */
  105818. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  105819. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  105820. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  105821. #define sqlite3_result_pointer sqlite3_api->result_pointer
  105822. #define sqlite3_value_pointer sqlite3_api->value_pointer
  105823. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  105824. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  105825. /* This case when the file really is being compiled as a loadable
  105826. ** extension */
  105827. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  105828. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  105829. # define SQLITE_EXTENSION_INIT3 \
  105830. extern const sqlite3_api_routines *sqlite3_api;
  105831. #else
  105832. /* This case when the file is being statically linked into the
  105833. ** application */
  105834. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  105835. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  105836. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  105837. #endif
  105838. #endif /* SQLITE3EXT_H */
  105839. /************** End of sqlite3ext.h ******************************************/
  105840. /************** Continuing where we left off in loadext.c ********************/
  105841. /* #include "sqliteInt.h" */
  105842. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  105843. /*
  105844. ** Some API routines are omitted when various features are
  105845. ** excluded from a build of SQLite. Substitute a NULL pointer
  105846. ** for any missing APIs.
  105847. */
  105848. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  105849. # define sqlite3_column_database_name 0
  105850. # define sqlite3_column_database_name16 0
  105851. # define sqlite3_column_table_name 0
  105852. # define sqlite3_column_table_name16 0
  105853. # define sqlite3_column_origin_name 0
  105854. # define sqlite3_column_origin_name16 0
  105855. #endif
  105856. #ifdef SQLITE_OMIT_AUTHORIZATION
  105857. # define sqlite3_set_authorizer 0
  105858. #endif
  105859. #ifdef SQLITE_OMIT_UTF16
  105860. # define sqlite3_bind_text16 0
  105861. # define sqlite3_collation_needed16 0
  105862. # define sqlite3_column_decltype16 0
  105863. # define sqlite3_column_name16 0
  105864. # define sqlite3_column_text16 0
  105865. # define sqlite3_complete16 0
  105866. # define sqlite3_create_collation16 0
  105867. # define sqlite3_create_function16 0
  105868. # define sqlite3_errmsg16 0
  105869. # define sqlite3_open16 0
  105870. # define sqlite3_prepare16 0
  105871. # define sqlite3_prepare16_v2 0
  105872. # define sqlite3_prepare16_v3 0
  105873. # define sqlite3_result_error16 0
  105874. # define sqlite3_result_text16 0
  105875. # define sqlite3_result_text16be 0
  105876. # define sqlite3_result_text16le 0
  105877. # define sqlite3_value_text16 0
  105878. # define sqlite3_value_text16be 0
  105879. # define sqlite3_value_text16le 0
  105880. # define sqlite3_column_database_name16 0
  105881. # define sqlite3_column_table_name16 0
  105882. # define sqlite3_column_origin_name16 0
  105883. #endif
  105884. #ifdef SQLITE_OMIT_COMPLETE
  105885. # define sqlite3_complete 0
  105886. # define sqlite3_complete16 0
  105887. #endif
  105888. #ifdef SQLITE_OMIT_DECLTYPE
  105889. # define sqlite3_column_decltype16 0
  105890. # define sqlite3_column_decltype 0
  105891. #endif
  105892. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  105893. # define sqlite3_progress_handler 0
  105894. #endif
  105895. #ifdef SQLITE_OMIT_VIRTUALTABLE
  105896. # define sqlite3_create_module 0
  105897. # define sqlite3_create_module_v2 0
  105898. # define sqlite3_declare_vtab 0
  105899. # define sqlite3_vtab_config 0
  105900. # define sqlite3_vtab_on_conflict 0
  105901. #endif
  105902. #ifdef SQLITE_OMIT_SHARED_CACHE
  105903. # define sqlite3_enable_shared_cache 0
  105904. #endif
  105905. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  105906. # define sqlite3_profile 0
  105907. # define sqlite3_trace 0
  105908. #endif
  105909. #ifdef SQLITE_OMIT_GET_TABLE
  105910. # define sqlite3_free_table 0
  105911. # define sqlite3_get_table 0
  105912. #endif
  105913. #ifdef SQLITE_OMIT_INCRBLOB
  105914. #define sqlite3_bind_zeroblob 0
  105915. #define sqlite3_blob_bytes 0
  105916. #define sqlite3_blob_close 0
  105917. #define sqlite3_blob_open 0
  105918. #define sqlite3_blob_read 0
  105919. #define sqlite3_blob_write 0
  105920. #define sqlite3_blob_reopen 0
  105921. #endif
  105922. #if defined(SQLITE_OMIT_TRACE)
  105923. # define sqlite3_trace_v2 0
  105924. #endif
  105925. /*
  105926. ** The following structure contains pointers to all SQLite API routines.
  105927. ** A pointer to this structure is passed into extensions when they are
  105928. ** loaded so that the extension can make calls back into the SQLite
  105929. ** library.
  105930. **
  105931. ** When adding new APIs, add them to the bottom of this structure
  105932. ** in order to preserve backwards compatibility.
  105933. **
  105934. ** Extensions that use newer APIs should first call the
  105935. ** sqlite3_libversion_number() to make sure that the API they
  105936. ** intend to use is supported by the library. Extensions should
  105937. ** also check to make sure that the pointer to the function is
  105938. ** not NULL before calling it.
  105939. */
  105940. static const sqlite3_api_routines sqlite3Apis = {
  105941. sqlite3_aggregate_context,
  105942. #ifndef SQLITE_OMIT_DEPRECATED
  105943. sqlite3_aggregate_count,
  105944. #else
  105945. 0,
  105946. #endif
  105947. sqlite3_bind_blob,
  105948. sqlite3_bind_double,
  105949. sqlite3_bind_int,
  105950. sqlite3_bind_int64,
  105951. sqlite3_bind_null,
  105952. sqlite3_bind_parameter_count,
  105953. sqlite3_bind_parameter_index,
  105954. sqlite3_bind_parameter_name,
  105955. sqlite3_bind_text,
  105956. sqlite3_bind_text16,
  105957. sqlite3_bind_value,
  105958. sqlite3_busy_handler,
  105959. sqlite3_busy_timeout,
  105960. sqlite3_changes,
  105961. sqlite3_close,
  105962. sqlite3_collation_needed,
  105963. sqlite3_collation_needed16,
  105964. sqlite3_column_blob,
  105965. sqlite3_column_bytes,
  105966. sqlite3_column_bytes16,
  105967. sqlite3_column_count,
  105968. sqlite3_column_database_name,
  105969. sqlite3_column_database_name16,
  105970. sqlite3_column_decltype,
  105971. sqlite3_column_decltype16,
  105972. sqlite3_column_double,
  105973. sqlite3_column_int,
  105974. sqlite3_column_int64,
  105975. sqlite3_column_name,
  105976. sqlite3_column_name16,
  105977. sqlite3_column_origin_name,
  105978. sqlite3_column_origin_name16,
  105979. sqlite3_column_table_name,
  105980. sqlite3_column_table_name16,
  105981. sqlite3_column_text,
  105982. sqlite3_column_text16,
  105983. sqlite3_column_type,
  105984. sqlite3_column_value,
  105985. sqlite3_commit_hook,
  105986. sqlite3_complete,
  105987. sqlite3_complete16,
  105988. sqlite3_create_collation,
  105989. sqlite3_create_collation16,
  105990. sqlite3_create_function,
  105991. sqlite3_create_function16,
  105992. sqlite3_create_module,
  105993. sqlite3_data_count,
  105994. sqlite3_db_handle,
  105995. sqlite3_declare_vtab,
  105996. sqlite3_enable_shared_cache,
  105997. sqlite3_errcode,
  105998. sqlite3_errmsg,
  105999. sqlite3_errmsg16,
  106000. sqlite3_exec,
  106001. #ifndef SQLITE_OMIT_DEPRECATED
  106002. sqlite3_expired,
  106003. #else
  106004. 0,
  106005. #endif
  106006. sqlite3_finalize,
  106007. sqlite3_free,
  106008. sqlite3_free_table,
  106009. sqlite3_get_autocommit,
  106010. sqlite3_get_auxdata,
  106011. sqlite3_get_table,
  106012. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  106013. sqlite3_interrupt,
  106014. sqlite3_last_insert_rowid,
  106015. sqlite3_libversion,
  106016. sqlite3_libversion_number,
  106017. sqlite3_malloc,
  106018. sqlite3_mprintf,
  106019. sqlite3_open,
  106020. sqlite3_open16,
  106021. sqlite3_prepare,
  106022. sqlite3_prepare16,
  106023. sqlite3_profile,
  106024. sqlite3_progress_handler,
  106025. sqlite3_realloc,
  106026. sqlite3_reset,
  106027. sqlite3_result_blob,
  106028. sqlite3_result_double,
  106029. sqlite3_result_error,
  106030. sqlite3_result_error16,
  106031. sqlite3_result_int,
  106032. sqlite3_result_int64,
  106033. sqlite3_result_null,
  106034. sqlite3_result_text,
  106035. sqlite3_result_text16,
  106036. sqlite3_result_text16be,
  106037. sqlite3_result_text16le,
  106038. sqlite3_result_value,
  106039. sqlite3_rollback_hook,
  106040. sqlite3_set_authorizer,
  106041. sqlite3_set_auxdata,
  106042. sqlite3_snprintf,
  106043. sqlite3_step,
  106044. sqlite3_table_column_metadata,
  106045. #ifndef SQLITE_OMIT_DEPRECATED
  106046. sqlite3_thread_cleanup,
  106047. #else
  106048. 0,
  106049. #endif
  106050. sqlite3_total_changes,
  106051. sqlite3_trace,
  106052. #ifndef SQLITE_OMIT_DEPRECATED
  106053. sqlite3_transfer_bindings,
  106054. #else
  106055. 0,
  106056. #endif
  106057. sqlite3_update_hook,
  106058. sqlite3_user_data,
  106059. sqlite3_value_blob,
  106060. sqlite3_value_bytes,
  106061. sqlite3_value_bytes16,
  106062. sqlite3_value_double,
  106063. sqlite3_value_int,
  106064. sqlite3_value_int64,
  106065. sqlite3_value_numeric_type,
  106066. sqlite3_value_text,
  106067. sqlite3_value_text16,
  106068. sqlite3_value_text16be,
  106069. sqlite3_value_text16le,
  106070. sqlite3_value_type,
  106071. sqlite3_vmprintf,
  106072. /*
  106073. ** The original API set ends here. All extensions can call any
  106074. ** of the APIs above provided that the pointer is not NULL. But
  106075. ** before calling APIs that follow, extension should check the
  106076. ** sqlite3_libversion_number() to make sure they are dealing with
  106077. ** a library that is new enough to support that API.
  106078. *************************************************************************
  106079. */
  106080. sqlite3_overload_function,
  106081. /*
  106082. ** Added after 3.3.13
  106083. */
  106084. sqlite3_prepare_v2,
  106085. sqlite3_prepare16_v2,
  106086. sqlite3_clear_bindings,
  106087. /*
  106088. ** Added for 3.4.1
  106089. */
  106090. sqlite3_create_module_v2,
  106091. /*
  106092. ** Added for 3.5.0
  106093. */
  106094. sqlite3_bind_zeroblob,
  106095. sqlite3_blob_bytes,
  106096. sqlite3_blob_close,
  106097. sqlite3_blob_open,
  106098. sqlite3_blob_read,
  106099. sqlite3_blob_write,
  106100. sqlite3_create_collation_v2,
  106101. sqlite3_file_control,
  106102. sqlite3_memory_highwater,
  106103. sqlite3_memory_used,
  106104. #ifdef SQLITE_MUTEX_OMIT
  106105. 0,
  106106. 0,
  106107. 0,
  106108. 0,
  106109. 0,
  106110. #else
  106111. sqlite3_mutex_alloc,
  106112. sqlite3_mutex_enter,
  106113. sqlite3_mutex_free,
  106114. sqlite3_mutex_leave,
  106115. sqlite3_mutex_try,
  106116. #endif
  106117. sqlite3_open_v2,
  106118. sqlite3_release_memory,
  106119. sqlite3_result_error_nomem,
  106120. sqlite3_result_error_toobig,
  106121. sqlite3_sleep,
  106122. sqlite3_soft_heap_limit,
  106123. sqlite3_vfs_find,
  106124. sqlite3_vfs_register,
  106125. sqlite3_vfs_unregister,
  106126. /*
  106127. ** Added for 3.5.8
  106128. */
  106129. sqlite3_threadsafe,
  106130. sqlite3_result_zeroblob,
  106131. sqlite3_result_error_code,
  106132. sqlite3_test_control,
  106133. sqlite3_randomness,
  106134. sqlite3_context_db_handle,
  106135. /*
  106136. ** Added for 3.6.0
  106137. */
  106138. sqlite3_extended_result_codes,
  106139. sqlite3_limit,
  106140. sqlite3_next_stmt,
  106141. sqlite3_sql,
  106142. sqlite3_status,
  106143. /*
  106144. ** Added for 3.7.4
  106145. */
  106146. sqlite3_backup_finish,
  106147. sqlite3_backup_init,
  106148. sqlite3_backup_pagecount,
  106149. sqlite3_backup_remaining,
  106150. sqlite3_backup_step,
  106151. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  106152. sqlite3_compileoption_get,
  106153. sqlite3_compileoption_used,
  106154. #else
  106155. 0,
  106156. 0,
  106157. #endif
  106158. sqlite3_create_function_v2,
  106159. sqlite3_db_config,
  106160. sqlite3_db_mutex,
  106161. sqlite3_db_status,
  106162. sqlite3_extended_errcode,
  106163. sqlite3_log,
  106164. sqlite3_soft_heap_limit64,
  106165. sqlite3_sourceid,
  106166. sqlite3_stmt_status,
  106167. sqlite3_strnicmp,
  106168. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  106169. sqlite3_unlock_notify,
  106170. #else
  106171. 0,
  106172. #endif
  106173. #ifndef SQLITE_OMIT_WAL
  106174. sqlite3_wal_autocheckpoint,
  106175. sqlite3_wal_checkpoint,
  106176. sqlite3_wal_hook,
  106177. #else
  106178. 0,
  106179. 0,
  106180. 0,
  106181. #endif
  106182. sqlite3_blob_reopen,
  106183. sqlite3_vtab_config,
  106184. sqlite3_vtab_on_conflict,
  106185. sqlite3_close_v2,
  106186. sqlite3_db_filename,
  106187. sqlite3_db_readonly,
  106188. sqlite3_db_release_memory,
  106189. sqlite3_errstr,
  106190. sqlite3_stmt_busy,
  106191. sqlite3_stmt_readonly,
  106192. sqlite3_stricmp,
  106193. sqlite3_uri_boolean,
  106194. sqlite3_uri_int64,
  106195. sqlite3_uri_parameter,
  106196. sqlite3_vsnprintf,
  106197. sqlite3_wal_checkpoint_v2,
  106198. /* Version 3.8.7 and later */
  106199. sqlite3_auto_extension,
  106200. sqlite3_bind_blob64,
  106201. sqlite3_bind_text64,
  106202. sqlite3_cancel_auto_extension,
  106203. sqlite3_load_extension,
  106204. sqlite3_malloc64,
  106205. sqlite3_msize,
  106206. sqlite3_realloc64,
  106207. sqlite3_reset_auto_extension,
  106208. sqlite3_result_blob64,
  106209. sqlite3_result_text64,
  106210. sqlite3_strglob,
  106211. /* Version 3.8.11 and later */
  106212. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  106213. sqlite3_value_free,
  106214. sqlite3_result_zeroblob64,
  106215. sqlite3_bind_zeroblob64,
  106216. /* Version 3.9.0 and later */
  106217. sqlite3_value_subtype,
  106218. sqlite3_result_subtype,
  106219. /* Version 3.10.0 and later */
  106220. sqlite3_status64,
  106221. sqlite3_strlike,
  106222. sqlite3_db_cacheflush,
  106223. /* Version 3.12.0 and later */
  106224. sqlite3_system_errno,
  106225. /* Version 3.14.0 and later */
  106226. sqlite3_trace_v2,
  106227. sqlite3_expanded_sql,
  106228. /* Version 3.18.0 and later */
  106229. sqlite3_set_last_insert_rowid,
  106230. /* Version 3.20.0 and later */
  106231. sqlite3_prepare_v3,
  106232. sqlite3_prepare16_v3,
  106233. sqlite3_bind_pointer,
  106234. sqlite3_result_pointer,
  106235. sqlite3_value_pointer
  106236. };
  106237. /*
  106238. ** Attempt to load an SQLite extension library contained in the file
  106239. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  106240. ** default entry point name (sqlite3_extension_init) is used. Use
  106241. ** of the default name is recommended.
  106242. **
  106243. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  106244. **
  106245. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  106246. ** error message text. The calling function should free this memory
  106247. ** by calling sqlite3DbFree(db, ).
  106248. */
  106249. static int sqlite3LoadExtension(
  106250. sqlite3 *db, /* Load the extension into this database connection */
  106251. const char *zFile, /* Name of the shared library containing extension */
  106252. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  106253. char **pzErrMsg /* Put error message here if not 0 */
  106254. ){
  106255. sqlite3_vfs *pVfs = db->pVfs;
  106256. void *handle;
  106257. sqlite3_loadext_entry xInit;
  106258. char *zErrmsg = 0;
  106259. const char *zEntry;
  106260. char *zAltEntry = 0;
  106261. void **aHandle;
  106262. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  106263. int ii;
  106264. int rc;
  106265. /* Shared library endings to try if zFile cannot be loaded as written */
  106266. static const char *azEndings[] = {
  106267. #if SQLITE_OS_WIN
  106268. "dll"
  106269. #elif defined(__APPLE__)
  106270. "dylib"
  106271. #else
  106272. "so"
  106273. #endif
  106274. };
  106275. if( pzErrMsg ) *pzErrMsg = 0;
  106276. /* Ticket #1863. To avoid a creating security problems for older
  106277. ** applications that relink against newer versions of SQLite, the
  106278. ** ability to run load_extension is turned off by default. One
  106279. ** must call either sqlite3_enable_load_extension(db) or
  106280. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  106281. ** to turn on extension loading.
  106282. */
  106283. if( (db->flags & SQLITE_LoadExtension)==0 ){
  106284. if( pzErrMsg ){
  106285. *pzErrMsg = sqlite3_mprintf("not authorized");
  106286. }
  106287. return SQLITE_ERROR;
  106288. }
  106289. zEntry = zProc ? zProc : "sqlite3_extension_init";
  106290. handle = sqlite3OsDlOpen(pVfs, zFile);
  106291. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  106292. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  106293. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  106294. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  106295. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  106296. sqlite3_free(zAltFile);
  106297. }
  106298. #endif
  106299. if( handle==0 ){
  106300. if( pzErrMsg ){
  106301. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  106302. if( zErrmsg ){
  106303. sqlite3_snprintf(nMsg, zErrmsg,
  106304. "unable to open shared library [%s]", zFile);
  106305. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  106306. }
  106307. }
  106308. return SQLITE_ERROR;
  106309. }
  106310. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  106311. /* If no entry point was specified and the default legacy
  106312. ** entry point name "sqlite3_extension_init" was not found, then
  106313. ** construct an entry point name "sqlite3_X_init" where the X is
  106314. ** replaced by the lowercase value of every ASCII alphabetic
  106315. ** character in the filename after the last "/" upto the first ".",
  106316. ** and eliding the first three characters if they are "lib".
  106317. ** Examples:
  106318. **
  106319. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  106320. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  106321. */
  106322. if( xInit==0 && zProc==0 ){
  106323. int iFile, iEntry, c;
  106324. int ncFile = sqlite3Strlen30(zFile);
  106325. zAltEntry = sqlite3_malloc64(ncFile+30);
  106326. if( zAltEntry==0 ){
  106327. sqlite3OsDlClose(pVfs, handle);
  106328. return SQLITE_NOMEM_BKPT;
  106329. }
  106330. memcpy(zAltEntry, "sqlite3_", 8);
  106331. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  106332. iFile++;
  106333. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  106334. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  106335. if( sqlite3Isalpha(c) ){
  106336. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  106337. }
  106338. }
  106339. memcpy(zAltEntry+iEntry, "_init", 6);
  106340. zEntry = zAltEntry;
  106341. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  106342. }
  106343. if( xInit==0 ){
  106344. if( pzErrMsg ){
  106345. nMsg += sqlite3Strlen30(zEntry);
  106346. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  106347. if( zErrmsg ){
  106348. sqlite3_snprintf(nMsg, zErrmsg,
  106349. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  106350. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  106351. }
  106352. }
  106353. sqlite3OsDlClose(pVfs, handle);
  106354. sqlite3_free(zAltEntry);
  106355. return SQLITE_ERROR;
  106356. }
  106357. sqlite3_free(zAltEntry);
  106358. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  106359. if( rc ){
  106360. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  106361. if( pzErrMsg ){
  106362. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  106363. }
  106364. sqlite3_free(zErrmsg);
  106365. sqlite3OsDlClose(pVfs, handle);
  106366. return SQLITE_ERROR;
  106367. }
  106368. /* Append the new shared library handle to the db->aExtension array. */
  106369. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  106370. if( aHandle==0 ){
  106371. return SQLITE_NOMEM_BKPT;
  106372. }
  106373. if( db->nExtension>0 ){
  106374. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  106375. }
  106376. sqlite3DbFree(db, db->aExtension);
  106377. db->aExtension = aHandle;
  106378. db->aExtension[db->nExtension++] = handle;
  106379. return SQLITE_OK;
  106380. }
  106381. SQLITE_API int sqlite3_load_extension(
  106382. sqlite3 *db, /* Load the extension into this database connection */
  106383. const char *zFile, /* Name of the shared library containing extension */
  106384. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  106385. char **pzErrMsg /* Put error message here if not 0 */
  106386. ){
  106387. int rc;
  106388. sqlite3_mutex_enter(db->mutex);
  106389. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  106390. rc = sqlite3ApiExit(db, rc);
  106391. sqlite3_mutex_leave(db->mutex);
  106392. return rc;
  106393. }
  106394. /*
  106395. ** Call this routine when the database connection is closing in order
  106396. ** to clean up loaded extensions
  106397. */
  106398. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  106399. int i;
  106400. assert( sqlite3_mutex_held(db->mutex) );
  106401. for(i=0; i<db->nExtension; i++){
  106402. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  106403. }
  106404. sqlite3DbFree(db, db->aExtension);
  106405. }
  106406. /*
  106407. ** Enable or disable extension loading. Extension loading is disabled by
  106408. ** default so as not to open security holes in older applications.
  106409. */
  106410. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  106411. sqlite3_mutex_enter(db->mutex);
  106412. if( onoff ){
  106413. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  106414. }else{
  106415. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  106416. }
  106417. sqlite3_mutex_leave(db->mutex);
  106418. return SQLITE_OK;
  106419. }
  106420. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  106421. /*
  106422. ** The following object holds the list of automatically loaded
  106423. ** extensions.
  106424. **
  106425. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  106426. ** mutex must be held while accessing this list.
  106427. */
  106428. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  106429. static SQLITE_WSD struct sqlite3AutoExtList {
  106430. u32 nExt; /* Number of entries in aExt[] */
  106431. void (**aExt)(void); /* Pointers to the extension init functions */
  106432. } sqlite3Autoext = { 0, 0 };
  106433. /* The "wsdAutoext" macro will resolve to the autoextension
  106434. ** state vector. If writable static data is unsupported on the target,
  106435. ** we have to locate the state vector at run-time. In the more common
  106436. ** case where writable static data is supported, wsdStat can refer directly
  106437. ** to the "sqlite3Autoext" state vector declared above.
  106438. */
  106439. #ifdef SQLITE_OMIT_WSD
  106440. # define wsdAutoextInit \
  106441. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  106442. # define wsdAutoext x[0]
  106443. #else
  106444. # define wsdAutoextInit
  106445. # define wsdAutoext sqlite3Autoext
  106446. #endif
  106447. /*
  106448. ** Register a statically linked extension that is automatically
  106449. ** loaded by every new database connection.
  106450. */
  106451. SQLITE_API int sqlite3_auto_extension(
  106452. void (*xInit)(void)
  106453. ){
  106454. int rc = SQLITE_OK;
  106455. #ifndef SQLITE_OMIT_AUTOINIT
  106456. rc = sqlite3_initialize();
  106457. if( rc ){
  106458. return rc;
  106459. }else
  106460. #endif
  106461. {
  106462. u32 i;
  106463. #if SQLITE_THREADSAFE
  106464. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  106465. #endif
  106466. wsdAutoextInit;
  106467. sqlite3_mutex_enter(mutex);
  106468. for(i=0; i<wsdAutoext.nExt; i++){
  106469. if( wsdAutoext.aExt[i]==xInit ) break;
  106470. }
  106471. if( i==wsdAutoext.nExt ){
  106472. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  106473. void (**aNew)(void);
  106474. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  106475. if( aNew==0 ){
  106476. rc = SQLITE_NOMEM_BKPT;
  106477. }else{
  106478. wsdAutoext.aExt = aNew;
  106479. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  106480. wsdAutoext.nExt++;
  106481. }
  106482. }
  106483. sqlite3_mutex_leave(mutex);
  106484. assert( (rc&0xff)==rc );
  106485. return rc;
  106486. }
  106487. }
  106488. /*
  106489. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  106490. ** set of routines that is invoked for each new database connection, if it
  106491. ** is currently on the list. If xInit is not on the list, then this
  106492. ** routine is a no-op.
  106493. **
  106494. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  106495. ** was not on the list.
  106496. */
  106497. SQLITE_API int sqlite3_cancel_auto_extension(
  106498. void (*xInit)(void)
  106499. ){
  106500. #if SQLITE_THREADSAFE
  106501. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  106502. #endif
  106503. int i;
  106504. int n = 0;
  106505. wsdAutoextInit;
  106506. sqlite3_mutex_enter(mutex);
  106507. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  106508. if( wsdAutoext.aExt[i]==xInit ){
  106509. wsdAutoext.nExt--;
  106510. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  106511. n++;
  106512. break;
  106513. }
  106514. }
  106515. sqlite3_mutex_leave(mutex);
  106516. return n;
  106517. }
  106518. /*
  106519. ** Reset the automatic extension loading mechanism.
  106520. */
  106521. SQLITE_API void sqlite3_reset_auto_extension(void){
  106522. #ifndef SQLITE_OMIT_AUTOINIT
  106523. if( sqlite3_initialize()==SQLITE_OK )
  106524. #endif
  106525. {
  106526. #if SQLITE_THREADSAFE
  106527. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  106528. #endif
  106529. wsdAutoextInit;
  106530. sqlite3_mutex_enter(mutex);
  106531. sqlite3_free(wsdAutoext.aExt);
  106532. wsdAutoext.aExt = 0;
  106533. wsdAutoext.nExt = 0;
  106534. sqlite3_mutex_leave(mutex);
  106535. }
  106536. }
  106537. /*
  106538. ** Load all automatic extensions.
  106539. **
  106540. ** If anything goes wrong, set an error in the database connection.
  106541. */
  106542. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  106543. u32 i;
  106544. int go = 1;
  106545. int rc;
  106546. sqlite3_loadext_entry xInit;
  106547. wsdAutoextInit;
  106548. if( wsdAutoext.nExt==0 ){
  106549. /* Common case: early out without every having to acquire a mutex */
  106550. return;
  106551. }
  106552. for(i=0; go; i++){
  106553. char *zErrmsg;
  106554. #if SQLITE_THREADSAFE
  106555. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  106556. #endif
  106557. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  106558. const sqlite3_api_routines *pThunk = 0;
  106559. #else
  106560. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  106561. #endif
  106562. sqlite3_mutex_enter(mutex);
  106563. if( i>=wsdAutoext.nExt ){
  106564. xInit = 0;
  106565. go = 0;
  106566. }else{
  106567. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  106568. }
  106569. sqlite3_mutex_leave(mutex);
  106570. zErrmsg = 0;
  106571. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  106572. sqlite3ErrorWithMsg(db, rc,
  106573. "automatic extension loading failed: %s", zErrmsg);
  106574. go = 0;
  106575. }
  106576. sqlite3_free(zErrmsg);
  106577. }
  106578. }
  106579. /************** End of loadext.c *********************************************/
  106580. /************** Begin file pragma.c ******************************************/
  106581. /*
  106582. ** 2003 April 6
  106583. **
  106584. ** The author disclaims copyright to this source code. In place of
  106585. ** a legal notice, here is a blessing:
  106586. **
  106587. ** May you do good and not evil.
  106588. ** May you find forgiveness for yourself and forgive others.
  106589. ** May you share freely, never taking more than you give.
  106590. **
  106591. *************************************************************************
  106592. ** This file contains code used to implement the PRAGMA command.
  106593. */
  106594. /* #include "sqliteInt.h" */
  106595. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  106596. # if defined(__APPLE__)
  106597. # define SQLITE_ENABLE_LOCKING_STYLE 1
  106598. # else
  106599. # define SQLITE_ENABLE_LOCKING_STYLE 0
  106600. # endif
  106601. #endif
  106602. /***************************************************************************
  106603. ** The "pragma.h" include file is an automatically generated file that
  106604. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  106605. ** object. This ensures that the aPragmaName[] table is arranged in
  106606. ** lexicographical order to facility a binary search of the pragma name.
  106607. ** Do not edit pragma.h directly. Edit and rerun the script in at
  106608. ** ../tool/mkpragmatab.tcl. */
  106609. /************** Include pragma.h in the middle of pragma.c *******************/
  106610. /************** Begin file pragma.h ******************************************/
  106611. /* DO NOT EDIT!
  106612. ** This file is automatically generated by the script at
  106613. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  106614. ** that script and rerun it.
  106615. */
  106616. /* The various pragma types */
  106617. #define PragTyp_HEADER_VALUE 0
  106618. #define PragTyp_AUTO_VACUUM 1
  106619. #define PragTyp_FLAG 2
  106620. #define PragTyp_BUSY_TIMEOUT 3
  106621. #define PragTyp_CACHE_SIZE 4
  106622. #define PragTyp_CACHE_SPILL 5
  106623. #define PragTyp_CASE_SENSITIVE_LIKE 6
  106624. #define PragTyp_COLLATION_LIST 7
  106625. #define PragTyp_COMPILE_OPTIONS 8
  106626. #define PragTyp_DATA_STORE_DIRECTORY 9
  106627. #define PragTyp_DATABASE_LIST 10
  106628. #define PragTyp_DEFAULT_CACHE_SIZE 11
  106629. #define PragTyp_ENCODING 12
  106630. #define PragTyp_FOREIGN_KEY_CHECK 13
  106631. #define PragTyp_FOREIGN_KEY_LIST 14
  106632. #define PragTyp_FUNCTION_LIST 15
  106633. #define PragTyp_INCREMENTAL_VACUUM 16
  106634. #define PragTyp_INDEX_INFO 17
  106635. #define PragTyp_INDEX_LIST 18
  106636. #define PragTyp_INTEGRITY_CHECK 19
  106637. #define PragTyp_JOURNAL_MODE 20
  106638. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  106639. #define PragTyp_LOCK_PROXY_FILE 22
  106640. #define PragTyp_LOCKING_MODE 23
  106641. #define PragTyp_PAGE_COUNT 24
  106642. #define PragTyp_MMAP_SIZE 25
  106643. #define PragTyp_MODULE_LIST 26
  106644. #define PragTyp_OPTIMIZE 27
  106645. #define PragTyp_PAGE_SIZE 28
  106646. #define PragTyp_PRAGMA_LIST 29
  106647. #define PragTyp_SECURE_DELETE 30
  106648. #define PragTyp_SHRINK_MEMORY 31
  106649. #define PragTyp_SOFT_HEAP_LIMIT 32
  106650. #define PragTyp_SYNCHRONOUS 33
  106651. #define PragTyp_TABLE_INFO 34
  106652. #define PragTyp_TEMP_STORE 35
  106653. #define PragTyp_TEMP_STORE_DIRECTORY 36
  106654. #define PragTyp_THREADS 37
  106655. #define PragTyp_WAL_AUTOCHECKPOINT 38
  106656. #define PragTyp_WAL_CHECKPOINT 39
  106657. #define PragTyp_ACTIVATE_EXTENSIONS 40
  106658. #define PragTyp_HEXKEY 41
  106659. #define PragTyp_KEY 42
  106660. #define PragTyp_REKEY 43
  106661. #define PragTyp_LOCK_STATUS 44
  106662. #define PragTyp_PARSER_TRACE 45
  106663. #define PragTyp_STATS 46
  106664. /* Property flags associated with various pragma. */
  106665. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  106666. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  106667. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  106668. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  106669. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  106670. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  106671. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  106672. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  106673. /* Names of columns for pragmas that return multi-column result
  106674. ** or that return single-column results where the name of the
  106675. ** result column is different from the name of the pragma
  106676. */
  106677. static const char *const pragCName[] = {
  106678. /* 0 */ "cache_size", /* Used by: default_cache_size */
  106679. /* 1 */ "cid", /* Used by: table_info */
  106680. /* 2 */ "name",
  106681. /* 3 */ "type",
  106682. /* 4 */ "notnull",
  106683. /* 5 */ "dflt_value",
  106684. /* 6 */ "pk",
  106685. /* 7 */ "tbl", /* Used by: stats */
  106686. /* 8 */ "idx",
  106687. /* 9 */ "wdth",
  106688. /* 10 */ "hght",
  106689. /* 11 */ "flgs",
  106690. /* 12 */ "seqno", /* Used by: index_info */
  106691. /* 13 */ "cid",
  106692. /* 14 */ "name",
  106693. /* 15 */ "seqno", /* Used by: index_xinfo */
  106694. /* 16 */ "cid",
  106695. /* 17 */ "name",
  106696. /* 18 */ "desc",
  106697. /* 19 */ "coll",
  106698. /* 20 */ "key",
  106699. /* 21 */ "seq", /* Used by: index_list */
  106700. /* 22 */ "name",
  106701. /* 23 */ "unique",
  106702. /* 24 */ "origin",
  106703. /* 25 */ "partial",
  106704. /* 26 */ "seq", /* Used by: database_list */
  106705. /* 27 */ "name",
  106706. /* 28 */ "file",
  106707. /* 29 */ "name", /* Used by: function_list */
  106708. /* 30 */ "builtin",
  106709. /* 31 */ "name", /* Used by: module_list pragma_list */
  106710. /* 32 */ "seq", /* Used by: collation_list */
  106711. /* 33 */ "name",
  106712. /* 34 */ "id", /* Used by: foreign_key_list */
  106713. /* 35 */ "seq",
  106714. /* 36 */ "table",
  106715. /* 37 */ "from",
  106716. /* 38 */ "to",
  106717. /* 39 */ "on_update",
  106718. /* 40 */ "on_delete",
  106719. /* 41 */ "match",
  106720. /* 42 */ "table", /* Used by: foreign_key_check */
  106721. /* 43 */ "rowid",
  106722. /* 44 */ "parent",
  106723. /* 45 */ "fkid",
  106724. /* 46 */ "busy", /* Used by: wal_checkpoint */
  106725. /* 47 */ "log",
  106726. /* 48 */ "checkpointed",
  106727. /* 49 */ "timeout", /* Used by: busy_timeout */
  106728. /* 50 */ "database", /* Used by: lock_status */
  106729. /* 51 */ "status",
  106730. };
  106731. /* Definitions of all built-in pragmas */
  106732. typedef struct PragmaName {
  106733. const char *const zName; /* Name of pragma */
  106734. u8 ePragTyp; /* PragTyp_XXX value */
  106735. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  106736. u8 iPragCName; /* Start of column names in pragCName[] */
  106737. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  106738. u32 iArg; /* Extra argument */
  106739. } PragmaName;
  106740. static const PragmaName aPragmaName[] = {
  106741. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  106742. {/* zName: */ "activate_extensions",
  106743. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  106744. /* ePragFlg: */ 0,
  106745. /* ColNames: */ 0, 0,
  106746. /* iArg: */ 0 },
  106747. #endif
  106748. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106749. {/* zName: */ "application_id",
  106750. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106751. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  106752. /* ColNames: */ 0, 0,
  106753. /* iArg: */ BTREE_APPLICATION_ID },
  106754. #endif
  106755. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  106756. {/* zName: */ "auto_vacuum",
  106757. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  106758. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106759. /* ColNames: */ 0, 0,
  106760. /* iArg: */ 0 },
  106761. #endif
  106762. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106763. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  106764. {/* zName: */ "automatic_index",
  106765. /* ePragTyp: */ PragTyp_FLAG,
  106766. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106767. /* ColNames: */ 0, 0,
  106768. /* iArg: */ SQLITE_AutoIndex },
  106769. #endif
  106770. #endif
  106771. {/* zName: */ "busy_timeout",
  106772. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  106773. /* ePragFlg: */ PragFlg_Result0,
  106774. /* ColNames: */ 49, 1,
  106775. /* iArg: */ 0 },
  106776. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106777. {/* zName: */ "cache_size",
  106778. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  106779. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106780. /* ColNames: */ 0, 0,
  106781. /* iArg: */ 0 },
  106782. #endif
  106783. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106784. {/* zName: */ "cache_spill",
  106785. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  106786. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106787. /* ColNames: */ 0, 0,
  106788. /* iArg: */ 0 },
  106789. #endif
  106790. {/* zName: */ "case_sensitive_like",
  106791. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  106792. /* ePragFlg: */ PragFlg_NoColumns,
  106793. /* ColNames: */ 0, 0,
  106794. /* iArg: */ 0 },
  106795. {/* zName: */ "cell_size_check",
  106796. /* ePragTyp: */ PragTyp_FLAG,
  106797. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106798. /* ColNames: */ 0, 0,
  106799. /* iArg: */ SQLITE_CellSizeCk },
  106800. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106801. {/* zName: */ "checkpoint_fullfsync",
  106802. /* ePragTyp: */ PragTyp_FLAG,
  106803. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106804. /* ColNames: */ 0, 0,
  106805. /* iArg: */ SQLITE_CkptFullFSync },
  106806. #endif
  106807. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106808. {/* zName: */ "collation_list",
  106809. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  106810. /* ePragFlg: */ PragFlg_Result0,
  106811. /* ColNames: */ 32, 2,
  106812. /* iArg: */ 0 },
  106813. #endif
  106814. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  106815. {/* zName: */ "compile_options",
  106816. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  106817. /* ePragFlg: */ PragFlg_Result0,
  106818. /* ColNames: */ 0, 0,
  106819. /* iArg: */ 0 },
  106820. #endif
  106821. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106822. {/* zName: */ "count_changes",
  106823. /* ePragTyp: */ PragTyp_FLAG,
  106824. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106825. /* ColNames: */ 0, 0,
  106826. /* iArg: */ SQLITE_CountRows },
  106827. #endif
  106828. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  106829. {/* zName: */ "data_store_directory",
  106830. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  106831. /* ePragFlg: */ PragFlg_NoColumns1,
  106832. /* ColNames: */ 0, 0,
  106833. /* iArg: */ 0 },
  106834. #endif
  106835. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106836. {/* zName: */ "data_version",
  106837. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106838. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  106839. /* ColNames: */ 0, 0,
  106840. /* iArg: */ BTREE_DATA_VERSION },
  106841. #endif
  106842. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106843. {/* zName: */ "database_list",
  106844. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  106845. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  106846. /* ColNames: */ 26, 3,
  106847. /* iArg: */ 0 },
  106848. #endif
  106849. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  106850. {/* zName: */ "default_cache_size",
  106851. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  106852. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106853. /* ColNames: */ 0, 1,
  106854. /* iArg: */ 0 },
  106855. #endif
  106856. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106857. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  106858. {/* zName: */ "defer_foreign_keys",
  106859. /* ePragTyp: */ PragTyp_FLAG,
  106860. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106861. /* ColNames: */ 0, 0,
  106862. /* iArg: */ SQLITE_DeferFKs },
  106863. #endif
  106864. #endif
  106865. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106866. {/* zName: */ "empty_result_callbacks",
  106867. /* ePragTyp: */ PragTyp_FLAG,
  106868. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106869. /* ColNames: */ 0, 0,
  106870. /* iArg: */ SQLITE_NullCallback },
  106871. #endif
  106872. #if !defined(SQLITE_OMIT_UTF16)
  106873. {/* zName: */ "encoding",
  106874. /* ePragTyp: */ PragTyp_ENCODING,
  106875. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106876. /* ColNames: */ 0, 0,
  106877. /* iArg: */ 0 },
  106878. #endif
  106879. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  106880. {/* zName: */ "foreign_key_check",
  106881. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  106882. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  106883. /* ColNames: */ 42, 4,
  106884. /* iArg: */ 0 },
  106885. #endif
  106886. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  106887. {/* zName: */ "foreign_key_list",
  106888. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  106889. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106890. /* ColNames: */ 34, 8,
  106891. /* iArg: */ 0 },
  106892. #endif
  106893. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106894. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  106895. {/* zName: */ "foreign_keys",
  106896. /* ePragTyp: */ PragTyp_FLAG,
  106897. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106898. /* ColNames: */ 0, 0,
  106899. /* iArg: */ SQLITE_ForeignKeys },
  106900. #endif
  106901. #endif
  106902. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106903. {/* zName: */ "freelist_count",
  106904. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106905. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  106906. /* ColNames: */ 0, 0,
  106907. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  106908. #endif
  106909. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106910. {/* zName: */ "full_column_names",
  106911. /* ePragTyp: */ PragTyp_FLAG,
  106912. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106913. /* ColNames: */ 0, 0,
  106914. /* iArg: */ SQLITE_FullColNames },
  106915. {/* zName: */ "fullfsync",
  106916. /* ePragTyp: */ PragTyp_FLAG,
  106917. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106918. /* ColNames: */ 0, 0,
  106919. /* iArg: */ SQLITE_FullFSync },
  106920. #endif
  106921. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106922. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  106923. {/* zName: */ "function_list",
  106924. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  106925. /* ePragFlg: */ PragFlg_Result0,
  106926. /* ColNames: */ 29, 2,
  106927. /* iArg: */ 0 },
  106928. #endif
  106929. #endif
  106930. #if defined(SQLITE_HAS_CODEC)
  106931. {/* zName: */ "hexkey",
  106932. /* ePragTyp: */ PragTyp_HEXKEY,
  106933. /* ePragFlg: */ 0,
  106934. /* ColNames: */ 0, 0,
  106935. /* iArg: */ 0 },
  106936. {/* zName: */ "hexrekey",
  106937. /* ePragTyp: */ PragTyp_HEXKEY,
  106938. /* ePragFlg: */ 0,
  106939. /* ColNames: */ 0, 0,
  106940. /* iArg: */ 0 },
  106941. #endif
  106942. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106943. #if !defined(SQLITE_OMIT_CHECK)
  106944. {/* zName: */ "ignore_check_constraints",
  106945. /* ePragTyp: */ PragTyp_FLAG,
  106946. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106947. /* ColNames: */ 0, 0,
  106948. /* iArg: */ SQLITE_IgnoreChecks },
  106949. #endif
  106950. #endif
  106951. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  106952. {/* zName: */ "incremental_vacuum",
  106953. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  106954. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  106955. /* ColNames: */ 0, 0,
  106956. /* iArg: */ 0 },
  106957. #endif
  106958. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106959. {/* zName: */ "index_info",
  106960. /* ePragTyp: */ PragTyp_INDEX_INFO,
  106961. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106962. /* ColNames: */ 12, 3,
  106963. /* iArg: */ 0 },
  106964. {/* zName: */ "index_list",
  106965. /* ePragTyp: */ PragTyp_INDEX_LIST,
  106966. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106967. /* ColNames: */ 21, 5,
  106968. /* iArg: */ 0 },
  106969. {/* zName: */ "index_xinfo",
  106970. /* ePragTyp: */ PragTyp_INDEX_INFO,
  106971. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106972. /* ColNames: */ 15, 6,
  106973. /* iArg: */ 1 },
  106974. #endif
  106975. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  106976. {/* zName: */ "integrity_check",
  106977. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  106978. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  106979. /* ColNames: */ 0, 0,
  106980. /* iArg: */ 0 },
  106981. #endif
  106982. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106983. {/* zName: */ "journal_mode",
  106984. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  106985. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106986. /* ColNames: */ 0, 0,
  106987. /* iArg: */ 0 },
  106988. {/* zName: */ "journal_size_limit",
  106989. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  106990. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  106991. /* ColNames: */ 0, 0,
  106992. /* iArg: */ 0 },
  106993. #endif
  106994. #if defined(SQLITE_HAS_CODEC)
  106995. {/* zName: */ "key",
  106996. /* ePragTyp: */ PragTyp_KEY,
  106997. /* ePragFlg: */ 0,
  106998. /* ColNames: */ 0, 0,
  106999. /* iArg: */ 0 },
  107000. #endif
  107001. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107002. {/* zName: */ "legacy_file_format",
  107003. /* ePragTyp: */ PragTyp_FLAG,
  107004. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107005. /* ColNames: */ 0, 0,
  107006. /* iArg: */ SQLITE_LegacyFileFmt },
  107007. #endif
  107008. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  107009. {/* zName: */ "lock_proxy_file",
  107010. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  107011. /* ePragFlg: */ PragFlg_NoColumns1,
  107012. /* ColNames: */ 0, 0,
  107013. /* iArg: */ 0 },
  107014. #endif
  107015. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  107016. {/* zName: */ "lock_status",
  107017. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  107018. /* ePragFlg: */ PragFlg_Result0,
  107019. /* ColNames: */ 50, 2,
  107020. /* iArg: */ 0 },
  107021. #endif
  107022. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107023. {/* zName: */ "locking_mode",
  107024. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  107025. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  107026. /* ColNames: */ 0, 0,
  107027. /* iArg: */ 0 },
  107028. {/* zName: */ "max_page_count",
  107029. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  107030. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  107031. /* ColNames: */ 0, 0,
  107032. /* iArg: */ 0 },
  107033. {/* zName: */ "mmap_size",
  107034. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  107035. /* ePragFlg: */ 0,
  107036. /* ColNames: */ 0, 0,
  107037. /* iArg: */ 0 },
  107038. #endif
  107039. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  107040. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  107041. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  107042. {/* zName: */ "module_list",
  107043. /* ePragTyp: */ PragTyp_MODULE_LIST,
  107044. /* ePragFlg: */ PragFlg_Result0,
  107045. /* ColNames: */ 31, 1,
  107046. /* iArg: */ 0 },
  107047. #endif
  107048. #endif
  107049. #endif
  107050. {/* zName: */ "optimize",
  107051. /* ePragTyp: */ PragTyp_OPTIMIZE,
  107052. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  107053. /* ColNames: */ 0, 0,
  107054. /* iArg: */ 0 },
  107055. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107056. {/* zName: */ "page_count",
  107057. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  107058. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  107059. /* ColNames: */ 0, 0,
  107060. /* iArg: */ 0 },
  107061. {/* zName: */ "page_size",
  107062. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  107063. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  107064. /* ColNames: */ 0, 0,
  107065. /* iArg: */ 0 },
  107066. #endif
  107067. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  107068. {/* zName: */ "parser_trace",
  107069. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  107070. /* ePragFlg: */ 0,
  107071. /* ColNames: */ 0, 0,
  107072. /* iArg: */ 0 },
  107073. #endif
  107074. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  107075. {/* zName: */ "pragma_list",
  107076. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  107077. /* ePragFlg: */ PragFlg_Result0,
  107078. /* ColNames: */ 31, 1,
  107079. /* iArg: */ 0 },
  107080. #endif
  107081. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107082. {/* zName: */ "query_only",
  107083. /* ePragTyp: */ PragTyp_FLAG,
  107084. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107085. /* ColNames: */ 0, 0,
  107086. /* iArg: */ SQLITE_QueryOnly },
  107087. #endif
  107088. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  107089. {/* zName: */ "quick_check",
  107090. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  107091. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  107092. /* ColNames: */ 0, 0,
  107093. /* iArg: */ 0 },
  107094. #endif
  107095. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107096. {/* zName: */ "read_uncommitted",
  107097. /* ePragTyp: */ PragTyp_FLAG,
  107098. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107099. /* ColNames: */ 0, 0,
  107100. /* iArg: */ SQLITE_ReadUncommit },
  107101. {/* zName: */ "recursive_triggers",
  107102. /* ePragTyp: */ PragTyp_FLAG,
  107103. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107104. /* ColNames: */ 0, 0,
  107105. /* iArg: */ SQLITE_RecTriggers },
  107106. #endif
  107107. #if defined(SQLITE_HAS_CODEC)
  107108. {/* zName: */ "rekey",
  107109. /* ePragTyp: */ PragTyp_REKEY,
  107110. /* ePragFlg: */ 0,
  107111. /* ColNames: */ 0, 0,
  107112. /* iArg: */ 0 },
  107113. #endif
  107114. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107115. {/* zName: */ "reverse_unordered_selects",
  107116. /* ePragTyp: */ PragTyp_FLAG,
  107117. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107118. /* ColNames: */ 0, 0,
  107119. /* iArg: */ SQLITE_ReverseOrder },
  107120. #endif
  107121. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  107122. {/* zName: */ "schema_version",
  107123. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  107124. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  107125. /* ColNames: */ 0, 0,
  107126. /* iArg: */ BTREE_SCHEMA_VERSION },
  107127. #endif
  107128. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107129. {/* zName: */ "secure_delete",
  107130. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  107131. /* ePragFlg: */ PragFlg_Result0,
  107132. /* ColNames: */ 0, 0,
  107133. /* iArg: */ 0 },
  107134. #endif
  107135. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107136. {/* zName: */ "short_column_names",
  107137. /* ePragTyp: */ PragTyp_FLAG,
  107138. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107139. /* ColNames: */ 0, 0,
  107140. /* iArg: */ SQLITE_ShortColNames },
  107141. #endif
  107142. {/* zName: */ "shrink_memory",
  107143. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  107144. /* ePragFlg: */ PragFlg_NoColumns,
  107145. /* ColNames: */ 0, 0,
  107146. /* iArg: */ 0 },
  107147. {/* zName: */ "soft_heap_limit",
  107148. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  107149. /* ePragFlg: */ PragFlg_Result0,
  107150. /* ColNames: */ 0, 0,
  107151. /* iArg: */ 0 },
  107152. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107153. #if defined(SQLITE_DEBUG)
  107154. {/* zName: */ "sql_trace",
  107155. /* ePragTyp: */ PragTyp_FLAG,
  107156. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107157. /* ColNames: */ 0, 0,
  107158. /* iArg: */ SQLITE_SqlTrace },
  107159. #endif
  107160. #endif
  107161. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  107162. {/* zName: */ "stats",
  107163. /* ePragTyp: */ PragTyp_STATS,
  107164. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  107165. /* ColNames: */ 7, 5,
  107166. /* iArg: */ 0 },
  107167. #endif
  107168. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107169. {/* zName: */ "synchronous",
  107170. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  107171. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  107172. /* ColNames: */ 0, 0,
  107173. /* iArg: */ 0 },
  107174. #endif
  107175. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  107176. {/* zName: */ "table_info",
  107177. /* ePragTyp: */ PragTyp_TABLE_INFO,
  107178. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  107179. /* ColNames: */ 1, 6,
  107180. /* iArg: */ 0 },
  107181. #endif
  107182. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107183. {/* zName: */ "temp_store",
  107184. /* ePragTyp: */ PragTyp_TEMP_STORE,
  107185. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107186. /* ColNames: */ 0, 0,
  107187. /* iArg: */ 0 },
  107188. {/* zName: */ "temp_store_directory",
  107189. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  107190. /* ePragFlg: */ PragFlg_NoColumns1,
  107191. /* ColNames: */ 0, 0,
  107192. /* iArg: */ 0 },
  107193. #endif
  107194. {/* zName: */ "threads",
  107195. /* ePragTyp: */ PragTyp_THREADS,
  107196. /* ePragFlg: */ PragFlg_Result0,
  107197. /* ColNames: */ 0, 0,
  107198. /* iArg: */ 0 },
  107199. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  107200. {/* zName: */ "user_version",
  107201. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  107202. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  107203. /* ColNames: */ 0, 0,
  107204. /* iArg: */ BTREE_USER_VERSION },
  107205. #endif
  107206. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107207. #if defined(SQLITE_DEBUG)
  107208. {/* zName: */ "vdbe_addoptrace",
  107209. /* ePragTyp: */ PragTyp_FLAG,
  107210. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107211. /* ColNames: */ 0, 0,
  107212. /* iArg: */ SQLITE_VdbeAddopTrace },
  107213. {/* zName: */ "vdbe_debug",
  107214. /* ePragTyp: */ PragTyp_FLAG,
  107215. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107216. /* ColNames: */ 0, 0,
  107217. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  107218. {/* zName: */ "vdbe_eqp",
  107219. /* ePragTyp: */ PragTyp_FLAG,
  107220. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107221. /* ColNames: */ 0, 0,
  107222. /* iArg: */ SQLITE_VdbeEQP },
  107223. {/* zName: */ "vdbe_listing",
  107224. /* ePragTyp: */ PragTyp_FLAG,
  107225. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107226. /* ColNames: */ 0, 0,
  107227. /* iArg: */ SQLITE_VdbeListing },
  107228. {/* zName: */ "vdbe_trace",
  107229. /* ePragTyp: */ PragTyp_FLAG,
  107230. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107231. /* ColNames: */ 0, 0,
  107232. /* iArg: */ SQLITE_VdbeTrace },
  107233. #endif
  107234. #endif
  107235. #if !defined(SQLITE_OMIT_WAL)
  107236. {/* zName: */ "wal_autocheckpoint",
  107237. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  107238. /* ePragFlg: */ 0,
  107239. /* ColNames: */ 0, 0,
  107240. /* iArg: */ 0 },
  107241. {/* zName: */ "wal_checkpoint",
  107242. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  107243. /* ePragFlg: */ PragFlg_NeedSchema,
  107244. /* ColNames: */ 46, 3,
  107245. /* iArg: */ 0 },
  107246. #endif
  107247. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  107248. {/* zName: */ "writable_schema",
  107249. /* ePragTyp: */ PragTyp_FLAG,
  107250. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  107251. /* ColNames: */ 0, 0,
  107252. /* iArg: */ SQLITE_WriteSchema },
  107253. #endif
  107254. };
  107255. /* Number of pragmas: 60 on by default, 77 total. */
  107256. /************** End of pragma.h **********************************************/
  107257. /************** Continuing where we left off in pragma.c *********************/
  107258. /*
  107259. ** Interpret the given string as a safety level. Return 0 for OFF,
  107260. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  107261. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  107262. ** if the omitFull parameter it 1.
  107263. **
  107264. ** Note that the values returned are one less that the values that
  107265. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  107266. ** to support legacy SQL code. The safety level used to be boolean
  107267. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  107268. */
  107269. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  107270. /* 123456789 123456789 123 */
  107271. static const char zText[] = "onoffalseyestruextrafull";
  107272. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  107273. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  107274. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  107275. /* on no off false yes true extra full */
  107276. int i, n;
  107277. if( sqlite3Isdigit(*z) ){
  107278. return (u8)sqlite3Atoi(z);
  107279. }
  107280. n = sqlite3Strlen30(z);
  107281. for(i=0; i<ArraySize(iLength); i++){
  107282. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  107283. && (!omitFull || iValue[i]<=1)
  107284. ){
  107285. return iValue[i];
  107286. }
  107287. }
  107288. return dflt;
  107289. }
  107290. /*
  107291. ** Interpret the given string as a boolean value.
  107292. */
  107293. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  107294. return getSafetyLevel(z,1,dflt)!=0;
  107295. }
  107296. /* The sqlite3GetBoolean() function is used by other modules but the
  107297. ** remainder of this file is specific to PRAGMA processing. So omit
  107298. ** the rest of the file if PRAGMAs are omitted from the build.
  107299. */
  107300. #if !defined(SQLITE_OMIT_PRAGMA)
  107301. /*
  107302. ** Interpret the given string as a locking mode value.
  107303. */
  107304. static int getLockingMode(const char *z){
  107305. if( z ){
  107306. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  107307. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  107308. }
  107309. return PAGER_LOCKINGMODE_QUERY;
  107310. }
  107311. #ifndef SQLITE_OMIT_AUTOVACUUM
  107312. /*
  107313. ** Interpret the given string as an auto-vacuum mode value.
  107314. **
  107315. ** The following strings, "none", "full" and "incremental" are
  107316. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  107317. */
  107318. static int getAutoVacuum(const char *z){
  107319. int i;
  107320. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  107321. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  107322. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  107323. i = sqlite3Atoi(z);
  107324. return (u8)((i>=0&&i<=2)?i:0);
  107325. }
  107326. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  107327. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  107328. /*
  107329. ** Interpret the given string as a temp db location. Return 1 for file
  107330. ** backed temporary databases, 2 for the Red-Black tree in memory database
  107331. ** and 0 to use the compile-time default.
  107332. */
  107333. static int getTempStore(const char *z){
  107334. if( z[0]>='0' && z[0]<='2' ){
  107335. return z[0] - '0';
  107336. }else if( sqlite3StrICmp(z, "file")==0 ){
  107337. return 1;
  107338. }else if( sqlite3StrICmp(z, "memory")==0 ){
  107339. return 2;
  107340. }else{
  107341. return 0;
  107342. }
  107343. }
  107344. #endif /* SQLITE_PAGER_PRAGMAS */
  107345. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  107346. /*
  107347. ** Invalidate temp storage, either when the temp storage is changed
  107348. ** from default, or when 'file' and the temp_store_directory has changed
  107349. */
  107350. static int invalidateTempStorage(Parse *pParse){
  107351. sqlite3 *db = pParse->db;
  107352. if( db->aDb[1].pBt!=0 ){
  107353. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  107354. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  107355. "from within a transaction");
  107356. return SQLITE_ERROR;
  107357. }
  107358. sqlite3BtreeClose(db->aDb[1].pBt);
  107359. db->aDb[1].pBt = 0;
  107360. sqlite3ResetAllSchemasOfConnection(db);
  107361. }
  107362. return SQLITE_OK;
  107363. }
  107364. #endif /* SQLITE_PAGER_PRAGMAS */
  107365. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  107366. /*
  107367. ** If the TEMP database is open, close it and mark the database schema
  107368. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  107369. ** or DEFAULT_TEMP_STORE pragmas.
  107370. */
  107371. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  107372. int ts = getTempStore(zStorageType);
  107373. sqlite3 *db = pParse->db;
  107374. if( db->temp_store==ts ) return SQLITE_OK;
  107375. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  107376. return SQLITE_ERROR;
  107377. }
  107378. db->temp_store = (u8)ts;
  107379. return SQLITE_OK;
  107380. }
  107381. #endif /* SQLITE_PAGER_PRAGMAS */
  107382. /*
  107383. ** Set result column names for a pragma.
  107384. */
  107385. static void setPragmaResultColumnNames(
  107386. Vdbe *v, /* The query under construction */
  107387. const PragmaName *pPragma /* The pragma */
  107388. ){
  107389. u8 n = pPragma->nPragCName;
  107390. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  107391. if( n==0 ){
  107392. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  107393. }else{
  107394. int i, j;
  107395. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  107396. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  107397. }
  107398. }
  107399. }
  107400. /*
  107401. ** Generate code to return a single integer value.
  107402. */
  107403. static void returnSingleInt(Vdbe *v, i64 value){
  107404. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  107405. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  107406. }
  107407. /*
  107408. ** Generate code to return a single text value.
  107409. */
  107410. static void returnSingleText(
  107411. Vdbe *v, /* Prepared statement under construction */
  107412. const char *zValue /* Value to be returned */
  107413. ){
  107414. if( zValue ){
  107415. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  107416. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  107417. }
  107418. }
  107419. /*
  107420. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  107421. ** set these values for all pagers.
  107422. */
  107423. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  107424. static void setAllPagerFlags(sqlite3 *db){
  107425. if( db->autoCommit ){
  107426. Db *pDb = db->aDb;
  107427. int n = db->nDb;
  107428. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  107429. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  107430. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  107431. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  107432. == PAGER_FLAGS_MASK );
  107433. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  107434. while( (n--) > 0 ){
  107435. if( pDb->pBt ){
  107436. sqlite3BtreeSetPagerFlags(pDb->pBt,
  107437. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  107438. }
  107439. pDb++;
  107440. }
  107441. }
  107442. }
  107443. #else
  107444. # define setAllPagerFlags(X) /* no-op */
  107445. #endif
  107446. /*
  107447. ** Return a human-readable name for a constraint resolution action.
  107448. */
  107449. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107450. static const char *actionName(u8 action){
  107451. const char *zName;
  107452. switch( action ){
  107453. case OE_SetNull: zName = "SET NULL"; break;
  107454. case OE_SetDflt: zName = "SET DEFAULT"; break;
  107455. case OE_Cascade: zName = "CASCADE"; break;
  107456. case OE_Restrict: zName = "RESTRICT"; break;
  107457. default: zName = "NO ACTION";
  107458. assert( action==OE_None ); break;
  107459. }
  107460. return zName;
  107461. }
  107462. #endif
  107463. /*
  107464. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  107465. ** defined in pager.h. This function returns the associated lowercase
  107466. ** journal-mode name.
  107467. */
  107468. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  107469. static char * const azModeName[] = {
  107470. "delete", "persist", "off", "truncate", "memory"
  107471. #ifndef SQLITE_OMIT_WAL
  107472. , "wal"
  107473. #endif
  107474. };
  107475. assert( PAGER_JOURNALMODE_DELETE==0 );
  107476. assert( PAGER_JOURNALMODE_PERSIST==1 );
  107477. assert( PAGER_JOURNALMODE_OFF==2 );
  107478. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  107479. assert( PAGER_JOURNALMODE_MEMORY==4 );
  107480. assert( PAGER_JOURNALMODE_WAL==5 );
  107481. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  107482. if( eMode==ArraySize(azModeName) ) return 0;
  107483. return azModeName[eMode];
  107484. }
  107485. /*
  107486. ** Locate a pragma in the aPragmaName[] array.
  107487. */
  107488. static const PragmaName *pragmaLocate(const char *zName){
  107489. int upr, lwr, mid = 0, rc;
  107490. lwr = 0;
  107491. upr = ArraySize(aPragmaName)-1;
  107492. while( lwr<=upr ){
  107493. mid = (lwr+upr)/2;
  107494. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  107495. if( rc==0 ) break;
  107496. if( rc<0 ){
  107497. upr = mid - 1;
  107498. }else{
  107499. lwr = mid + 1;
  107500. }
  107501. }
  107502. return lwr>upr ? 0 : &aPragmaName[mid];
  107503. }
  107504. /*
  107505. ** Helper subroutine for PRAGMA integrity_check:
  107506. **
  107507. ** Generate code to output a single-column result row with a value of the
  107508. ** string held in register 3. Decrement the result count in register 1
  107509. ** and halt if the maximum number of result rows have been issued.
  107510. */
  107511. static int integrityCheckResultRow(Vdbe *v){
  107512. int addr;
  107513. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  107514. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  107515. VdbeCoverage(v);
  107516. sqlite3VdbeAddOp0(v, OP_Halt);
  107517. return addr;
  107518. }
  107519. /*
  107520. ** Process a pragma statement.
  107521. **
  107522. ** Pragmas are of this form:
  107523. **
  107524. ** PRAGMA [schema.]id [= value]
  107525. **
  107526. ** The identifier might also be a string. The value is a string, and
  107527. ** identifier, or a number. If minusFlag is true, then the value is
  107528. ** a number that was preceded by a minus sign.
  107529. **
  107530. ** If the left side is "database.id" then pId1 is the database name
  107531. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  107532. ** id and pId2 is any empty string.
  107533. */
  107534. SQLITE_PRIVATE void sqlite3Pragma(
  107535. Parse *pParse,
  107536. Token *pId1, /* First part of [schema.]id field */
  107537. Token *pId2, /* Second part of [schema.]id field, or NULL */
  107538. Token *pValue, /* Token for <value>, or NULL */
  107539. int minusFlag /* True if a '-' sign preceded <value> */
  107540. ){
  107541. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  107542. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  107543. const char *zDb = 0; /* The database name */
  107544. Token *pId; /* Pointer to <id> token */
  107545. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  107546. int iDb; /* Database index for <database> */
  107547. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  107548. sqlite3 *db = pParse->db; /* The database connection */
  107549. Db *pDb; /* The specific database being pragmaed */
  107550. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  107551. const PragmaName *pPragma; /* The pragma */
  107552. if( v==0 ) return;
  107553. sqlite3VdbeRunOnlyOnce(v);
  107554. pParse->nMem = 2;
  107555. /* Interpret the [schema.] part of the pragma statement. iDb is the
  107556. ** index of the database this pragma is being applied to in db.aDb[]. */
  107557. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  107558. if( iDb<0 ) return;
  107559. pDb = &db->aDb[iDb];
  107560. /* If the temp database has been explicitly named as part of the
  107561. ** pragma, make sure it is open.
  107562. */
  107563. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  107564. return;
  107565. }
  107566. zLeft = sqlite3NameFromToken(db, pId);
  107567. if( !zLeft ) return;
  107568. if( minusFlag ){
  107569. zRight = sqlite3MPrintf(db, "-%T", pValue);
  107570. }else{
  107571. zRight = sqlite3NameFromToken(db, pValue);
  107572. }
  107573. assert( pId2 );
  107574. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  107575. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  107576. goto pragma_out;
  107577. }
  107578. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  107579. ** connection. If it returns SQLITE_OK, then assume that the VFS
  107580. ** handled the pragma and generate a no-op prepared statement.
  107581. **
  107582. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  107583. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  107584. ** object corresponding to the database file to which the pragma
  107585. ** statement refers.
  107586. **
  107587. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  107588. ** file control is an array of pointers to strings (char**) in which the
  107589. ** second element of the array is the name of the pragma and the third
  107590. ** element is the argument to the pragma or NULL if the pragma has no
  107591. ** argument.
  107592. */
  107593. aFcntl[0] = 0;
  107594. aFcntl[1] = zLeft;
  107595. aFcntl[2] = zRight;
  107596. aFcntl[3] = 0;
  107597. db->busyHandler.nBusy = 0;
  107598. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  107599. if( rc==SQLITE_OK ){
  107600. sqlite3VdbeSetNumCols(v, 1);
  107601. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  107602. returnSingleText(v, aFcntl[0]);
  107603. sqlite3_free(aFcntl[0]);
  107604. goto pragma_out;
  107605. }
  107606. if( rc!=SQLITE_NOTFOUND ){
  107607. if( aFcntl[0] ){
  107608. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  107609. sqlite3_free(aFcntl[0]);
  107610. }
  107611. pParse->nErr++;
  107612. pParse->rc = rc;
  107613. goto pragma_out;
  107614. }
  107615. /* Locate the pragma in the lookup table */
  107616. pPragma = pragmaLocate(zLeft);
  107617. if( pPragma==0 ) goto pragma_out;
  107618. /* Make sure the database schema is loaded if the pragma requires that */
  107619. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  107620. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  107621. }
  107622. /* Register the result column names for pragmas that return results */
  107623. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  107624. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  107625. ){
  107626. setPragmaResultColumnNames(v, pPragma);
  107627. }
  107628. /* Jump to the appropriate pragma handler */
  107629. switch( pPragma->ePragTyp ){
  107630. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  107631. /*
  107632. ** PRAGMA [schema.]default_cache_size
  107633. ** PRAGMA [schema.]default_cache_size=N
  107634. **
  107635. ** The first form reports the current persistent setting for the
  107636. ** page cache size. The value returned is the maximum number of
  107637. ** pages in the page cache. The second form sets both the current
  107638. ** page cache size value and the persistent page cache size value
  107639. ** stored in the database file.
  107640. **
  107641. ** Older versions of SQLite would set the default cache size to a
  107642. ** negative number to indicate synchronous=OFF. These days, synchronous
  107643. ** is always on by default regardless of the sign of the default cache
  107644. ** size. But continue to take the absolute value of the default cache
  107645. ** size of historical compatibility.
  107646. */
  107647. case PragTyp_DEFAULT_CACHE_SIZE: {
  107648. static const int iLn = VDBE_OFFSET_LINENO(2);
  107649. static const VdbeOpList getCacheSize[] = {
  107650. { OP_Transaction, 0, 0, 0}, /* 0 */
  107651. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  107652. { OP_IfPos, 1, 8, 0},
  107653. { OP_Integer, 0, 2, 0},
  107654. { OP_Subtract, 1, 2, 1},
  107655. { OP_IfPos, 1, 8, 0},
  107656. { OP_Integer, 0, 1, 0}, /* 6 */
  107657. { OP_Noop, 0, 0, 0},
  107658. { OP_ResultRow, 1, 1, 0},
  107659. };
  107660. VdbeOp *aOp;
  107661. sqlite3VdbeUsesBtree(v, iDb);
  107662. if( !zRight ){
  107663. pParse->nMem += 2;
  107664. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  107665. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  107666. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107667. aOp[0].p1 = iDb;
  107668. aOp[1].p1 = iDb;
  107669. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  107670. }else{
  107671. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  107672. sqlite3BeginWriteOperation(pParse, 0, iDb);
  107673. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  107674. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107675. pDb->pSchema->cache_size = size;
  107676. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  107677. }
  107678. break;
  107679. }
  107680. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  107681. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  107682. /*
  107683. ** PRAGMA [schema.]page_size
  107684. ** PRAGMA [schema.]page_size=N
  107685. **
  107686. ** The first form reports the current setting for the
  107687. ** database page size in bytes. The second form sets the
  107688. ** database page size value. The value can only be set if
  107689. ** the database has not yet been created.
  107690. */
  107691. case PragTyp_PAGE_SIZE: {
  107692. Btree *pBt = pDb->pBt;
  107693. assert( pBt!=0 );
  107694. if( !zRight ){
  107695. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  107696. returnSingleInt(v, size);
  107697. }else{
  107698. /* Malloc may fail when setting the page-size, as there is an internal
  107699. ** buffer that the pager module resizes using sqlite3_realloc().
  107700. */
  107701. db->nextPagesize = sqlite3Atoi(zRight);
  107702. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  107703. sqlite3OomFault(db);
  107704. }
  107705. }
  107706. break;
  107707. }
  107708. /*
  107709. ** PRAGMA [schema.]secure_delete
  107710. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  107711. **
  107712. ** The first form reports the current setting for the
  107713. ** secure_delete flag. The second form changes the secure_delete
  107714. ** flag setting and reports the new value.
  107715. */
  107716. case PragTyp_SECURE_DELETE: {
  107717. Btree *pBt = pDb->pBt;
  107718. int b = -1;
  107719. assert( pBt!=0 );
  107720. if( zRight ){
  107721. if( sqlite3_stricmp(zRight, "fast")==0 ){
  107722. b = 2;
  107723. }else{
  107724. b = sqlite3GetBoolean(zRight, 0);
  107725. }
  107726. }
  107727. if( pId2->n==0 && b>=0 ){
  107728. int ii;
  107729. for(ii=0; ii<db->nDb; ii++){
  107730. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  107731. }
  107732. }
  107733. b = sqlite3BtreeSecureDelete(pBt, b);
  107734. returnSingleInt(v, b);
  107735. break;
  107736. }
  107737. /*
  107738. ** PRAGMA [schema.]max_page_count
  107739. ** PRAGMA [schema.]max_page_count=N
  107740. **
  107741. ** The first form reports the current setting for the
  107742. ** maximum number of pages in the database file. The
  107743. ** second form attempts to change this setting. Both
  107744. ** forms return the current setting.
  107745. **
  107746. ** The absolute value of N is used. This is undocumented and might
  107747. ** change. The only purpose is to provide an easy way to test
  107748. ** the sqlite3AbsInt32() function.
  107749. **
  107750. ** PRAGMA [schema.]page_count
  107751. **
  107752. ** Return the number of pages in the specified database.
  107753. */
  107754. case PragTyp_PAGE_COUNT: {
  107755. int iReg;
  107756. sqlite3CodeVerifySchema(pParse, iDb);
  107757. iReg = ++pParse->nMem;
  107758. if( sqlite3Tolower(zLeft[0])=='p' ){
  107759. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  107760. }else{
  107761. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  107762. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  107763. }
  107764. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  107765. break;
  107766. }
  107767. /*
  107768. ** PRAGMA [schema.]locking_mode
  107769. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  107770. */
  107771. case PragTyp_LOCKING_MODE: {
  107772. const char *zRet = "normal";
  107773. int eMode = getLockingMode(zRight);
  107774. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  107775. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  107776. ** the current default locking mode (which may be different to
  107777. ** the locking-mode of the main database).
  107778. */
  107779. eMode = db->dfltLockMode;
  107780. }else{
  107781. Pager *pPager;
  107782. if( pId2->n==0 ){
  107783. /* This indicates that no database name was specified as part
  107784. ** of the PRAGMA command. In this case the locking-mode must be
  107785. ** set on all attached databases, as well as the main db file.
  107786. **
  107787. ** Also, the sqlite3.dfltLockMode variable is set so that
  107788. ** any subsequently attached databases also use the specified
  107789. ** locking mode.
  107790. */
  107791. int ii;
  107792. assert(pDb==&db->aDb[0]);
  107793. for(ii=2; ii<db->nDb; ii++){
  107794. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  107795. sqlite3PagerLockingMode(pPager, eMode);
  107796. }
  107797. db->dfltLockMode = (u8)eMode;
  107798. }
  107799. pPager = sqlite3BtreePager(pDb->pBt);
  107800. eMode = sqlite3PagerLockingMode(pPager, eMode);
  107801. }
  107802. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  107803. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  107804. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  107805. zRet = "exclusive";
  107806. }
  107807. returnSingleText(v, zRet);
  107808. break;
  107809. }
  107810. /*
  107811. ** PRAGMA [schema.]journal_mode
  107812. ** PRAGMA [schema.]journal_mode =
  107813. ** (delete|persist|off|truncate|memory|wal|off)
  107814. */
  107815. case PragTyp_JOURNAL_MODE: {
  107816. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  107817. int ii; /* Loop counter */
  107818. if( zRight==0 ){
  107819. /* If there is no "=MODE" part of the pragma, do a query for the
  107820. ** current mode */
  107821. eMode = PAGER_JOURNALMODE_QUERY;
  107822. }else{
  107823. const char *zMode;
  107824. int n = sqlite3Strlen30(zRight);
  107825. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  107826. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  107827. }
  107828. if( !zMode ){
  107829. /* If the "=MODE" part does not match any known journal mode,
  107830. ** then do a query */
  107831. eMode = PAGER_JOURNALMODE_QUERY;
  107832. }
  107833. }
  107834. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  107835. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  107836. iDb = 0;
  107837. pId2->n = 1;
  107838. }
  107839. for(ii=db->nDb-1; ii>=0; ii--){
  107840. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  107841. sqlite3VdbeUsesBtree(v, ii);
  107842. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  107843. }
  107844. }
  107845. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  107846. break;
  107847. }
  107848. /*
  107849. ** PRAGMA [schema.]journal_size_limit
  107850. ** PRAGMA [schema.]journal_size_limit=N
  107851. **
  107852. ** Get or set the size limit on rollback journal files.
  107853. */
  107854. case PragTyp_JOURNAL_SIZE_LIMIT: {
  107855. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  107856. i64 iLimit = -2;
  107857. if( zRight ){
  107858. sqlite3DecOrHexToI64(zRight, &iLimit);
  107859. if( iLimit<-1 ) iLimit = -1;
  107860. }
  107861. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  107862. returnSingleInt(v, iLimit);
  107863. break;
  107864. }
  107865. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  107866. /*
  107867. ** PRAGMA [schema.]auto_vacuum
  107868. ** PRAGMA [schema.]auto_vacuum=N
  107869. **
  107870. ** Get or set the value of the database 'auto-vacuum' parameter.
  107871. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  107872. */
  107873. #ifndef SQLITE_OMIT_AUTOVACUUM
  107874. case PragTyp_AUTO_VACUUM: {
  107875. Btree *pBt = pDb->pBt;
  107876. assert( pBt!=0 );
  107877. if( !zRight ){
  107878. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  107879. }else{
  107880. int eAuto = getAutoVacuum(zRight);
  107881. assert( eAuto>=0 && eAuto<=2 );
  107882. db->nextAutovac = (u8)eAuto;
  107883. /* Call SetAutoVacuum() to set initialize the internal auto and
  107884. ** incr-vacuum flags. This is required in case this connection
  107885. ** creates the database file. It is important that it is created
  107886. ** as an auto-vacuum capable db.
  107887. */
  107888. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  107889. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  107890. /* When setting the auto_vacuum mode to either "full" or
  107891. ** "incremental", write the value of meta[6] in the database
  107892. ** file. Before writing to meta[6], check that meta[3] indicates
  107893. ** that this really is an auto-vacuum capable database.
  107894. */
  107895. static const int iLn = VDBE_OFFSET_LINENO(2);
  107896. static const VdbeOpList setMeta6[] = {
  107897. { OP_Transaction, 0, 1, 0}, /* 0 */
  107898. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  107899. { OP_If, 1, 0, 0}, /* 2 */
  107900. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  107901. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  107902. };
  107903. VdbeOp *aOp;
  107904. int iAddr = sqlite3VdbeCurrentAddr(v);
  107905. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  107906. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  107907. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107908. aOp[0].p1 = iDb;
  107909. aOp[1].p1 = iDb;
  107910. aOp[2].p2 = iAddr+4;
  107911. aOp[4].p1 = iDb;
  107912. aOp[4].p3 = eAuto - 1;
  107913. sqlite3VdbeUsesBtree(v, iDb);
  107914. }
  107915. }
  107916. break;
  107917. }
  107918. #endif
  107919. /*
  107920. ** PRAGMA [schema.]incremental_vacuum(N)
  107921. **
  107922. ** Do N steps of incremental vacuuming on a database.
  107923. */
  107924. #ifndef SQLITE_OMIT_AUTOVACUUM
  107925. case PragTyp_INCREMENTAL_VACUUM: {
  107926. int iLimit, addr;
  107927. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  107928. iLimit = 0x7fffffff;
  107929. }
  107930. sqlite3BeginWriteOperation(pParse, 0, iDb);
  107931. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  107932. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  107933. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  107934. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  107935. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  107936. sqlite3VdbeJumpHere(v, addr);
  107937. break;
  107938. }
  107939. #endif
  107940. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  107941. /*
  107942. ** PRAGMA [schema.]cache_size
  107943. ** PRAGMA [schema.]cache_size=N
  107944. **
  107945. ** The first form reports the current local setting for the
  107946. ** page cache size. The second form sets the local
  107947. ** page cache size value. If N is positive then that is the
  107948. ** number of pages in the cache. If N is negative, then the
  107949. ** number of pages is adjusted so that the cache uses -N kibibytes
  107950. ** of memory.
  107951. */
  107952. case PragTyp_CACHE_SIZE: {
  107953. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107954. if( !zRight ){
  107955. returnSingleInt(v, pDb->pSchema->cache_size);
  107956. }else{
  107957. int size = sqlite3Atoi(zRight);
  107958. pDb->pSchema->cache_size = size;
  107959. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  107960. }
  107961. break;
  107962. }
  107963. /*
  107964. ** PRAGMA [schema.]cache_spill
  107965. ** PRAGMA cache_spill=BOOLEAN
  107966. ** PRAGMA [schema.]cache_spill=N
  107967. **
  107968. ** The first form reports the current local setting for the
  107969. ** page cache spill size. The second form turns cache spill on
  107970. ** or off. When turnning cache spill on, the size is set to the
  107971. ** current cache_size. The third form sets a spill size that
  107972. ** may be different form the cache size.
  107973. ** If N is positive then that is the
  107974. ** number of pages in the cache. If N is negative, then the
  107975. ** number of pages is adjusted so that the cache uses -N kibibytes
  107976. ** of memory.
  107977. **
  107978. ** If the number of cache_spill pages is less then the number of
  107979. ** cache_size pages, no spilling occurs until the page count exceeds
  107980. ** the number of cache_size pages.
  107981. **
  107982. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  107983. ** not just the schema specified.
  107984. */
  107985. case PragTyp_CACHE_SPILL: {
  107986. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  107987. if( !zRight ){
  107988. returnSingleInt(v,
  107989. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  107990. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  107991. }else{
  107992. int size = 1;
  107993. if( sqlite3GetInt32(zRight, &size) ){
  107994. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  107995. }
  107996. if( sqlite3GetBoolean(zRight, size!=0) ){
  107997. db->flags |= SQLITE_CacheSpill;
  107998. }else{
  107999. db->flags &= ~SQLITE_CacheSpill;
  108000. }
  108001. setAllPagerFlags(db);
  108002. }
  108003. break;
  108004. }
  108005. /*
  108006. ** PRAGMA [schema.]mmap_size(N)
  108007. **
  108008. ** Used to set mapping size limit. The mapping size limit is
  108009. ** used to limit the aggregate size of all memory mapped regions of the
  108010. ** database file. If this parameter is set to zero, then memory mapping
  108011. ** is not used at all. If N is negative, then the default memory map
  108012. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  108013. ** The parameter N is measured in bytes.
  108014. **
  108015. ** This value is advisory. The underlying VFS is free to memory map
  108016. ** as little or as much as it wants. Except, if N is set to 0 then the
  108017. ** upper layers will never invoke the xFetch interfaces to the VFS.
  108018. */
  108019. case PragTyp_MMAP_SIZE: {
  108020. sqlite3_int64 sz;
  108021. #if SQLITE_MAX_MMAP_SIZE>0
  108022. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108023. if( zRight ){
  108024. int ii;
  108025. sqlite3DecOrHexToI64(zRight, &sz);
  108026. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  108027. if( pId2->n==0 ) db->szMmap = sz;
  108028. for(ii=db->nDb-1; ii>=0; ii--){
  108029. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  108030. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  108031. }
  108032. }
  108033. }
  108034. sz = -1;
  108035. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  108036. #else
  108037. sz = 0;
  108038. rc = SQLITE_OK;
  108039. #endif
  108040. if( rc==SQLITE_OK ){
  108041. returnSingleInt(v, sz);
  108042. }else if( rc!=SQLITE_NOTFOUND ){
  108043. pParse->nErr++;
  108044. pParse->rc = rc;
  108045. }
  108046. break;
  108047. }
  108048. /*
  108049. ** PRAGMA temp_store
  108050. ** PRAGMA temp_store = "default"|"memory"|"file"
  108051. **
  108052. ** Return or set the local value of the temp_store flag. Changing
  108053. ** the local value does not make changes to the disk file and the default
  108054. ** value will be restored the next time the database is opened.
  108055. **
  108056. ** Note that it is possible for the library compile-time options to
  108057. ** override this setting
  108058. */
  108059. case PragTyp_TEMP_STORE: {
  108060. if( !zRight ){
  108061. returnSingleInt(v, db->temp_store);
  108062. }else{
  108063. changeTempStorage(pParse, zRight);
  108064. }
  108065. break;
  108066. }
  108067. /*
  108068. ** PRAGMA temp_store_directory
  108069. ** PRAGMA temp_store_directory = ""|"directory_name"
  108070. **
  108071. ** Return or set the local value of the temp_store_directory flag. Changing
  108072. ** the value sets a specific directory to be used for temporary files.
  108073. ** Setting to a null string reverts to the default temporary directory search.
  108074. ** If temporary directory is changed, then invalidateTempStorage.
  108075. **
  108076. */
  108077. case PragTyp_TEMP_STORE_DIRECTORY: {
  108078. if( !zRight ){
  108079. returnSingleText(v, sqlite3_temp_directory);
  108080. }else{
  108081. #ifndef SQLITE_OMIT_WSD
  108082. if( zRight[0] ){
  108083. int res;
  108084. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  108085. if( rc!=SQLITE_OK || res==0 ){
  108086. sqlite3ErrorMsg(pParse, "not a writable directory");
  108087. goto pragma_out;
  108088. }
  108089. }
  108090. if( SQLITE_TEMP_STORE==0
  108091. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  108092. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  108093. ){
  108094. invalidateTempStorage(pParse);
  108095. }
  108096. sqlite3_free(sqlite3_temp_directory);
  108097. if( zRight[0] ){
  108098. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  108099. }else{
  108100. sqlite3_temp_directory = 0;
  108101. }
  108102. #endif /* SQLITE_OMIT_WSD */
  108103. }
  108104. break;
  108105. }
  108106. #if SQLITE_OS_WIN
  108107. /*
  108108. ** PRAGMA data_store_directory
  108109. ** PRAGMA data_store_directory = ""|"directory_name"
  108110. **
  108111. ** Return or set the local value of the data_store_directory flag. Changing
  108112. ** the value sets a specific directory to be used for database files that
  108113. ** were specified with a relative pathname. Setting to a null string reverts
  108114. ** to the default database directory, which for database files specified with
  108115. ** a relative path will probably be based on the current directory for the
  108116. ** process. Database file specified with an absolute path are not impacted
  108117. ** by this setting, regardless of its value.
  108118. **
  108119. */
  108120. case PragTyp_DATA_STORE_DIRECTORY: {
  108121. if( !zRight ){
  108122. returnSingleText(v, sqlite3_data_directory);
  108123. }else{
  108124. #ifndef SQLITE_OMIT_WSD
  108125. if( zRight[0] ){
  108126. int res;
  108127. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  108128. if( rc!=SQLITE_OK || res==0 ){
  108129. sqlite3ErrorMsg(pParse, "not a writable directory");
  108130. goto pragma_out;
  108131. }
  108132. }
  108133. sqlite3_free(sqlite3_data_directory);
  108134. if( zRight[0] ){
  108135. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  108136. }else{
  108137. sqlite3_data_directory = 0;
  108138. }
  108139. #endif /* SQLITE_OMIT_WSD */
  108140. }
  108141. break;
  108142. }
  108143. #endif
  108144. #if SQLITE_ENABLE_LOCKING_STYLE
  108145. /*
  108146. ** PRAGMA [schema.]lock_proxy_file
  108147. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  108148. **
  108149. ** Return or set the value of the lock_proxy_file flag. Changing
  108150. ** the value sets a specific file to be used for database access locks.
  108151. **
  108152. */
  108153. case PragTyp_LOCK_PROXY_FILE: {
  108154. if( !zRight ){
  108155. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  108156. char *proxy_file_path = NULL;
  108157. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  108158. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  108159. &proxy_file_path);
  108160. returnSingleText(v, proxy_file_path);
  108161. }else{
  108162. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  108163. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  108164. int res;
  108165. if( zRight[0] ){
  108166. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  108167. zRight);
  108168. } else {
  108169. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  108170. NULL);
  108171. }
  108172. if( res!=SQLITE_OK ){
  108173. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  108174. goto pragma_out;
  108175. }
  108176. }
  108177. break;
  108178. }
  108179. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  108180. /*
  108181. ** PRAGMA [schema.]synchronous
  108182. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  108183. **
  108184. ** Return or set the local value of the synchronous flag. Changing
  108185. ** the local value does not make changes to the disk file and the
  108186. ** default value will be restored the next time the database is
  108187. ** opened.
  108188. */
  108189. case PragTyp_SYNCHRONOUS: {
  108190. if( !zRight ){
  108191. returnSingleInt(v, pDb->safety_level-1);
  108192. }else{
  108193. if( !db->autoCommit ){
  108194. sqlite3ErrorMsg(pParse,
  108195. "Safety level may not be changed inside a transaction");
  108196. }else if( iDb!=1 ){
  108197. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  108198. if( iLevel==0 ) iLevel = 1;
  108199. pDb->safety_level = iLevel;
  108200. pDb->bSyncSet = 1;
  108201. setAllPagerFlags(db);
  108202. }
  108203. }
  108204. break;
  108205. }
  108206. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  108207. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  108208. case PragTyp_FLAG: {
  108209. if( zRight==0 ){
  108210. setPragmaResultColumnNames(v, pPragma);
  108211. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  108212. }else{
  108213. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  108214. if( db->autoCommit==0 ){
  108215. /* Foreign key support may not be enabled or disabled while not
  108216. ** in auto-commit mode. */
  108217. mask &= ~(SQLITE_ForeignKeys);
  108218. }
  108219. #if SQLITE_USER_AUTHENTICATION
  108220. if( db->auth.authLevel==UAUTH_User ){
  108221. /* Do not allow non-admin users to modify the schema arbitrarily */
  108222. mask &= ~(SQLITE_WriteSchema);
  108223. }
  108224. #endif
  108225. if( sqlite3GetBoolean(zRight, 0) ){
  108226. db->flags |= mask;
  108227. }else{
  108228. db->flags &= ~mask;
  108229. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  108230. }
  108231. /* Many of the flag-pragmas modify the code generated by the SQL
  108232. ** compiler (eg. count_changes). So add an opcode to expire all
  108233. ** compiled SQL statements after modifying a pragma value.
  108234. */
  108235. sqlite3VdbeAddOp0(v, OP_Expire);
  108236. setAllPagerFlags(db);
  108237. }
  108238. break;
  108239. }
  108240. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  108241. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  108242. /*
  108243. ** PRAGMA table_info(<table>)
  108244. **
  108245. ** Return a single row for each column of the named table. The columns of
  108246. ** the returned data set are:
  108247. **
  108248. ** cid: Column id (numbered from left to right, starting at 0)
  108249. ** name: Column name
  108250. ** type: Column declaration type.
  108251. ** notnull: True if 'NOT NULL' is part of column declaration
  108252. ** dflt_value: The default value for the column, if any.
  108253. */
  108254. case PragTyp_TABLE_INFO: if( zRight ){
  108255. Table *pTab;
  108256. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  108257. if( pTab ){
  108258. int i, k;
  108259. int nHidden = 0;
  108260. Column *pCol;
  108261. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  108262. pParse->nMem = 6;
  108263. sqlite3CodeVerifySchema(pParse, iDb);
  108264. sqlite3ViewGetColumnNames(pParse, pTab);
  108265. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  108266. if( IsHiddenColumn(pCol) ){
  108267. nHidden++;
  108268. continue;
  108269. }
  108270. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  108271. k = 0;
  108272. }else if( pPk==0 ){
  108273. k = 1;
  108274. }else{
  108275. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  108276. }
  108277. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  108278. sqlite3VdbeMultiLoad(v, 1, "issisi",
  108279. i-nHidden,
  108280. pCol->zName,
  108281. sqlite3ColumnType(pCol,""),
  108282. pCol->notNull ? 1 : 0,
  108283. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  108284. k);
  108285. }
  108286. }
  108287. }
  108288. break;
  108289. #ifdef SQLITE_DEBUG
  108290. case PragTyp_STATS: {
  108291. Index *pIdx;
  108292. HashElem *i;
  108293. pParse->nMem = 5;
  108294. sqlite3CodeVerifySchema(pParse, iDb);
  108295. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  108296. Table *pTab = sqliteHashData(i);
  108297. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  108298. pTab->zName,
  108299. 0,
  108300. pTab->szTabRow,
  108301. pTab->nRowLogEst,
  108302. pTab->tabFlags);
  108303. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108304. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  108305. pIdx->zName,
  108306. pIdx->szIdxRow,
  108307. pIdx->aiRowLogEst[0],
  108308. pIdx->hasStat1);
  108309. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  108310. }
  108311. }
  108312. }
  108313. break;
  108314. #endif
  108315. case PragTyp_INDEX_INFO: if( zRight ){
  108316. Index *pIdx;
  108317. Table *pTab;
  108318. pIdx = sqlite3FindIndex(db, zRight, zDb);
  108319. if( pIdx ){
  108320. int i;
  108321. int mx;
  108322. if( pPragma->iArg ){
  108323. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  108324. mx = pIdx->nColumn;
  108325. pParse->nMem = 6;
  108326. }else{
  108327. /* PRAGMA index_info (legacy version) */
  108328. mx = pIdx->nKeyCol;
  108329. pParse->nMem = 3;
  108330. }
  108331. pTab = pIdx->pTable;
  108332. sqlite3CodeVerifySchema(pParse, iDb);
  108333. assert( pParse->nMem<=pPragma->nPragCName );
  108334. for(i=0; i<mx; i++){
  108335. i16 cnum = pIdx->aiColumn[i];
  108336. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  108337. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  108338. if( pPragma->iArg ){
  108339. sqlite3VdbeMultiLoad(v, 4, "isiX",
  108340. pIdx->aSortOrder[i],
  108341. pIdx->azColl[i],
  108342. i<pIdx->nKeyCol);
  108343. }
  108344. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  108345. }
  108346. }
  108347. }
  108348. break;
  108349. case PragTyp_INDEX_LIST: if( zRight ){
  108350. Index *pIdx;
  108351. Table *pTab;
  108352. int i;
  108353. pTab = sqlite3FindTable(db, zRight, zDb);
  108354. if( pTab ){
  108355. pParse->nMem = 5;
  108356. sqlite3CodeVerifySchema(pParse, iDb);
  108357. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  108358. const char *azOrigin[] = { "c", "u", "pk" };
  108359. sqlite3VdbeMultiLoad(v, 1, "isisi",
  108360. i,
  108361. pIdx->zName,
  108362. IsUniqueIndex(pIdx),
  108363. azOrigin[pIdx->idxType],
  108364. pIdx->pPartIdxWhere!=0);
  108365. }
  108366. }
  108367. }
  108368. break;
  108369. case PragTyp_DATABASE_LIST: {
  108370. int i;
  108371. pParse->nMem = 3;
  108372. for(i=0; i<db->nDb; i++){
  108373. if( db->aDb[i].pBt==0 ) continue;
  108374. assert( db->aDb[i].zDbSName!=0 );
  108375. sqlite3VdbeMultiLoad(v, 1, "iss",
  108376. i,
  108377. db->aDb[i].zDbSName,
  108378. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  108379. }
  108380. }
  108381. break;
  108382. case PragTyp_COLLATION_LIST: {
  108383. int i = 0;
  108384. HashElem *p;
  108385. pParse->nMem = 2;
  108386. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  108387. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  108388. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  108389. }
  108390. }
  108391. break;
  108392. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  108393. case PragTyp_FUNCTION_LIST: {
  108394. int i;
  108395. HashElem *j;
  108396. FuncDef *p;
  108397. pParse->nMem = 2;
  108398. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  108399. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  108400. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  108401. }
  108402. }
  108403. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  108404. p = (FuncDef*)sqliteHashData(j);
  108405. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  108406. }
  108407. }
  108408. break;
  108409. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108410. case PragTyp_MODULE_LIST: {
  108411. HashElem *j;
  108412. pParse->nMem = 1;
  108413. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  108414. Module *pMod = (Module*)sqliteHashData(j);
  108415. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  108416. }
  108417. }
  108418. break;
  108419. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108420. case PragTyp_PRAGMA_LIST: {
  108421. int i;
  108422. for(i=0; i<ArraySize(aPragmaName); i++){
  108423. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  108424. }
  108425. }
  108426. break;
  108427. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  108428. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  108429. #ifndef SQLITE_OMIT_FOREIGN_KEY
  108430. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  108431. FKey *pFK;
  108432. Table *pTab;
  108433. pTab = sqlite3FindTable(db, zRight, zDb);
  108434. if( pTab ){
  108435. pFK = pTab->pFKey;
  108436. if( pFK ){
  108437. int i = 0;
  108438. pParse->nMem = 8;
  108439. sqlite3CodeVerifySchema(pParse, iDb);
  108440. while(pFK){
  108441. int j;
  108442. for(j=0; j<pFK->nCol; j++){
  108443. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  108444. i,
  108445. j,
  108446. pFK->zTo,
  108447. pTab->aCol[pFK->aCol[j].iFrom].zName,
  108448. pFK->aCol[j].zCol,
  108449. actionName(pFK->aAction[1]), /* ON UPDATE */
  108450. actionName(pFK->aAction[0]), /* ON DELETE */
  108451. "NONE");
  108452. }
  108453. ++i;
  108454. pFK = pFK->pNextFrom;
  108455. }
  108456. }
  108457. }
  108458. }
  108459. break;
  108460. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  108461. #ifndef SQLITE_OMIT_FOREIGN_KEY
  108462. #ifndef SQLITE_OMIT_TRIGGER
  108463. case PragTyp_FOREIGN_KEY_CHECK: {
  108464. FKey *pFK; /* A foreign key constraint */
  108465. Table *pTab; /* Child table contain "REFERENCES" keyword */
  108466. Table *pParent; /* Parent table that child points to */
  108467. Index *pIdx; /* Index in the parent table */
  108468. int i; /* Loop counter: Foreign key number for pTab */
  108469. int j; /* Loop counter: Field of the foreign key */
  108470. HashElem *k; /* Loop counter: Next table in schema */
  108471. int x; /* result variable */
  108472. int regResult; /* 3 registers to hold a result row */
  108473. int regKey; /* Register to hold key for checking the FK */
  108474. int regRow; /* Registers to hold a row from pTab */
  108475. int addrTop; /* Top of a loop checking foreign keys */
  108476. int addrOk; /* Jump here if the key is OK */
  108477. int *aiCols; /* child to parent column mapping */
  108478. regResult = pParse->nMem+1;
  108479. pParse->nMem += 4;
  108480. regKey = ++pParse->nMem;
  108481. regRow = ++pParse->nMem;
  108482. sqlite3CodeVerifySchema(pParse, iDb);
  108483. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  108484. while( k ){
  108485. if( zRight ){
  108486. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  108487. k = 0;
  108488. }else{
  108489. pTab = (Table*)sqliteHashData(k);
  108490. k = sqliteHashNext(k);
  108491. }
  108492. if( pTab==0 || pTab->pFKey==0 ) continue;
  108493. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  108494. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  108495. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  108496. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  108497. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  108498. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  108499. if( pParent==0 ) continue;
  108500. pIdx = 0;
  108501. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  108502. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  108503. if( x==0 ){
  108504. if( pIdx==0 ){
  108505. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  108506. }else{
  108507. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  108508. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  108509. }
  108510. }else{
  108511. k = 0;
  108512. break;
  108513. }
  108514. }
  108515. assert( pParse->nErr>0 || pFK==0 );
  108516. if( pFK ) break;
  108517. if( pParse->nTab<i ) pParse->nTab = i;
  108518. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  108519. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  108520. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  108521. pIdx = 0;
  108522. aiCols = 0;
  108523. if( pParent ){
  108524. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  108525. assert( x==0 );
  108526. }
  108527. addrOk = sqlite3VdbeMakeLabel(v);
  108528. /* Generate code to read the child key values into registers
  108529. ** regRow..regRow+n. If any of the child key values are NULL, this
  108530. ** row cannot cause an FK violation. Jump directly to addrOk in
  108531. ** this case. */
  108532. for(j=0; j<pFK->nCol; j++){
  108533. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  108534. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  108535. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  108536. }
  108537. /* Generate code to query the parent index for a matching parent
  108538. ** key. If a match is found, jump to addrOk. */
  108539. if( pIdx ){
  108540. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  108541. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  108542. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  108543. VdbeCoverage(v);
  108544. }else if( pParent ){
  108545. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  108546. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  108547. sqlite3VdbeGoto(v, addrOk);
  108548. assert( pFK->nCol==1 );
  108549. }
  108550. /* Generate code to report an FK violation to the caller. */
  108551. if( HasRowid(pTab) ){
  108552. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  108553. }else{
  108554. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  108555. }
  108556. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  108557. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  108558. sqlite3VdbeResolveLabel(v, addrOk);
  108559. sqlite3DbFree(db, aiCols);
  108560. }
  108561. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  108562. sqlite3VdbeJumpHere(v, addrTop);
  108563. }
  108564. }
  108565. break;
  108566. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  108567. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  108568. #ifndef NDEBUG
  108569. case PragTyp_PARSER_TRACE: {
  108570. if( zRight ){
  108571. if( sqlite3GetBoolean(zRight, 0) ){
  108572. sqlite3ParserTrace(stdout, "parser: ");
  108573. }else{
  108574. sqlite3ParserTrace(0, 0);
  108575. }
  108576. }
  108577. }
  108578. break;
  108579. #endif
  108580. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  108581. ** used will be case sensitive or not depending on the RHS.
  108582. */
  108583. case PragTyp_CASE_SENSITIVE_LIKE: {
  108584. if( zRight ){
  108585. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  108586. }
  108587. }
  108588. break;
  108589. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  108590. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  108591. #endif
  108592. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  108593. /* PRAGMA integrity_check
  108594. ** PRAGMA integrity_check(N)
  108595. ** PRAGMA quick_check
  108596. ** PRAGMA quick_check(N)
  108597. **
  108598. ** Verify the integrity of the database.
  108599. **
  108600. ** The "quick_check" is reduced version of
  108601. ** integrity_check designed to detect most database corruption
  108602. ** without the overhead of cross-checking indexes. Quick_check
  108603. ** is linear time wherease integrity_check is O(NlogN).
  108604. */
  108605. case PragTyp_INTEGRITY_CHECK: {
  108606. int i, j, addr, mxErr;
  108607. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  108608. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  108609. ** then iDb is set to the index of the database identified by <db>.
  108610. ** In this case, the integrity of database iDb only is verified by
  108611. ** the VDBE created below.
  108612. **
  108613. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  108614. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  108615. ** to -1 here, to indicate that the VDBE should verify the integrity
  108616. ** of all attached databases. */
  108617. assert( iDb>=0 );
  108618. assert( iDb==0 || pId2->z );
  108619. if( pId2->z==0 ) iDb = -1;
  108620. /* Initialize the VDBE program */
  108621. pParse->nMem = 6;
  108622. /* Set the maximum error count */
  108623. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  108624. if( zRight ){
  108625. sqlite3GetInt32(zRight, &mxErr);
  108626. if( mxErr<=0 ){
  108627. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  108628. }
  108629. }
  108630. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  108631. /* Do an integrity check on each database file */
  108632. for(i=0; i<db->nDb; i++){
  108633. HashElem *x; /* For looping over tables in the schema */
  108634. Hash *pTbls; /* Set of all tables in the schema */
  108635. int *aRoot; /* Array of root page numbers of all btrees */
  108636. int cnt = 0; /* Number of entries in aRoot[] */
  108637. int mxIdx = 0; /* Maximum number of indexes for any table */
  108638. if( OMIT_TEMPDB && i==1 ) continue;
  108639. if( iDb>=0 && i!=iDb ) continue;
  108640. sqlite3CodeVerifySchema(pParse, i);
  108641. /* Do an integrity check of the B-Tree
  108642. **
  108643. ** Begin by finding the root pages numbers
  108644. ** for all tables and indices in the database.
  108645. */
  108646. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  108647. pTbls = &db->aDb[i].pSchema->tblHash;
  108648. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  108649. Table *pTab = sqliteHashData(x); /* Current table */
  108650. Index *pIdx; /* An index on pTab */
  108651. int nIdx; /* Number of indexes on pTab */
  108652. if( HasRowid(pTab) ) cnt++;
  108653. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  108654. if( nIdx>mxIdx ) mxIdx = nIdx;
  108655. }
  108656. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  108657. if( aRoot==0 ) break;
  108658. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  108659. Table *pTab = sqliteHashData(x);
  108660. Index *pIdx;
  108661. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  108662. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108663. aRoot[++cnt] = pIdx->tnum;
  108664. }
  108665. }
  108666. aRoot[0] = cnt;
  108667. /* Make sure sufficient number of registers have been allocated */
  108668. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  108669. sqlite3ClearTempRegCache(pParse);
  108670. /* Do the b-tree integrity checks */
  108671. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  108672. sqlite3VdbeChangeP5(v, (u8)i);
  108673. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  108674. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  108675. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  108676. P4_DYNAMIC);
  108677. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  108678. integrityCheckResultRow(v);
  108679. sqlite3VdbeJumpHere(v, addr);
  108680. /* Make sure all the indices are constructed correctly.
  108681. */
  108682. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  108683. Table *pTab = sqliteHashData(x);
  108684. Index *pIdx, *pPk;
  108685. Index *pPrior = 0;
  108686. int loopTop;
  108687. int iDataCur, iIdxCur;
  108688. int r1 = -1;
  108689. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  108690. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  108691. sqlite3ExprCacheClear(pParse);
  108692. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  108693. 1, 0, &iDataCur, &iIdxCur);
  108694. /* reg[7] counts the number of entries in the table.
  108695. ** reg[8+i] counts the number of entries in the i-th index
  108696. */
  108697. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  108698. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  108699. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  108700. }
  108701. assert( pParse->nMem>=8+j );
  108702. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  108703. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  108704. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  108705. /* Verify that all NOT NULL columns really are NOT NULL */
  108706. for(j=0; j<pTab->nCol; j++){
  108707. char *zErr;
  108708. int jmp2;
  108709. if( j==pTab->iPKey ) continue;
  108710. if( pTab->aCol[j].notNull==0 ) continue;
  108711. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  108712. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  108713. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  108714. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  108715. pTab->aCol[j].zName);
  108716. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  108717. integrityCheckResultRow(v);
  108718. sqlite3VdbeJumpHere(v, jmp2);
  108719. }
  108720. /* Verify CHECK constraints */
  108721. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  108722. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  108723. if( db->mallocFailed==0 ){
  108724. int addrCkFault = sqlite3VdbeMakeLabel(v);
  108725. int addrCkOk = sqlite3VdbeMakeLabel(v);
  108726. char *zErr;
  108727. int k;
  108728. pParse->iSelfTab = iDataCur + 1;
  108729. sqlite3ExprCachePush(pParse);
  108730. for(k=pCheck->nExpr-1; k>0; k--){
  108731. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  108732. }
  108733. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  108734. SQLITE_JUMPIFNULL);
  108735. sqlite3VdbeResolveLabel(v, addrCkFault);
  108736. pParse->iSelfTab = 0;
  108737. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  108738. pTab->zName);
  108739. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  108740. integrityCheckResultRow(v);
  108741. sqlite3VdbeResolveLabel(v, addrCkOk);
  108742. sqlite3ExprCachePop(pParse);
  108743. }
  108744. sqlite3ExprListDelete(db, pCheck);
  108745. }
  108746. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  108747. /* Sanity check on record header decoding */
  108748. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  108749. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  108750. /* Validate index entries for the current row */
  108751. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  108752. int jmp2, jmp3, jmp4, jmp5;
  108753. int ckUniq = sqlite3VdbeMakeLabel(v);
  108754. if( pPk==pIdx ) continue;
  108755. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  108756. pPrior, r1);
  108757. pPrior = pIdx;
  108758. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  108759. /* Verify that an index entry exists for the current table row */
  108760. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  108761. pIdx->nColumn); VdbeCoverage(v);
  108762. sqlite3VdbeLoadString(v, 3, "row ");
  108763. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  108764. sqlite3VdbeLoadString(v, 4, " missing from index ");
  108765. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  108766. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  108767. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  108768. jmp4 = integrityCheckResultRow(v);
  108769. sqlite3VdbeJumpHere(v, jmp2);
  108770. /* For UNIQUE indexes, verify that only one entry exists with the
  108771. ** current key. The entry is unique if (1) any column is NULL
  108772. ** or (2) the next entry has a different key */
  108773. if( IsUniqueIndex(pIdx) ){
  108774. int uniqOk = sqlite3VdbeMakeLabel(v);
  108775. int jmp6;
  108776. int kk;
  108777. for(kk=0; kk<pIdx->nKeyCol; kk++){
  108778. int iCol = pIdx->aiColumn[kk];
  108779. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  108780. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  108781. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  108782. VdbeCoverage(v);
  108783. }
  108784. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  108785. sqlite3VdbeGoto(v, uniqOk);
  108786. sqlite3VdbeJumpHere(v, jmp6);
  108787. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  108788. pIdx->nKeyCol); VdbeCoverage(v);
  108789. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  108790. sqlite3VdbeGoto(v, jmp5);
  108791. sqlite3VdbeResolveLabel(v, uniqOk);
  108792. }
  108793. sqlite3VdbeJumpHere(v, jmp4);
  108794. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  108795. }
  108796. }
  108797. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  108798. sqlite3VdbeJumpHere(v, loopTop-1);
  108799. #ifndef SQLITE_OMIT_BTREECOUNT
  108800. if( !isQuick ){
  108801. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  108802. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  108803. if( pPk==pIdx ) continue;
  108804. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  108805. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  108806. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  108807. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  108808. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  108809. integrityCheckResultRow(v);
  108810. sqlite3VdbeJumpHere(v, addr);
  108811. }
  108812. }
  108813. #endif /* SQLITE_OMIT_BTREECOUNT */
  108814. }
  108815. }
  108816. {
  108817. static const int iLn = VDBE_OFFSET_LINENO(2);
  108818. static const VdbeOpList endCode[] = {
  108819. { OP_AddImm, 1, 0, 0}, /* 0 */
  108820. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  108821. { OP_String8, 0, 3, 0}, /* 2 */
  108822. { OP_ResultRow, 3, 1, 0}, /* 3 */
  108823. { OP_Halt, 0, 0, 0}, /* 4 */
  108824. { OP_String8, 0, 3, 0}, /* 5 */
  108825. { OP_Goto, 0, 3, 0}, /* 6 */
  108826. };
  108827. VdbeOp *aOp;
  108828. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  108829. if( aOp ){
  108830. aOp[0].p2 = 1-mxErr;
  108831. aOp[2].p4type = P4_STATIC;
  108832. aOp[2].p4.z = "ok";
  108833. aOp[5].p4type = P4_STATIC;
  108834. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  108835. }
  108836. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  108837. }
  108838. }
  108839. break;
  108840. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  108841. #ifndef SQLITE_OMIT_UTF16
  108842. /*
  108843. ** PRAGMA encoding
  108844. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  108845. **
  108846. ** In its first form, this pragma returns the encoding of the main
  108847. ** database. If the database is not initialized, it is initialized now.
  108848. **
  108849. ** The second form of this pragma is a no-op if the main database file
  108850. ** has not already been initialized. In this case it sets the default
  108851. ** encoding that will be used for the main database file if a new file
  108852. ** is created. If an existing main database file is opened, then the
  108853. ** default text encoding for the existing database is used.
  108854. **
  108855. ** In all cases new databases created using the ATTACH command are
  108856. ** created to use the same default text encoding as the main database. If
  108857. ** the main database has not been initialized and/or created when ATTACH
  108858. ** is executed, this is done before the ATTACH operation.
  108859. **
  108860. ** In the second form this pragma sets the text encoding to be used in
  108861. ** new database files created using this database handle. It is only
  108862. ** useful if invoked immediately after the main database i
  108863. */
  108864. case PragTyp_ENCODING: {
  108865. static const struct EncName {
  108866. char *zName;
  108867. u8 enc;
  108868. } encnames[] = {
  108869. { "UTF8", SQLITE_UTF8 },
  108870. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  108871. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  108872. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  108873. { "UTF16le", SQLITE_UTF16LE },
  108874. { "UTF16be", SQLITE_UTF16BE },
  108875. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  108876. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  108877. { 0, 0 }
  108878. };
  108879. const struct EncName *pEnc;
  108880. if( !zRight ){ /* "PRAGMA encoding" */
  108881. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  108882. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  108883. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  108884. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  108885. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  108886. }else{ /* "PRAGMA encoding = XXX" */
  108887. /* Only change the value of sqlite.enc if the database handle is not
  108888. ** initialized. If the main database exists, the new sqlite.enc value
  108889. ** will be overwritten when the schema is next loaded. If it does not
  108890. ** already exists, it will be created to use the new encoding value.
  108891. */
  108892. if(
  108893. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  108894. DbHasProperty(db, 0, DB_Empty)
  108895. ){
  108896. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  108897. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  108898. SCHEMA_ENC(db) = ENC(db) =
  108899. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  108900. break;
  108901. }
  108902. }
  108903. if( !pEnc->zName ){
  108904. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  108905. }
  108906. }
  108907. }
  108908. }
  108909. break;
  108910. #endif /* SQLITE_OMIT_UTF16 */
  108911. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  108912. /*
  108913. ** PRAGMA [schema.]schema_version
  108914. ** PRAGMA [schema.]schema_version = <integer>
  108915. **
  108916. ** PRAGMA [schema.]user_version
  108917. ** PRAGMA [schema.]user_version = <integer>
  108918. **
  108919. ** PRAGMA [schema.]freelist_count
  108920. **
  108921. ** PRAGMA [schema.]data_version
  108922. **
  108923. ** PRAGMA [schema.]application_id
  108924. ** PRAGMA [schema.]application_id = <integer>
  108925. **
  108926. ** The pragma's schema_version and user_version are used to set or get
  108927. ** the value of the schema-version and user-version, respectively. Both
  108928. ** the schema-version and the user-version are 32-bit signed integers
  108929. ** stored in the database header.
  108930. **
  108931. ** The schema-cookie is usually only manipulated internally by SQLite. It
  108932. ** is incremented by SQLite whenever the database schema is modified (by
  108933. ** creating or dropping a table or index). The schema version is used by
  108934. ** SQLite each time a query is executed to ensure that the internal cache
  108935. ** of the schema used when compiling the SQL query matches the schema of
  108936. ** the database against which the compiled query is actually executed.
  108937. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  108938. ** the schema-version is potentially dangerous and may lead to program
  108939. ** crashes or database corruption. Use with caution!
  108940. **
  108941. ** The user-version is not used internally by SQLite. It may be used by
  108942. ** applications for any purpose.
  108943. */
  108944. case PragTyp_HEADER_VALUE: {
  108945. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  108946. sqlite3VdbeUsesBtree(v, iDb);
  108947. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  108948. /* Write the specified cookie value */
  108949. static const VdbeOpList setCookie[] = {
  108950. { OP_Transaction, 0, 1, 0}, /* 0 */
  108951. { OP_SetCookie, 0, 0, 0}, /* 1 */
  108952. };
  108953. VdbeOp *aOp;
  108954. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  108955. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  108956. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  108957. aOp[0].p1 = iDb;
  108958. aOp[1].p1 = iDb;
  108959. aOp[1].p2 = iCookie;
  108960. aOp[1].p3 = sqlite3Atoi(zRight);
  108961. }else{
  108962. /* Read the specified cookie value */
  108963. static const VdbeOpList readCookie[] = {
  108964. { OP_Transaction, 0, 0, 0}, /* 0 */
  108965. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  108966. { OP_ResultRow, 1, 1, 0}
  108967. };
  108968. VdbeOp *aOp;
  108969. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  108970. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  108971. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  108972. aOp[0].p1 = iDb;
  108973. aOp[1].p1 = iDb;
  108974. aOp[1].p3 = iCookie;
  108975. sqlite3VdbeReusable(v);
  108976. }
  108977. }
  108978. break;
  108979. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  108980. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  108981. /*
  108982. ** PRAGMA compile_options
  108983. **
  108984. ** Return the names of all compile-time options used in this build,
  108985. ** one option per row.
  108986. */
  108987. case PragTyp_COMPILE_OPTIONS: {
  108988. int i = 0;
  108989. const char *zOpt;
  108990. pParse->nMem = 1;
  108991. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  108992. sqlite3VdbeLoadString(v, 1, zOpt);
  108993. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  108994. }
  108995. sqlite3VdbeReusable(v);
  108996. }
  108997. break;
  108998. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  108999. #ifndef SQLITE_OMIT_WAL
  109000. /*
  109001. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  109002. **
  109003. ** Checkpoint the database.
  109004. */
  109005. case PragTyp_WAL_CHECKPOINT: {
  109006. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  109007. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  109008. if( zRight ){
  109009. if( sqlite3StrICmp(zRight, "full")==0 ){
  109010. eMode = SQLITE_CHECKPOINT_FULL;
  109011. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  109012. eMode = SQLITE_CHECKPOINT_RESTART;
  109013. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  109014. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  109015. }
  109016. }
  109017. pParse->nMem = 3;
  109018. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  109019. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  109020. }
  109021. break;
  109022. /*
  109023. ** PRAGMA wal_autocheckpoint
  109024. ** PRAGMA wal_autocheckpoint = N
  109025. **
  109026. ** Configure a database connection to automatically checkpoint a database
  109027. ** after accumulating N frames in the log. Or query for the current value
  109028. ** of N.
  109029. */
  109030. case PragTyp_WAL_AUTOCHECKPOINT: {
  109031. if( zRight ){
  109032. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  109033. }
  109034. returnSingleInt(v,
  109035. db->xWalCallback==sqlite3WalDefaultHook ?
  109036. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  109037. }
  109038. break;
  109039. #endif
  109040. /*
  109041. ** PRAGMA shrink_memory
  109042. **
  109043. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  109044. ** connection on which it is invoked to free up as much memory as it
  109045. ** can, by calling sqlite3_db_release_memory().
  109046. */
  109047. case PragTyp_SHRINK_MEMORY: {
  109048. sqlite3_db_release_memory(db);
  109049. break;
  109050. }
  109051. /*
  109052. ** PRAGMA optimize
  109053. ** PRAGMA optimize(MASK)
  109054. ** PRAGMA schema.optimize
  109055. ** PRAGMA schema.optimize(MASK)
  109056. **
  109057. ** Attempt to optimize the database. All schemas are optimized in the first
  109058. ** two forms, and only the specified schema is optimized in the latter two.
  109059. **
  109060. ** The details of optimizations performed by this pragma are expected
  109061. ** to change and improve over time. Applications should anticipate that
  109062. ** this pragma will perform new optimizations in future releases.
  109063. **
  109064. ** The optional argument is a bitmask of optimizations to perform:
  109065. **
  109066. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  109067. ** but instead return one line of text for each optimization
  109068. ** that would have been done. Off by default.
  109069. **
  109070. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  109071. ** See below for additional information.
  109072. **
  109073. ** 0x0004 (Not yet implemented) Record usage and performance
  109074. ** information from the current session in the
  109075. ** database file so that it will be available to "optimize"
  109076. ** pragmas run by future database connections.
  109077. **
  109078. ** 0x0008 (Not yet implemented) Create indexes that might have
  109079. ** been helpful to recent queries
  109080. **
  109081. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  109082. ** of the optimizations listed above except Debug Mode, including new
  109083. ** optimizations that have not yet been invented. If new optimizations are
  109084. ** ever added that should be off by default, those off-by-default
  109085. ** optimizations will have bitmasks of 0x10000 or larger.
  109086. **
  109087. ** DETERMINATION OF WHEN TO RUN ANALYZE
  109088. **
  109089. ** In the current implementation, a table is analyzed if only if all of
  109090. ** the following are true:
  109091. **
  109092. ** (1) MASK bit 0x02 is set.
  109093. **
  109094. ** (2) The query planner used sqlite_stat1-style statistics for one or
  109095. ** more indexes of the table at some point during the lifetime of
  109096. ** the current connection.
  109097. **
  109098. ** (3) One or more indexes of the table are currently unanalyzed OR
  109099. ** the number of rows in the table has increased by 25 times or more
  109100. ** since the last time ANALYZE was run.
  109101. **
  109102. ** The rules for when tables are analyzed are likely to change in
  109103. ** future releases.
  109104. */
  109105. case PragTyp_OPTIMIZE: {
  109106. int iDbLast; /* Loop termination point for the schema loop */
  109107. int iTabCur; /* Cursor for a table whose size needs checking */
  109108. HashElem *k; /* Loop over tables of a schema */
  109109. Schema *pSchema; /* The current schema */
  109110. Table *pTab; /* A table in the schema */
  109111. Index *pIdx; /* An index of the table */
  109112. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  109113. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  109114. u32 opMask; /* Mask of operations to perform */
  109115. if( zRight ){
  109116. opMask = (u32)sqlite3Atoi(zRight);
  109117. if( (opMask & 0x02)==0 ) break;
  109118. }else{
  109119. opMask = 0xfffe;
  109120. }
  109121. iTabCur = pParse->nTab++;
  109122. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  109123. if( iDb==1 ) continue;
  109124. sqlite3CodeVerifySchema(pParse, iDb);
  109125. pSchema = db->aDb[iDb].pSchema;
  109126. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  109127. pTab = (Table*)sqliteHashData(k);
  109128. /* If table pTab has not been used in a way that would benefit from
  109129. ** having analysis statistics during the current session, then skip it.
  109130. ** This also has the effect of skipping virtual tables and views */
  109131. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  109132. /* Reanalyze if the table is 25 times larger than the last analysis */
  109133. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  109134. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  109135. if( !pIdx->hasStat1 ){
  109136. szThreshold = 0; /* Always analyze if any index lacks statistics */
  109137. break;
  109138. }
  109139. }
  109140. if( szThreshold ){
  109141. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  109142. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  109143. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  109144. VdbeCoverage(v);
  109145. }
  109146. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  109147. db->aDb[iDb].zDbSName, pTab->zName);
  109148. if( opMask & 0x01 ){
  109149. int r1 = sqlite3GetTempReg(pParse);
  109150. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  109151. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  109152. }else{
  109153. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  109154. }
  109155. }
  109156. }
  109157. sqlite3VdbeAddOp0(v, OP_Expire);
  109158. break;
  109159. }
  109160. /*
  109161. ** PRAGMA busy_timeout
  109162. ** PRAGMA busy_timeout = N
  109163. **
  109164. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  109165. ** if one is set. If no busy handler or a different busy handler is set
  109166. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  109167. ** disables the timeout.
  109168. */
  109169. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  109170. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  109171. if( zRight ){
  109172. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  109173. }
  109174. returnSingleInt(v, db->busyTimeout);
  109175. break;
  109176. }
  109177. /*
  109178. ** PRAGMA soft_heap_limit
  109179. ** PRAGMA soft_heap_limit = N
  109180. **
  109181. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  109182. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  109183. ** specified and is a non-negative integer.
  109184. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  109185. ** returns the same integer that would be returned by the
  109186. ** sqlite3_soft_heap_limit64(-1) C-language function.
  109187. */
  109188. case PragTyp_SOFT_HEAP_LIMIT: {
  109189. sqlite3_int64 N;
  109190. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  109191. sqlite3_soft_heap_limit64(N);
  109192. }
  109193. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  109194. break;
  109195. }
  109196. /*
  109197. ** PRAGMA threads
  109198. ** PRAGMA threads = N
  109199. **
  109200. ** Configure the maximum number of worker threads. Return the new
  109201. ** maximum, which might be less than requested.
  109202. */
  109203. case PragTyp_THREADS: {
  109204. sqlite3_int64 N;
  109205. if( zRight
  109206. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  109207. && N>=0
  109208. ){
  109209. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  109210. }
  109211. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  109212. break;
  109213. }
  109214. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  109215. /*
  109216. ** Report the current state of file logs for all databases
  109217. */
  109218. case PragTyp_LOCK_STATUS: {
  109219. static const char *const azLockName[] = {
  109220. "unlocked", "shared", "reserved", "pending", "exclusive"
  109221. };
  109222. int i;
  109223. pParse->nMem = 2;
  109224. for(i=0; i<db->nDb; i++){
  109225. Btree *pBt;
  109226. const char *zState = "unknown";
  109227. int j;
  109228. if( db->aDb[i].zDbSName==0 ) continue;
  109229. pBt = db->aDb[i].pBt;
  109230. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  109231. zState = "closed";
  109232. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  109233. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  109234. zState = azLockName[j];
  109235. }
  109236. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  109237. }
  109238. break;
  109239. }
  109240. #endif
  109241. #ifdef SQLITE_HAS_CODEC
  109242. case PragTyp_KEY: {
  109243. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  109244. break;
  109245. }
  109246. case PragTyp_REKEY: {
  109247. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  109248. break;
  109249. }
  109250. case PragTyp_HEXKEY: {
  109251. if( zRight ){
  109252. u8 iByte;
  109253. int i;
  109254. char zKey[40];
  109255. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  109256. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  109257. if( (i&1)!=0 ) zKey[i/2] = iByte;
  109258. }
  109259. if( (zLeft[3] & 0xf)==0xb ){
  109260. sqlite3_key_v2(db, zDb, zKey, i/2);
  109261. }else{
  109262. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  109263. }
  109264. }
  109265. break;
  109266. }
  109267. #endif
  109268. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  109269. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  109270. #ifdef SQLITE_HAS_CODEC
  109271. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  109272. sqlite3_activate_see(&zRight[4]);
  109273. }
  109274. #endif
  109275. #ifdef SQLITE_ENABLE_CEROD
  109276. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  109277. sqlite3_activate_cerod(&zRight[6]);
  109278. }
  109279. #endif
  109280. }
  109281. break;
  109282. #endif
  109283. } /* End of the PRAGMA switch */
  109284. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  109285. ** purpose is to execute assert() statements to verify that if the
  109286. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  109287. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  109288. ** instructions to the VM. */
  109289. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  109290. sqlite3VdbeVerifyNoResultRow(v);
  109291. }
  109292. pragma_out:
  109293. sqlite3DbFree(db, zLeft);
  109294. sqlite3DbFree(db, zRight);
  109295. }
  109296. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109297. /*****************************************************************************
  109298. ** Implementation of an eponymous virtual table that runs a pragma.
  109299. **
  109300. */
  109301. typedef struct PragmaVtab PragmaVtab;
  109302. typedef struct PragmaVtabCursor PragmaVtabCursor;
  109303. struct PragmaVtab {
  109304. sqlite3_vtab base; /* Base class. Must be first */
  109305. sqlite3 *db; /* The database connection to which it belongs */
  109306. const PragmaName *pName; /* Name of the pragma */
  109307. u8 nHidden; /* Number of hidden columns */
  109308. u8 iHidden; /* Index of the first hidden column */
  109309. };
  109310. struct PragmaVtabCursor {
  109311. sqlite3_vtab_cursor base; /* Base class. Must be first */
  109312. sqlite3_stmt *pPragma; /* The pragma statement to run */
  109313. sqlite_int64 iRowid; /* Current rowid */
  109314. char *azArg[2]; /* Value of the argument and schema */
  109315. };
  109316. /*
  109317. ** Pragma virtual table module xConnect method.
  109318. */
  109319. static int pragmaVtabConnect(
  109320. sqlite3 *db,
  109321. void *pAux,
  109322. int argc, const char *const*argv,
  109323. sqlite3_vtab **ppVtab,
  109324. char **pzErr
  109325. ){
  109326. const PragmaName *pPragma = (const PragmaName*)pAux;
  109327. PragmaVtab *pTab = 0;
  109328. int rc;
  109329. int i, j;
  109330. char cSep = '(';
  109331. StrAccum acc;
  109332. char zBuf[200];
  109333. UNUSED_PARAMETER(argc);
  109334. UNUSED_PARAMETER(argv);
  109335. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  109336. sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
  109337. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  109338. sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  109339. cSep = ',';
  109340. }
  109341. if( i==0 ){
  109342. sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
  109343. cSep = ',';
  109344. i++;
  109345. }
  109346. j = 0;
  109347. if( pPragma->mPragFlg & PragFlg_Result1 ){
  109348. sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
  109349. j++;
  109350. }
  109351. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  109352. sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
  109353. j++;
  109354. }
  109355. sqlite3StrAccumAppend(&acc, ")", 1);
  109356. sqlite3StrAccumFinish(&acc);
  109357. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  109358. rc = sqlite3_declare_vtab(db, zBuf);
  109359. if( rc==SQLITE_OK ){
  109360. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  109361. if( pTab==0 ){
  109362. rc = SQLITE_NOMEM;
  109363. }else{
  109364. memset(pTab, 0, sizeof(PragmaVtab));
  109365. pTab->pName = pPragma;
  109366. pTab->db = db;
  109367. pTab->iHidden = i;
  109368. pTab->nHidden = j;
  109369. }
  109370. }else{
  109371. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  109372. }
  109373. *ppVtab = (sqlite3_vtab*)pTab;
  109374. return rc;
  109375. }
  109376. /*
  109377. ** Pragma virtual table module xDisconnect method.
  109378. */
  109379. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  109380. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  109381. sqlite3_free(pTab);
  109382. return SQLITE_OK;
  109383. }
  109384. /* Figure out the best index to use to search a pragma virtual table.
  109385. **
  109386. ** There are not really any index choices. But we want to encourage the
  109387. ** query planner to give == constraints on as many hidden parameters as
  109388. ** possible, and especially on the first hidden parameter. So return a
  109389. ** high cost if hidden parameters are unconstrained.
  109390. */
  109391. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  109392. PragmaVtab *pTab = (PragmaVtab*)tab;
  109393. const struct sqlite3_index_constraint *pConstraint;
  109394. int i, j;
  109395. int seen[2];
  109396. pIdxInfo->estimatedCost = (double)1;
  109397. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  109398. pConstraint = pIdxInfo->aConstraint;
  109399. seen[0] = 0;
  109400. seen[1] = 0;
  109401. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  109402. if( pConstraint->usable==0 ) continue;
  109403. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  109404. if( pConstraint->iColumn < pTab->iHidden ) continue;
  109405. j = pConstraint->iColumn - pTab->iHidden;
  109406. assert( j < 2 );
  109407. seen[j] = i+1;
  109408. }
  109409. if( seen[0]==0 ){
  109410. pIdxInfo->estimatedCost = (double)2147483647;
  109411. pIdxInfo->estimatedRows = 2147483647;
  109412. return SQLITE_OK;
  109413. }
  109414. j = seen[0]-1;
  109415. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  109416. pIdxInfo->aConstraintUsage[j].omit = 1;
  109417. if( seen[1]==0 ) return SQLITE_OK;
  109418. pIdxInfo->estimatedCost = (double)20;
  109419. pIdxInfo->estimatedRows = 20;
  109420. j = seen[1]-1;
  109421. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  109422. pIdxInfo->aConstraintUsage[j].omit = 1;
  109423. return SQLITE_OK;
  109424. }
  109425. /* Create a new cursor for the pragma virtual table */
  109426. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  109427. PragmaVtabCursor *pCsr;
  109428. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  109429. if( pCsr==0 ) return SQLITE_NOMEM;
  109430. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  109431. pCsr->base.pVtab = pVtab;
  109432. *ppCursor = &pCsr->base;
  109433. return SQLITE_OK;
  109434. }
  109435. /* Clear all content from pragma virtual table cursor. */
  109436. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  109437. int i;
  109438. sqlite3_finalize(pCsr->pPragma);
  109439. pCsr->pPragma = 0;
  109440. for(i=0; i<ArraySize(pCsr->azArg); i++){
  109441. sqlite3_free(pCsr->azArg[i]);
  109442. pCsr->azArg[i] = 0;
  109443. }
  109444. }
  109445. /* Close a pragma virtual table cursor */
  109446. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  109447. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  109448. pragmaVtabCursorClear(pCsr);
  109449. sqlite3_free(pCsr);
  109450. return SQLITE_OK;
  109451. }
  109452. /* Advance the pragma virtual table cursor to the next row */
  109453. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  109454. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  109455. int rc = SQLITE_OK;
  109456. /* Increment the xRowid value */
  109457. pCsr->iRowid++;
  109458. assert( pCsr->pPragma );
  109459. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  109460. rc = sqlite3_finalize(pCsr->pPragma);
  109461. pCsr->pPragma = 0;
  109462. pragmaVtabCursorClear(pCsr);
  109463. }
  109464. return rc;
  109465. }
  109466. /*
  109467. ** Pragma virtual table module xFilter method.
  109468. */
  109469. static int pragmaVtabFilter(
  109470. sqlite3_vtab_cursor *pVtabCursor,
  109471. int idxNum, const char *idxStr,
  109472. int argc, sqlite3_value **argv
  109473. ){
  109474. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  109475. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  109476. int rc;
  109477. int i, j;
  109478. StrAccum acc;
  109479. char *zSql;
  109480. UNUSED_PARAMETER(idxNum);
  109481. UNUSED_PARAMETER(idxStr);
  109482. pragmaVtabCursorClear(pCsr);
  109483. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  109484. for(i=0; i<argc; i++, j++){
  109485. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  109486. assert( j<ArraySize(pCsr->azArg) );
  109487. assert( pCsr->azArg[j]==0 );
  109488. if( zText ){
  109489. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  109490. if( pCsr->azArg[j]==0 ){
  109491. return SQLITE_NOMEM;
  109492. }
  109493. }
  109494. }
  109495. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  109496. sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
  109497. if( pCsr->azArg[1] ){
  109498. sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
  109499. }
  109500. sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
  109501. if( pCsr->azArg[0] ){
  109502. sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
  109503. }
  109504. zSql = sqlite3StrAccumFinish(&acc);
  109505. if( zSql==0 ) return SQLITE_NOMEM;
  109506. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  109507. sqlite3_free(zSql);
  109508. if( rc!=SQLITE_OK ){
  109509. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  109510. return rc;
  109511. }
  109512. return pragmaVtabNext(pVtabCursor);
  109513. }
  109514. /*
  109515. ** Pragma virtual table module xEof method.
  109516. */
  109517. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  109518. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  109519. return (pCsr->pPragma==0);
  109520. }
  109521. /* The xColumn method simply returns the corresponding column from
  109522. ** the PRAGMA.
  109523. */
  109524. static int pragmaVtabColumn(
  109525. sqlite3_vtab_cursor *pVtabCursor,
  109526. sqlite3_context *ctx,
  109527. int i
  109528. ){
  109529. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  109530. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  109531. if( i<pTab->iHidden ){
  109532. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  109533. }else{
  109534. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  109535. }
  109536. return SQLITE_OK;
  109537. }
  109538. /*
  109539. ** Pragma virtual table module xRowid method.
  109540. */
  109541. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  109542. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  109543. *p = pCsr->iRowid;
  109544. return SQLITE_OK;
  109545. }
  109546. /* The pragma virtual table object */
  109547. static const sqlite3_module pragmaVtabModule = {
  109548. 0, /* iVersion */
  109549. 0, /* xCreate - create a table */
  109550. pragmaVtabConnect, /* xConnect - connect to an existing table */
  109551. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  109552. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  109553. 0, /* xDestroy - Drop a table */
  109554. pragmaVtabOpen, /* xOpen - open a cursor */
  109555. pragmaVtabClose, /* xClose - close a cursor */
  109556. pragmaVtabFilter, /* xFilter - configure scan constraints */
  109557. pragmaVtabNext, /* xNext - advance a cursor */
  109558. pragmaVtabEof, /* xEof */
  109559. pragmaVtabColumn, /* xColumn - read data */
  109560. pragmaVtabRowid, /* xRowid - read data */
  109561. 0, /* xUpdate - write data */
  109562. 0, /* xBegin - begin transaction */
  109563. 0, /* xSync - sync transaction */
  109564. 0, /* xCommit - commit transaction */
  109565. 0, /* xRollback - rollback transaction */
  109566. 0, /* xFindFunction - function overloading */
  109567. 0, /* xRename - rename the table */
  109568. 0, /* xSavepoint */
  109569. 0, /* xRelease */
  109570. 0 /* xRollbackTo */
  109571. };
  109572. /*
  109573. ** Check to see if zTabName is really the name of a pragma. If it is,
  109574. ** then register an eponymous virtual table for that pragma and return
  109575. ** a pointer to the Module object for the new virtual table.
  109576. */
  109577. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  109578. const PragmaName *pName;
  109579. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  109580. pName = pragmaLocate(zName+7);
  109581. if( pName==0 ) return 0;
  109582. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  109583. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  109584. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  109585. }
  109586. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109587. #endif /* SQLITE_OMIT_PRAGMA */
  109588. /************** End of pragma.c **********************************************/
  109589. /************** Begin file prepare.c *****************************************/
  109590. /*
  109591. ** 2005 May 25
  109592. **
  109593. ** The author disclaims copyright to this source code. In place of
  109594. ** a legal notice, here is a blessing:
  109595. **
  109596. ** May you do good and not evil.
  109597. ** May you find forgiveness for yourself and forgive others.
  109598. ** May you share freely, never taking more than you give.
  109599. **
  109600. *************************************************************************
  109601. ** This file contains the implementation of the sqlite3_prepare()
  109602. ** interface, and routines that contribute to loading the database schema
  109603. ** from disk.
  109604. */
  109605. /* #include "sqliteInt.h" */
  109606. /*
  109607. ** Fill the InitData structure with an error message that indicates
  109608. ** that the database is corrupt.
  109609. */
  109610. static void corruptSchema(
  109611. InitData *pData, /* Initialization context */
  109612. const char *zObj, /* Object being parsed at the point of error */
  109613. const char *zExtra /* Error information */
  109614. ){
  109615. sqlite3 *db = pData->db;
  109616. if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
  109617. char *z;
  109618. if( zObj==0 ) zObj = "?";
  109619. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  109620. if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  109621. sqlite3DbFree(db, *pData->pzErrMsg);
  109622. *pData->pzErrMsg = z;
  109623. }
  109624. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  109625. }
  109626. /*
  109627. ** This is the callback routine for the code that initializes the
  109628. ** database. See sqlite3Init() below for additional information.
  109629. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  109630. **
  109631. ** Each callback contains the following information:
  109632. **
  109633. ** argv[0] = name of thing being created
  109634. ** argv[1] = root page number for table or index. 0 for trigger or view.
  109635. ** argv[2] = SQL text for the CREATE statement.
  109636. **
  109637. */
  109638. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  109639. InitData *pData = (InitData*)pInit;
  109640. sqlite3 *db = pData->db;
  109641. int iDb = pData->iDb;
  109642. assert( argc==3 );
  109643. UNUSED_PARAMETER2(NotUsed, argc);
  109644. assert( sqlite3_mutex_held(db->mutex) );
  109645. DbClearProperty(db, iDb, DB_Empty);
  109646. if( db->mallocFailed ){
  109647. corruptSchema(pData, argv[0], 0);
  109648. return 1;
  109649. }
  109650. assert( iDb>=0 && iDb<db->nDb );
  109651. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  109652. if( argv[1]==0 ){
  109653. corruptSchema(pData, argv[0], 0);
  109654. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  109655. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  109656. ** But because db->init.busy is set to 1, no VDBE code is generated
  109657. ** or executed. All the parser does is build the internal data
  109658. ** structures that describe the table, index, or view.
  109659. */
  109660. int rc;
  109661. u8 saved_iDb = db->init.iDb;
  109662. sqlite3_stmt *pStmt;
  109663. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  109664. assert( db->init.busy );
  109665. db->init.iDb = iDb;
  109666. db->init.newTnum = sqlite3Atoi(argv[1]);
  109667. db->init.orphanTrigger = 0;
  109668. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  109669. rc = db->errCode;
  109670. assert( (rc&0xFF)==(rcp&0xFF) );
  109671. db->init.iDb = saved_iDb;
  109672. assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  109673. if( SQLITE_OK!=rc ){
  109674. if( db->init.orphanTrigger ){
  109675. assert( iDb==1 );
  109676. }else{
  109677. pData->rc = rc;
  109678. if( rc==SQLITE_NOMEM ){
  109679. sqlite3OomFault(db);
  109680. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  109681. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  109682. }
  109683. }
  109684. }
  109685. sqlite3_finalize(pStmt);
  109686. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  109687. corruptSchema(pData, argv[0], 0);
  109688. }else{
  109689. /* If the SQL column is blank it means this is an index that
  109690. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  109691. ** constraint for a CREATE TABLE. The index should have already
  109692. ** been created when we processed the CREATE TABLE. All we have
  109693. ** to do here is record the root page number for that index.
  109694. */
  109695. Index *pIndex;
  109696. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  109697. if( pIndex==0 ){
  109698. /* This can occur if there exists an index on a TEMP table which
  109699. ** has the same name as another index on a permanent index. Since
  109700. ** the permanent table is hidden by the TEMP table, we can also
  109701. ** safely ignore the index on the permanent table.
  109702. */
  109703. /* Do Nothing */;
  109704. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  109705. corruptSchema(pData, argv[0], "invalid rootpage");
  109706. }
  109707. }
  109708. return 0;
  109709. }
  109710. /*
  109711. ** Attempt to read the database schema and initialize internal
  109712. ** data structures for a single database file. The index of the
  109713. ** database file is given by iDb. iDb==0 is used for the main
  109714. ** database. iDb==1 should never be used. iDb>=2 is used for
  109715. ** auxiliary databases. Return one of the SQLITE_ error codes to
  109716. ** indicate success or failure.
  109717. */
  109718. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  109719. int rc;
  109720. int i;
  109721. #ifndef SQLITE_OMIT_DEPRECATED
  109722. int size;
  109723. #endif
  109724. Db *pDb;
  109725. char const *azArg[4];
  109726. int meta[5];
  109727. InitData initData;
  109728. const char *zMasterName;
  109729. int openedTransaction = 0;
  109730. assert( iDb>=0 && iDb<db->nDb );
  109731. assert( db->aDb[iDb].pSchema );
  109732. assert( sqlite3_mutex_held(db->mutex) );
  109733. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  109734. db->init.busy = 1;
  109735. /* Construct the in-memory representation schema tables (sqlite_master or
  109736. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  109737. ** table name will be inserted automatically by the parser so we can just
  109738. ** use the abbreviation "x" here. The parser will also automatically tag
  109739. ** the schema table as read-only. */
  109740. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  109741. azArg[1] = "1";
  109742. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  109743. "rootpage int,sql text)";
  109744. azArg[3] = 0;
  109745. initData.db = db;
  109746. initData.iDb = iDb;
  109747. initData.rc = SQLITE_OK;
  109748. initData.pzErrMsg = pzErrMsg;
  109749. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  109750. if( initData.rc ){
  109751. rc = initData.rc;
  109752. goto error_out;
  109753. }
  109754. /* Create a cursor to hold the database open
  109755. */
  109756. pDb = &db->aDb[iDb];
  109757. if( pDb->pBt==0 ){
  109758. assert( iDb==1 );
  109759. DbSetProperty(db, 1, DB_SchemaLoaded);
  109760. rc = SQLITE_OK;
  109761. goto error_out;
  109762. }
  109763. /* If there is not already a read-only (or read-write) transaction opened
  109764. ** on the b-tree database, open one now. If a transaction is opened, it
  109765. ** will be closed before this function returns. */
  109766. sqlite3BtreeEnter(pDb->pBt);
  109767. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  109768. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  109769. if( rc!=SQLITE_OK ){
  109770. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  109771. goto initone_error_out;
  109772. }
  109773. openedTransaction = 1;
  109774. }
  109775. /* Get the database meta information.
  109776. **
  109777. ** Meta values are as follows:
  109778. ** meta[0] Schema cookie. Changes with each schema change.
  109779. ** meta[1] File format of schema layer.
  109780. ** meta[2] Size of the page cache.
  109781. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  109782. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  109783. ** meta[5] User version
  109784. ** meta[6] Incremental vacuum mode
  109785. ** meta[7] unused
  109786. ** meta[8] unused
  109787. ** meta[9] unused
  109788. **
  109789. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  109790. ** the possible values of meta[4].
  109791. */
  109792. for(i=0; i<ArraySize(meta); i++){
  109793. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  109794. }
  109795. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  109796. /* If opening a non-empty database, check the text encoding. For the
  109797. ** main database, set sqlite3.enc to the encoding of the main database.
  109798. ** For an attached db, it is an error if the encoding is not the same
  109799. ** as sqlite3.enc.
  109800. */
  109801. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  109802. if( iDb==0 ){
  109803. #ifndef SQLITE_OMIT_UTF16
  109804. u8 encoding;
  109805. /* If opening the main database, set ENC(db). */
  109806. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  109807. if( encoding==0 ) encoding = SQLITE_UTF8;
  109808. ENC(db) = encoding;
  109809. #else
  109810. ENC(db) = SQLITE_UTF8;
  109811. #endif
  109812. }else{
  109813. /* If opening an attached database, the encoding much match ENC(db) */
  109814. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  109815. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  109816. " text encoding as main database");
  109817. rc = SQLITE_ERROR;
  109818. goto initone_error_out;
  109819. }
  109820. }
  109821. }else{
  109822. DbSetProperty(db, iDb, DB_Empty);
  109823. }
  109824. pDb->pSchema->enc = ENC(db);
  109825. if( pDb->pSchema->cache_size==0 ){
  109826. #ifndef SQLITE_OMIT_DEPRECATED
  109827. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  109828. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  109829. pDb->pSchema->cache_size = size;
  109830. #else
  109831. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  109832. #endif
  109833. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  109834. }
  109835. /*
  109836. ** file_format==1 Version 3.0.0.
  109837. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  109838. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  109839. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  109840. */
  109841. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  109842. if( pDb->pSchema->file_format==0 ){
  109843. pDb->pSchema->file_format = 1;
  109844. }
  109845. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  109846. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  109847. rc = SQLITE_ERROR;
  109848. goto initone_error_out;
  109849. }
  109850. /* Ticket #2804: When we open a database in the newer file format,
  109851. ** clear the legacy_file_format pragma flag so that a VACUUM will
  109852. ** not downgrade the database and thus invalidate any descending
  109853. ** indices that the user might have created.
  109854. */
  109855. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  109856. db->flags &= ~SQLITE_LegacyFileFmt;
  109857. }
  109858. /* Read the schema information out of the schema tables
  109859. */
  109860. assert( db->init.busy );
  109861. {
  109862. char *zSql;
  109863. zSql = sqlite3MPrintf(db,
  109864. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  109865. db->aDb[iDb].zDbSName, zMasterName);
  109866. #ifndef SQLITE_OMIT_AUTHORIZATION
  109867. {
  109868. sqlite3_xauth xAuth;
  109869. xAuth = db->xAuth;
  109870. db->xAuth = 0;
  109871. #endif
  109872. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  109873. #ifndef SQLITE_OMIT_AUTHORIZATION
  109874. db->xAuth = xAuth;
  109875. }
  109876. #endif
  109877. if( rc==SQLITE_OK ) rc = initData.rc;
  109878. sqlite3DbFree(db, zSql);
  109879. #ifndef SQLITE_OMIT_ANALYZE
  109880. if( rc==SQLITE_OK ){
  109881. sqlite3AnalysisLoad(db, iDb);
  109882. }
  109883. #endif
  109884. }
  109885. if( db->mallocFailed ){
  109886. rc = SQLITE_NOMEM_BKPT;
  109887. sqlite3ResetAllSchemasOfConnection(db);
  109888. }
  109889. if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
  109890. /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
  109891. ** the schema loaded, even if errors occurred. In this situation the
  109892. ** current sqlite3_prepare() operation will fail, but the following one
  109893. ** will attempt to compile the supplied statement against whatever subset
  109894. ** of the schema was loaded before the error occurred. The primary
  109895. ** purpose of this is to allow access to the sqlite_master table
  109896. ** even when its contents have been corrupted.
  109897. */
  109898. DbSetProperty(db, iDb, DB_SchemaLoaded);
  109899. rc = SQLITE_OK;
  109900. }
  109901. /* Jump here for an error that occurs after successfully allocating
  109902. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  109903. ** before that point, jump to error_out.
  109904. */
  109905. initone_error_out:
  109906. if( openedTransaction ){
  109907. sqlite3BtreeCommit(pDb->pBt);
  109908. }
  109909. sqlite3BtreeLeave(pDb->pBt);
  109910. error_out:
  109911. if( rc ){
  109912. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  109913. sqlite3OomFault(db);
  109914. }
  109915. sqlite3ResetOneSchema(db, iDb);
  109916. }
  109917. db->init.busy = 0;
  109918. return rc;
  109919. }
  109920. /*
  109921. ** Initialize all database files - the main database file, the file
  109922. ** used to store temporary tables, and any additional database files
  109923. ** created using ATTACH statements. Return a success code. If an
  109924. ** error occurs, write an error message into *pzErrMsg.
  109925. **
  109926. ** After a database is initialized, the DB_SchemaLoaded bit is set
  109927. ** bit is set in the flags field of the Db structure. If the database
  109928. ** file was of zero-length, then the DB_Empty flag is also set.
  109929. */
  109930. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  109931. int i, rc;
  109932. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  109933. assert( sqlite3_mutex_held(db->mutex) );
  109934. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  109935. assert( db->init.busy==0 );
  109936. ENC(db) = SCHEMA_ENC(db);
  109937. assert( db->nDb>0 );
  109938. /* Do the main schema first */
  109939. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  109940. rc = sqlite3InitOne(db, 0, pzErrMsg);
  109941. if( rc ) return rc;
  109942. }
  109943. /* All other schemas after the main schema. The "temp" schema must be last */
  109944. for(i=db->nDb-1; i>0; i--){
  109945. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  109946. rc = sqlite3InitOne(db, i, pzErrMsg);
  109947. if( rc ) return rc;
  109948. }
  109949. }
  109950. if( commit_internal ){
  109951. sqlite3CommitInternalChanges(db);
  109952. }
  109953. return SQLITE_OK;
  109954. }
  109955. /*
  109956. ** This routine is a no-op if the database schema is already initialized.
  109957. ** Otherwise, the schema is loaded. An error code is returned.
  109958. */
  109959. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  109960. int rc = SQLITE_OK;
  109961. sqlite3 *db = pParse->db;
  109962. assert( sqlite3_mutex_held(db->mutex) );
  109963. if( !db->init.busy ){
  109964. rc = sqlite3Init(db, &pParse->zErrMsg);
  109965. }
  109966. if( rc!=SQLITE_OK ){
  109967. pParse->rc = rc;
  109968. pParse->nErr++;
  109969. }
  109970. return rc;
  109971. }
  109972. /*
  109973. ** Check schema cookies in all databases. If any cookie is out
  109974. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  109975. ** make no changes to pParse->rc.
  109976. */
  109977. static void schemaIsValid(Parse *pParse){
  109978. sqlite3 *db = pParse->db;
  109979. int iDb;
  109980. int rc;
  109981. int cookie;
  109982. assert( pParse->checkSchema );
  109983. assert( sqlite3_mutex_held(db->mutex) );
  109984. for(iDb=0; iDb<db->nDb; iDb++){
  109985. int openedTransaction = 0; /* True if a transaction is opened */
  109986. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  109987. if( pBt==0 ) continue;
  109988. /* If there is not already a read-only (or read-write) transaction opened
  109989. ** on the b-tree database, open one now. If a transaction is opened, it
  109990. ** will be closed immediately after reading the meta-value. */
  109991. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  109992. rc = sqlite3BtreeBeginTrans(pBt, 0);
  109993. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  109994. sqlite3OomFault(db);
  109995. }
  109996. if( rc!=SQLITE_OK ) return;
  109997. openedTransaction = 1;
  109998. }
  109999. /* Read the schema cookie from the database. If it does not match the
  110000. ** value stored as part of the in-memory schema representation,
  110001. ** set Parse.rc to SQLITE_SCHEMA. */
  110002. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  110003. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  110004. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  110005. sqlite3ResetOneSchema(db, iDb);
  110006. pParse->rc = SQLITE_SCHEMA;
  110007. }
  110008. /* Close the transaction, if one was opened. */
  110009. if( openedTransaction ){
  110010. sqlite3BtreeCommit(pBt);
  110011. }
  110012. }
  110013. }
  110014. /*
  110015. ** Convert a schema pointer into the iDb index that indicates
  110016. ** which database file in db->aDb[] the schema refers to.
  110017. **
  110018. ** If the same database is attached more than once, the first
  110019. ** attached database is returned.
  110020. */
  110021. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  110022. int i = -1000000;
  110023. /* If pSchema is NULL, then return -1000000. This happens when code in
  110024. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  110025. ** created by a sub-select). In this case the return value of this
  110026. ** function should never be used.
  110027. **
  110028. ** We return -1000000 instead of the more usual -1 simply because using
  110029. ** -1000000 as the incorrect index into db->aDb[] is much
  110030. ** more likely to cause a segfault than -1 (of course there are assert()
  110031. ** statements too, but it never hurts to play the odds).
  110032. */
  110033. assert( sqlite3_mutex_held(db->mutex) );
  110034. if( pSchema ){
  110035. for(i=0; ALWAYS(i<db->nDb); i++){
  110036. if( db->aDb[i].pSchema==pSchema ){
  110037. break;
  110038. }
  110039. }
  110040. assert( i>=0 && i<db->nDb );
  110041. }
  110042. return i;
  110043. }
  110044. /*
  110045. ** Free all memory allocations in the pParse object
  110046. */
  110047. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  110048. sqlite3 *db = pParse->db;
  110049. sqlite3DbFree(db, pParse->aLabel);
  110050. sqlite3ExprListDelete(db, pParse->pConstExpr);
  110051. if( db ){
  110052. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  110053. db->lookaside.bDisable -= pParse->disableLookaside;
  110054. }
  110055. pParse->disableLookaside = 0;
  110056. }
  110057. /*
  110058. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  110059. */
  110060. static int sqlite3Prepare(
  110061. sqlite3 *db, /* Database handle. */
  110062. const char *zSql, /* UTF-8 encoded SQL statement. */
  110063. int nBytes, /* Length of zSql in bytes. */
  110064. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  110065. Vdbe *pReprepare, /* VM being reprepared */
  110066. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110067. const char **pzTail /* OUT: End of parsed string */
  110068. ){
  110069. char *zErrMsg = 0; /* Error message */
  110070. int rc = SQLITE_OK; /* Result code */
  110071. int i; /* Loop counter */
  110072. Parse sParse; /* Parsing context */
  110073. memset(&sParse, 0, PARSE_HDR_SZ);
  110074. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  110075. sParse.pReprepare = pReprepare;
  110076. assert( ppStmt && *ppStmt==0 );
  110077. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  110078. assert( sqlite3_mutex_held(db->mutex) );
  110079. /* For a long-term use prepared statement avoid the use of
  110080. ** lookaside memory.
  110081. */
  110082. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  110083. sParse.disableLookaside++;
  110084. db->lookaside.bDisable++;
  110085. }
  110086. /* Check to verify that it is possible to get a read lock on all
  110087. ** database schemas. The inability to get a read lock indicates that
  110088. ** some other database connection is holding a write-lock, which in
  110089. ** turn means that the other connection has made uncommitted changes
  110090. ** to the schema.
  110091. **
  110092. ** Were we to proceed and prepare the statement against the uncommitted
  110093. ** schema changes and if those schema changes are subsequently rolled
  110094. ** back and different changes are made in their place, then when this
  110095. ** prepared statement goes to run the schema cookie would fail to detect
  110096. ** the schema change. Disaster would follow.
  110097. **
  110098. ** This thread is currently holding mutexes on all Btrees (because
  110099. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  110100. ** is not possible for another thread to start a new schema change
  110101. ** while this routine is running. Hence, we do not need to hold
  110102. ** locks on the schema, we just need to make sure nobody else is
  110103. ** holding them.
  110104. **
  110105. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  110106. ** but it does *not* override schema lock detection, so this all still
  110107. ** works even if READ_UNCOMMITTED is set.
  110108. */
  110109. for(i=0; i<db->nDb; i++) {
  110110. Btree *pBt = db->aDb[i].pBt;
  110111. if( pBt ){
  110112. assert( sqlite3BtreeHoldsMutex(pBt) );
  110113. rc = sqlite3BtreeSchemaLocked(pBt);
  110114. if( rc ){
  110115. const char *zDb = db->aDb[i].zDbSName;
  110116. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  110117. testcase( db->flags & SQLITE_ReadUncommit );
  110118. goto end_prepare;
  110119. }
  110120. }
  110121. }
  110122. sqlite3VtabUnlockList(db);
  110123. sParse.db = db;
  110124. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  110125. char *zSqlCopy;
  110126. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  110127. testcase( nBytes==mxLen );
  110128. testcase( nBytes==mxLen+1 );
  110129. if( nBytes>mxLen ){
  110130. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  110131. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  110132. goto end_prepare;
  110133. }
  110134. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  110135. if( zSqlCopy ){
  110136. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  110137. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  110138. sqlite3DbFree(db, zSqlCopy);
  110139. }else{
  110140. sParse.zTail = &zSql[nBytes];
  110141. }
  110142. }else{
  110143. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  110144. }
  110145. assert( 0==sParse.nQueryLoop );
  110146. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  110147. if( sParse.checkSchema ){
  110148. schemaIsValid(&sParse);
  110149. }
  110150. if( db->mallocFailed ){
  110151. sParse.rc = SQLITE_NOMEM_BKPT;
  110152. }
  110153. if( pzTail ){
  110154. *pzTail = sParse.zTail;
  110155. }
  110156. rc = sParse.rc;
  110157. #ifndef SQLITE_OMIT_EXPLAIN
  110158. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  110159. static const char * const azColName[] = {
  110160. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  110161. "selectid", "order", "from", "detail"
  110162. };
  110163. int iFirst, mx;
  110164. if( sParse.explain==2 ){
  110165. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  110166. iFirst = 8;
  110167. mx = 12;
  110168. }else{
  110169. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  110170. iFirst = 0;
  110171. mx = 8;
  110172. }
  110173. for(i=iFirst; i<mx; i++){
  110174. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  110175. azColName[i], SQLITE_STATIC);
  110176. }
  110177. }
  110178. #endif
  110179. if( db->init.busy==0 ){
  110180. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  110181. }
  110182. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  110183. sqlite3VdbeFinalize(sParse.pVdbe);
  110184. assert(!(*ppStmt));
  110185. }else{
  110186. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  110187. }
  110188. if( zErrMsg ){
  110189. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  110190. sqlite3DbFree(db, zErrMsg);
  110191. }else{
  110192. sqlite3Error(db, rc);
  110193. }
  110194. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  110195. while( sParse.pTriggerPrg ){
  110196. TriggerPrg *pT = sParse.pTriggerPrg;
  110197. sParse.pTriggerPrg = pT->pNext;
  110198. sqlite3DbFree(db, pT);
  110199. }
  110200. end_prepare:
  110201. sqlite3ParserReset(&sParse);
  110202. rc = sqlite3ApiExit(db, rc);
  110203. assert( (rc&db->errMask)==rc );
  110204. return rc;
  110205. }
  110206. static int sqlite3LockAndPrepare(
  110207. sqlite3 *db, /* Database handle. */
  110208. const char *zSql, /* UTF-8 encoded SQL statement. */
  110209. int nBytes, /* Length of zSql in bytes. */
  110210. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  110211. Vdbe *pOld, /* VM being reprepared */
  110212. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110213. const char **pzTail /* OUT: End of parsed string */
  110214. ){
  110215. int rc;
  110216. #ifdef SQLITE_ENABLE_API_ARMOR
  110217. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  110218. #endif
  110219. *ppStmt = 0;
  110220. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  110221. return SQLITE_MISUSE_BKPT;
  110222. }
  110223. sqlite3_mutex_enter(db->mutex);
  110224. sqlite3BtreeEnterAll(db);
  110225. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  110226. if( rc==SQLITE_SCHEMA ){
  110227. sqlite3ResetOneSchema(db, -1);
  110228. sqlite3_finalize(*ppStmt);
  110229. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  110230. }
  110231. sqlite3BtreeLeaveAll(db);
  110232. sqlite3_mutex_leave(db->mutex);
  110233. assert( rc==SQLITE_OK || *ppStmt==0 );
  110234. return rc;
  110235. }
  110236. /*
  110237. ** Rerun the compilation of a statement after a schema change.
  110238. **
  110239. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  110240. ** if the statement cannot be recompiled because another connection has
  110241. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  110242. ** occurs, return SQLITE_SCHEMA.
  110243. */
  110244. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  110245. int rc;
  110246. sqlite3_stmt *pNew;
  110247. const char *zSql;
  110248. sqlite3 *db;
  110249. u8 prepFlags;
  110250. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  110251. zSql = sqlite3_sql((sqlite3_stmt *)p);
  110252. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  110253. db = sqlite3VdbeDb(p);
  110254. assert( sqlite3_mutex_held(db->mutex) );
  110255. prepFlags = sqlite3VdbePrepareFlags(p);
  110256. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  110257. if( rc ){
  110258. if( rc==SQLITE_NOMEM ){
  110259. sqlite3OomFault(db);
  110260. }
  110261. assert( pNew==0 );
  110262. return rc;
  110263. }else{
  110264. assert( pNew!=0 );
  110265. }
  110266. sqlite3VdbeSwap((Vdbe*)pNew, p);
  110267. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  110268. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  110269. sqlite3VdbeFinalize((Vdbe*)pNew);
  110270. return SQLITE_OK;
  110271. }
  110272. /*
  110273. ** Two versions of the official API. Legacy and new use. In the legacy
  110274. ** version, the original SQL text is not saved in the prepared statement
  110275. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  110276. ** sqlite3_step(). In the new version, the original SQL text is retained
  110277. ** and the statement is automatically recompiled if an schema change
  110278. ** occurs.
  110279. */
  110280. SQLITE_API int sqlite3_prepare(
  110281. sqlite3 *db, /* Database handle. */
  110282. const char *zSql, /* UTF-8 encoded SQL statement. */
  110283. int nBytes, /* Length of zSql in bytes. */
  110284. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110285. const char **pzTail /* OUT: End of parsed string */
  110286. ){
  110287. int rc;
  110288. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  110289. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  110290. return rc;
  110291. }
  110292. SQLITE_API int sqlite3_prepare_v2(
  110293. sqlite3 *db, /* Database handle. */
  110294. const char *zSql, /* UTF-8 encoded SQL statement. */
  110295. int nBytes, /* Length of zSql in bytes. */
  110296. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110297. const char **pzTail /* OUT: End of parsed string */
  110298. ){
  110299. int rc;
  110300. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  110301. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  110302. ** parameter.
  110303. **
  110304. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  110305. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  110306. ppStmt,pzTail);
  110307. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  110308. return rc;
  110309. }
  110310. SQLITE_API int sqlite3_prepare_v3(
  110311. sqlite3 *db, /* Database handle. */
  110312. const char *zSql, /* UTF-8 encoded SQL statement. */
  110313. int nBytes, /* Length of zSql in bytes. */
  110314. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  110315. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110316. const char **pzTail /* OUT: End of parsed string */
  110317. ){
  110318. int rc;
  110319. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  110320. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  110321. ** which is a bit array consisting of zero or more of the
  110322. ** SQLITE_PREPARE_* flags.
  110323. **
  110324. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  110325. ** directly above. */
  110326. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  110327. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  110328. 0,ppStmt,pzTail);
  110329. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  110330. return rc;
  110331. }
  110332. #ifndef SQLITE_OMIT_UTF16
  110333. /*
  110334. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  110335. */
  110336. static int sqlite3Prepare16(
  110337. sqlite3 *db, /* Database handle. */
  110338. const void *zSql, /* UTF-16 encoded SQL statement. */
  110339. int nBytes, /* Length of zSql in bytes. */
  110340. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  110341. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110342. const void **pzTail /* OUT: End of parsed string */
  110343. ){
  110344. /* This function currently works by first transforming the UTF-16
  110345. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  110346. ** tricky bit is figuring out the pointer to return in *pzTail.
  110347. */
  110348. char *zSql8;
  110349. const char *zTail8 = 0;
  110350. int rc = SQLITE_OK;
  110351. #ifdef SQLITE_ENABLE_API_ARMOR
  110352. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  110353. #endif
  110354. *ppStmt = 0;
  110355. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  110356. return SQLITE_MISUSE_BKPT;
  110357. }
  110358. if( nBytes>=0 ){
  110359. int sz;
  110360. const char *z = (const char*)zSql;
  110361. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  110362. nBytes = sz;
  110363. }
  110364. sqlite3_mutex_enter(db->mutex);
  110365. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  110366. if( zSql8 ){
  110367. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  110368. }
  110369. if( zTail8 && pzTail ){
  110370. /* If sqlite3_prepare returns a tail pointer, we calculate the
  110371. ** equivalent pointer into the UTF-16 string by counting the unicode
  110372. ** characters between zSql8 and zTail8, and then returning a pointer
  110373. ** the same number of characters into the UTF-16 string.
  110374. */
  110375. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  110376. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  110377. }
  110378. sqlite3DbFree(db, zSql8);
  110379. rc = sqlite3ApiExit(db, rc);
  110380. sqlite3_mutex_leave(db->mutex);
  110381. return rc;
  110382. }
  110383. /*
  110384. ** Two versions of the official API. Legacy and new use. In the legacy
  110385. ** version, the original SQL text is not saved in the prepared statement
  110386. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  110387. ** sqlite3_step(). In the new version, the original SQL text is retained
  110388. ** and the statement is automatically recompiled if an schema change
  110389. ** occurs.
  110390. */
  110391. SQLITE_API int sqlite3_prepare16(
  110392. sqlite3 *db, /* Database handle. */
  110393. const void *zSql, /* UTF-16 encoded SQL statement. */
  110394. int nBytes, /* Length of zSql in bytes. */
  110395. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110396. const void **pzTail /* OUT: End of parsed string */
  110397. ){
  110398. int rc;
  110399. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  110400. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  110401. return rc;
  110402. }
  110403. SQLITE_API int sqlite3_prepare16_v2(
  110404. sqlite3 *db, /* Database handle. */
  110405. const void *zSql, /* UTF-16 encoded SQL statement. */
  110406. int nBytes, /* Length of zSql in bytes. */
  110407. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110408. const void **pzTail /* OUT: End of parsed string */
  110409. ){
  110410. int rc;
  110411. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  110412. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  110413. return rc;
  110414. }
  110415. SQLITE_API int sqlite3_prepare16_v3(
  110416. sqlite3 *db, /* Database handle. */
  110417. const void *zSql, /* UTF-16 encoded SQL statement. */
  110418. int nBytes, /* Length of zSql in bytes. */
  110419. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  110420. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  110421. const void **pzTail /* OUT: End of parsed string */
  110422. ){
  110423. int rc;
  110424. rc = sqlite3Prepare16(db,zSql,nBytes,
  110425. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  110426. ppStmt,pzTail);
  110427. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  110428. return rc;
  110429. }
  110430. #endif /* SQLITE_OMIT_UTF16 */
  110431. /************** End of prepare.c *********************************************/
  110432. /************** Begin file select.c ******************************************/
  110433. /*
  110434. ** 2001 September 15
  110435. **
  110436. ** The author disclaims copyright to this source code. In place of
  110437. ** a legal notice, here is a blessing:
  110438. **
  110439. ** May you do good and not evil.
  110440. ** May you find forgiveness for yourself and forgive others.
  110441. ** May you share freely, never taking more than you give.
  110442. **
  110443. *************************************************************************
  110444. ** This file contains C code routines that are called by the parser
  110445. ** to handle SELECT statements in SQLite.
  110446. */
  110447. /* #include "sqliteInt.h" */
  110448. /*
  110449. ** Trace output macros
  110450. */
  110451. #if SELECTTRACE_ENABLED
  110452. /***/ int sqlite3SelectTrace = 0;
  110453. # define SELECTTRACE(K,P,S,X) \
  110454. if(sqlite3SelectTrace&(K)) \
  110455. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  110456. (S)->zSelName,(S)),\
  110457. sqlite3DebugPrintf X
  110458. #else
  110459. # define SELECTTRACE(K,P,S,X)
  110460. #endif
  110461. /*
  110462. ** An instance of the following object is used to record information about
  110463. ** how to process the DISTINCT keyword, to simplify passing that information
  110464. ** into the selectInnerLoop() routine.
  110465. */
  110466. typedef struct DistinctCtx DistinctCtx;
  110467. struct DistinctCtx {
  110468. u8 isTnct; /* True if the DISTINCT keyword is present */
  110469. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  110470. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  110471. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  110472. };
  110473. /*
  110474. ** An instance of the following object is used to record information about
  110475. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  110476. */
  110477. typedef struct SortCtx SortCtx;
  110478. struct SortCtx {
  110479. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  110480. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  110481. int iECursor; /* Cursor number for the sorter */
  110482. int regReturn; /* Register holding block-output return address */
  110483. int labelBkOut; /* Start label for the block-output subroutine */
  110484. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  110485. int labelDone; /* Jump here when done, ex: LIMIT reached */
  110486. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  110487. u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
  110488. };
  110489. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  110490. /*
  110491. ** Delete all the content of a Select structure. Deallocate the structure
  110492. ** itself only if bFree is true.
  110493. */
  110494. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  110495. while( p ){
  110496. Select *pPrior = p->pPrior;
  110497. sqlite3ExprListDelete(db, p->pEList);
  110498. sqlite3SrcListDelete(db, p->pSrc);
  110499. sqlite3ExprDelete(db, p->pWhere);
  110500. sqlite3ExprListDelete(db, p->pGroupBy);
  110501. sqlite3ExprDelete(db, p->pHaving);
  110502. sqlite3ExprListDelete(db, p->pOrderBy);
  110503. sqlite3ExprDelete(db, p->pLimit);
  110504. sqlite3ExprDelete(db, p->pOffset);
  110505. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  110506. if( bFree ) sqlite3DbFreeNN(db, p);
  110507. p = pPrior;
  110508. bFree = 1;
  110509. }
  110510. }
  110511. /*
  110512. ** Initialize a SelectDest structure.
  110513. */
  110514. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  110515. pDest->eDest = (u8)eDest;
  110516. pDest->iSDParm = iParm;
  110517. pDest->zAffSdst = 0;
  110518. pDest->iSdst = 0;
  110519. pDest->nSdst = 0;
  110520. }
  110521. /*
  110522. ** Allocate a new Select structure and return a pointer to that
  110523. ** structure.
  110524. */
  110525. SQLITE_PRIVATE Select *sqlite3SelectNew(
  110526. Parse *pParse, /* Parsing context */
  110527. ExprList *pEList, /* which columns to include in the result */
  110528. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  110529. Expr *pWhere, /* the WHERE clause */
  110530. ExprList *pGroupBy, /* the GROUP BY clause */
  110531. Expr *pHaving, /* the HAVING clause */
  110532. ExprList *pOrderBy, /* the ORDER BY clause */
  110533. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  110534. Expr *pLimit, /* LIMIT value. NULL means not used */
  110535. Expr *pOffset /* OFFSET value. NULL means no offset */
  110536. ){
  110537. Select *pNew;
  110538. Select standin;
  110539. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  110540. if( pNew==0 ){
  110541. assert( pParse->db->mallocFailed );
  110542. pNew = &standin;
  110543. }
  110544. if( pEList==0 ){
  110545. pEList = sqlite3ExprListAppend(pParse, 0,
  110546. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  110547. }
  110548. pNew->pEList = pEList;
  110549. pNew->op = TK_SELECT;
  110550. pNew->selFlags = selFlags;
  110551. pNew->iLimit = 0;
  110552. pNew->iOffset = 0;
  110553. #if SELECTTRACE_ENABLED
  110554. pNew->zSelName[0] = 0;
  110555. #endif
  110556. pNew->addrOpenEphm[0] = -1;
  110557. pNew->addrOpenEphm[1] = -1;
  110558. pNew->nSelectRow = 0;
  110559. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  110560. pNew->pSrc = pSrc;
  110561. pNew->pWhere = pWhere;
  110562. pNew->pGroupBy = pGroupBy;
  110563. pNew->pHaving = pHaving;
  110564. pNew->pOrderBy = pOrderBy;
  110565. pNew->pPrior = 0;
  110566. pNew->pNext = 0;
  110567. pNew->pLimit = pLimit;
  110568. pNew->pOffset = pOffset;
  110569. pNew->pWith = 0;
  110570. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0
  110571. || pParse->db->mallocFailed!=0 );
  110572. if( pParse->db->mallocFailed ) {
  110573. clearSelect(pParse->db, pNew, pNew!=&standin);
  110574. pNew = 0;
  110575. }else{
  110576. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  110577. }
  110578. assert( pNew!=&standin );
  110579. return pNew;
  110580. }
  110581. #if SELECTTRACE_ENABLED
  110582. /*
  110583. ** Set the name of a Select object
  110584. */
  110585. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  110586. if( p && zName ){
  110587. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  110588. }
  110589. }
  110590. #endif
  110591. /*
  110592. ** Delete the given Select structure and all of its substructures.
  110593. */
  110594. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  110595. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  110596. }
  110597. /*
  110598. ** Return a pointer to the right-most SELECT statement in a compound.
  110599. */
  110600. static Select *findRightmost(Select *p){
  110601. while( p->pNext ) p = p->pNext;
  110602. return p;
  110603. }
  110604. /*
  110605. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  110606. ** type of join. Return an integer constant that expresses that type
  110607. ** in terms of the following bit values:
  110608. **
  110609. ** JT_INNER
  110610. ** JT_CROSS
  110611. ** JT_OUTER
  110612. ** JT_NATURAL
  110613. ** JT_LEFT
  110614. ** JT_RIGHT
  110615. **
  110616. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  110617. **
  110618. ** If an illegal or unsupported join type is seen, then still return
  110619. ** a join type, but put an error in the pParse structure.
  110620. */
  110621. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  110622. int jointype = 0;
  110623. Token *apAll[3];
  110624. Token *p;
  110625. /* 0123456789 123456789 123456789 123 */
  110626. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  110627. static const struct {
  110628. u8 i; /* Beginning of keyword text in zKeyText[] */
  110629. u8 nChar; /* Length of the keyword in characters */
  110630. u8 code; /* Join type mask */
  110631. } aKeyword[] = {
  110632. /* natural */ { 0, 7, JT_NATURAL },
  110633. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  110634. /* outer */ { 10, 5, JT_OUTER },
  110635. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  110636. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  110637. /* inner */ { 23, 5, JT_INNER },
  110638. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  110639. };
  110640. int i, j;
  110641. apAll[0] = pA;
  110642. apAll[1] = pB;
  110643. apAll[2] = pC;
  110644. for(i=0; i<3 && apAll[i]; i++){
  110645. p = apAll[i];
  110646. for(j=0; j<ArraySize(aKeyword); j++){
  110647. if( p->n==aKeyword[j].nChar
  110648. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  110649. jointype |= aKeyword[j].code;
  110650. break;
  110651. }
  110652. }
  110653. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  110654. if( j>=ArraySize(aKeyword) ){
  110655. jointype |= JT_ERROR;
  110656. break;
  110657. }
  110658. }
  110659. if(
  110660. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  110661. (jointype & JT_ERROR)!=0
  110662. ){
  110663. const char *zSp = " ";
  110664. assert( pB!=0 );
  110665. if( pC==0 ){ zSp++; }
  110666. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  110667. "%T %T%s%T", pA, pB, zSp, pC);
  110668. jointype = JT_INNER;
  110669. }else if( (jointype & JT_OUTER)!=0
  110670. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  110671. sqlite3ErrorMsg(pParse,
  110672. "RIGHT and FULL OUTER JOINs are not currently supported");
  110673. jointype = JT_INNER;
  110674. }
  110675. return jointype;
  110676. }
  110677. /*
  110678. ** Return the index of a column in a table. Return -1 if the column
  110679. ** is not contained in the table.
  110680. */
  110681. static int columnIndex(Table *pTab, const char *zCol){
  110682. int i;
  110683. for(i=0; i<pTab->nCol; i++){
  110684. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  110685. }
  110686. return -1;
  110687. }
  110688. /*
  110689. ** Search the first N tables in pSrc, from left to right, looking for a
  110690. ** table that has a column named zCol.
  110691. **
  110692. ** When found, set *piTab and *piCol to the table index and column index
  110693. ** of the matching column and return TRUE.
  110694. **
  110695. ** If not found, return FALSE.
  110696. */
  110697. static int tableAndColumnIndex(
  110698. SrcList *pSrc, /* Array of tables to search */
  110699. int N, /* Number of tables in pSrc->a[] to search */
  110700. const char *zCol, /* Name of the column we are looking for */
  110701. int *piTab, /* Write index of pSrc->a[] here */
  110702. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  110703. ){
  110704. int i; /* For looping over tables in pSrc */
  110705. int iCol; /* Index of column matching zCol */
  110706. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  110707. for(i=0; i<N; i++){
  110708. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  110709. if( iCol>=0 ){
  110710. if( piTab ){
  110711. *piTab = i;
  110712. *piCol = iCol;
  110713. }
  110714. return 1;
  110715. }
  110716. }
  110717. return 0;
  110718. }
  110719. /*
  110720. ** This function is used to add terms implied by JOIN syntax to the
  110721. ** WHERE clause expression of a SELECT statement. The new term, which
  110722. ** is ANDed with the existing WHERE clause, is of the form:
  110723. **
  110724. ** (tab1.col1 = tab2.col2)
  110725. **
  110726. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  110727. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  110728. ** column iColRight of tab2.
  110729. */
  110730. static void addWhereTerm(
  110731. Parse *pParse, /* Parsing context */
  110732. SrcList *pSrc, /* List of tables in FROM clause */
  110733. int iLeft, /* Index of first table to join in pSrc */
  110734. int iColLeft, /* Index of column in first table */
  110735. int iRight, /* Index of second table in pSrc */
  110736. int iColRight, /* Index of column in second table */
  110737. int isOuterJoin, /* True if this is an OUTER join */
  110738. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  110739. ){
  110740. sqlite3 *db = pParse->db;
  110741. Expr *pE1;
  110742. Expr *pE2;
  110743. Expr *pEq;
  110744. assert( iLeft<iRight );
  110745. assert( pSrc->nSrc>iRight );
  110746. assert( pSrc->a[iLeft].pTab );
  110747. assert( pSrc->a[iRight].pTab );
  110748. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  110749. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  110750. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  110751. if( pEq && isOuterJoin ){
  110752. ExprSetProperty(pEq, EP_FromJoin);
  110753. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  110754. ExprSetVVAProperty(pEq, EP_NoReduce);
  110755. pEq->iRightJoinTable = (i16)pE2->iTable;
  110756. }
  110757. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  110758. }
  110759. /*
  110760. ** Set the EP_FromJoin property on all terms of the given expression.
  110761. ** And set the Expr.iRightJoinTable to iTable for every term in the
  110762. ** expression.
  110763. **
  110764. ** The EP_FromJoin property is used on terms of an expression to tell
  110765. ** the LEFT OUTER JOIN processing logic that this term is part of the
  110766. ** join restriction specified in the ON or USING clause and not a part
  110767. ** of the more general WHERE clause. These terms are moved over to the
  110768. ** WHERE clause during join processing but we need to remember that they
  110769. ** originated in the ON or USING clause.
  110770. **
  110771. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  110772. ** expression depends on table iRightJoinTable even if that table is not
  110773. ** explicitly mentioned in the expression. That information is needed
  110774. ** for cases like this:
  110775. **
  110776. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  110777. **
  110778. ** The where clause needs to defer the handling of the t1.x=5
  110779. ** term until after the t2 loop of the join. In that way, a
  110780. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  110781. ** defer the handling of t1.x=5, it will be processed immediately
  110782. ** after the t1 loop and rows with t1.x!=5 will never appear in
  110783. ** the output, which is incorrect.
  110784. */
  110785. static void setJoinExpr(Expr *p, int iTable){
  110786. while( p ){
  110787. ExprSetProperty(p, EP_FromJoin);
  110788. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  110789. ExprSetVVAProperty(p, EP_NoReduce);
  110790. p->iRightJoinTable = (i16)iTable;
  110791. if( p->op==TK_FUNCTION && p->x.pList ){
  110792. int i;
  110793. for(i=0; i<p->x.pList->nExpr; i++){
  110794. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  110795. }
  110796. }
  110797. setJoinExpr(p->pLeft, iTable);
  110798. p = p->pRight;
  110799. }
  110800. }
  110801. /*
  110802. ** This routine processes the join information for a SELECT statement.
  110803. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  110804. ** NATURAL joins also create extra WHERE clause terms.
  110805. **
  110806. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  110807. ** The left most table is the first entry in Select.pSrc. The right-most
  110808. ** table is the last entry. The join operator is held in the entry to
  110809. ** the left. Thus entry 0 contains the join operator for the join between
  110810. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  110811. ** also attached to the left entry.
  110812. **
  110813. ** This routine returns the number of errors encountered.
  110814. */
  110815. static int sqliteProcessJoin(Parse *pParse, Select *p){
  110816. SrcList *pSrc; /* All tables in the FROM clause */
  110817. int i, j; /* Loop counters */
  110818. struct SrcList_item *pLeft; /* Left table being joined */
  110819. struct SrcList_item *pRight; /* Right table being joined */
  110820. pSrc = p->pSrc;
  110821. pLeft = &pSrc->a[0];
  110822. pRight = &pLeft[1];
  110823. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  110824. Table *pRightTab = pRight->pTab;
  110825. int isOuter;
  110826. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  110827. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  110828. /* When the NATURAL keyword is present, add WHERE clause terms for
  110829. ** every column that the two tables have in common.
  110830. */
  110831. if( pRight->fg.jointype & JT_NATURAL ){
  110832. if( pRight->pOn || pRight->pUsing ){
  110833. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  110834. "an ON or USING clause", 0);
  110835. return 1;
  110836. }
  110837. for(j=0; j<pRightTab->nCol; j++){
  110838. char *zName; /* Name of column in the right table */
  110839. int iLeft; /* Matching left table */
  110840. int iLeftCol; /* Matching column in the left table */
  110841. zName = pRightTab->aCol[j].zName;
  110842. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  110843. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  110844. isOuter, &p->pWhere);
  110845. }
  110846. }
  110847. }
  110848. /* Disallow both ON and USING clauses in the same join
  110849. */
  110850. if( pRight->pOn && pRight->pUsing ){
  110851. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  110852. "clauses in the same join");
  110853. return 1;
  110854. }
  110855. /* Add the ON clause to the end of the WHERE clause, connected by
  110856. ** an AND operator.
  110857. */
  110858. if( pRight->pOn ){
  110859. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  110860. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  110861. pRight->pOn = 0;
  110862. }
  110863. /* Create extra terms on the WHERE clause for each column named
  110864. ** in the USING clause. Example: If the two tables to be joined are
  110865. ** A and B and the USING clause names X, Y, and Z, then add this
  110866. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  110867. ** Report an error if any column mentioned in the USING clause is
  110868. ** not contained in both tables to be joined.
  110869. */
  110870. if( pRight->pUsing ){
  110871. IdList *pList = pRight->pUsing;
  110872. for(j=0; j<pList->nId; j++){
  110873. char *zName; /* Name of the term in the USING clause */
  110874. int iLeft; /* Table on the left with matching column name */
  110875. int iLeftCol; /* Column number of matching column on the left */
  110876. int iRightCol; /* Column number of matching column on the right */
  110877. zName = pList->a[j].zName;
  110878. iRightCol = columnIndex(pRightTab, zName);
  110879. if( iRightCol<0
  110880. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  110881. ){
  110882. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  110883. "not present in both tables", zName);
  110884. return 1;
  110885. }
  110886. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  110887. isOuter, &p->pWhere);
  110888. }
  110889. }
  110890. }
  110891. return 0;
  110892. }
  110893. /* Forward reference */
  110894. static KeyInfo *keyInfoFromExprList(
  110895. Parse *pParse, /* Parsing context */
  110896. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  110897. int iStart, /* Begin with this column of pList */
  110898. int nExtra /* Add this many extra columns to the end */
  110899. );
  110900. /*
  110901. ** Generate code that will push the record in registers regData
  110902. ** through regData+nData-1 onto the sorter.
  110903. */
  110904. static void pushOntoSorter(
  110905. Parse *pParse, /* Parser context */
  110906. SortCtx *pSort, /* Information about the ORDER BY clause */
  110907. Select *pSelect, /* The whole SELECT statement */
  110908. int regData, /* First register holding data to be sorted */
  110909. int regOrigData, /* First register holding data before packing */
  110910. int nData, /* Number of elements in the data array */
  110911. int nPrefixReg /* No. of reg prior to regData available for use */
  110912. ){
  110913. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  110914. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  110915. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  110916. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  110917. int regBase; /* Regs for sorter record */
  110918. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  110919. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  110920. int op; /* Opcode to add sorter record to sorter */
  110921. int iLimit; /* LIMIT counter */
  110922. assert( bSeq==0 || bSeq==1 );
  110923. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  110924. if( nPrefixReg ){
  110925. assert( nPrefixReg==nExpr+bSeq );
  110926. regBase = regData - nExpr - bSeq;
  110927. }else{
  110928. regBase = pParse->nMem + 1;
  110929. pParse->nMem += nBase;
  110930. }
  110931. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  110932. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  110933. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  110934. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  110935. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  110936. if( bSeq ){
  110937. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  110938. }
  110939. if( nPrefixReg==0 && nData>0 ){
  110940. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  110941. }
  110942. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  110943. if( nOBSat>0 ){
  110944. int regPrevKey; /* The first nOBSat columns of the previous row */
  110945. int addrFirst; /* Address of the OP_IfNot opcode */
  110946. int addrJmp; /* Address of the OP_Jump opcode */
  110947. VdbeOp *pOp; /* Opcode that opens the sorter */
  110948. int nKey; /* Number of sorting key columns, including OP_Sequence */
  110949. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  110950. regPrevKey = pParse->nMem+1;
  110951. pParse->nMem += pSort->nOBSat;
  110952. nKey = nExpr - pSort->nOBSat + bSeq;
  110953. if( bSeq ){
  110954. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  110955. }else{
  110956. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  110957. }
  110958. VdbeCoverage(v);
  110959. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  110960. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  110961. if( pParse->db->mallocFailed ) return;
  110962. pOp->p2 = nKey + nData;
  110963. pKI = pOp->p4.pKeyInfo;
  110964. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  110965. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  110966. testcase( pKI->nAllField > pKI->nKeyField+2 );
  110967. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  110968. pKI->nAllField-pKI->nKeyField-1);
  110969. addrJmp = sqlite3VdbeCurrentAddr(v);
  110970. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  110971. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  110972. pSort->regReturn = ++pParse->nMem;
  110973. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  110974. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  110975. if( iLimit ){
  110976. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  110977. VdbeCoverage(v);
  110978. }
  110979. sqlite3VdbeJumpHere(v, addrFirst);
  110980. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  110981. sqlite3VdbeJumpHere(v, addrJmp);
  110982. }
  110983. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  110984. op = OP_SorterInsert;
  110985. }else{
  110986. op = OP_IdxInsert;
  110987. }
  110988. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  110989. regBase+nOBSat, nBase-nOBSat);
  110990. if( iLimit ){
  110991. int addr;
  110992. int r1 = 0;
  110993. /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
  110994. ** register is initialized with value of LIMIT+OFFSET.) After the sorter
  110995. ** fills up, delete the least entry in the sorter after each insert.
  110996. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
  110997. addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
  110998. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  110999. if( pSort->bOrderedInnerLoop ){
  111000. r1 = ++pParse->nMem;
  111001. sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
  111002. VdbeComment((v, "seq"));
  111003. }
  111004. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  111005. if( pSort->bOrderedInnerLoop ){
  111006. /* If the inner loop is driven by an index such that values from
  111007. ** the same iteration of the inner loop are in sorted order, then
  111008. ** immediately jump to the next iteration of an inner loop if the
  111009. ** entry from the current iteration does not fit into the top
  111010. ** LIMIT+OFFSET entries of the sorter. */
  111011. int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
  111012. sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
  111013. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  111014. VdbeCoverage(v);
  111015. }
  111016. sqlite3VdbeJumpHere(v, addr);
  111017. }
  111018. }
  111019. /*
  111020. ** Add code to implement the OFFSET
  111021. */
  111022. static void codeOffset(
  111023. Vdbe *v, /* Generate code into this VM */
  111024. int iOffset, /* Register holding the offset counter */
  111025. int iContinue /* Jump here to skip the current record */
  111026. ){
  111027. if( iOffset>0 ){
  111028. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  111029. VdbeComment((v, "OFFSET"));
  111030. }
  111031. }
  111032. /*
  111033. ** Add code that will check to make sure the N registers starting at iMem
  111034. ** form a distinct entry. iTab is a sorting index that holds previously
  111035. ** seen combinations of the N values. A new entry is made in iTab
  111036. ** if the current N values are new.
  111037. **
  111038. ** A jump to addrRepeat is made and the N+1 values are popped from the
  111039. ** stack if the top N elements are not distinct.
  111040. */
  111041. static void codeDistinct(
  111042. Parse *pParse, /* Parsing and code generating context */
  111043. int iTab, /* A sorting index used to test for distinctness */
  111044. int addrRepeat, /* Jump to here if not distinct */
  111045. int N, /* Number of elements */
  111046. int iMem /* First element */
  111047. ){
  111048. Vdbe *v;
  111049. int r1;
  111050. v = pParse->pVdbe;
  111051. r1 = sqlite3GetTempReg(pParse);
  111052. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  111053. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  111054. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  111055. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  111056. sqlite3ReleaseTempReg(pParse, r1);
  111057. }
  111058. /*
  111059. ** This routine generates the code for the inside of the inner loop
  111060. ** of a SELECT.
  111061. **
  111062. ** If srcTab is negative, then the p->pEList expressions
  111063. ** are evaluated in order to get the data for this row. If srcTab is
  111064. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  111065. ** to get the number of columns and the collation sequence for each column.
  111066. */
  111067. static void selectInnerLoop(
  111068. Parse *pParse, /* The parser context */
  111069. Select *p, /* The complete select statement being coded */
  111070. int srcTab, /* Pull data from this table if non-negative */
  111071. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  111072. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  111073. SelectDest *pDest, /* How to dispose of the results */
  111074. int iContinue, /* Jump here to continue with next row */
  111075. int iBreak /* Jump here to break out of the inner loop */
  111076. ){
  111077. Vdbe *v = pParse->pVdbe;
  111078. int i;
  111079. int hasDistinct; /* True if the DISTINCT keyword is present */
  111080. int eDest = pDest->eDest; /* How to dispose of results */
  111081. int iParm = pDest->iSDParm; /* First argument to disposal method */
  111082. int nResultCol; /* Number of result columns */
  111083. int nPrefixReg = 0; /* Number of extra registers before regResult */
  111084. /* Usually, regResult is the first cell in an array of memory cells
  111085. ** containing the current result row. In this case regOrig is set to the
  111086. ** same value. However, if the results are being sent to the sorter, the
  111087. ** values for any expressions that are also part of the sort-key are omitted
  111088. ** from this array. In this case regOrig is set to zero. */
  111089. int regResult; /* Start of memory holding current results */
  111090. int regOrig; /* Start of memory holding full result (or 0) */
  111091. assert( v );
  111092. assert( p->pEList!=0 );
  111093. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  111094. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  111095. if( pSort==0 && !hasDistinct ){
  111096. assert( iContinue!=0 );
  111097. codeOffset(v, p->iOffset, iContinue);
  111098. }
  111099. /* Pull the requested columns.
  111100. */
  111101. nResultCol = p->pEList->nExpr;
  111102. if( pDest->iSdst==0 ){
  111103. if( pSort ){
  111104. nPrefixReg = pSort->pOrderBy->nExpr;
  111105. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  111106. pParse->nMem += nPrefixReg;
  111107. }
  111108. pDest->iSdst = pParse->nMem+1;
  111109. pParse->nMem += nResultCol;
  111110. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  111111. /* This is an error condition that can result, for example, when a SELECT
  111112. ** on the right-hand side of an INSERT contains more result columns than
  111113. ** there are columns in the table on the left. The error will be caught
  111114. ** and reported later. But we need to make sure enough memory is allocated
  111115. ** to avoid other spurious errors in the meantime. */
  111116. pParse->nMem += nResultCol;
  111117. }
  111118. pDest->nSdst = nResultCol;
  111119. regOrig = regResult = pDest->iSdst;
  111120. if( srcTab>=0 ){
  111121. for(i=0; i<nResultCol; i++){
  111122. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  111123. VdbeComment((v, "%s", p->pEList->a[i].zName));
  111124. }
  111125. }else if( eDest!=SRT_Exists ){
  111126. /* If the destination is an EXISTS(...) expression, the actual
  111127. ** values returned by the SELECT are not required.
  111128. */
  111129. u8 ecelFlags;
  111130. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  111131. ecelFlags = SQLITE_ECEL_DUP;
  111132. }else{
  111133. ecelFlags = 0;
  111134. }
  111135. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  111136. /* For each expression in p->pEList that is a copy of an expression in
  111137. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  111138. ** iOrderByCol value to one more than the index of the ORDER BY
  111139. ** expression within the sort-key that pushOntoSorter() will generate.
  111140. ** This allows the p->pEList field to be omitted from the sorted record,
  111141. ** saving space and CPU cycles. */
  111142. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  111143. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  111144. int j;
  111145. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  111146. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  111147. }
  111148. }
  111149. regOrig = 0;
  111150. assert( eDest==SRT_Set || eDest==SRT_Mem
  111151. || eDest==SRT_Coroutine || eDest==SRT_Output );
  111152. }
  111153. nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
  111154. 0,ecelFlags);
  111155. }
  111156. /* If the DISTINCT keyword was present on the SELECT statement
  111157. ** and this row has been seen before, then do not make this row
  111158. ** part of the result.
  111159. */
  111160. if( hasDistinct ){
  111161. switch( pDistinct->eTnctType ){
  111162. case WHERE_DISTINCT_ORDERED: {
  111163. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  111164. int iJump; /* Jump destination */
  111165. int regPrev; /* Previous row content */
  111166. /* Allocate space for the previous row */
  111167. regPrev = pParse->nMem+1;
  111168. pParse->nMem += nResultCol;
  111169. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  111170. ** sets the MEM_Cleared bit on the first register of the
  111171. ** previous value. This will cause the OP_Ne below to always
  111172. ** fail on the first iteration of the loop even if the first
  111173. ** row is all NULLs.
  111174. */
  111175. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  111176. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  111177. pOp->opcode = OP_Null;
  111178. pOp->p1 = 1;
  111179. pOp->p2 = regPrev;
  111180. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  111181. for(i=0; i<nResultCol; i++){
  111182. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  111183. if( i<nResultCol-1 ){
  111184. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  111185. VdbeCoverage(v);
  111186. }else{
  111187. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  111188. VdbeCoverage(v);
  111189. }
  111190. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  111191. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  111192. }
  111193. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  111194. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  111195. break;
  111196. }
  111197. case WHERE_DISTINCT_UNIQUE: {
  111198. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  111199. break;
  111200. }
  111201. default: {
  111202. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  111203. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  111204. regResult);
  111205. break;
  111206. }
  111207. }
  111208. if( pSort==0 ){
  111209. codeOffset(v, p->iOffset, iContinue);
  111210. }
  111211. }
  111212. switch( eDest ){
  111213. /* In this mode, write each query result to the key of the temporary
  111214. ** table iParm.
  111215. */
  111216. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  111217. case SRT_Union: {
  111218. int r1;
  111219. r1 = sqlite3GetTempReg(pParse);
  111220. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  111221. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  111222. sqlite3ReleaseTempReg(pParse, r1);
  111223. break;
  111224. }
  111225. /* Construct a record from the query result, but instead of
  111226. ** saving that record, use it as a key to delete elements from
  111227. ** the temporary table iParm.
  111228. */
  111229. case SRT_Except: {
  111230. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  111231. break;
  111232. }
  111233. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  111234. /* Store the result as data using a unique key.
  111235. */
  111236. case SRT_Fifo:
  111237. case SRT_DistFifo:
  111238. case SRT_Table:
  111239. case SRT_EphemTab: {
  111240. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  111241. testcase( eDest==SRT_Table );
  111242. testcase( eDest==SRT_EphemTab );
  111243. testcase( eDest==SRT_Fifo );
  111244. testcase( eDest==SRT_DistFifo );
  111245. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  111246. #ifndef SQLITE_OMIT_CTE
  111247. if( eDest==SRT_DistFifo ){
  111248. /* If the destination is DistFifo, then cursor (iParm+1) is open
  111249. ** on an ephemeral index. If the current row is already present
  111250. ** in the index, do not write it to the output. If not, add the
  111251. ** current row to the index and proceed with writing it to the
  111252. ** output table as well. */
  111253. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  111254. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  111255. VdbeCoverage(v);
  111256. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  111257. assert( pSort==0 );
  111258. }
  111259. #endif
  111260. if( pSort ){
  111261. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  111262. }else{
  111263. int r2 = sqlite3GetTempReg(pParse);
  111264. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  111265. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  111266. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  111267. sqlite3ReleaseTempReg(pParse, r2);
  111268. }
  111269. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  111270. break;
  111271. }
  111272. #ifndef SQLITE_OMIT_SUBQUERY
  111273. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  111274. ** then there should be a single item on the stack. Write this
  111275. ** item into the set table with bogus data.
  111276. */
  111277. case SRT_Set: {
  111278. if( pSort ){
  111279. /* At first glance you would think we could optimize out the
  111280. ** ORDER BY in this case since the order of entries in the set
  111281. ** does not matter. But there might be a LIMIT clause, in which
  111282. ** case the order does matter */
  111283. pushOntoSorter(
  111284. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  111285. }else{
  111286. int r1 = sqlite3GetTempReg(pParse);
  111287. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  111288. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  111289. r1, pDest->zAffSdst, nResultCol);
  111290. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  111291. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  111292. sqlite3ReleaseTempReg(pParse, r1);
  111293. }
  111294. break;
  111295. }
  111296. /* If any row exist in the result set, record that fact and abort.
  111297. */
  111298. case SRT_Exists: {
  111299. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  111300. /* The LIMIT clause will terminate the loop for us */
  111301. break;
  111302. }
  111303. /* If this is a scalar select that is part of an expression, then
  111304. ** store the results in the appropriate memory cell or array of
  111305. ** memory cells and break out of the scan loop.
  111306. */
  111307. case SRT_Mem: {
  111308. if( pSort ){
  111309. assert( nResultCol<=pDest->nSdst );
  111310. pushOntoSorter(
  111311. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  111312. }else{
  111313. assert( nResultCol==pDest->nSdst );
  111314. assert( regResult==iParm );
  111315. /* The LIMIT clause will jump out of the loop for us */
  111316. }
  111317. break;
  111318. }
  111319. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  111320. case SRT_Coroutine: /* Send data to a co-routine */
  111321. case SRT_Output: { /* Return the results */
  111322. testcase( eDest==SRT_Coroutine );
  111323. testcase( eDest==SRT_Output );
  111324. if( pSort ){
  111325. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  111326. nPrefixReg);
  111327. }else if( eDest==SRT_Coroutine ){
  111328. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  111329. }else{
  111330. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  111331. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  111332. }
  111333. break;
  111334. }
  111335. #ifndef SQLITE_OMIT_CTE
  111336. /* Write the results into a priority queue that is order according to
  111337. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  111338. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  111339. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  111340. ** final OP_Sequence column. The last column is the record as a blob.
  111341. */
  111342. case SRT_DistQueue:
  111343. case SRT_Queue: {
  111344. int nKey;
  111345. int r1, r2, r3;
  111346. int addrTest = 0;
  111347. ExprList *pSO;
  111348. pSO = pDest->pOrderBy;
  111349. assert( pSO );
  111350. nKey = pSO->nExpr;
  111351. r1 = sqlite3GetTempReg(pParse);
  111352. r2 = sqlite3GetTempRange(pParse, nKey+2);
  111353. r3 = r2+nKey+1;
  111354. if( eDest==SRT_DistQueue ){
  111355. /* If the destination is DistQueue, then cursor (iParm+1) is open
  111356. ** on a second ephemeral index that holds all values every previously
  111357. ** added to the queue. */
  111358. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  111359. regResult, nResultCol);
  111360. VdbeCoverage(v);
  111361. }
  111362. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  111363. if( eDest==SRT_DistQueue ){
  111364. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  111365. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  111366. }
  111367. for(i=0; i<nKey; i++){
  111368. sqlite3VdbeAddOp2(v, OP_SCopy,
  111369. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  111370. r2+i);
  111371. }
  111372. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  111373. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  111374. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  111375. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  111376. sqlite3ReleaseTempReg(pParse, r1);
  111377. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  111378. break;
  111379. }
  111380. #endif /* SQLITE_OMIT_CTE */
  111381. #if !defined(SQLITE_OMIT_TRIGGER)
  111382. /* Discard the results. This is used for SELECT statements inside
  111383. ** the body of a TRIGGER. The purpose of such selects is to call
  111384. ** user-defined functions that have side effects. We do not care
  111385. ** about the actual results of the select.
  111386. */
  111387. default: {
  111388. assert( eDest==SRT_Discard );
  111389. break;
  111390. }
  111391. #endif
  111392. }
  111393. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  111394. ** there is a sorter, in which case the sorter has already limited
  111395. ** the output for us.
  111396. */
  111397. if( pSort==0 && p->iLimit ){
  111398. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  111399. }
  111400. }
  111401. /*
  111402. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  111403. ** X extra columns.
  111404. */
  111405. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  111406. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  111407. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  111408. if( p ){
  111409. p->aSortOrder = (u8*)&p->aColl[N+X];
  111410. p->nKeyField = (u16)N;
  111411. p->nAllField = (u16)(N+X);
  111412. p->enc = ENC(db);
  111413. p->db = db;
  111414. p->nRef = 1;
  111415. memset(&p[1], 0, nExtra);
  111416. }else{
  111417. sqlite3OomFault(db);
  111418. }
  111419. return p;
  111420. }
  111421. /*
  111422. ** Deallocate a KeyInfo object
  111423. */
  111424. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  111425. if( p ){
  111426. assert( p->nRef>0 );
  111427. p->nRef--;
  111428. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  111429. }
  111430. }
  111431. /*
  111432. ** Make a new pointer to a KeyInfo object
  111433. */
  111434. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  111435. if( p ){
  111436. assert( p->nRef>0 );
  111437. p->nRef++;
  111438. }
  111439. return p;
  111440. }
  111441. #ifdef SQLITE_DEBUG
  111442. /*
  111443. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  111444. ** can only be changed if this is just a single reference to the object.
  111445. **
  111446. ** This routine is used only inside of assert() statements.
  111447. */
  111448. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  111449. #endif /* SQLITE_DEBUG */
  111450. /*
  111451. ** Given an expression list, generate a KeyInfo structure that records
  111452. ** the collating sequence for each expression in that expression list.
  111453. **
  111454. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  111455. ** KeyInfo structure is appropriate for initializing a virtual index to
  111456. ** implement that clause. If the ExprList is the result set of a SELECT
  111457. ** then the KeyInfo structure is appropriate for initializing a virtual
  111458. ** index to implement a DISTINCT test.
  111459. **
  111460. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  111461. ** function is responsible for seeing that this structure is eventually
  111462. ** freed.
  111463. */
  111464. static KeyInfo *keyInfoFromExprList(
  111465. Parse *pParse, /* Parsing context */
  111466. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  111467. int iStart, /* Begin with this column of pList */
  111468. int nExtra /* Add this many extra columns to the end */
  111469. ){
  111470. int nExpr;
  111471. KeyInfo *pInfo;
  111472. struct ExprList_item *pItem;
  111473. sqlite3 *db = pParse->db;
  111474. int i;
  111475. nExpr = pList->nExpr;
  111476. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  111477. if( pInfo ){
  111478. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  111479. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  111480. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  111481. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  111482. }
  111483. }
  111484. return pInfo;
  111485. }
  111486. /*
  111487. ** Name of the connection operator, used for error messages.
  111488. */
  111489. static const char *selectOpName(int id){
  111490. char *z;
  111491. switch( id ){
  111492. case TK_ALL: z = "UNION ALL"; break;
  111493. case TK_INTERSECT: z = "INTERSECT"; break;
  111494. case TK_EXCEPT: z = "EXCEPT"; break;
  111495. default: z = "UNION"; break;
  111496. }
  111497. return z;
  111498. }
  111499. #ifndef SQLITE_OMIT_EXPLAIN
  111500. /*
  111501. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  111502. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  111503. ** where the caption is of the form:
  111504. **
  111505. ** "USE TEMP B-TREE FOR xxx"
  111506. **
  111507. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  111508. ** is determined by the zUsage argument.
  111509. */
  111510. static void explainTempTable(Parse *pParse, const char *zUsage){
  111511. if( pParse->explain==2 ){
  111512. Vdbe *v = pParse->pVdbe;
  111513. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  111514. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  111515. }
  111516. }
  111517. /*
  111518. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  111519. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  111520. ** in sqlite3Select() to assign values to structure member variables that
  111521. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  111522. ** code with #ifndef directives.
  111523. */
  111524. # define explainSetInteger(a, b) a = b
  111525. #else
  111526. /* No-op versions of the explainXXX() functions and macros. */
  111527. # define explainTempTable(y,z)
  111528. # define explainSetInteger(y,z)
  111529. #endif
  111530. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  111531. /*
  111532. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  111533. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  111534. ** where the caption is of one of the two forms:
  111535. **
  111536. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  111537. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  111538. **
  111539. ** where iSub1 and iSub2 are the integers passed as the corresponding
  111540. ** function parameters, and op is the text representation of the parameter
  111541. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  111542. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  111543. ** false, or the second form if it is true.
  111544. */
  111545. static void explainComposite(
  111546. Parse *pParse, /* Parse context */
  111547. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  111548. int iSub1, /* Subquery id 1 */
  111549. int iSub2, /* Subquery id 2 */
  111550. int bUseTmp /* True if a temp table was used */
  111551. ){
  111552. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  111553. if( pParse->explain==2 ){
  111554. Vdbe *v = pParse->pVdbe;
  111555. char *zMsg = sqlite3MPrintf(
  111556. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  111557. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  111558. );
  111559. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  111560. }
  111561. }
  111562. #else
  111563. /* No-op versions of the explainXXX() functions and macros. */
  111564. # define explainComposite(v,w,x,y,z)
  111565. #endif
  111566. /*
  111567. ** If the inner loop was generated using a non-null pOrderBy argument,
  111568. ** then the results were placed in a sorter. After the loop is terminated
  111569. ** we need to run the sorter and output the results. The following
  111570. ** routine generates the code needed to do that.
  111571. */
  111572. static void generateSortTail(
  111573. Parse *pParse, /* Parsing context */
  111574. Select *p, /* The SELECT statement */
  111575. SortCtx *pSort, /* Information on the ORDER BY clause */
  111576. int nColumn, /* Number of columns of data */
  111577. SelectDest *pDest /* Write the sorted results here */
  111578. ){
  111579. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  111580. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  111581. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  111582. int addr;
  111583. int addrOnce = 0;
  111584. int iTab;
  111585. ExprList *pOrderBy = pSort->pOrderBy;
  111586. int eDest = pDest->eDest;
  111587. int iParm = pDest->iSDParm;
  111588. int regRow;
  111589. int regRowid;
  111590. int iCol;
  111591. int nKey;
  111592. int iSortTab; /* Sorter cursor to read from */
  111593. int nSortData; /* Trailing values to read from sorter */
  111594. int i;
  111595. int bSeq; /* True if sorter record includes seq. no. */
  111596. struct ExprList_item *aOutEx = p->pEList->a;
  111597. assert( addrBreak<0 );
  111598. if( pSort->labelBkOut ){
  111599. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  111600. sqlite3VdbeGoto(v, addrBreak);
  111601. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  111602. }
  111603. iTab = pSort->iECursor;
  111604. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  111605. regRowid = 0;
  111606. regRow = pDest->iSdst;
  111607. nSortData = nColumn;
  111608. }else{
  111609. regRowid = sqlite3GetTempReg(pParse);
  111610. regRow = sqlite3GetTempRange(pParse, nColumn);
  111611. nSortData = nColumn;
  111612. }
  111613. nKey = pOrderBy->nExpr - pSort->nOBSat;
  111614. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  111615. int regSortOut = ++pParse->nMem;
  111616. iSortTab = pParse->nTab++;
  111617. if( pSort->labelBkOut ){
  111618. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  111619. }
  111620. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  111621. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  111622. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  111623. VdbeCoverage(v);
  111624. codeOffset(v, p->iOffset, addrContinue);
  111625. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  111626. bSeq = 0;
  111627. }else{
  111628. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  111629. codeOffset(v, p->iOffset, addrContinue);
  111630. iSortTab = iTab;
  111631. bSeq = 1;
  111632. }
  111633. for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
  111634. int iRead;
  111635. if( aOutEx[i].u.x.iOrderByCol ){
  111636. iRead = aOutEx[i].u.x.iOrderByCol-1;
  111637. }else{
  111638. iRead = iCol++;
  111639. }
  111640. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  111641. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  111642. }
  111643. switch( eDest ){
  111644. case SRT_Table:
  111645. case SRT_EphemTab: {
  111646. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  111647. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  111648. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  111649. break;
  111650. }
  111651. #ifndef SQLITE_OMIT_SUBQUERY
  111652. case SRT_Set: {
  111653. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  111654. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  111655. pDest->zAffSdst, nColumn);
  111656. sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
  111657. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  111658. break;
  111659. }
  111660. case SRT_Mem: {
  111661. /* The LIMIT clause will terminate the loop for us */
  111662. break;
  111663. }
  111664. #endif
  111665. default: {
  111666. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  111667. testcase( eDest==SRT_Output );
  111668. testcase( eDest==SRT_Coroutine );
  111669. if( eDest==SRT_Output ){
  111670. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  111671. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  111672. }else{
  111673. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  111674. }
  111675. break;
  111676. }
  111677. }
  111678. if( regRowid ){
  111679. if( eDest==SRT_Set ){
  111680. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  111681. }else{
  111682. sqlite3ReleaseTempReg(pParse, regRow);
  111683. }
  111684. sqlite3ReleaseTempReg(pParse, regRowid);
  111685. }
  111686. /* The bottom of the loop
  111687. */
  111688. sqlite3VdbeResolveLabel(v, addrContinue);
  111689. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  111690. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  111691. }else{
  111692. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  111693. }
  111694. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  111695. sqlite3VdbeResolveLabel(v, addrBreak);
  111696. }
  111697. /*
  111698. ** Return a pointer to a string containing the 'declaration type' of the
  111699. ** expression pExpr. The string may be treated as static by the caller.
  111700. **
  111701. ** Also try to estimate the size of the returned value and return that
  111702. ** result in *pEstWidth.
  111703. **
  111704. ** The declaration type is the exact datatype definition extracted from the
  111705. ** original CREATE TABLE statement if the expression is a column. The
  111706. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  111707. ** is considered a column can be complex in the presence of subqueries. The
  111708. ** result-set expression in all of the following SELECT statements is
  111709. ** considered a column by this function.
  111710. **
  111711. ** SELECT col FROM tbl;
  111712. ** SELECT (SELECT col FROM tbl;
  111713. ** SELECT (SELECT col FROM tbl);
  111714. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  111715. **
  111716. ** The declaration type for any expression other than a column is NULL.
  111717. **
  111718. ** This routine has either 3 or 6 parameters depending on whether or not
  111719. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  111720. */
  111721. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  111722. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  111723. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  111724. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  111725. #endif
  111726. static const char *columnTypeImpl(
  111727. NameContext *pNC,
  111728. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  111729. Expr *pExpr
  111730. #else
  111731. Expr *pExpr,
  111732. const char **pzOrigDb,
  111733. const char **pzOrigTab,
  111734. const char **pzOrigCol
  111735. #endif
  111736. ){
  111737. char const *zType = 0;
  111738. int j;
  111739. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  111740. char const *zOrigDb = 0;
  111741. char const *zOrigTab = 0;
  111742. char const *zOrigCol = 0;
  111743. #endif
  111744. assert( pExpr!=0 );
  111745. assert( pNC->pSrcList!=0 );
  111746. switch( pExpr->op ){
  111747. case TK_AGG_COLUMN:
  111748. case TK_COLUMN: {
  111749. /* The expression is a column. Locate the table the column is being
  111750. ** extracted from in NameContext.pSrcList. This table may be real
  111751. ** database table or a subquery.
  111752. */
  111753. Table *pTab = 0; /* Table structure column is extracted from */
  111754. Select *pS = 0; /* Select the column is extracted from */
  111755. int iCol = pExpr->iColumn; /* Index of column in pTab */
  111756. testcase( pExpr->op==TK_AGG_COLUMN );
  111757. testcase( pExpr->op==TK_COLUMN );
  111758. while( pNC && !pTab ){
  111759. SrcList *pTabList = pNC->pSrcList;
  111760. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  111761. if( j<pTabList->nSrc ){
  111762. pTab = pTabList->a[j].pTab;
  111763. pS = pTabList->a[j].pSelect;
  111764. }else{
  111765. pNC = pNC->pNext;
  111766. }
  111767. }
  111768. if( pTab==0 ){
  111769. /* At one time, code such as "SELECT new.x" within a trigger would
  111770. ** cause this condition to run. Since then, we have restructured how
  111771. ** trigger code is generated and so this condition is no longer
  111772. ** possible. However, it can still be true for statements like
  111773. ** the following:
  111774. **
  111775. ** CREATE TABLE t1(col INTEGER);
  111776. ** SELECT (SELECT t1.col) FROM FROM t1;
  111777. **
  111778. ** when columnType() is called on the expression "t1.col" in the
  111779. ** sub-select. In this case, set the column type to NULL, even
  111780. ** though it should really be "INTEGER".
  111781. **
  111782. ** This is not a problem, as the column type of "t1.col" is never
  111783. ** used. When columnType() is called on the expression
  111784. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  111785. ** branch below. */
  111786. break;
  111787. }
  111788. assert( pTab && pExpr->pTab==pTab );
  111789. if( pS ){
  111790. /* The "table" is actually a sub-select or a view in the FROM clause
  111791. ** of the SELECT statement. Return the declaration type and origin
  111792. ** data for the result-set column of the sub-select.
  111793. */
  111794. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  111795. /* If iCol is less than zero, then the expression requests the
  111796. ** rowid of the sub-select or view. This expression is legal (see
  111797. ** test case misc2.2.2) - it always evaluates to NULL.
  111798. */
  111799. NameContext sNC;
  111800. Expr *p = pS->pEList->a[iCol].pExpr;
  111801. sNC.pSrcList = pS->pSrc;
  111802. sNC.pNext = pNC;
  111803. sNC.pParse = pNC->pParse;
  111804. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  111805. }
  111806. }else{
  111807. /* A real table or a CTE table */
  111808. assert( !pS );
  111809. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  111810. if( iCol<0 ) iCol = pTab->iPKey;
  111811. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  111812. if( iCol<0 ){
  111813. zType = "INTEGER";
  111814. zOrigCol = "rowid";
  111815. }else{
  111816. zOrigCol = pTab->aCol[iCol].zName;
  111817. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  111818. }
  111819. zOrigTab = pTab->zName;
  111820. if( pNC->pParse && pTab->pSchema ){
  111821. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  111822. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  111823. }
  111824. #else
  111825. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  111826. if( iCol<0 ){
  111827. zType = "INTEGER";
  111828. }else{
  111829. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  111830. }
  111831. #endif
  111832. }
  111833. break;
  111834. }
  111835. #ifndef SQLITE_OMIT_SUBQUERY
  111836. case TK_SELECT: {
  111837. /* The expression is a sub-select. Return the declaration type and
  111838. ** origin info for the single column in the result set of the SELECT
  111839. ** statement.
  111840. */
  111841. NameContext sNC;
  111842. Select *pS = pExpr->x.pSelect;
  111843. Expr *p = pS->pEList->a[0].pExpr;
  111844. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  111845. sNC.pSrcList = pS->pSrc;
  111846. sNC.pNext = pNC;
  111847. sNC.pParse = pNC->pParse;
  111848. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  111849. break;
  111850. }
  111851. #endif
  111852. }
  111853. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  111854. if( pzOrigDb ){
  111855. assert( pzOrigTab && pzOrigCol );
  111856. *pzOrigDb = zOrigDb;
  111857. *pzOrigTab = zOrigTab;
  111858. *pzOrigCol = zOrigCol;
  111859. }
  111860. #endif
  111861. return zType;
  111862. }
  111863. /*
  111864. ** Generate code that will tell the VDBE the declaration types of columns
  111865. ** in the result set.
  111866. */
  111867. static void generateColumnTypes(
  111868. Parse *pParse, /* Parser context */
  111869. SrcList *pTabList, /* List of tables */
  111870. ExprList *pEList /* Expressions defining the result set */
  111871. ){
  111872. #ifndef SQLITE_OMIT_DECLTYPE
  111873. Vdbe *v = pParse->pVdbe;
  111874. int i;
  111875. NameContext sNC;
  111876. sNC.pSrcList = pTabList;
  111877. sNC.pParse = pParse;
  111878. sNC.pNext = 0;
  111879. for(i=0; i<pEList->nExpr; i++){
  111880. Expr *p = pEList->a[i].pExpr;
  111881. const char *zType;
  111882. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  111883. const char *zOrigDb = 0;
  111884. const char *zOrigTab = 0;
  111885. const char *zOrigCol = 0;
  111886. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  111887. /* The vdbe must make its own copy of the column-type and other
  111888. ** column specific strings, in case the schema is reset before this
  111889. ** virtual machine is deleted.
  111890. */
  111891. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  111892. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  111893. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  111894. #else
  111895. zType = columnType(&sNC, p, 0, 0, 0);
  111896. #endif
  111897. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  111898. }
  111899. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  111900. }
  111901. /*
  111902. ** Compute the column names for a SELECT statement.
  111903. **
  111904. ** The only guarantee that SQLite makes about column names is that if the
  111905. ** column has an AS clause assigning it a name, that will be the name used.
  111906. ** That is the only documented guarantee. However, countless applications
  111907. ** developed over the years have made baseless assumptions about column names
  111908. ** and will break if those assumptions changes. Hence, use extreme caution
  111909. ** when modifying this routine to avoid breaking legacy.
  111910. **
  111911. ** See Also: sqlite3ColumnsFromExprList()
  111912. **
  111913. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  111914. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  111915. ** applications should operate this way. Nevertheless, we need to support the
  111916. ** other modes for legacy:
  111917. **
  111918. ** short=OFF, full=OFF: Column name is the text of the expression has it
  111919. ** originally appears in the SELECT statement. In
  111920. ** other words, the zSpan of the result expression.
  111921. **
  111922. ** short=ON, full=OFF: (This is the default setting). If the result
  111923. ** refers directly to a table column, then the
  111924. ** result column name is just the table column
  111925. ** name: COLUMN. Otherwise use zSpan.
  111926. **
  111927. ** full=ON, short=ANY: If the result refers directly to a table column,
  111928. ** then the result column name with the table name
  111929. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  111930. */
  111931. static void generateColumnNames(
  111932. Parse *pParse, /* Parser context */
  111933. Select *pSelect /* Generate column names for this SELECT statement */
  111934. ){
  111935. Vdbe *v = pParse->pVdbe;
  111936. int i;
  111937. Table *pTab;
  111938. SrcList *pTabList;
  111939. ExprList *pEList;
  111940. sqlite3 *db = pParse->db;
  111941. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  111942. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  111943. #ifndef SQLITE_OMIT_EXPLAIN
  111944. /* If this is an EXPLAIN, skip this step */
  111945. if( pParse->explain ){
  111946. return;
  111947. }
  111948. #endif
  111949. if( pParse->colNamesSet || db->mallocFailed ) return;
  111950. /* Column names are determined by the left-most term of a compound select */
  111951. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  111952. pTabList = pSelect->pSrc;
  111953. pEList = pSelect->pEList;
  111954. assert( v!=0 );
  111955. assert( pTabList!=0 );
  111956. pParse->colNamesSet = 1;
  111957. fullName = (db->flags & SQLITE_FullColNames)!=0;
  111958. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  111959. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  111960. for(i=0; i<pEList->nExpr; i++){
  111961. Expr *p = pEList->a[i].pExpr;
  111962. assert( p!=0 );
  111963. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  111964. assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
  111965. if( pEList->a[i].zName ){
  111966. /* An AS clause always takes first priority */
  111967. char *zName = pEList->a[i].zName;
  111968. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  111969. }else if( srcName && p->op==TK_COLUMN ){
  111970. char *zCol;
  111971. int iCol = p->iColumn;
  111972. pTab = p->pTab;
  111973. assert( pTab!=0 );
  111974. if( iCol<0 ) iCol = pTab->iPKey;
  111975. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  111976. if( iCol<0 ){
  111977. zCol = "rowid";
  111978. }else{
  111979. zCol = pTab->aCol[iCol].zName;
  111980. }
  111981. if( fullName ){
  111982. char *zName = 0;
  111983. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  111984. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  111985. }else{
  111986. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  111987. }
  111988. }else{
  111989. const char *z = pEList->a[i].zSpan;
  111990. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  111991. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  111992. }
  111993. }
  111994. generateColumnTypes(pParse, pTabList, pEList);
  111995. }
  111996. /*
  111997. ** Given an expression list (which is really the list of expressions
  111998. ** that form the result set of a SELECT statement) compute appropriate
  111999. ** column names for a table that would hold the expression list.
  112000. **
  112001. ** All column names will be unique.
  112002. **
  112003. ** Only the column names are computed. Column.zType, Column.zColl,
  112004. ** and other fields of Column are zeroed.
  112005. **
  112006. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  112007. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  112008. **
  112009. ** The only guarantee that SQLite makes about column names is that if the
  112010. ** column has an AS clause assigning it a name, that will be the name used.
  112011. ** That is the only documented guarantee. However, countless applications
  112012. ** developed over the years have made baseless assumptions about column names
  112013. ** and will break if those assumptions changes. Hence, use extreme caution
  112014. ** when modifying this routine to avoid breaking legacy.
  112015. **
  112016. ** See Also: generateColumnNames()
  112017. */
  112018. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  112019. Parse *pParse, /* Parsing context */
  112020. ExprList *pEList, /* Expr list from which to derive column names */
  112021. i16 *pnCol, /* Write the number of columns here */
  112022. Column **paCol /* Write the new column list here */
  112023. ){
  112024. sqlite3 *db = pParse->db; /* Database connection */
  112025. int i, j; /* Loop counters */
  112026. u32 cnt; /* Index added to make the name unique */
  112027. Column *aCol, *pCol; /* For looping over result columns */
  112028. int nCol; /* Number of columns in the result set */
  112029. char *zName; /* Column name */
  112030. int nName; /* Size of name in zName[] */
  112031. Hash ht; /* Hash table of column names */
  112032. sqlite3HashInit(&ht);
  112033. if( pEList ){
  112034. nCol = pEList->nExpr;
  112035. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  112036. testcase( aCol==0 );
  112037. if( nCol>32767 ) nCol = 32767;
  112038. }else{
  112039. nCol = 0;
  112040. aCol = 0;
  112041. }
  112042. assert( nCol==(i16)nCol );
  112043. *pnCol = nCol;
  112044. *paCol = aCol;
  112045. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  112046. /* Get an appropriate name for the column
  112047. */
  112048. if( (zName = pEList->a[i].zName)!=0 ){
  112049. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  112050. }else{
  112051. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  112052. while( pColExpr->op==TK_DOT ){
  112053. pColExpr = pColExpr->pRight;
  112054. assert( pColExpr!=0 );
  112055. }
  112056. if( (pColExpr->op==TK_COLUMN || pColExpr->op==TK_AGG_COLUMN)
  112057. && pColExpr->pTab!=0
  112058. ){
  112059. /* For columns use the column name name */
  112060. int iCol = pColExpr->iColumn;
  112061. Table *pTab = pColExpr->pTab;
  112062. if( iCol<0 ) iCol = pTab->iPKey;
  112063. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  112064. }else if( pColExpr->op==TK_ID ){
  112065. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  112066. zName = pColExpr->u.zToken;
  112067. }else{
  112068. /* Use the original text of the column expression as its name */
  112069. zName = pEList->a[i].zSpan;
  112070. }
  112071. }
  112072. if( zName ){
  112073. zName = sqlite3DbStrDup(db, zName);
  112074. }else{
  112075. zName = sqlite3MPrintf(db,"column%d",i+1);
  112076. }
  112077. /* Make sure the column name is unique. If the name is not unique,
  112078. ** append an integer to the name so that it becomes unique.
  112079. */
  112080. cnt = 0;
  112081. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  112082. nName = sqlite3Strlen30(zName);
  112083. if( nName>0 ){
  112084. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  112085. if( zName[j]==':' ) nName = j;
  112086. }
  112087. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  112088. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  112089. }
  112090. pCol->zName = zName;
  112091. sqlite3ColumnPropertiesFromName(0, pCol);
  112092. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  112093. sqlite3OomFault(db);
  112094. }
  112095. }
  112096. sqlite3HashClear(&ht);
  112097. if( db->mallocFailed ){
  112098. for(j=0; j<i; j++){
  112099. sqlite3DbFree(db, aCol[j].zName);
  112100. }
  112101. sqlite3DbFree(db, aCol);
  112102. *paCol = 0;
  112103. *pnCol = 0;
  112104. return SQLITE_NOMEM_BKPT;
  112105. }
  112106. return SQLITE_OK;
  112107. }
  112108. /*
  112109. ** Add type and collation information to a column list based on
  112110. ** a SELECT statement.
  112111. **
  112112. ** The column list presumably came from selectColumnNamesFromExprList().
  112113. ** The column list has only names, not types or collations. This
  112114. ** routine goes through and adds the types and collations.
  112115. **
  112116. ** This routine requires that all identifiers in the SELECT
  112117. ** statement be resolved.
  112118. */
  112119. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  112120. Parse *pParse, /* Parsing contexts */
  112121. Table *pTab, /* Add column type information to this table */
  112122. Select *pSelect /* SELECT used to determine types and collations */
  112123. ){
  112124. sqlite3 *db = pParse->db;
  112125. NameContext sNC;
  112126. Column *pCol;
  112127. CollSeq *pColl;
  112128. int i;
  112129. Expr *p;
  112130. struct ExprList_item *a;
  112131. assert( pSelect!=0 );
  112132. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  112133. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  112134. if( db->mallocFailed ) return;
  112135. memset(&sNC, 0, sizeof(sNC));
  112136. sNC.pSrcList = pSelect->pSrc;
  112137. a = pSelect->pEList->a;
  112138. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  112139. const char *zType;
  112140. int n, m;
  112141. p = a[i].pExpr;
  112142. zType = columnType(&sNC, p, 0, 0, 0);
  112143. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  112144. pCol->affinity = sqlite3ExprAffinity(p);
  112145. if( zType ){
  112146. m = sqlite3Strlen30(zType);
  112147. n = sqlite3Strlen30(pCol->zName);
  112148. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  112149. if( pCol->zName ){
  112150. memcpy(&pCol->zName[n+1], zType, m+1);
  112151. pCol->colFlags |= COLFLAG_HASTYPE;
  112152. }
  112153. }
  112154. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  112155. pColl = sqlite3ExprCollSeq(pParse, p);
  112156. if( pColl && pCol->zColl==0 ){
  112157. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  112158. }
  112159. }
  112160. pTab->szTabRow = 1; /* Any non-zero value works */
  112161. }
  112162. /*
  112163. ** Given a SELECT statement, generate a Table structure that describes
  112164. ** the result set of that SELECT.
  112165. */
  112166. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  112167. Table *pTab;
  112168. sqlite3 *db = pParse->db;
  112169. int savedFlags;
  112170. savedFlags = db->flags;
  112171. db->flags &= ~SQLITE_FullColNames;
  112172. db->flags |= SQLITE_ShortColNames;
  112173. sqlite3SelectPrep(pParse, pSelect, 0);
  112174. if( pParse->nErr ) return 0;
  112175. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  112176. db->flags = savedFlags;
  112177. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  112178. if( pTab==0 ){
  112179. return 0;
  112180. }
  112181. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  112182. ** is disabled */
  112183. assert( db->lookaside.bDisable );
  112184. pTab->nTabRef = 1;
  112185. pTab->zName = 0;
  112186. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  112187. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  112188. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  112189. pTab->iPKey = -1;
  112190. if( db->mallocFailed ){
  112191. sqlite3DeleteTable(db, pTab);
  112192. return 0;
  112193. }
  112194. return pTab;
  112195. }
  112196. /*
  112197. ** Get a VDBE for the given parser context. Create a new one if necessary.
  112198. ** If an error occurs, return NULL and leave a message in pParse.
  112199. */
  112200. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  112201. if( pParse->pVdbe ){
  112202. return pParse->pVdbe;
  112203. }
  112204. if( pParse->pToplevel==0
  112205. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  112206. ){
  112207. pParse->okConstFactor = 1;
  112208. }
  112209. return sqlite3VdbeCreate(pParse);
  112210. }
  112211. /*
  112212. ** Compute the iLimit and iOffset fields of the SELECT based on the
  112213. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  112214. ** that appear in the original SQL statement after the LIMIT and OFFSET
  112215. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  112216. ** are the integer memory register numbers for counters used to compute
  112217. ** the limit and offset. If there is no limit and/or offset, then
  112218. ** iLimit and iOffset are negative.
  112219. **
  112220. ** This routine changes the values of iLimit and iOffset only if
  112221. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  112222. ** iOffset should have been preset to appropriate default values (zero)
  112223. ** prior to calling this routine.
  112224. **
  112225. ** The iOffset register (if it exists) is initialized to the value
  112226. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  112227. ** iOffset+1 is initialized to LIMIT+OFFSET.
  112228. **
  112229. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  112230. ** redefined. The UNION ALL operator uses this property to force
  112231. ** the reuse of the same limit and offset registers across multiple
  112232. ** SELECT statements.
  112233. */
  112234. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  112235. Vdbe *v = 0;
  112236. int iLimit = 0;
  112237. int iOffset;
  112238. int n;
  112239. if( p->iLimit ) return;
  112240. /*
  112241. ** "LIMIT -1" always shows all rows. There is some
  112242. ** controversy about what the correct behavior should be.
  112243. ** The current implementation interprets "LIMIT 0" to mean
  112244. ** no rows.
  112245. */
  112246. sqlite3ExprCacheClear(pParse);
  112247. assert( p->pOffset==0 || p->pLimit!=0 );
  112248. if( p->pLimit ){
  112249. p->iLimit = iLimit = ++pParse->nMem;
  112250. v = sqlite3GetVdbe(pParse);
  112251. assert( v!=0 );
  112252. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  112253. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  112254. VdbeComment((v, "LIMIT counter"));
  112255. if( n==0 ){
  112256. sqlite3VdbeGoto(v, iBreak);
  112257. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  112258. p->nSelectRow = sqlite3LogEst((u64)n);
  112259. p->selFlags |= SF_FixedLimit;
  112260. }
  112261. }else{
  112262. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  112263. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  112264. VdbeComment((v, "LIMIT counter"));
  112265. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  112266. }
  112267. if( p->pOffset ){
  112268. p->iOffset = iOffset = ++pParse->nMem;
  112269. pParse->nMem++; /* Allocate an extra register for limit+offset */
  112270. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  112271. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  112272. VdbeComment((v, "OFFSET counter"));
  112273. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  112274. VdbeComment((v, "LIMIT+OFFSET"));
  112275. }
  112276. }
  112277. }
  112278. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  112279. /*
  112280. ** Return the appropriate collating sequence for the iCol-th column of
  112281. ** the result set for the compound-select statement "p". Return NULL if
  112282. ** the column has no default collating sequence.
  112283. **
  112284. ** The collating sequence for the compound select is taken from the
  112285. ** left-most term of the select that has a collating sequence.
  112286. */
  112287. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  112288. CollSeq *pRet;
  112289. if( p->pPrior ){
  112290. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  112291. }else{
  112292. pRet = 0;
  112293. }
  112294. assert( iCol>=0 );
  112295. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  112296. ** have been thrown during name resolution and we would not have gotten
  112297. ** this far */
  112298. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  112299. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  112300. }
  112301. return pRet;
  112302. }
  112303. /*
  112304. ** The select statement passed as the second parameter is a compound SELECT
  112305. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  112306. ** structure suitable for implementing the ORDER BY.
  112307. **
  112308. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  112309. ** function is responsible for ensuring that this structure is eventually
  112310. ** freed.
  112311. */
  112312. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  112313. ExprList *pOrderBy = p->pOrderBy;
  112314. int nOrderBy = p->pOrderBy->nExpr;
  112315. sqlite3 *db = pParse->db;
  112316. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  112317. if( pRet ){
  112318. int i;
  112319. for(i=0; i<nOrderBy; i++){
  112320. struct ExprList_item *pItem = &pOrderBy->a[i];
  112321. Expr *pTerm = pItem->pExpr;
  112322. CollSeq *pColl;
  112323. if( pTerm->flags & EP_Collate ){
  112324. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  112325. }else{
  112326. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  112327. if( pColl==0 ) pColl = db->pDfltColl;
  112328. pOrderBy->a[i].pExpr =
  112329. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  112330. }
  112331. assert( sqlite3KeyInfoIsWriteable(pRet) );
  112332. pRet->aColl[i] = pColl;
  112333. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  112334. }
  112335. }
  112336. return pRet;
  112337. }
  112338. #ifndef SQLITE_OMIT_CTE
  112339. /*
  112340. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  112341. ** query of the form:
  112342. **
  112343. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  112344. ** \___________/ \_______________/
  112345. ** p->pPrior p
  112346. **
  112347. **
  112348. ** There is exactly one reference to the recursive-table in the FROM clause
  112349. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  112350. **
  112351. ** The setup-query runs once to generate an initial set of rows that go
  112352. ** into a Queue table. Rows are extracted from the Queue table one by
  112353. ** one. Each row extracted from Queue is output to pDest. Then the single
  112354. ** extracted row (now in the iCurrent table) becomes the content of the
  112355. ** recursive-table for a recursive-query run. The output of the recursive-query
  112356. ** is added back into the Queue table. Then another row is extracted from Queue
  112357. ** and the iteration continues until the Queue table is empty.
  112358. **
  112359. ** If the compound query operator is UNION then no duplicate rows are ever
  112360. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  112361. ** that have ever been inserted into Queue and causes duplicates to be
  112362. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  112363. **
  112364. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  112365. ** ORDER BY order and the first entry is extracted for each cycle. Without
  112366. ** an ORDER BY, the Queue table is just a FIFO.
  112367. **
  112368. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  112369. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  112370. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  112371. ** with a positive value, then the first OFFSET outputs are discarded rather
  112372. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  112373. ** rows have been skipped.
  112374. */
  112375. static void generateWithRecursiveQuery(
  112376. Parse *pParse, /* Parsing context */
  112377. Select *p, /* The recursive SELECT to be coded */
  112378. SelectDest *pDest /* What to do with query results */
  112379. ){
  112380. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  112381. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  112382. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  112383. Select *pSetup = p->pPrior; /* The setup query */
  112384. int addrTop; /* Top of the loop */
  112385. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  112386. int iCurrent = 0; /* The Current table */
  112387. int regCurrent; /* Register holding Current table */
  112388. int iQueue; /* The Queue table */
  112389. int iDistinct = 0; /* To ensure unique results if UNION */
  112390. int eDest = SRT_Fifo; /* How to write to Queue */
  112391. SelectDest destQueue; /* SelectDest targetting the Queue table */
  112392. int i; /* Loop counter */
  112393. int rc; /* Result code */
  112394. ExprList *pOrderBy; /* The ORDER BY clause */
  112395. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  112396. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  112397. /* Obtain authorization to do a recursive query */
  112398. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  112399. /* Process the LIMIT and OFFSET clauses, if they exist */
  112400. addrBreak = sqlite3VdbeMakeLabel(v);
  112401. p->nSelectRow = 320; /* 4 billion rows */
  112402. computeLimitRegisters(pParse, p, addrBreak);
  112403. pLimit = p->pLimit;
  112404. pOffset = p->pOffset;
  112405. regLimit = p->iLimit;
  112406. regOffset = p->iOffset;
  112407. p->pLimit = p->pOffset = 0;
  112408. p->iLimit = p->iOffset = 0;
  112409. pOrderBy = p->pOrderBy;
  112410. /* Locate the cursor number of the Current table */
  112411. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  112412. if( pSrc->a[i].fg.isRecursive ){
  112413. iCurrent = pSrc->a[i].iCursor;
  112414. break;
  112415. }
  112416. }
  112417. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  112418. ** the Distinct table must be exactly one greater than Queue in order
  112419. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  112420. iQueue = pParse->nTab++;
  112421. if( p->op==TK_UNION ){
  112422. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  112423. iDistinct = pParse->nTab++;
  112424. }else{
  112425. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  112426. }
  112427. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  112428. /* Allocate cursors for Current, Queue, and Distinct. */
  112429. regCurrent = ++pParse->nMem;
  112430. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  112431. if( pOrderBy ){
  112432. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  112433. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  112434. (char*)pKeyInfo, P4_KEYINFO);
  112435. destQueue.pOrderBy = pOrderBy;
  112436. }else{
  112437. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  112438. }
  112439. VdbeComment((v, "Queue table"));
  112440. if( iDistinct ){
  112441. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  112442. p->selFlags |= SF_UsesEphemeral;
  112443. }
  112444. /* Detach the ORDER BY clause from the compound SELECT */
  112445. p->pOrderBy = 0;
  112446. /* Store the results of the setup-query in Queue. */
  112447. pSetup->pNext = 0;
  112448. rc = sqlite3Select(pParse, pSetup, &destQueue);
  112449. pSetup->pNext = p;
  112450. if( rc ) goto end_of_recursive_query;
  112451. /* Find the next row in the Queue and output that row */
  112452. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  112453. /* Transfer the next row in Queue over to Current */
  112454. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  112455. if( pOrderBy ){
  112456. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  112457. }else{
  112458. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  112459. }
  112460. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  112461. /* Output the single row in Current */
  112462. addrCont = sqlite3VdbeMakeLabel(v);
  112463. codeOffset(v, regOffset, addrCont);
  112464. selectInnerLoop(pParse, p, iCurrent,
  112465. 0, 0, pDest, addrCont, addrBreak);
  112466. if( regLimit ){
  112467. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  112468. VdbeCoverage(v);
  112469. }
  112470. sqlite3VdbeResolveLabel(v, addrCont);
  112471. /* Execute the recursive SELECT taking the single row in Current as
  112472. ** the value for the recursive-table. Store the results in the Queue.
  112473. */
  112474. if( p->selFlags & SF_Aggregate ){
  112475. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  112476. }else{
  112477. p->pPrior = 0;
  112478. sqlite3Select(pParse, p, &destQueue);
  112479. assert( p->pPrior==0 );
  112480. p->pPrior = pSetup;
  112481. }
  112482. /* Keep running the loop until the Queue is empty */
  112483. sqlite3VdbeGoto(v, addrTop);
  112484. sqlite3VdbeResolveLabel(v, addrBreak);
  112485. end_of_recursive_query:
  112486. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  112487. p->pOrderBy = pOrderBy;
  112488. p->pLimit = pLimit;
  112489. p->pOffset = pOffset;
  112490. return;
  112491. }
  112492. #endif /* SQLITE_OMIT_CTE */
  112493. /* Forward references */
  112494. static int multiSelectOrderBy(
  112495. Parse *pParse, /* Parsing context */
  112496. Select *p, /* The right-most of SELECTs to be coded */
  112497. SelectDest *pDest /* What to do with query results */
  112498. );
  112499. /*
  112500. ** Handle the special case of a compound-select that originates from a
  112501. ** VALUES clause. By handling this as a special case, we avoid deep
  112502. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  112503. ** on a VALUES clause.
  112504. **
  112505. ** Because the Select object originates from a VALUES clause:
  112506. ** (1) It has no LIMIT or OFFSET
  112507. ** (2) All terms are UNION ALL
  112508. ** (3) There is no ORDER BY clause
  112509. */
  112510. static int multiSelectValues(
  112511. Parse *pParse, /* Parsing context */
  112512. Select *p, /* The right-most of SELECTs to be coded */
  112513. SelectDest *pDest /* What to do with query results */
  112514. ){
  112515. Select *pPrior;
  112516. int nRow = 1;
  112517. int rc = 0;
  112518. assert( p->selFlags & SF_MultiValue );
  112519. do{
  112520. assert( p->selFlags & SF_Values );
  112521. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  112522. assert( p->pLimit==0 );
  112523. assert( p->pOffset==0 );
  112524. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  112525. if( p->pPrior==0 ) break;
  112526. assert( p->pPrior->pNext==p );
  112527. p = p->pPrior;
  112528. nRow++;
  112529. }while(1);
  112530. while( p ){
  112531. pPrior = p->pPrior;
  112532. p->pPrior = 0;
  112533. rc = sqlite3Select(pParse, p, pDest);
  112534. p->pPrior = pPrior;
  112535. if( rc ) break;
  112536. p->nSelectRow = nRow;
  112537. p = p->pNext;
  112538. }
  112539. return rc;
  112540. }
  112541. /*
  112542. ** This routine is called to process a compound query form from
  112543. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  112544. ** INTERSECT
  112545. **
  112546. ** "p" points to the right-most of the two queries. the query on the
  112547. ** left is p->pPrior. The left query could also be a compound query
  112548. ** in which case this routine will be called recursively.
  112549. **
  112550. ** The results of the total query are to be written into a destination
  112551. ** of type eDest with parameter iParm.
  112552. **
  112553. ** Example 1: Consider a three-way compound SQL statement.
  112554. **
  112555. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  112556. **
  112557. ** This statement is parsed up as follows:
  112558. **
  112559. ** SELECT c FROM t3
  112560. ** |
  112561. ** `-----> SELECT b FROM t2
  112562. ** |
  112563. ** `------> SELECT a FROM t1
  112564. **
  112565. ** The arrows in the diagram above represent the Select.pPrior pointer.
  112566. ** So if this routine is called with p equal to the t3 query, then
  112567. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  112568. **
  112569. ** Notice that because of the way SQLite parses compound SELECTs, the
  112570. ** individual selects always group from left to right.
  112571. */
  112572. static int multiSelect(
  112573. Parse *pParse, /* Parsing context */
  112574. Select *p, /* The right-most of SELECTs to be coded */
  112575. SelectDest *pDest /* What to do with query results */
  112576. ){
  112577. int rc = SQLITE_OK; /* Success code from a subroutine */
  112578. Select *pPrior; /* Another SELECT immediately to our left */
  112579. Vdbe *v; /* Generate code to this VDBE */
  112580. SelectDest dest; /* Alternative data destination */
  112581. Select *pDelete = 0; /* Chain of simple selects to delete */
  112582. sqlite3 *db; /* Database connection */
  112583. #ifndef SQLITE_OMIT_EXPLAIN
  112584. int iSub1 = 0; /* EQP id of left-hand query */
  112585. int iSub2 = 0; /* EQP id of right-hand query */
  112586. #endif
  112587. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  112588. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  112589. */
  112590. assert( p && p->pPrior ); /* Calling function guarantees this much */
  112591. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  112592. db = pParse->db;
  112593. pPrior = p->pPrior;
  112594. dest = *pDest;
  112595. if( pPrior->pOrderBy || pPrior->pLimit ){
  112596. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  112597. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  112598. rc = 1;
  112599. goto multi_select_end;
  112600. }
  112601. v = sqlite3GetVdbe(pParse);
  112602. assert( v!=0 ); /* The VDBE already created by calling function */
  112603. /* Create the destination temporary table if necessary
  112604. */
  112605. if( dest.eDest==SRT_EphemTab ){
  112606. assert( p->pEList );
  112607. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  112608. dest.eDest = SRT_Table;
  112609. }
  112610. /* Special handling for a compound-select that originates as a VALUES clause.
  112611. */
  112612. if( p->selFlags & SF_MultiValue ){
  112613. rc = multiSelectValues(pParse, p, &dest);
  112614. goto multi_select_end;
  112615. }
  112616. /* Make sure all SELECTs in the statement have the same number of elements
  112617. ** in their result sets.
  112618. */
  112619. assert( p->pEList && pPrior->pEList );
  112620. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  112621. #ifndef SQLITE_OMIT_CTE
  112622. if( p->selFlags & SF_Recursive ){
  112623. generateWithRecursiveQuery(pParse, p, &dest);
  112624. }else
  112625. #endif
  112626. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  112627. */
  112628. if( p->pOrderBy ){
  112629. return multiSelectOrderBy(pParse, p, pDest);
  112630. }else
  112631. /* Generate code for the left and right SELECT statements.
  112632. */
  112633. switch( p->op ){
  112634. case TK_ALL: {
  112635. int addr = 0;
  112636. int nLimit;
  112637. assert( !pPrior->pLimit );
  112638. pPrior->iLimit = p->iLimit;
  112639. pPrior->iOffset = p->iOffset;
  112640. pPrior->pLimit = p->pLimit;
  112641. pPrior->pOffset = p->pOffset;
  112642. explainSetInteger(iSub1, pParse->iNextSelectId);
  112643. rc = sqlite3Select(pParse, pPrior, &dest);
  112644. p->pLimit = 0;
  112645. p->pOffset = 0;
  112646. if( rc ){
  112647. goto multi_select_end;
  112648. }
  112649. p->pPrior = 0;
  112650. p->iLimit = pPrior->iLimit;
  112651. p->iOffset = pPrior->iOffset;
  112652. if( p->iLimit ){
  112653. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  112654. VdbeComment((v, "Jump ahead if LIMIT reached"));
  112655. if( p->iOffset ){
  112656. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  112657. p->iLimit, p->iOffset+1, p->iOffset);
  112658. }
  112659. }
  112660. explainSetInteger(iSub2, pParse->iNextSelectId);
  112661. rc = sqlite3Select(pParse, p, &dest);
  112662. testcase( rc!=SQLITE_OK );
  112663. pDelete = p->pPrior;
  112664. p->pPrior = pPrior;
  112665. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  112666. if( pPrior->pLimit
  112667. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  112668. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  112669. ){
  112670. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  112671. }
  112672. if( addr ){
  112673. sqlite3VdbeJumpHere(v, addr);
  112674. }
  112675. break;
  112676. }
  112677. case TK_EXCEPT:
  112678. case TK_UNION: {
  112679. int unionTab; /* Cursor number of the temporary table holding result */
  112680. u8 op = 0; /* One of the SRT_ operations to apply to self */
  112681. int priorOp; /* The SRT_ operation to apply to prior selects */
  112682. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  112683. int addr;
  112684. SelectDest uniondest;
  112685. testcase( p->op==TK_EXCEPT );
  112686. testcase( p->op==TK_UNION );
  112687. priorOp = SRT_Union;
  112688. if( dest.eDest==priorOp ){
  112689. /* We can reuse a temporary table generated by a SELECT to our
  112690. ** right.
  112691. */
  112692. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  112693. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  112694. unionTab = dest.iSDParm;
  112695. }else{
  112696. /* We will need to create our own temporary table to hold the
  112697. ** intermediate results.
  112698. */
  112699. unionTab = pParse->nTab++;
  112700. assert( p->pOrderBy==0 );
  112701. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  112702. assert( p->addrOpenEphm[0] == -1 );
  112703. p->addrOpenEphm[0] = addr;
  112704. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  112705. assert( p->pEList );
  112706. }
  112707. /* Code the SELECT statements to our left
  112708. */
  112709. assert( !pPrior->pOrderBy );
  112710. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  112711. explainSetInteger(iSub1, pParse->iNextSelectId);
  112712. rc = sqlite3Select(pParse, pPrior, &uniondest);
  112713. if( rc ){
  112714. goto multi_select_end;
  112715. }
  112716. /* Code the current SELECT statement
  112717. */
  112718. if( p->op==TK_EXCEPT ){
  112719. op = SRT_Except;
  112720. }else{
  112721. assert( p->op==TK_UNION );
  112722. op = SRT_Union;
  112723. }
  112724. p->pPrior = 0;
  112725. pLimit = p->pLimit;
  112726. p->pLimit = 0;
  112727. pOffset = p->pOffset;
  112728. p->pOffset = 0;
  112729. uniondest.eDest = op;
  112730. explainSetInteger(iSub2, pParse->iNextSelectId);
  112731. rc = sqlite3Select(pParse, p, &uniondest);
  112732. testcase( rc!=SQLITE_OK );
  112733. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  112734. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  112735. sqlite3ExprListDelete(db, p->pOrderBy);
  112736. pDelete = p->pPrior;
  112737. p->pPrior = pPrior;
  112738. p->pOrderBy = 0;
  112739. if( p->op==TK_UNION ){
  112740. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  112741. }
  112742. sqlite3ExprDelete(db, p->pLimit);
  112743. p->pLimit = pLimit;
  112744. p->pOffset = pOffset;
  112745. p->iLimit = 0;
  112746. p->iOffset = 0;
  112747. /* Convert the data in the temporary table into whatever form
  112748. ** it is that we currently need.
  112749. */
  112750. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  112751. if( dest.eDest!=priorOp ){
  112752. int iCont, iBreak, iStart;
  112753. assert( p->pEList );
  112754. iBreak = sqlite3VdbeMakeLabel(v);
  112755. iCont = sqlite3VdbeMakeLabel(v);
  112756. computeLimitRegisters(pParse, p, iBreak);
  112757. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  112758. iStart = sqlite3VdbeCurrentAddr(v);
  112759. selectInnerLoop(pParse, p, unionTab,
  112760. 0, 0, &dest, iCont, iBreak);
  112761. sqlite3VdbeResolveLabel(v, iCont);
  112762. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  112763. sqlite3VdbeResolveLabel(v, iBreak);
  112764. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  112765. }
  112766. break;
  112767. }
  112768. default: assert( p->op==TK_INTERSECT ); {
  112769. int tab1, tab2;
  112770. int iCont, iBreak, iStart;
  112771. Expr *pLimit, *pOffset;
  112772. int addr;
  112773. SelectDest intersectdest;
  112774. int r1;
  112775. /* INTERSECT is different from the others since it requires
  112776. ** two temporary tables. Hence it has its own case. Begin
  112777. ** by allocating the tables we will need.
  112778. */
  112779. tab1 = pParse->nTab++;
  112780. tab2 = pParse->nTab++;
  112781. assert( p->pOrderBy==0 );
  112782. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  112783. assert( p->addrOpenEphm[0] == -1 );
  112784. p->addrOpenEphm[0] = addr;
  112785. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  112786. assert( p->pEList );
  112787. /* Code the SELECTs to our left into temporary table "tab1".
  112788. */
  112789. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  112790. explainSetInteger(iSub1, pParse->iNextSelectId);
  112791. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  112792. if( rc ){
  112793. goto multi_select_end;
  112794. }
  112795. /* Code the current SELECT into temporary table "tab2"
  112796. */
  112797. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  112798. assert( p->addrOpenEphm[1] == -1 );
  112799. p->addrOpenEphm[1] = addr;
  112800. p->pPrior = 0;
  112801. pLimit = p->pLimit;
  112802. p->pLimit = 0;
  112803. pOffset = p->pOffset;
  112804. p->pOffset = 0;
  112805. intersectdest.iSDParm = tab2;
  112806. explainSetInteger(iSub2, pParse->iNextSelectId);
  112807. rc = sqlite3Select(pParse, p, &intersectdest);
  112808. testcase( rc!=SQLITE_OK );
  112809. pDelete = p->pPrior;
  112810. p->pPrior = pPrior;
  112811. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  112812. sqlite3ExprDelete(db, p->pLimit);
  112813. p->pLimit = pLimit;
  112814. p->pOffset = pOffset;
  112815. /* Generate code to take the intersection of the two temporary
  112816. ** tables.
  112817. */
  112818. assert( p->pEList );
  112819. iBreak = sqlite3VdbeMakeLabel(v);
  112820. iCont = sqlite3VdbeMakeLabel(v);
  112821. computeLimitRegisters(pParse, p, iBreak);
  112822. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  112823. r1 = sqlite3GetTempReg(pParse);
  112824. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  112825. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  112826. sqlite3ReleaseTempReg(pParse, r1);
  112827. selectInnerLoop(pParse, p, tab1,
  112828. 0, 0, &dest, iCont, iBreak);
  112829. sqlite3VdbeResolveLabel(v, iCont);
  112830. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  112831. sqlite3VdbeResolveLabel(v, iBreak);
  112832. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  112833. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  112834. break;
  112835. }
  112836. }
  112837. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  112838. /* Compute collating sequences used by
  112839. ** temporary tables needed to implement the compound select.
  112840. ** Attach the KeyInfo structure to all temporary tables.
  112841. **
  112842. ** This section is run by the right-most SELECT statement only.
  112843. ** SELECT statements to the left always skip this part. The right-most
  112844. ** SELECT might also skip this part if it has no ORDER BY clause and
  112845. ** no temp tables are required.
  112846. */
  112847. if( p->selFlags & SF_UsesEphemeral ){
  112848. int i; /* Loop counter */
  112849. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  112850. Select *pLoop; /* For looping through SELECT statements */
  112851. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  112852. int nCol; /* Number of columns in result set */
  112853. assert( p->pNext==0 );
  112854. nCol = p->pEList->nExpr;
  112855. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  112856. if( !pKeyInfo ){
  112857. rc = SQLITE_NOMEM_BKPT;
  112858. goto multi_select_end;
  112859. }
  112860. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  112861. *apColl = multiSelectCollSeq(pParse, p, i);
  112862. if( 0==*apColl ){
  112863. *apColl = db->pDfltColl;
  112864. }
  112865. }
  112866. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  112867. for(i=0; i<2; i++){
  112868. int addr = pLoop->addrOpenEphm[i];
  112869. if( addr<0 ){
  112870. /* If [0] is unused then [1] is also unused. So we can
  112871. ** always safely abort as soon as the first unused slot is found */
  112872. assert( pLoop->addrOpenEphm[1]<0 );
  112873. break;
  112874. }
  112875. sqlite3VdbeChangeP2(v, addr, nCol);
  112876. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  112877. P4_KEYINFO);
  112878. pLoop->addrOpenEphm[i] = -1;
  112879. }
  112880. }
  112881. sqlite3KeyInfoUnref(pKeyInfo);
  112882. }
  112883. multi_select_end:
  112884. pDest->iSdst = dest.iSdst;
  112885. pDest->nSdst = dest.nSdst;
  112886. sqlite3SelectDelete(db, pDelete);
  112887. return rc;
  112888. }
  112889. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  112890. /*
  112891. ** Error message for when two or more terms of a compound select have different
  112892. ** size result sets.
  112893. */
  112894. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  112895. if( p->selFlags & SF_Values ){
  112896. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  112897. }else{
  112898. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  112899. " do not have the same number of result columns", selectOpName(p->op));
  112900. }
  112901. }
  112902. /*
  112903. ** Code an output subroutine for a coroutine implementation of a
  112904. ** SELECT statment.
  112905. **
  112906. ** The data to be output is contained in pIn->iSdst. There are
  112907. ** pIn->nSdst columns to be output. pDest is where the output should
  112908. ** be sent.
  112909. **
  112910. ** regReturn is the number of the register holding the subroutine
  112911. ** return address.
  112912. **
  112913. ** If regPrev>0 then it is the first register in a vector that
  112914. ** records the previous output. mem[regPrev] is a flag that is false
  112915. ** if there has been no previous output. If regPrev>0 then code is
  112916. ** generated to suppress duplicates. pKeyInfo is used for comparing
  112917. ** keys.
  112918. **
  112919. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  112920. ** iBreak.
  112921. */
  112922. static int generateOutputSubroutine(
  112923. Parse *pParse, /* Parsing context */
  112924. Select *p, /* The SELECT statement */
  112925. SelectDest *pIn, /* Coroutine supplying data */
  112926. SelectDest *pDest, /* Where to send the data */
  112927. int regReturn, /* The return address register */
  112928. int regPrev, /* Previous result register. No uniqueness if 0 */
  112929. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  112930. int iBreak /* Jump here if we hit the LIMIT */
  112931. ){
  112932. Vdbe *v = pParse->pVdbe;
  112933. int iContinue;
  112934. int addr;
  112935. addr = sqlite3VdbeCurrentAddr(v);
  112936. iContinue = sqlite3VdbeMakeLabel(v);
  112937. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  112938. */
  112939. if( regPrev ){
  112940. int addr1, addr2;
  112941. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  112942. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  112943. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  112944. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  112945. sqlite3VdbeJumpHere(v, addr1);
  112946. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  112947. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  112948. }
  112949. if( pParse->db->mallocFailed ) return 0;
  112950. /* Suppress the first OFFSET entries if there is an OFFSET clause
  112951. */
  112952. codeOffset(v, p->iOffset, iContinue);
  112953. assert( pDest->eDest!=SRT_Exists );
  112954. assert( pDest->eDest!=SRT_Table );
  112955. switch( pDest->eDest ){
  112956. /* Store the result as data using a unique key.
  112957. */
  112958. case SRT_EphemTab: {
  112959. int r1 = sqlite3GetTempReg(pParse);
  112960. int r2 = sqlite3GetTempReg(pParse);
  112961. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  112962. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  112963. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  112964. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  112965. sqlite3ReleaseTempReg(pParse, r2);
  112966. sqlite3ReleaseTempReg(pParse, r1);
  112967. break;
  112968. }
  112969. #ifndef SQLITE_OMIT_SUBQUERY
  112970. /* If we are creating a set for an "expr IN (SELECT ...)".
  112971. */
  112972. case SRT_Set: {
  112973. int r1;
  112974. testcase( pIn->nSdst>1 );
  112975. r1 = sqlite3GetTempReg(pParse);
  112976. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  112977. r1, pDest->zAffSdst, pIn->nSdst);
  112978. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  112979. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  112980. pIn->iSdst, pIn->nSdst);
  112981. sqlite3ReleaseTempReg(pParse, r1);
  112982. break;
  112983. }
  112984. /* If this is a scalar select that is part of an expression, then
  112985. ** store the results in the appropriate memory cell and break out
  112986. ** of the scan loop.
  112987. */
  112988. case SRT_Mem: {
  112989. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  112990. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  112991. /* The LIMIT clause will jump out of the loop for us */
  112992. break;
  112993. }
  112994. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  112995. /* The results are stored in a sequence of registers
  112996. ** starting at pDest->iSdst. Then the co-routine yields.
  112997. */
  112998. case SRT_Coroutine: {
  112999. if( pDest->iSdst==0 ){
  113000. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  113001. pDest->nSdst = pIn->nSdst;
  113002. }
  113003. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  113004. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  113005. break;
  113006. }
  113007. /* If none of the above, then the result destination must be
  113008. ** SRT_Output. This routine is never called with any other
  113009. ** destination other than the ones handled above or SRT_Output.
  113010. **
  113011. ** For SRT_Output, results are stored in a sequence of registers.
  113012. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  113013. ** return the next row of result.
  113014. */
  113015. default: {
  113016. assert( pDest->eDest==SRT_Output );
  113017. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  113018. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  113019. break;
  113020. }
  113021. }
  113022. /* Jump to the end of the loop if the LIMIT is reached.
  113023. */
  113024. if( p->iLimit ){
  113025. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  113026. }
  113027. /* Generate the subroutine return
  113028. */
  113029. sqlite3VdbeResolveLabel(v, iContinue);
  113030. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  113031. return addr;
  113032. }
  113033. /*
  113034. ** Alternative compound select code generator for cases when there
  113035. ** is an ORDER BY clause.
  113036. **
  113037. ** We assume a query of the following form:
  113038. **
  113039. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  113040. **
  113041. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  113042. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  113043. ** co-routines. Then run the co-routines in parallel and merge the results
  113044. ** into the output. In addition to the two coroutines (called selectA and
  113045. ** selectB) there are 7 subroutines:
  113046. **
  113047. ** outA: Move the output of the selectA coroutine into the output
  113048. ** of the compound query.
  113049. **
  113050. ** outB: Move the output of the selectB coroutine into the output
  113051. ** of the compound query. (Only generated for UNION and
  113052. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  113053. ** appears only in B.)
  113054. **
  113055. ** AltB: Called when there is data from both coroutines and A<B.
  113056. **
  113057. ** AeqB: Called when there is data from both coroutines and A==B.
  113058. **
  113059. ** AgtB: Called when there is data from both coroutines and A>B.
  113060. **
  113061. ** EofA: Called when data is exhausted from selectA.
  113062. **
  113063. ** EofB: Called when data is exhausted from selectB.
  113064. **
  113065. ** The implementation of the latter five subroutines depend on which
  113066. ** <operator> is used:
  113067. **
  113068. **
  113069. ** UNION ALL UNION EXCEPT INTERSECT
  113070. ** ------------- ----------------- -------------- -----------------
  113071. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  113072. **
  113073. ** AeqB: outA, nextA nextA nextA outA, nextA
  113074. **
  113075. ** AgtB: outB, nextB outB, nextB nextB nextB
  113076. **
  113077. ** EofA: outB, nextB outB, nextB halt halt
  113078. **
  113079. ** EofB: outA, nextA outA, nextA outA, nextA halt
  113080. **
  113081. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  113082. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  113083. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  113084. ** following nextX causes a jump to the end of the select processing.
  113085. **
  113086. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  113087. ** within the output subroutine. The regPrev register set holds the previously
  113088. ** output value. A comparison is made against this value and the output
  113089. ** is skipped if the next results would be the same as the previous.
  113090. **
  113091. ** The implementation plan is to implement the two coroutines and seven
  113092. ** subroutines first, then put the control logic at the bottom. Like this:
  113093. **
  113094. ** goto Init
  113095. ** coA: coroutine for left query (A)
  113096. ** coB: coroutine for right query (B)
  113097. ** outA: output one row of A
  113098. ** outB: output one row of B (UNION and UNION ALL only)
  113099. ** EofA: ...
  113100. ** EofB: ...
  113101. ** AltB: ...
  113102. ** AeqB: ...
  113103. ** AgtB: ...
  113104. ** Init: initialize coroutine registers
  113105. ** yield coA
  113106. ** if eof(A) goto EofA
  113107. ** yield coB
  113108. ** if eof(B) goto EofB
  113109. ** Cmpr: Compare A, B
  113110. ** Jump AltB, AeqB, AgtB
  113111. ** End: ...
  113112. **
  113113. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  113114. ** actually called using Gosub and they do not Return. EofA and EofB loop
  113115. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  113116. ** and AgtB jump to either L2 or to one of EofA or EofB.
  113117. */
  113118. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  113119. static int multiSelectOrderBy(
  113120. Parse *pParse, /* Parsing context */
  113121. Select *p, /* The right-most of SELECTs to be coded */
  113122. SelectDest *pDest /* What to do with query results */
  113123. ){
  113124. int i, j; /* Loop counters */
  113125. Select *pPrior; /* Another SELECT immediately to our left */
  113126. Vdbe *v; /* Generate code to this VDBE */
  113127. SelectDest destA; /* Destination for coroutine A */
  113128. SelectDest destB; /* Destination for coroutine B */
  113129. int regAddrA; /* Address register for select-A coroutine */
  113130. int regAddrB; /* Address register for select-B coroutine */
  113131. int addrSelectA; /* Address of the select-A coroutine */
  113132. int addrSelectB; /* Address of the select-B coroutine */
  113133. int regOutA; /* Address register for the output-A subroutine */
  113134. int regOutB; /* Address register for the output-B subroutine */
  113135. int addrOutA; /* Address of the output-A subroutine */
  113136. int addrOutB = 0; /* Address of the output-B subroutine */
  113137. int addrEofA; /* Address of the select-A-exhausted subroutine */
  113138. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  113139. int addrEofB; /* Address of the select-B-exhausted subroutine */
  113140. int addrAltB; /* Address of the A<B subroutine */
  113141. int addrAeqB; /* Address of the A==B subroutine */
  113142. int addrAgtB; /* Address of the A>B subroutine */
  113143. int regLimitA; /* Limit register for select-A */
  113144. int regLimitB; /* Limit register for select-A */
  113145. int regPrev; /* A range of registers to hold previous output */
  113146. int savedLimit; /* Saved value of p->iLimit */
  113147. int savedOffset; /* Saved value of p->iOffset */
  113148. int labelCmpr; /* Label for the start of the merge algorithm */
  113149. int labelEnd; /* Label for the end of the overall SELECT stmt */
  113150. int addr1; /* Jump instructions that get retargetted */
  113151. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  113152. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  113153. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  113154. sqlite3 *db; /* Database connection */
  113155. ExprList *pOrderBy; /* The ORDER BY clause */
  113156. int nOrderBy; /* Number of terms in the ORDER BY clause */
  113157. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  113158. #ifndef SQLITE_OMIT_EXPLAIN
  113159. int iSub1; /* EQP id of left-hand query */
  113160. int iSub2; /* EQP id of right-hand query */
  113161. #endif
  113162. assert( p->pOrderBy!=0 );
  113163. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  113164. db = pParse->db;
  113165. v = pParse->pVdbe;
  113166. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  113167. labelEnd = sqlite3VdbeMakeLabel(v);
  113168. labelCmpr = sqlite3VdbeMakeLabel(v);
  113169. /* Patch up the ORDER BY clause
  113170. */
  113171. op = p->op;
  113172. pPrior = p->pPrior;
  113173. assert( pPrior->pOrderBy==0 );
  113174. pOrderBy = p->pOrderBy;
  113175. assert( pOrderBy );
  113176. nOrderBy = pOrderBy->nExpr;
  113177. /* For operators other than UNION ALL we have to make sure that
  113178. ** the ORDER BY clause covers every term of the result set. Add
  113179. ** terms to the ORDER BY clause as necessary.
  113180. */
  113181. if( op!=TK_ALL ){
  113182. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  113183. struct ExprList_item *pItem;
  113184. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  113185. assert( pItem->u.x.iOrderByCol>0 );
  113186. if( pItem->u.x.iOrderByCol==i ) break;
  113187. }
  113188. if( j==nOrderBy ){
  113189. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  113190. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  113191. pNew->flags |= EP_IntValue;
  113192. pNew->u.iValue = i;
  113193. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  113194. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  113195. }
  113196. }
  113197. }
  113198. /* Compute the comparison permutation and keyinfo that is used with
  113199. ** the permutation used to determine if the next
  113200. ** row of results comes from selectA or selectB. Also add explicit
  113201. ** collations to the ORDER BY clause terms so that when the subqueries
  113202. ** to the right and the left are evaluated, they use the correct
  113203. ** collation.
  113204. */
  113205. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  113206. if( aPermute ){
  113207. struct ExprList_item *pItem;
  113208. aPermute[0] = nOrderBy;
  113209. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  113210. assert( pItem->u.x.iOrderByCol>0 );
  113211. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  113212. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  113213. }
  113214. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  113215. }else{
  113216. pKeyMerge = 0;
  113217. }
  113218. /* Reattach the ORDER BY clause to the query.
  113219. */
  113220. p->pOrderBy = pOrderBy;
  113221. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  113222. /* Allocate a range of temporary registers and the KeyInfo needed
  113223. ** for the logic that removes duplicate result rows when the
  113224. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  113225. */
  113226. if( op==TK_ALL ){
  113227. regPrev = 0;
  113228. }else{
  113229. int nExpr = p->pEList->nExpr;
  113230. assert( nOrderBy>=nExpr || db->mallocFailed );
  113231. regPrev = pParse->nMem+1;
  113232. pParse->nMem += nExpr+1;
  113233. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  113234. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  113235. if( pKeyDup ){
  113236. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  113237. for(i=0; i<nExpr; i++){
  113238. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  113239. pKeyDup->aSortOrder[i] = 0;
  113240. }
  113241. }
  113242. }
  113243. /* Separate the left and the right query from one another
  113244. */
  113245. p->pPrior = 0;
  113246. pPrior->pNext = 0;
  113247. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  113248. if( pPrior->pPrior==0 ){
  113249. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  113250. }
  113251. /* Compute the limit registers */
  113252. computeLimitRegisters(pParse, p, labelEnd);
  113253. if( p->iLimit && op==TK_ALL ){
  113254. regLimitA = ++pParse->nMem;
  113255. regLimitB = ++pParse->nMem;
  113256. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  113257. regLimitA);
  113258. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  113259. }else{
  113260. regLimitA = regLimitB = 0;
  113261. }
  113262. sqlite3ExprDelete(db, p->pLimit);
  113263. p->pLimit = 0;
  113264. sqlite3ExprDelete(db, p->pOffset);
  113265. p->pOffset = 0;
  113266. regAddrA = ++pParse->nMem;
  113267. regAddrB = ++pParse->nMem;
  113268. regOutA = ++pParse->nMem;
  113269. regOutB = ++pParse->nMem;
  113270. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  113271. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  113272. /* Generate a coroutine to evaluate the SELECT statement to the
  113273. ** left of the compound operator - the "A" select.
  113274. */
  113275. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  113276. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  113277. VdbeComment((v, "left SELECT"));
  113278. pPrior->iLimit = regLimitA;
  113279. explainSetInteger(iSub1, pParse->iNextSelectId);
  113280. sqlite3Select(pParse, pPrior, &destA);
  113281. sqlite3VdbeEndCoroutine(v, regAddrA);
  113282. sqlite3VdbeJumpHere(v, addr1);
  113283. /* Generate a coroutine to evaluate the SELECT statement on
  113284. ** the right - the "B" select
  113285. */
  113286. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  113287. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  113288. VdbeComment((v, "right SELECT"));
  113289. savedLimit = p->iLimit;
  113290. savedOffset = p->iOffset;
  113291. p->iLimit = regLimitB;
  113292. p->iOffset = 0;
  113293. explainSetInteger(iSub2, pParse->iNextSelectId);
  113294. sqlite3Select(pParse, p, &destB);
  113295. p->iLimit = savedLimit;
  113296. p->iOffset = savedOffset;
  113297. sqlite3VdbeEndCoroutine(v, regAddrB);
  113298. /* Generate a subroutine that outputs the current row of the A
  113299. ** select as the next output row of the compound select.
  113300. */
  113301. VdbeNoopComment((v, "Output routine for A"));
  113302. addrOutA = generateOutputSubroutine(pParse,
  113303. p, &destA, pDest, regOutA,
  113304. regPrev, pKeyDup, labelEnd);
  113305. /* Generate a subroutine that outputs the current row of the B
  113306. ** select as the next output row of the compound select.
  113307. */
  113308. if( op==TK_ALL || op==TK_UNION ){
  113309. VdbeNoopComment((v, "Output routine for B"));
  113310. addrOutB = generateOutputSubroutine(pParse,
  113311. p, &destB, pDest, regOutB,
  113312. regPrev, pKeyDup, labelEnd);
  113313. }
  113314. sqlite3KeyInfoUnref(pKeyDup);
  113315. /* Generate a subroutine to run when the results from select A
  113316. ** are exhausted and only data in select B remains.
  113317. */
  113318. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  113319. addrEofA_noB = addrEofA = labelEnd;
  113320. }else{
  113321. VdbeNoopComment((v, "eof-A subroutine"));
  113322. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  113323. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  113324. VdbeCoverage(v);
  113325. sqlite3VdbeGoto(v, addrEofA);
  113326. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  113327. }
  113328. /* Generate a subroutine to run when the results from select B
  113329. ** are exhausted and only data in select A remains.
  113330. */
  113331. if( op==TK_INTERSECT ){
  113332. addrEofB = addrEofA;
  113333. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  113334. }else{
  113335. VdbeNoopComment((v, "eof-B subroutine"));
  113336. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  113337. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  113338. sqlite3VdbeGoto(v, addrEofB);
  113339. }
  113340. /* Generate code to handle the case of A<B
  113341. */
  113342. VdbeNoopComment((v, "A-lt-B subroutine"));
  113343. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  113344. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  113345. sqlite3VdbeGoto(v, labelCmpr);
  113346. /* Generate code to handle the case of A==B
  113347. */
  113348. if( op==TK_ALL ){
  113349. addrAeqB = addrAltB;
  113350. }else if( op==TK_INTERSECT ){
  113351. addrAeqB = addrAltB;
  113352. addrAltB++;
  113353. }else{
  113354. VdbeNoopComment((v, "A-eq-B subroutine"));
  113355. addrAeqB =
  113356. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  113357. sqlite3VdbeGoto(v, labelCmpr);
  113358. }
  113359. /* Generate code to handle the case of A>B
  113360. */
  113361. VdbeNoopComment((v, "A-gt-B subroutine"));
  113362. addrAgtB = sqlite3VdbeCurrentAddr(v);
  113363. if( op==TK_ALL || op==TK_UNION ){
  113364. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  113365. }
  113366. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  113367. sqlite3VdbeGoto(v, labelCmpr);
  113368. /* This code runs once to initialize everything.
  113369. */
  113370. sqlite3VdbeJumpHere(v, addr1);
  113371. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  113372. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  113373. /* Implement the main merge loop
  113374. */
  113375. sqlite3VdbeResolveLabel(v, labelCmpr);
  113376. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  113377. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  113378. (char*)pKeyMerge, P4_KEYINFO);
  113379. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  113380. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  113381. /* Jump to the this point in order to terminate the query.
  113382. */
  113383. sqlite3VdbeResolveLabel(v, labelEnd);
  113384. /* Reassembly the compound query so that it will be freed correctly
  113385. ** by the calling function */
  113386. if( p->pPrior ){
  113387. sqlite3SelectDelete(db, p->pPrior);
  113388. }
  113389. p->pPrior = pPrior;
  113390. pPrior->pNext = p;
  113391. /*** TBD: Insert subroutine calls to close cursors on incomplete
  113392. **** subqueries ****/
  113393. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  113394. return pParse->nErr!=0;
  113395. }
  113396. #endif
  113397. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  113398. /* An instance of the SubstContext object describes an substitution edit
  113399. ** to be performed on a parse tree.
  113400. **
  113401. ** All references to columns in table iTable are to be replaced by corresponding
  113402. ** expressions in pEList.
  113403. */
  113404. typedef struct SubstContext {
  113405. Parse *pParse; /* The parsing context */
  113406. int iTable; /* Replace references to this table */
  113407. int iNewTable; /* New table number */
  113408. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  113409. ExprList *pEList; /* Replacement expressions */
  113410. } SubstContext;
  113411. /* Forward Declarations */
  113412. static void substExprList(SubstContext*, ExprList*);
  113413. static void substSelect(SubstContext*, Select*, int);
  113414. /*
  113415. ** Scan through the expression pExpr. Replace every reference to
  113416. ** a column in table number iTable with a copy of the iColumn-th
  113417. ** entry in pEList. (But leave references to the ROWID column
  113418. ** unchanged.)
  113419. **
  113420. ** This routine is part of the flattening procedure. A subquery
  113421. ** whose result set is defined by pEList appears as entry in the
  113422. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  113423. ** FORM clause entry is iTable. This routine makes the necessary
  113424. ** changes to pExpr so that it refers directly to the source table
  113425. ** of the subquery rather the result set of the subquery.
  113426. */
  113427. static Expr *substExpr(
  113428. SubstContext *pSubst, /* Description of the substitution */
  113429. Expr *pExpr /* Expr in which substitution occurs */
  113430. ){
  113431. if( pExpr==0 ) return 0;
  113432. if( ExprHasProperty(pExpr, EP_FromJoin)
  113433. && pExpr->iRightJoinTable==pSubst->iTable
  113434. ){
  113435. pExpr->iRightJoinTable = pSubst->iNewTable;
  113436. }
  113437. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  113438. if( pExpr->iColumn<0 ){
  113439. pExpr->op = TK_NULL;
  113440. }else{
  113441. Expr *pNew;
  113442. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  113443. Expr ifNullRow;
  113444. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  113445. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  113446. if( sqlite3ExprIsVector(pCopy) ){
  113447. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  113448. }else{
  113449. sqlite3 *db = pSubst->pParse->db;
  113450. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  113451. memset(&ifNullRow, 0, sizeof(ifNullRow));
  113452. ifNullRow.op = TK_IF_NULL_ROW;
  113453. ifNullRow.pLeft = pCopy;
  113454. ifNullRow.iTable = pSubst->iNewTable;
  113455. pCopy = &ifNullRow;
  113456. }
  113457. pNew = sqlite3ExprDup(db, pCopy, 0);
  113458. if( pNew && pSubst->isLeftJoin ){
  113459. ExprSetProperty(pNew, EP_CanBeNull);
  113460. }
  113461. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  113462. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  113463. ExprSetProperty(pNew, EP_FromJoin);
  113464. }
  113465. sqlite3ExprDelete(db, pExpr);
  113466. pExpr = pNew;
  113467. }
  113468. }
  113469. }else{
  113470. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  113471. pExpr->iTable = pSubst->iNewTable;
  113472. }
  113473. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  113474. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  113475. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  113476. substSelect(pSubst, pExpr->x.pSelect, 1);
  113477. }else{
  113478. substExprList(pSubst, pExpr->x.pList);
  113479. }
  113480. }
  113481. return pExpr;
  113482. }
  113483. static void substExprList(
  113484. SubstContext *pSubst, /* Description of the substitution */
  113485. ExprList *pList /* List to scan and in which to make substitutes */
  113486. ){
  113487. int i;
  113488. if( pList==0 ) return;
  113489. for(i=0; i<pList->nExpr; i++){
  113490. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  113491. }
  113492. }
  113493. static void substSelect(
  113494. SubstContext *pSubst, /* Description of the substitution */
  113495. Select *p, /* SELECT statement in which to make substitutions */
  113496. int doPrior /* Do substitutes on p->pPrior too */
  113497. ){
  113498. SrcList *pSrc;
  113499. struct SrcList_item *pItem;
  113500. int i;
  113501. if( !p ) return;
  113502. do{
  113503. substExprList(pSubst, p->pEList);
  113504. substExprList(pSubst, p->pGroupBy);
  113505. substExprList(pSubst, p->pOrderBy);
  113506. p->pHaving = substExpr(pSubst, p->pHaving);
  113507. p->pWhere = substExpr(pSubst, p->pWhere);
  113508. pSrc = p->pSrc;
  113509. assert( pSrc!=0 );
  113510. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  113511. substSelect(pSubst, pItem->pSelect, 1);
  113512. if( pItem->fg.isTabFunc ){
  113513. substExprList(pSubst, pItem->u1.pFuncArg);
  113514. }
  113515. }
  113516. }while( doPrior && (p = p->pPrior)!=0 );
  113517. }
  113518. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  113519. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  113520. /*
  113521. ** This routine attempts to flatten subqueries as a performance optimization.
  113522. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  113523. **
  113524. ** To understand the concept of flattening, consider the following
  113525. ** query:
  113526. **
  113527. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  113528. **
  113529. ** The default way of implementing this query is to execute the
  113530. ** subquery first and store the results in a temporary table, then
  113531. ** run the outer query on that temporary table. This requires two
  113532. ** passes over the data. Furthermore, because the temporary table
  113533. ** has no indices, the WHERE clause on the outer query cannot be
  113534. ** optimized.
  113535. **
  113536. ** This routine attempts to rewrite queries such as the above into
  113537. ** a single flat select, like this:
  113538. **
  113539. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  113540. **
  113541. ** The code generated for this simplification gives the same result
  113542. ** but only has to scan the data once. And because indices might
  113543. ** exist on the table t1, a complete scan of the data might be
  113544. ** avoided.
  113545. **
  113546. ** Flattening is subject to the following constraints:
  113547. **
  113548. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  113549. ** The subquery and the outer query cannot both be aggregates.
  113550. **
  113551. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  113552. ** (2) If the subquery is an aggregate then
  113553. ** (2a) the outer query must not be a join and
  113554. ** (2b) the outer query must not use subqueries
  113555. ** other than the one FROM-clause subquery that is a candidate
  113556. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  113557. ** from 2015-02-09.)
  113558. **
  113559. ** (3) If the subquery is the right operand of a LEFT JOIN then
  113560. ** (3a) the subquery may not be a join and
  113561. ** (3b) the FROM clause of the subquery may not contain a virtual
  113562. ** table and
  113563. ** (3c) the outer query may not be an aggregate.
  113564. **
  113565. ** (4) The subquery can not be DISTINCT.
  113566. **
  113567. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  113568. ** sub-queries that were excluded from this optimization. Restriction
  113569. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  113570. **
  113571. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  113572. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  113573. **
  113574. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  113575. ** A FROM clause, consider adding a FROM clause with the special
  113576. ** table sqlite_once that consists of a single row containing a
  113577. ** single NULL.
  113578. **
  113579. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  113580. **
  113581. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  113582. **
  113583. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  113584. ** accidently carried the comment forward until 2014-09-15. Original
  113585. ** constraint: "If the subquery is aggregate then the outer query
  113586. ** may not use LIMIT."
  113587. **
  113588. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  113589. **
  113590. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  113591. ** a separate restriction deriving from ticket #350.
  113592. **
  113593. ** (13) The subquery and outer query may not both use LIMIT.
  113594. **
  113595. ** (14) The subquery may not use OFFSET.
  113596. **
  113597. ** (15) If the outer query is part of a compound select, then the
  113598. ** subquery may not use LIMIT.
  113599. ** (See ticket #2339 and ticket [02a8e81d44]).
  113600. **
  113601. ** (16) If the outer query is aggregate, then the subquery may not
  113602. ** use ORDER BY. (Ticket #2942) This used to not matter
  113603. ** until we introduced the group_concat() function.
  113604. **
  113605. ** (17) If the subquery is a compound select, then
  113606. ** (17a) all compound operators must be a UNION ALL, and
  113607. ** (17b) no terms within the subquery compound may be aggregate
  113608. ** or DISTINCT, and
  113609. ** (17c) every term within the subquery compound must have a FROM clause
  113610. ** (17d) the outer query may not be
  113611. ** (17d1) aggregate, or
  113612. ** (17d2) DISTINCT, or
  113613. ** (17d3) a join.
  113614. **
  113615. ** The parent and sub-query may contain WHERE clauses. Subject to
  113616. ** rules (11), (13) and (14), they may also contain ORDER BY,
  113617. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  113618. ** operator other than UNION ALL because all the other compound
  113619. ** operators have an implied DISTINCT which is disallowed by
  113620. ** restriction (4).
  113621. **
  113622. ** Also, each component of the sub-query must return the same number
  113623. ** of result columns. This is actually a requirement for any compound
  113624. ** SELECT statement, but all the code here does is make sure that no
  113625. ** such (illegal) sub-query is flattened. The caller will detect the
  113626. ** syntax error and return a detailed message.
  113627. **
  113628. ** (18) If the sub-query is a compound select, then all terms of the
  113629. ** ORDER BY clause of the parent must be simple references to
  113630. ** columns of the sub-query.
  113631. **
  113632. ** (19) If the subquery uses LIMIT then the outer query may not
  113633. ** have a WHERE clause.
  113634. **
  113635. ** (**) Subsumed into (17d3). Was: If the sub-query is a compound select,
  113636. ** then it must not use an ORDER BY clause - Ticket #3773. Because
  113637. ** of (17d3), then only way to have a compound subquery is if it is
  113638. ** the only term in the FROM clause of the outer query. But if the
  113639. ** only term in the FROM clause has an ORDER BY, then it will be
  113640. ** implemented as a co-routine and the flattener will never be called.
  113641. **
  113642. ** (21) If the subquery uses LIMIT then the outer query may not be
  113643. ** DISTINCT. (See ticket [752e1646fc]).
  113644. **
  113645. ** (22) The subquery may not be a recursive CTE.
  113646. **
  113647. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  113648. ** a recursive CTE, then the sub-query may not be a compound query.
  113649. ** This restriction is because transforming the
  113650. ** parent to a compound query confuses the code that handles
  113651. ** recursive queries in multiSelect().
  113652. **
  113653. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  113654. ** The subquery may not be an aggregate that uses the built-in min() or
  113655. ** or max() functions. (Without this restriction, a query like:
  113656. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  113657. ** return the value X for which Y was maximal.)
  113658. **
  113659. **
  113660. ** In this routine, the "p" parameter is a pointer to the outer query.
  113661. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  113662. ** uses aggregates.
  113663. **
  113664. ** If flattening is not attempted, this routine is a no-op and returns 0.
  113665. ** If flattening is attempted this routine returns 1.
  113666. **
  113667. ** All of the expression analysis must occur on both the outer query and
  113668. ** the subquery before this routine runs.
  113669. */
  113670. static int flattenSubquery(
  113671. Parse *pParse, /* Parsing context */
  113672. Select *p, /* The parent or outer SELECT statement */
  113673. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  113674. int isAgg /* True if outer SELECT uses aggregate functions */
  113675. ){
  113676. const char *zSavedAuthContext = pParse->zAuthContext;
  113677. Select *pParent; /* Current UNION ALL term of the other query */
  113678. Select *pSub; /* The inner query or "subquery" */
  113679. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  113680. SrcList *pSrc; /* The FROM clause of the outer query */
  113681. SrcList *pSubSrc; /* The FROM clause of the subquery */
  113682. int iParent; /* VDBE cursor number of the pSub result set temp table */
  113683. int iNewParent = -1;/* Replacement table for iParent */
  113684. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  113685. int i; /* Loop counter */
  113686. Expr *pWhere; /* The WHERE clause */
  113687. struct SrcList_item *pSubitem; /* The subquery */
  113688. sqlite3 *db = pParse->db;
  113689. /* Check to see if flattening is permitted. Return 0 if not.
  113690. */
  113691. assert( p!=0 );
  113692. assert( p->pPrior==0 );
  113693. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  113694. pSrc = p->pSrc;
  113695. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  113696. pSubitem = &pSrc->a[iFrom];
  113697. iParent = pSubitem->iCursor;
  113698. pSub = pSubitem->pSelect;
  113699. assert( pSub!=0 );
  113700. pSubSrc = pSub->pSrc;
  113701. assert( pSubSrc );
  113702. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  113703. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  113704. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  113705. ** became arbitrary expressions, we were forced to add restrictions (13)
  113706. ** and (14). */
  113707. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  113708. if( pSub->pOffset ) return 0; /* Restriction (14) */
  113709. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  113710. return 0; /* Restriction (15) */
  113711. }
  113712. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  113713. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  113714. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  113715. return 0; /* Restrictions (8)(9) */
  113716. }
  113717. if( p->pOrderBy && pSub->pOrderBy ){
  113718. return 0; /* Restriction (11) */
  113719. }
  113720. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  113721. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  113722. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  113723. return 0; /* Restriction (21) */
  113724. }
  113725. if( pSub->selFlags & (SF_Recursive) ){
  113726. return 0; /* Restrictions (22) */
  113727. }
  113728. /*
  113729. ** If the subquery is the right operand of a LEFT JOIN, then the
  113730. ** subquery may not be a join itself (3a). Example of why this is not
  113731. ** allowed:
  113732. **
  113733. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  113734. **
  113735. ** If we flatten the above, we would get
  113736. **
  113737. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  113738. **
  113739. ** which is not at all the same thing.
  113740. **
  113741. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  113742. ** query cannot be an aggregate. (3c) This is an artifact of the way
  113743. ** aggregates are processed - there is no mechanism to determine if
  113744. ** the LEFT JOIN table should be all-NULL.
  113745. **
  113746. ** See also tickets #306, #350, and #3300.
  113747. */
  113748. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  113749. isLeftJoin = 1;
  113750. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  113751. /* (3a) (3c) (3b) */
  113752. return 0;
  113753. }
  113754. }
  113755. #ifdef SQLITE_EXTRA_IFNULLROW
  113756. else if( iFrom>0 && !isAgg ){
  113757. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  113758. ** every reference to any result column from subquery in a join, even
  113759. ** though they are not necessary. This will stress-test the OP_IfNullRow
  113760. ** opcode. */
  113761. isLeftJoin = -1;
  113762. }
  113763. #endif
  113764. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  113765. ** use only the UNION ALL operator. And none of the simple select queries
  113766. ** that make up the compound SELECT are allowed to be aggregate or distinct
  113767. ** queries.
  113768. */
  113769. if( pSub->pPrior ){
  113770. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  113771. return 0; /* (17d1), (17d2), or (17d3) */
  113772. }
  113773. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  113774. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  113775. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  113776. assert( pSub->pSrc!=0 );
  113777. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  113778. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  113779. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  113780. || pSub1->pSrc->nSrc<1 /* (17c) */
  113781. ){
  113782. return 0;
  113783. }
  113784. testcase( pSub1->pSrc->nSrc>1 );
  113785. }
  113786. /* Restriction (18). */
  113787. if( p->pOrderBy ){
  113788. int ii;
  113789. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  113790. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  113791. }
  113792. }
  113793. }
  113794. /* Ex-restriction (23):
  113795. ** The only way that the recursive part of a CTE can contain a compound
  113796. ** subquery is for the subquery to be one term of a join. But if the
  113797. ** subquery is a join, then the flattening has already been stopped by
  113798. ** restriction (17d3)
  113799. */
  113800. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  113801. /* Ex-restriction (20):
  113802. ** A compound subquery must be the only term in the FROM clause of the
  113803. ** outer query by restriction (17d3). But if that term also has an
  113804. ** ORDER BY clause, then the subquery will be implemented by co-routine
  113805. ** and so the flattener will never be invoked. Hence, it is not possible
  113806. ** for the subquery to be a compound and have an ORDER BY clause.
  113807. */
  113808. assert( pSub->pPrior==0 || pSub->pOrderBy==0 );
  113809. /***** If we reach this point, flattening is permitted. *****/
  113810. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  113811. pSub->zSelName, pSub, iFrom));
  113812. /* Authorize the subquery */
  113813. pParse->zAuthContext = pSubitem->zName;
  113814. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  113815. testcase( i==SQLITE_DENY );
  113816. pParse->zAuthContext = zSavedAuthContext;
  113817. /* If the sub-query is a compound SELECT statement, then (by restrictions
  113818. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  113819. ** be of the form:
  113820. **
  113821. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  113822. **
  113823. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  113824. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  113825. ** OFFSET clauses and joins them to the left-hand-side of the original
  113826. ** using UNION ALL operators. In this case N is the number of simple
  113827. ** select statements in the compound sub-query.
  113828. **
  113829. ** Example:
  113830. **
  113831. ** SELECT a+1 FROM (
  113832. ** SELECT x FROM tab
  113833. ** UNION ALL
  113834. ** SELECT y FROM tab
  113835. ** UNION ALL
  113836. ** SELECT abs(z*2) FROM tab2
  113837. ** ) WHERE a!=5 ORDER BY 1
  113838. **
  113839. ** Transformed into:
  113840. **
  113841. ** SELECT x+1 FROM tab WHERE x+1!=5
  113842. ** UNION ALL
  113843. ** SELECT y+1 FROM tab WHERE y+1!=5
  113844. ** UNION ALL
  113845. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  113846. ** ORDER BY 1
  113847. **
  113848. ** We call this the "compound-subquery flattening".
  113849. */
  113850. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  113851. Select *pNew;
  113852. ExprList *pOrderBy = p->pOrderBy;
  113853. Expr *pLimit = p->pLimit;
  113854. Expr *pOffset = p->pOffset;
  113855. Select *pPrior = p->pPrior;
  113856. p->pOrderBy = 0;
  113857. p->pSrc = 0;
  113858. p->pPrior = 0;
  113859. p->pLimit = 0;
  113860. p->pOffset = 0;
  113861. pNew = sqlite3SelectDup(db, p, 0);
  113862. sqlite3SelectSetName(pNew, pSub->zSelName);
  113863. p->pOffset = pOffset;
  113864. p->pLimit = pLimit;
  113865. p->pOrderBy = pOrderBy;
  113866. p->pSrc = pSrc;
  113867. p->op = TK_ALL;
  113868. if( pNew==0 ){
  113869. p->pPrior = pPrior;
  113870. }else{
  113871. pNew->pPrior = pPrior;
  113872. if( pPrior ) pPrior->pNext = pNew;
  113873. pNew->pNext = p;
  113874. p->pPrior = pNew;
  113875. SELECTTRACE(2,pParse,p,
  113876. ("compound-subquery flattener creates %s.%p as peer\n",
  113877. pNew->zSelName, pNew));
  113878. }
  113879. if( db->mallocFailed ) return 1;
  113880. }
  113881. /* Begin flattening the iFrom-th entry of the FROM clause
  113882. ** in the outer query.
  113883. */
  113884. pSub = pSub1 = pSubitem->pSelect;
  113885. /* Delete the transient table structure associated with the
  113886. ** subquery
  113887. */
  113888. sqlite3DbFree(db, pSubitem->zDatabase);
  113889. sqlite3DbFree(db, pSubitem->zName);
  113890. sqlite3DbFree(db, pSubitem->zAlias);
  113891. pSubitem->zDatabase = 0;
  113892. pSubitem->zName = 0;
  113893. pSubitem->zAlias = 0;
  113894. pSubitem->pSelect = 0;
  113895. /* Defer deleting the Table object associated with the
  113896. ** subquery until code generation is
  113897. ** complete, since there may still exist Expr.pTab entries that
  113898. ** refer to the subquery even after flattening. Ticket #3346.
  113899. **
  113900. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  113901. */
  113902. if( ALWAYS(pSubitem->pTab!=0) ){
  113903. Table *pTabToDel = pSubitem->pTab;
  113904. if( pTabToDel->nTabRef==1 ){
  113905. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  113906. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  113907. pToplevel->pZombieTab = pTabToDel;
  113908. }else{
  113909. pTabToDel->nTabRef--;
  113910. }
  113911. pSubitem->pTab = 0;
  113912. }
  113913. /* The following loop runs once for each term in a compound-subquery
  113914. ** flattening (as described above). If we are doing a different kind
  113915. ** of flattening - a flattening other than a compound-subquery flattening -
  113916. ** then this loop only runs once.
  113917. **
  113918. ** This loop moves all of the FROM elements of the subquery into the
  113919. ** the FROM clause of the outer query. Before doing this, remember
  113920. ** the cursor number for the original outer query FROM element in
  113921. ** iParent. The iParent cursor will never be used. Subsequent code
  113922. ** will scan expressions looking for iParent references and replace
  113923. ** those references with expressions that resolve to the subquery FROM
  113924. ** elements we are now copying in.
  113925. */
  113926. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  113927. int nSubSrc;
  113928. u8 jointype = 0;
  113929. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  113930. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  113931. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  113932. if( pSrc ){
  113933. assert( pParent==p ); /* First time through the loop */
  113934. jointype = pSubitem->fg.jointype;
  113935. }else{
  113936. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  113937. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  113938. if( pSrc==0 ){
  113939. assert( db->mallocFailed );
  113940. break;
  113941. }
  113942. }
  113943. /* The subquery uses a single slot of the FROM clause of the outer
  113944. ** query. If the subquery has more than one element in its FROM clause,
  113945. ** then expand the outer query to make space for it to hold all elements
  113946. ** of the subquery.
  113947. **
  113948. ** Example:
  113949. **
  113950. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  113951. **
  113952. ** The outer query has 3 slots in its FROM clause. One slot of the
  113953. ** outer query (the middle slot) is used by the subquery. The next
  113954. ** block of code will expand the outer query FROM clause to 4 slots.
  113955. ** The middle slot is expanded to two slots in order to make space
  113956. ** for the two elements in the FROM clause of the subquery.
  113957. */
  113958. if( nSubSrc>1 ){
  113959. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  113960. if( db->mallocFailed ){
  113961. break;
  113962. }
  113963. }
  113964. /* Transfer the FROM clause terms from the subquery into the
  113965. ** outer query.
  113966. */
  113967. for(i=0; i<nSubSrc; i++){
  113968. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  113969. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  113970. pSrc->a[i+iFrom] = pSubSrc->a[i];
  113971. iNewParent = pSubSrc->a[i].iCursor;
  113972. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  113973. }
  113974. pSrc->a[iFrom].fg.jointype = jointype;
  113975. /* Now begin substituting subquery result set expressions for
  113976. ** references to the iParent in the outer query.
  113977. **
  113978. ** Example:
  113979. **
  113980. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  113981. ** \ \_____________ subquery __________/ /
  113982. ** \_____________________ outer query ______________________________/
  113983. **
  113984. ** We look at every expression in the outer query and every place we see
  113985. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  113986. */
  113987. if( pSub->pOrderBy ){
  113988. /* At this point, any non-zero iOrderByCol values indicate that the
  113989. ** ORDER BY column expression is identical to the iOrderByCol'th
  113990. ** expression returned by SELECT statement pSub. Since these values
  113991. ** do not necessarily correspond to columns in SELECT statement pParent,
  113992. ** zero them before transfering the ORDER BY clause.
  113993. **
  113994. ** Not doing this may cause an error if a subsequent call to this
  113995. ** function attempts to flatten a compound sub-query into pParent
  113996. ** (the only way this can happen is if the compound sub-query is
  113997. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  113998. ExprList *pOrderBy = pSub->pOrderBy;
  113999. for(i=0; i<pOrderBy->nExpr; i++){
  114000. pOrderBy->a[i].u.x.iOrderByCol = 0;
  114001. }
  114002. assert( pParent->pOrderBy==0 );
  114003. assert( pSub->pPrior==0 );
  114004. pParent->pOrderBy = pOrderBy;
  114005. pSub->pOrderBy = 0;
  114006. }
  114007. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  114008. if( isLeftJoin>0 ){
  114009. setJoinExpr(pWhere, iNewParent);
  114010. }
  114011. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  114012. if( db->mallocFailed==0 ){
  114013. SubstContext x;
  114014. x.pParse = pParse;
  114015. x.iTable = iParent;
  114016. x.iNewTable = iNewParent;
  114017. x.isLeftJoin = isLeftJoin;
  114018. x.pEList = pSub->pEList;
  114019. substSelect(&x, pParent, 0);
  114020. }
  114021. /* The flattened query is distinct if either the inner or the
  114022. ** outer query is distinct.
  114023. */
  114024. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  114025. /*
  114026. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  114027. **
  114028. ** One is tempted to try to add a and b to combine the limits. But this
  114029. ** does not work if either limit is negative.
  114030. */
  114031. if( pSub->pLimit ){
  114032. pParent->pLimit = pSub->pLimit;
  114033. pSub->pLimit = 0;
  114034. }
  114035. }
  114036. /* Finially, delete what is left of the subquery and return
  114037. ** success.
  114038. */
  114039. sqlite3SelectDelete(db, pSub1);
  114040. #if SELECTTRACE_ENABLED
  114041. if( sqlite3SelectTrace & 0x100 ){
  114042. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  114043. sqlite3TreeViewSelect(0, p, 0);
  114044. }
  114045. #endif
  114046. return 1;
  114047. }
  114048. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  114049. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  114050. /*
  114051. ** Make copies of relevant WHERE clause terms of the outer query into
  114052. ** the WHERE clause of subquery. Example:
  114053. **
  114054. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  114055. **
  114056. ** Transformed into:
  114057. **
  114058. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  114059. ** WHERE x=5 AND y=10;
  114060. **
  114061. ** The hope is that the terms added to the inner query will make it more
  114062. ** efficient.
  114063. **
  114064. ** Do not attempt this optimization if:
  114065. **
  114066. ** (1) (** This restriction was removed on 2017-09-29. We used to
  114067. ** disallow this optimization for aggregate subqueries, but now
  114068. ** it is allowed by putting the extra terms on the HAVING clause.
  114069. ** The added HAVING clause is pointless if the subquery lacks
  114070. ** a GROUP BY clause. But such a HAVING clause is also harmless
  114071. ** so there does not appear to be any reason to add extra logic
  114072. ** to suppress it. **)
  114073. **
  114074. ** (2) The inner query is the recursive part of a common table expression.
  114075. **
  114076. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  114077. ** close would change the meaning of the LIMIT).
  114078. **
  114079. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  114080. ** enforces this restriction since this routine does not have enough
  114081. ** information to know.)
  114082. **
  114083. ** (5) The WHERE clause expression originates in the ON or USING clause
  114084. ** of a LEFT JOIN.
  114085. **
  114086. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  114087. ** terms are duplicated into the subquery.
  114088. */
  114089. static int pushDownWhereTerms(
  114090. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  114091. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  114092. Expr *pWhere, /* The WHERE clause of the outer query */
  114093. int iCursor /* Cursor number of the subquery */
  114094. ){
  114095. Expr *pNew;
  114096. int nChng = 0;
  114097. if( pWhere==0 ) return 0;
  114098. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  114099. #ifdef SQLITE_DEBUG
  114100. /* Only the first term of a compound can have a WITH clause. But make
  114101. ** sure no other terms are marked SF_Recursive in case something changes
  114102. ** in the future.
  114103. */
  114104. {
  114105. Select *pX;
  114106. for(pX=pSubq; pX; pX=pX->pPrior){
  114107. assert( (pX->selFlags & (SF_Recursive))==0 );
  114108. }
  114109. }
  114110. #endif
  114111. if( pSubq->pLimit!=0 ){
  114112. return 0; /* restriction (3) */
  114113. }
  114114. while( pWhere->op==TK_AND ){
  114115. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
  114116. pWhere = pWhere->pLeft;
  114117. }
  114118. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction (5) */
  114119. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  114120. nChng++;
  114121. while( pSubq ){
  114122. SubstContext x;
  114123. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  114124. x.pParse = pParse;
  114125. x.iTable = iCursor;
  114126. x.iNewTable = iCursor;
  114127. x.isLeftJoin = 0;
  114128. x.pEList = pSubq->pEList;
  114129. pNew = substExpr(&x, pNew);
  114130. if( pSubq->selFlags & SF_Aggregate ){
  114131. pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
  114132. }else{
  114133. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  114134. }
  114135. pSubq = pSubq->pPrior;
  114136. }
  114137. }
  114138. return nChng;
  114139. }
  114140. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  114141. /*
  114142. ** Based on the contents of the AggInfo structure indicated by the first
  114143. ** argument, this function checks if the following are true:
  114144. **
  114145. ** * the query contains just a single aggregate function,
  114146. ** * the aggregate function is either min() or max(), and
  114147. ** * the argument to the aggregate function is a column value.
  114148. **
  114149. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  114150. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  114151. ** list of arguments passed to the aggregate before returning.
  114152. **
  114153. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  114154. ** WHERE_ORDERBY_NORMAL is returned.
  114155. */
  114156. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  114157. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  114158. *ppMinMax = 0;
  114159. if( pAggInfo->nFunc==1 ){
  114160. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  114161. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  114162. assert( pExpr->op==TK_AGG_FUNCTION );
  114163. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  114164. const char *zFunc = pExpr->u.zToken;
  114165. if( sqlite3StrICmp(zFunc, "min")==0 ){
  114166. eRet = WHERE_ORDERBY_MIN;
  114167. *ppMinMax = pEList;
  114168. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  114169. eRet = WHERE_ORDERBY_MAX;
  114170. *ppMinMax = pEList;
  114171. }
  114172. }
  114173. }
  114174. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  114175. return eRet;
  114176. }
  114177. /*
  114178. ** The select statement passed as the first argument is an aggregate query.
  114179. ** The second argument is the associated aggregate-info object. This
  114180. ** function tests if the SELECT is of the form:
  114181. **
  114182. ** SELECT count(*) FROM <tbl>
  114183. **
  114184. ** where table is a database table, not a sub-select or view. If the query
  114185. ** does match this pattern, then a pointer to the Table object representing
  114186. ** <tbl> is returned. Otherwise, 0 is returned.
  114187. */
  114188. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  114189. Table *pTab;
  114190. Expr *pExpr;
  114191. assert( !p->pGroupBy );
  114192. if( p->pWhere || p->pEList->nExpr!=1
  114193. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  114194. ){
  114195. return 0;
  114196. }
  114197. pTab = p->pSrc->a[0].pTab;
  114198. pExpr = p->pEList->a[0].pExpr;
  114199. assert( pTab && !pTab->pSelect && pExpr );
  114200. if( IsVirtual(pTab) ) return 0;
  114201. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  114202. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  114203. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  114204. if( pExpr->flags&EP_Distinct ) return 0;
  114205. return pTab;
  114206. }
  114207. /*
  114208. ** If the source-list item passed as an argument was augmented with an
  114209. ** INDEXED BY clause, then try to locate the specified index. If there
  114210. ** was such a clause and the named index cannot be found, return
  114211. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  114212. ** pFrom->pIndex and return SQLITE_OK.
  114213. */
  114214. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  114215. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  114216. Table *pTab = pFrom->pTab;
  114217. char *zIndexedBy = pFrom->u1.zIndexedBy;
  114218. Index *pIdx;
  114219. for(pIdx=pTab->pIndex;
  114220. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  114221. pIdx=pIdx->pNext
  114222. );
  114223. if( !pIdx ){
  114224. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  114225. pParse->checkSchema = 1;
  114226. return SQLITE_ERROR;
  114227. }
  114228. pFrom->pIBIndex = pIdx;
  114229. }
  114230. return SQLITE_OK;
  114231. }
  114232. /*
  114233. ** Detect compound SELECT statements that use an ORDER BY clause with
  114234. ** an alternative collating sequence.
  114235. **
  114236. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  114237. **
  114238. ** These are rewritten as a subquery:
  114239. **
  114240. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  114241. ** ORDER BY ... COLLATE ...
  114242. **
  114243. ** This transformation is necessary because the multiSelectOrderBy() routine
  114244. ** above that generates the code for a compound SELECT with an ORDER BY clause
  114245. ** uses a merge algorithm that requires the same collating sequence on the
  114246. ** result columns as on the ORDER BY clause. See ticket
  114247. ** http://www.sqlite.org/src/info/6709574d2a
  114248. **
  114249. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  114250. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  114251. ** there are COLLATE terms in the ORDER BY.
  114252. */
  114253. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  114254. int i;
  114255. Select *pNew;
  114256. Select *pX;
  114257. sqlite3 *db;
  114258. struct ExprList_item *a;
  114259. SrcList *pNewSrc;
  114260. Parse *pParse;
  114261. Token dummy;
  114262. if( p->pPrior==0 ) return WRC_Continue;
  114263. if( p->pOrderBy==0 ) return WRC_Continue;
  114264. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  114265. if( pX==0 ) return WRC_Continue;
  114266. a = p->pOrderBy->a;
  114267. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  114268. if( a[i].pExpr->flags & EP_Collate ) break;
  114269. }
  114270. if( i<0 ) return WRC_Continue;
  114271. /* If we reach this point, that means the transformation is required. */
  114272. pParse = pWalker->pParse;
  114273. db = pParse->db;
  114274. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  114275. if( pNew==0 ) return WRC_Abort;
  114276. memset(&dummy, 0, sizeof(dummy));
  114277. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  114278. if( pNewSrc==0 ) return WRC_Abort;
  114279. *pNew = *p;
  114280. p->pSrc = pNewSrc;
  114281. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  114282. p->op = TK_SELECT;
  114283. p->pWhere = 0;
  114284. pNew->pGroupBy = 0;
  114285. pNew->pHaving = 0;
  114286. pNew->pOrderBy = 0;
  114287. p->pPrior = 0;
  114288. p->pNext = 0;
  114289. p->pWith = 0;
  114290. p->selFlags &= ~SF_Compound;
  114291. assert( (p->selFlags & SF_Converted)==0 );
  114292. p->selFlags |= SF_Converted;
  114293. assert( pNew->pPrior!=0 );
  114294. pNew->pPrior->pNext = pNew;
  114295. pNew->pLimit = 0;
  114296. pNew->pOffset = 0;
  114297. return WRC_Continue;
  114298. }
  114299. /*
  114300. ** Check to see if the FROM clause term pFrom has table-valued function
  114301. ** arguments. If it does, leave an error message in pParse and return
  114302. ** non-zero, since pFrom is not allowed to be a table-valued function.
  114303. */
  114304. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  114305. if( pFrom->fg.isTabFunc ){
  114306. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  114307. return 1;
  114308. }
  114309. return 0;
  114310. }
  114311. #ifndef SQLITE_OMIT_CTE
  114312. /*
  114313. ** Argument pWith (which may be NULL) points to a linked list of nested
  114314. ** WITH contexts, from inner to outermost. If the table identified by
  114315. ** FROM clause element pItem is really a common-table-expression (CTE)
  114316. ** then return a pointer to the CTE definition for that table. Otherwise
  114317. ** return NULL.
  114318. **
  114319. ** If a non-NULL value is returned, set *ppContext to point to the With
  114320. ** object that the returned CTE belongs to.
  114321. */
  114322. static struct Cte *searchWith(
  114323. With *pWith, /* Current innermost WITH clause */
  114324. struct SrcList_item *pItem, /* FROM clause element to resolve */
  114325. With **ppContext /* OUT: WITH clause return value belongs to */
  114326. ){
  114327. const char *zName;
  114328. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  114329. With *p;
  114330. for(p=pWith; p; p=p->pOuter){
  114331. int i;
  114332. for(i=0; i<p->nCte; i++){
  114333. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  114334. *ppContext = p;
  114335. return &p->a[i];
  114336. }
  114337. }
  114338. }
  114339. }
  114340. return 0;
  114341. }
  114342. /* The code generator maintains a stack of active WITH clauses
  114343. ** with the inner-most WITH clause being at the top of the stack.
  114344. **
  114345. ** This routine pushes the WITH clause passed as the second argument
  114346. ** onto the top of the stack. If argument bFree is true, then this
  114347. ** WITH clause will never be popped from the stack. In this case it
  114348. ** should be freed along with the Parse object. In other cases, when
  114349. ** bFree==0, the With object will be freed along with the SELECT
  114350. ** statement with which it is associated.
  114351. */
  114352. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  114353. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  114354. if( pWith ){
  114355. assert( pParse->pWith!=pWith );
  114356. pWith->pOuter = pParse->pWith;
  114357. pParse->pWith = pWith;
  114358. if( bFree ) pParse->pWithToFree = pWith;
  114359. }
  114360. }
  114361. /*
  114362. ** This function checks if argument pFrom refers to a CTE declared by
  114363. ** a WITH clause on the stack currently maintained by the parser. And,
  114364. ** if currently processing a CTE expression, if it is a recursive
  114365. ** reference to the current CTE.
  114366. **
  114367. ** If pFrom falls into either of the two categories above, pFrom->pTab
  114368. ** and other fields are populated accordingly. The caller should check
  114369. ** (pFrom->pTab!=0) to determine whether or not a successful match
  114370. ** was found.
  114371. **
  114372. ** Whether or not a match is found, SQLITE_OK is returned if no error
  114373. ** occurs. If an error does occur, an error message is stored in the
  114374. ** parser and some error code other than SQLITE_OK returned.
  114375. */
  114376. static int withExpand(
  114377. Walker *pWalker,
  114378. struct SrcList_item *pFrom
  114379. ){
  114380. Parse *pParse = pWalker->pParse;
  114381. sqlite3 *db = pParse->db;
  114382. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  114383. With *pWith; /* WITH clause that pCte belongs to */
  114384. assert( pFrom->pTab==0 );
  114385. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  114386. if( pCte ){
  114387. Table *pTab;
  114388. ExprList *pEList;
  114389. Select *pSel;
  114390. Select *pLeft; /* Left-most SELECT statement */
  114391. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  114392. With *pSavedWith; /* Initial value of pParse->pWith */
  114393. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  114394. ** recursive reference to CTE pCte. Leave an error in pParse and return
  114395. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  114396. ** In this case, proceed. */
  114397. if( pCte->zCteErr ){
  114398. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  114399. return SQLITE_ERROR;
  114400. }
  114401. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  114402. assert( pFrom->pTab==0 );
  114403. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  114404. if( pTab==0 ) return WRC_Abort;
  114405. pTab->nTabRef = 1;
  114406. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  114407. pTab->iPKey = -1;
  114408. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  114409. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  114410. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  114411. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  114412. assert( pFrom->pSelect );
  114413. /* Check if this is a recursive CTE. */
  114414. pSel = pFrom->pSelect;
  114415. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  114416. if( bMayRecursive ){
  114417. int i;
  114418. SrcList *pSrc = pFrom->pSelect->pSrc;
  114419. for(i=0; i<pSrc->nSrc; i++){
  114420. struct SrcList_item *pItem = &pSrc->a[i];
  114421. if( pItem->zDatabase==0
  114422. && pItem->zName!=0
  114423. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  114424. ){
  114425. pItem->pTab = pTab;
  114426. pItem->fg.isRecursive = 1;
  114427. pTab->nTabRef++;
  114428. pSel->selFlags |= SF_Recursive;
  114429. }
  114430. }
  114431. }
  114432. /* Only one recursive reference is permitted. */
  114433. if( pTab->nTabRef>2 ){
  114434. sqlite3ErrorMsg(
  114435. pParse, "multiple references to recursive table: %s", pCte->zName
  114436. );
  114437. return SQLITE_ERROR;
  114438. }
  114439. assert( pTab->nTabRef==1 ||
  114440. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  114441. pCte->zCteErr = "circular reference: %s";
  114442. pSavedWith = pParse->pWith;
  114443. pParse->pWith = pWith;
  114444. if( bMayRecursive ){
  114445. Select *pPrior = pSel->pPrior;
  114446. assert( pPrior->pWith==0 );
  114447. pPrior->pWith = pSel->pWith;
  114448. sqlite3WalkSelect(pWalker, pPrior);
  114449. pPrior->pWith = 0;
  114450. }else{
  114451. sqlite3WalkSelect(pWalker, pSel);
  114452. }
  114453. pParse->pWith = pWith;
  114454. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  114455. pEList = pLeft->pEList;
  114456. if( pCte->pCols ){
  114457. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  114458. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  114459. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  114460. );
  114461. pParse->pWith = pSavedWith;
  114462. return SQLITE_ERROR;
  114463. }
  114464. pEList = pCte->pCols;
  114465. }
  114466. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  114467. if( bMayRecursive ){
  114468. if( pSel->selFlags & SF_Recursive ){
  114469. pCte->zCteErr = "multiple recursive references: %s";
  114470. }else{
  114471. pCte->zCteErr = "recursive reference in a subquery: %s";
  114472. }
  114473. sqlite3WalkSelect(pWalker, pSel);
  114474. }
  114475. pCte->zCteErr = 0;
  114476. pParse->pWith = pSavedWith;
  114477. }
  114478. return SQLITE_OK;
  114479. }
  114480. #endif
  114481. #ifndef SQLITE_OMIT_CTE
  114482. /*
  114483. ** If the SELECT passed as the second argument has an associated WITH
  114484. ** clause, pop it from the stack stored as part of the Parse object.
  114485. **
  114486. ** This function is used as the xSelectCallback2() callback by
  114487. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  114488. ** names and other FROM clause elements.
  114489. */
  114490. static void selectPopWith(Walker *pWalker, Select *p){
  114491. Parse *pParse = pWalker->pParse;
  114492. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  114493. With *pWith = findRightmost(p)->pWith;
  114494. if( pWith!=0 ){
  114495. assert( pParse->pWith==pWith );
  114496. pParse->pWith = pWith->pOuter;
  114497. }
  114498. }
  114499. }
  114500. #else
  114501. #define selectPopWith 0
  114502. #endif
  114503. /*
  114504. ** This routine is a Walker callback for "expanding" a SELECT statement.
  114505. ** "Expanding" means to do the following:
  114506. **
  114507. ** (1) Make sure VDBE cursor numbers have been assigned to every
  114508. ** element of the FROM clause.
  114509. **
  114510. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  114511. ** defines FROM clause. When views appear in the FROM clause,
  114512. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  114513. ** that implements the view. A copy is made of the view's SELECT
  114514. ** statement so that we can freely modify or delete that statement
  114515. ** without worrying about messing up the persistent representation
  114516. ** of the view.
  114517. **
  114518. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  114519. ** on joins and the ON and USING clause of joins.
  114520. **
  114521. ** (4) Scan the list of columns in the result set (pEList) looking
  114522. ** for instances of the "*" operator or the TABLE.* operator.
  114523. ** If found, expand each "*" to be every column in every table
  114524. ** and TABLE.* to be every column in TABLE.
  114525. **
  114526. */
  114527. static int selectExpander(Walker *pWalker, Select *p){
  114528. Parse *pParse = pWalker->pParse;
  114529. int i, j, k;
  114530. SrcList *pTabList;
  114531. ExprList *pEList;
  114532. struct SrcList_item *pFrom;
  114533. sqlite3 *db = pParse->db;
  114534. Expr *pE, *pRight, *pExpr;
  114535. u16 selFlags = p->selFlags;
  114536. p->selFlags |= SF_Expanded;
  114537. if( db->mallocFailed ){
  114538. return WRC_Abort;
  114539. }
  114540. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  114541. return WRC_Prune;
  114542. }
  114543. pTabList = p->pSrc;
  114544. pEList = p->pEList;
  114545. if( OK_IF_ALWAYS_TRUE(p->pWith) ){
  114546. sqlite3WithPush(pParse, p->pWith, 0);
  114547. }
  114548. /* Make sure cursor numbers have been assigned to all entries in
  114549. ** the FROM clause of the SELECT statement.
  114550. */
  114551. sqlite3SrcListAssignCursors(pParse, pTabList);
  114552. /* Look up every table named in the FROM clause of the select. If
  114553. ** an entry of the FROM clause is a subquery instead of a table or view,
  114554. ** then create a transient table structure to describe the subquery.
  114555. */
  114556. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  114557. Table *pTab;
  114558. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  114559. if( pFrom->fg.isRecursive ) continue;
  114560. assert( pFrom->pTab==0 );
  114561. #ifndef SQLITE_OMIT_CTE
  114562. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  114563. if( pFrom->pTab ) {} else
  114564. #endif
  114565. if( pFrom->zName==0 ){
  114566. #ifndef SQLITE_OMIT_SUBQUERY
  114567. Select *pSel = pFrom->pSelect;
  114568. /* A sub-query in the FROM clause of a SELECT */
  114569. assert( pSel!=0 );
  114570. assert( pFrom->pTab==0 );
  114571. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  114572. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  114573. if( pTab==0 ) return WRC_Abort;
  114574. pTab->nTabRef = 1;
  114575. if( pFrom->zAlias ){
  114576. pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
  114577. }else{
  114578. pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
  114579. }
  114580. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  114581. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  114582. pTab->iPKey = -1;
  114583. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  114584. pTab->tabFlags |= TF_Ephemeral;
  114585. #endif
  114586. }else{
  114587. /* An ordinary table or view name in the FROM clause */
  114588. assert( pFrom->pTab==0 );
  114589. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  114590. if( pTab==0 ) return WRC_Abort;
  114591. if( pTab->nTabRef>=0xffff ){
  114592. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  114593. pTab->zName);
  114594. pFrom->pTab = 0;
  114595. return WRC_Abort;
  114596. }
  114597. pTab->nTabRef++;
  114598. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  114599. return WRC_Abort;
  114600. }
  114601. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  114602. if( IsVirtual(pTab) || pTab->pSelect ){
  114603. i16 nCol;
  114604. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  114605. assert( pFrom->pSelect==0 );
  114606. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  114607. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  114608. nCol = pTab->nCol;
  114609. pTab->nCol = -1;
  114610. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  114611. pTab->nCol = nCol;
  114612. }
  114613. #endif
  114614. }
  114615. /* Locate the index named by the INDEXED BY clause, if any. */
  114616. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  114617. return WRC_Abort;
  114618. }
  114619. }
  114620. /* Process NATURAL keywords, and ON and USING clauses of joins.
  114621. */
  114622. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  114623. return WRC_Abort;
  114624. }
  114625. /* For every "*" that occurs in the column list, insert the names of
  114626. ** all columns in all tables. And for every TABLE.* insert the names
  114627. ** of all columns in TABLE. The parser inserted a special expression
  114628. ** with the TK_ASTERISK operator for each "*" that it found in the column
  114629. ** list. The following code just has to locate the TK_ASTERISK
  114630. ** expressions and expand each one to the list of all columns in
  114631. ** all tables.
  114632. **
  114633. ** The first loop just checks to see if there are any "*" operators
  114634. ** that need expanding.
  114635. */
  114636. for(k=0; k<pEList->nExpr; k++){
  114637. pE = pEList->a[k].pExpr;
  114638. if( pE->op==TK_ASTERISK ) break;
  114639. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  114640. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  114641. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  114642. }
  114643. if( k<pEList->nExpr ){
  114644. /*
  114645. ** If we get here it means the result set contains one or more "*"
  114646. ** operators that need to be expanded. Loop through each expression
  114647. ** in the result set and expand them one by one.
  114648. */
  114649. struct ExprList_item *a = pEList->a;
  114650. ExprList *pNew = 0;
  114651. int flags = pParse->db->flags;
  114652. int longNames = (flags & SQLITE_FullColNames)!=0
  114653. && (flags & SQLITE_ShortColNames)==0;
  114654. for(k=0; k<pEList->nExpr; k++){
  114655. pE = a[k].pExpr;
  114656. pRight = pE->pRight;
  114657. assert( pE->op!=TK_DOT || pRight!=0 );
  114658. if( pE->op!=TK_ASTERISK
  114659. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  114660. ){
  114661. /* This particular expression does not need to be expanded.
  114662. */
  114663. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  114664. if( pNew ){
  114665. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  114666. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  114667. a[k].zName = 0;
  114668. a[k].zSpan = 0;
  114669. }
  114670. a[k].pExpr = 0;
  114671. }else{
  114672. /* This expression is a "*" or a "TABLE.*" and needs to be
  114673. ** expanded. */
  114674. int tableSeen = 0; /* Set to 1 when TABLE matches */
  114675. char *zTName = 0; /* text of name of TABLE */
  114676. if( pE->op==TK_DOT ){
  114677. assert( pE->pLeft!=0 );
  114678. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  114679. zTName = pE->pLeft->u.zToken;
  114680. }
  114681. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  114682. Table *pTab = pFrom->pTab;
  114683. Select *pSub = pFrom->pSelect;
  114684. char *zTabName = pFrom->zAlias;
  114685. const char *zSchemaName = 0;
  114686. int iDb;
  114687. if( zTabName==0 ){
  114688. zTabName = pTab->zName;
  114689. }
  114690. if( db->mallocFailed ) break;
  114691. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  114692. pSub = 0;
  114693. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  114694. continue;
  114695. }
  114696. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  114697. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  114698. }
  114699. for(j=0; j<pTab->nCol; j++){
  114700. char *zName = pTab->aCol[j].zName;
  114701. char *zColname; /* The computed column name */
  114702. char *zToFree; /* Malloced string that needs to be freed */
  114703. Token sColname; /* Computed column name as a token */
  114704. assert( zName );
  114705. if( zTName && pSub
  114706. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  114707. ){
  114708. continue;
  114709. }
  114710. /* If a column is marked as 'hidden', omit it from the expanded
  114711. ** result-set list unless the SELECT has the SF_IncludeHidden
  114712. ** bit set.
  114713. */
  114714. if( (p->selFlags & SF_IncludeHidden)==0
  114715. && IsHiddenColumn(&pTab->aCol[j])
  114716. ){
  114717. continue;
  114718. }
  114719. tableSeen = 1;
  114720. if( i>0 && zTName==0 ){
  114721. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  114722. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  114723. ){
  114724. /* In a NATURAL join, omit the join columns from the
  114725. ** table to the right of the join */
  114726. continue;
  114727. }
  114728. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  114729. /* In a join with a USING clause, omit columns in the
  114730. ** using clause from the table on the right. */
  114731. continue;
  114732. }
  114733. }
  114734. pRight = sqlite3Expr(db, TK_ID, zName);
  114735. zColname = zName;
  114736. zToFree = 0;
  114737. if( longNames || pTabList->nSrc>1 ){
  114738. Expr *pLeft;
  114739. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  114740. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  114741. if( zSchemaName ){
  114742. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  114743. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  114744. }
  114745. if( longNames ){
  114746. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  114747. zToFree = zColname;
  114748. }
  114749. }else{
  114750. pExpr = pRight;
  114751. }
  114752. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  114753. sqlite3TokenInit(&sColname, zColname);
  114754. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  114755. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  114756. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  114757. if( pSub ){
  114758. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  114759. testcase( pX->zSpan==0 );
  114760. }else{
  114761. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  114762. zSchemaName, zTabName, zColname);
  114763. testcase( pX->zSpan==0 );
  114764. }
  114765. pX->bSpanIsTab = 1;
  114766. }
  114767. sqlite3DbFree(db, zToFree);
  114768. }
  114769. }
  114770. if( !tableSeen ){
  114771. if( zTName ){
  114772. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  114773. }else{
  114774. sqlite3ErrorMsg(pParse, "no tables specified");
  114775. }
  114776. }
  114777. }
  114778. }
  114779. sqlite3ExprListDelete(db, pEList);
  114780. p->pEList = pNew;
  114781. }
  114782. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  114783. sqlite3ErrorMsg(pParse, "too many columns in result set");
  114784. return WRC_Abort;
  114785. }
  114786. return WRC_Continue;
  114787. }
  114788. /*
  114789. ** No-op routine for the parse-tree walker.
  114790. **
  114791. ** When this routine is the Walker.xExprCallback then expression trees
  114792. ** are walked without any actions being taken at each node. Presumably,
  114793. ** when this routine is used for Walker.xExprCallback then
  114794. ** Walker.xSelectCallback is set to do something useful for every
  114795. ** subquery in the parser tree.
  114796. */
  114797. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  114798. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  114799. return WRC_Continue;
  114800. }
  114801. /*
  114802. ** No-op routine for the parse-tree walker for SELECT statements.
  114803. ** subquery in the parser tree.
  114804. */
  114805. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  114806. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  114807. return WRC_Continue;
  114808. }
  114809. #if SQLITE_DEBUG
  114810. /*
  114811. ** Always assert. This xSelectCallback2 implementation proves that the
  114812. ** xSelectCallback2 is never invoked.
  114813. */
  114814. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  114815. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  114816. assert( 0 );
  114817. }
  114818. #endif
  114819. /*
  114820. ** This routine "expands" a SELECT statement and all of its subqueries.
  114821. ** For additional information on what it means to "expand" a SELECT
  114822. ** statement, see the comment on the selectExpand worker callback above.
  114823. **
  114824. ** Expanding a SELECT statement is the first step in processing a
  114825. ** SELECT statement. The SELECT statement must be expanded before
  114826. ** name resolution is performed.
  114827. **
  114828. ** If anything goes wrong, an error message is written into pParse.
  114829. ** The calling function can detect the problem by looking at pParse->nErr
  114830. ** and/or pParse->db->mallocFailed.
  114831. */
  114832. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  114833. Walker w;
  114834. w.xExprCallback = sqlite3ExprWalkNoop;
  114835. w.pParse = pParse;
  114836. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  114837. w.xSelectCallback = convertCompoundSelectToSubquery;
  114838. w.xSelectCallback2 = 0;
  114839. sqlite3WalkSelect(&w, pSelect);
  114840. }
  114841. w.xSelectCallback = selectExpander;
  114842. w.xSelectCallback2 = selectPopWith;
  114843. sqlite3WalkSelect(&w, pSelect);
  114844. }
  114845. #ifndef SQLITE_OMIT_SUBQUERY
  114846. /*
  114847. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  114848. ** interface.
  114849. **
  114850. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  114851. ** information to the Table structure that represents the result set
  114852. ** of that subquery.
  114853. **
  114854. ** The Table structure that represents the result set was constructed
  114855. ** by selectExpander() but the type and collation information was omitted
  114856. ** at that point because identifiers had not yet been resolved. This
  114857. ** routine is called after identifier resolution.
  114858. */
  114859. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  114860. Parse *pParse;
  114861. int i;
  114862. SrcList *pTabList;
  114863. struct SrcList_item *pFrom;
  114864. assert( p->selFlags & SF_Resolved );
  114865. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  114866. p->selFlags |= SF_HasTypeInfo;
  114867. pParse = pWalker->pParse;
  114868. pTabList = p->pSrc;
  114869. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  114870. Table *pTab = pFrom->pTab;
  114871. assert( pTab!=0 );
  114872. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  114873. /* A sub-query in the FROM clause of a SELECT */
  114874. Select *pSel = pFrom->pSelect;
  114875. if( pSel ){
  114876. while( pSel->pPrior ) pSel = pSel->pPrior;
  114877. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  114878. }
  114879. }
  114880. }
  114881. }
  114882. #endif
  114883. /*
  114884. ** This routine adds datatype and collating sequence information to
  114885. ** the Table structures of all FROM-clause subqueries in a
  114886. ** SELECT statement.
  114887. **
  114888. ** Use this routine after name resolution.
  114889. */
  114890. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  114891. #ifndef SQLITE_OMIT_SUBQUERY
  114892. Walker w;
  114893. w.xSelectCallback = sqlite3SelectWalkNoop;
  114894. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  114895. w.xExprCallback = sqlite3ExprWalkNoop;
  114896. w.pParse = pParse;
  114897. sqlite3WalkSelect(&w, pSelect);
  114898. #endif
  114899. }
  114900. /*
  114901. ** This routine sets up a SELECT statement for processing. The
  114902. ** following is accomplished:
  114903. **
  114904. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  114905. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  114906. ** * ON and USING clauses are shifted into WHERE statements
  114907. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  114908. ** * Identifiers in expression are matched to tables.
  114909. **
  114910. ** This routine acts recursively on all subqueries within the SELECT.
  114911. */
  114912. SQLITE_PRIVATE void sqlite3SelectPrep(
  114913. Parse *pParse, /* The parser context */
  114914. Select *p, /* The SELECT statement being coded. */
  114915. NameContext *pOuterNC /* Name context for container */
  114916. ){
  114917. assert( p!=0 || pParse->db->mallocFailed );
  114918. if( pParse->db->mallocFailed ) return;
  114919. if( p->selFlags & SF_HasTypeInfo ) return;
  114920. sqlite3SelectExpand(pParse, p);
  114921. if( pParse->nErr || pParse->db->mallocFailed ) return;
  114922. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  114923. if( pParse->nErr || pParse->db->mallocFailed ) return;
  114924. sqlite3SelectAddTypeInfo(pParse, p);
  114925. }
  114926. /*
  114927. ** Reset the aggregate accumulator.
  114928. **
  114929. ** The aggregate accumulator is a set of memory cells that hold
  114930. ** intermediate results while calculating an aggregate. This
  114931. ** routine generates code that stores NULLs in all of those memory
  114932. ** cells.
  114933. */
  114934. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  114935. Vdbe *v = pParse->pVdbe;
  114936. int i;
  114937. struct AggInfo_func *pFunc;
  114938. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  114939. if( nReg==0 ) return;
  114940. #ifdef SQLITE_DEBUG
  114941. /* Verify that all AggInfo registers are within the range specified by
  114942. ** AggInfo.mnReg..AggInfo.mxReg */
  114943. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  114944. for(i=0; i<pAggInfo->nColumn; i++){
  114945. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  114946. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  114947. }
  114948. for(i=0; i<pAggInfo->nFunc; i++){
  114949. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  114950. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  114951. }
  114952. #endif
  114953. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  114954. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  114955. if( pFunc->iDistinct>=0 ){
  114956. Expr *pE = pFunc->pExpr;
  114957. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  114958. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  114959. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  114960. "argument");
  114961. pFunc->iDistinct = -1;
  114962. }else{
  114963. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  114964. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  114965. (char*)pKeyInfo, P4_KEYINFO);
  114966. }
  114967. }
  114968. }
  114969. }
  114970. /*
  114971. ** Invoke the OP_AggFinalize opcode for every aggregate function
  114972. ** in the AggInfo structure.
  114973. */
  114974. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  114975. Vdbe *v = pParse->pVdbe;
  114976. int i;
  114977. struct AggInfo_func *pF;
  114978. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  114979. ExprList *pList = pF->pExpr->x.pList;
  114980. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  114981. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  114982. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  114983. }
  114984. }
  114985. /*
  114986. ** Update the accumulator memory cells for an aggregate based on
  114987. ** the current cursor position.
  114988. */
  114989. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  114990. Vdbe *v = pParse->pVdbe;
  114991. int i;
  114992. int regHit = 0;
  114993. int addrHitTest = 0;
  114994. struct AggInfo_func *pF;
  114995. struct AggInfo_col *pC;
  114996. pAggInfo->directMode = 1;
  114997. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  114998. int nArg;
  114999. int addrNext = 0;
  115000. int regAgg;
  115001. ExprList *pList = pF->pExpr->x.pList;
  115002. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  115003. if( pList ){
  115004. nArg = pList->nExpr;
  115005. regAgg = sqlite3GetTempRange(pParse, nArg);
  115006. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  115007. }else{
  115008. nArg = 0;
  115009. regAgg = 0;
  115010. }
  115011. if( pF->iDistinct>=0 ){
  115012. addrNext = sqlite3VdbeMakeLabel(v);
  115013. testcase( nArg==0 ); /* Error condition */
  115014. testcase( nArg>1 ); /* Also an error */
  115015. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  115016. }
  115017. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  115018. CollSeq *pColl = 0;
  115019. struct ExprList_item *pItem;
  115020. int j;
  115021. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  115022. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  115023. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  115024. }
  115025. if( !pColl ){
  115026. pColl = pParse->db->pDfltColl;
  115027. }
  115028. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  115029. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  115030. }
  115031. sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
  115032. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  115033. sqlite3VdbeChangeP5(v, (u8)nArg);
  115034. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  115035. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  115036. if( addrNext ){
  115037. sqlite3VdbeResolveLabel(v, addrNext);
  115038. sqlite3ExprCacheClear(pParse);
  115039. }
  115040. }
  115041. /* Before populating the accumulator registers, clear the column cache.
  115042. ** Otherwise, if any of the required column values are already present
  115043. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  115044. ** to pC->iMem. But by the time the value is used, the original register
  115045. ** may have been used, invalidating the underlying buffer holding the
  115046. ** text or blob value. See ticket [883034dcb5].
  115047. **
  115048. ** Another solution would be to change the OP_SCopy used to copy cached
  115049. ** values to an OP_Copy.
  115050. */
  115051. if( regHit ){
  115052. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  115053. }
  115054. sqlite3ExprCacheClear(pParse);
  115055. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  115056. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  115057. }
  115058. pAggInfo->directMode = 0;
  115059. sqlite3ExprCacheClear(pParse);
  115060. if( addrHitTest ){
  115061. sqlite3VdbeJumpHere(v, addrHitTest);
  115062. }
  115063. }
  115064. /*
  115065. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  115066. ** count(*) query ("SELECT count(*) FROM pTab").
  115067. */
  115068. #ifndef SQLITE_OMIT_EXPLAIN
  115069. static void explainSimpleCount(
  115070. Parse *pParse, /* Parse context */
  115071. Table *pTab, /* Table being queried */
  115072. Index *pIdx /* Index used to optimize scan, or NULL */
  115073. ){
  115074. if( pParse->explain==2 ){
  115075. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  115076. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  115077. pTab->zName,
  115078. bCover ? " USING COVERING INDEX " : "",
  115079. bCover ? pIdx->zName : ""
  115080. );
  115081. sqlite3VdbeAddOp4(
  115082. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  115083. );
  115084. }
  115085. }
  115086. #else
  115087. # define explainSimpleCount(a,b,c)
  115088. #endif
  115089. /*
  115090. ** Context object for havingToWhereExprCb().
  115091. */
  115092. struct HavingToWhereCtx {
  115093. Expr **ppWhere;
  115094. ExprList *pGroupBy;
  115095. };
  115096. /*
  115097. ** sqlite3WalkExpr() callback used by havingToWhere().
  115098. **
  115099. ** If the node passed to the callback is a TK_AND node, return
  115100. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  115101. **
  115102. ** Otherwise, return WRC_Prune. In this case, also check if the
  115103. ** sub-expression matches the criteria for being moved to the WHERE
  115104. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  115105. ** within the HAVING expression with a constant "1".
  115106. */
  115107. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  115108. if( pExpr->op!=TK_AND ){
  115109. struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
  115110. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
  115111. sqlite3 *db = pWalker->pParse->db;
  115112. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  115113. if( pNew ){
  115114. Expr *pWhere = *(p->ppWhere);
  115115. SWAP(Expr, *pNew, *pExpr);
  115116. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  115117. *(p->ppWhere) = pNew;
  115118. }
  115119. }
  115120. return WRC_Prune;
  115121. }
  115122. return WRC_Continue;
  115123. }
  115124. /*
  115125. ** Transfer eligible terms from the HAVING clause of a query, which is
  115126. ** processed after grouping, to the WHERE clause, which is processed before
  115127. ** grouping. For example, the query:
  115128. **
  115129. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  115130. **
  115131. ** can be rewritten as:
  115132. **
  115133. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  115134. **
  115135. ** A term of the HAVING expression is eligible for transfer if it consists
  115136. ** entirely of constants and expressions that are also GROUP BY terms that
  115137. ** use the "BINARY" collation sequence.
  115138. */
  115139. static void havingToWhere(
  115140. Parse *pParse,
  115141. ExprList *pGroupBy,
  115142. Expr *pHaving,
  115143. Expr **ppWhere
  115144. ){
  115145. struct HavingToWhereCtx sCtx;
  115146. Walker sWalker;
  115147. sCtx.ppWhere = ppWhere;
  115148. sCtx.pGroupBy = pGroupBy;
  115149. memset(&sWalker, 0, sizeof(sWalker));
  115150. sWalker.pParse = pParse;
  115151. sWalker.xExprCallback = havingToWhereExprCb;
  115152. sWalker.u.pHavingCtx = &sCtx;
  115153. sqlite3WalkExpr(&sWalker, pHaving);
  115154. }
  115155. /*
  115156. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  115157. ** If it is, then return the SrcList_item for the prior view. If it is not,
  115158. ** then return 0.
  115159. */
  115160. static struct SrcList_item *isSelfJoinView(
  115161. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  115162. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  115163. ){
  115164. struct SrcList_item *pItem;
  115165. for(pItem = pTabList->a; pItem<pThis; pItem++){
  115166. if( pItem->pSelect==0 ) continue;
  115167. if( pItem->fg.viaCoroutine ) continue;
  115168. if( pItem->zName==0 ) continue;
  115169. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  115170. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  115171. if( sqlite3ExprCompare(0,
  115172. pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
  115173. ){
  115174. /* The view was modified by some other optimization such as
  115175. ** pushDownWhereTerms() */
  115176. continue;
  115177. }
  115178. return pItem;
  115179. }
  115180. return 0;
  115181. }
  115182. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  115183. /*
  115184. ** Attempt to transform a query of the form
  115185. **
  115186. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  115187. **
  115188. ** Into this:
  115189. **
  115190. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  115191. **
  115192. ** The transformation only works if all of the following are true:
  115193. **
  115194. ** * The subquery is a UNION ALL of two or more terms
  115195. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  115196. ** * The outer query is a simple count(*)
  115197. **
  115198. ** Return TRUE if the optimization is undertaken.
  115199. */
  115200. static int countOfViewOptimization(Parse *pParse, Select *p){
  115201. Select *pSub, *pPrior;
  115202. Expr *pExpr;
  115203. Expr *pCount;
  115204. sqlite3 *db;
  115205. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  115206. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  115207. pExpr = p->pEList->a[0].pExpr;
  115208. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  115209. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  115210. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  115211. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  115212. pSub = p->pSrc->a[0].pSelect;
  115213. if( pSub==0 ) return 0; /* The FROM is a subquery */
  115214. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  115215. do{
  115216. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  115217. if( pSub->pWhere ) return 0; /* No WHERE clause */
  115218. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  115219. pSub = pSub->pPrior; /* Repeat over compound */
  115220. }while( pSub );
  115221. /* If we reach this point then it is OK to perform the transformation */
  115222. db = pParse->db;
  115223. pCount = pExpr;
  115224. pExpr = 0;
  115225. pSub = p->pSrc->a[0].pSelect;
  115226. p->pSrc->a[0].pSelect = 0;
  115227. sqlite3SrcListDelete(db, p->pSrc);
  115228. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  115229. while( pSub ){
  115230. Expr *pTerm;
  115231. pPrior = pSub->pPrior;
  115232. pSub->pPrior = 0;
  115233. pSub->pNext = 0;
  115234. pSub->selFlags |= SF_Aggregate;
  115235. pSub->selFlags &= ~SF_Compound;
  115236. pSub->nSelectRow = 0;
  115237. sqlite3ExprListDelete(db, pSub->pEList);
  115238. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  115239. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  115240. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  115241. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  115242. if( pExpr==0 ){
  115243. pExpr = pTerm;
  115244. }else{
  115245. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  115246. }
  115247. pSub = pPrior;
  115248. }
  115249. p->pEList->a[0].pExpr = pExpr;
  115250. p->selFlags &= ~SF_Aggregate;
  115251. #if SELECTTRACE_ENABLED
  115252. if( sqlite3SelectTrace & 0x400 ){
  115253. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  115254. sqlite3TreeViewSelect(0, p, 0);
  115255. }
  115256. #endif
  115257. return 1;
  115258. }
  115259. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  115260. /*
  115261. ** Generate code for the SELECT statement given in the p argument.
  115262. **
  115263. ** The results are returned according to the SelectDest structure.
  115264. ** See comments in sqliteInt.h for further information.
  115265. **
  115266. ** This routine returns the number of errors. If any errors are
  115267. ** encountered, then an appropriate error message is left in
  115268. ** pParse->zErrMsg.
  115269. **
  115270. ** This routine does NOT free the Select structure passed in. The
  115271. ** calling function needs to do that.
  115272. */
  115273. SQLITE_PRIVATE int sqlite3Select(
  115274. Parse *pParse, /* The parser context */
  115275. Select *p, /* The SELECT statement being coded. */
  115276. SelectDest *pDest /* What to do with the query results */
  115277. ){
  115278. int i, j; /* Loop counters */
  115279. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  115280. Vdbe *v; /* The virtual machine under construction */
  115281. int isAgg; /* True for select lists like "count(*)" */
  115282. ExprList *pEList = 0; /* List of columns to extract. */
  115283. SrcList *pTabList; /* List of tables to select from */
  115284. Expr *pWhere; /* The WHERE clause. May be NULL */
  115285. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  115286. Expr *pHaving; /* The HAVING clause. May be NULL */
  115287. int rc = 1; /* Value to return from this function */
  115288. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  115289. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  115290. AggInfo sAggInfo; /* Information used by aggregate queries */
  115291. int iEnd; /* Address of the end of the query */
  115292. sqlite3 *db; /* The database connection */
  115293. #ifndef SQLITE_OMIT_EXPLAIN
  115294. int iRestoreSelectId = pParse->iSelectId;
  115295. pParse->iSelectId = pParse->iNextSelectId++;
  115296. #endif
  115297. db = pParse->db;
  115298. if( p==0 || db->mallocFailed || pParse->nErr ){
  115299. return 1;
  115300. }
  115301. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  115302. memset(&sAggInfo, 0, sizeof(sAggInfo));
  115303. #if SELECTTRACE_ENABLED
  115304. pParse->nSelectIndent++;
  115305. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  115306. if( sqlite3SelectTrace & 0x100 ){
  115307. sqlite3TreeViewSelect(0, p, 0);
  115308. }
  115309. #endif
  115310. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  115311. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  115312. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  115313. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  115314. if( IgnorableOrderby(pDest) ){
  115315. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  115316. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  115317. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  115318. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  115319. /* If ORDER BY makes no difference in the output then neither does
  115320. ** DISTINCT so it can be removed too. */
  115321. sqlite3ExprListDelete(db, p->pOrderBy);
  115322. p->pOrderBy = 0;
  115323. p->selFlags &= ~SF_Distinct;
  115324. }
  115325. sqlite3SelectPrep(pParse, p, 0);
  115326. memset(&sSort, 0, sizeof(sSort));
  115327. sSort.pOrderBy = p->pOrderBy;
  115328. pTabList = p->pSrc;
  115329. if( pParse->nErr || db->mallocFailed ){
  115330. goto select_end;
  115331. }
  115332. assert( p->pEList!=0 );
  115333. isAgg = (p->selFlags & SF_Aggregate)!=0;
  115334. #if SELECTTRACE_ENABLED
  115335. if( sqlite3SelectTrace & 0x100 ){
  115336. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  115337. sqlite3TreeViewSelect(0, p, 0);
  115338. }
  115339. #endif
  115340. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  115341. ** does not already exist */
  115342. v = sqlite3GetVdbe(pParse);
  115343. if( v==0 ) goto select_end;
  115344. if( pDest->eDest==SRT_Output ){
  115345. generateColumnNames(pParse, p);
  115346. }
  115347. /* Try to flatten subqueries in the FROM clause up into the main query
  115348. */
  115349. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  115350. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  115351. struct SrcList_item *pItem = &pTabList->a[i];
  115352. Select *pSub = pItem->pSelect;
  115353. Table *pTab = pItem->pTab;
  115354. if( pSub==0 ) continue;
  115355. /* Catch mismatch in the declared columns of a view and the number of
  115356. ** columns in the SELECT on the RHS */
  115357. if( pTab->nCol!=pSub->pEList->nExpr ){
  115358. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  115359. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  115360. goto select_end;
  115361. }
  115362. /* Do not try to flatten an aggregate subquery.
  115363. **
  115364. ** Flattening an aggregate subquery is only possible if the outer query
  115365. ** is not a join. But if the outer query is not a join, then the subquery
  115366. ** will be implemented as a co-routine and there is no advantage to
  115367. ** flattening in that case.
  115368. */
  115369. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  115370. assert( pSub->pGroupBy==0 );
  115371. /* If the subquery contains an ORDER BY clause and if
  115372. ** it will be implemented as a co-routine, then do not flatten. This
  115373. ** restriction allows SQL constructs like this:
  115374. **
  115375. ** SELECT expensive_function(x)
  115376. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  115377. **
  115378. ** The expensive_function() is only computed on the 10 rows that
  115379. ** are output, rather than every row of the table.
  115380. */
  115381. if( pSub->pOrderBy!=0
  115382. && i==0
  115383. && (pTabList->nSrc==1
  115384. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  115385. ){
  115386. continue;
  115387. }
  115388. if( flattenSubquery(pParse, p, i, isAgg) ){
  115389. /* This subquery can be absorbed into its parent. */
  115390. i = -1;
  115391. }
  115392. pTabList = p->pSrc;
  115393. if( db->mallocFailed ) goto select_end;
  115394. if( !IgnorableOrderby(pDest) ){
  115395. sSort.pOrderBy = p->pOrderBy;
  115396. }
  115397. }
  115398. #endif
  115399. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  115400. /* Handle compound SELECT statements using the separate multiSelect()
  115401. ** procedure.
  115402. */
  115403. if( p->pPrior ){
  115404. rc = multiSelect(pParse, p, pDest);
  115405. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  115406. #if SELECTTRACE_ENABLED
  115407. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  115408. pParse->nSelectIndent--;
  115409. #endif
  115410. return rc;
  115411. }
  115412. #endif
  115413. /* For each term in the FROM clause, do two things:
  115414. ** (1) Authorized unreferenced tables
  115415. ** (2) Generate code for all sub-queries
  115416. */
  115417. for(i=0; i<pTabList->nSrc; i++){
  115418. struct SrcList_item *pItem = &pTabList->a[i];
  115419. SelectDest dest;
  115420. Select *pSub;
  115421. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  115422. const char *zSavedAuthContext;
  115423. #endif
  115424. /* Issue SQLITE_READ authorizations with a fake column name for any
  115425. ** tables that are referenced but from which no values are extracted.
  115426. ** Examples of where these kinds of null SQLITE_READ authorizations
  115427. ** would occur:
  115428. **
  115429. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  115430. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  115431. **
  115432. ** The fake column name is an empty string. It is possible for a table to
  115433. ** have a column named by the empty string, in which case there is no way to
  115434. ** distinguish between an unreferenced table and an actual reference to the
  115435. ** "" column. The original design was for the fake column name to be a NULL,
  115436. ** which would be unambiguous. But legacy authorization callbacks might
  115437. ** assume the column name is non-NULL and segfault. The use of an empty
  115438. ** string for the fake column name seems safer.
  115439. */
  115440. if( pItem->colUsed==0 ){
  115441. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  115442. }
  115443. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  115444. /* Generate code for all sub-queries in the FROM clause
  115445. */
  115446. pSub = pItem->pSelect;
  115447. if( pSub==0 ) continue;
  115448. /* Sometimes the code for a subquery will be generated more than
  115449. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  115450. ** for example. In that case, do not regenerate the code to manifest
  115451. ** a view or the co-routine to implement a view. The first instance
  115452. ** is sufficient, though the subroutine to manifest the view does need
  115453. ** to be invoked again. */
  115454. if( pItem->addrFillSub ){
  115455. if( pItem->fg.viaCoroutine==0 ){
  115456. /* The subroutine that manifests the view might be a one-time routine,
  115457. ** or it might need to be rerun on each iteration because it
  115458. ** encodes a correlated subquery. */
  115459. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  115460. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  115461. }
  115462. continue;
  115463. }
  115464. /* Increment Parse.nHeight by the height of the largest expression
  115465. ** tree referred to by this, the parent select. The child select
  115466. ** may contain expression trees of at most
  115467. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  115468. ** more conservative than necessary, but much easier than enforcing
  115469. ** an exact limit.
  115470. */
  115471. pParse->nHeight += sqlite3SelectExprHeight(p);
  115472. /* Make copies of constant WHERE-clause terms in the outer query down
  115473. ** inside the subquery. This can help the subquery to run more efficiently.
  115474. */
  115475. if( (pItem->fg.jointype & JT_OUTER)==0
  115476. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
  115477. ){
  115478. #if SELECTTRACE_ENABLED
  115479. if( sqlite3SelectTrace & 0x100 ){
  115480. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  115481. sqlite3TreeViewSelect(0, p, 0);
  115482. }
  115483. #endif
  115484. }
  115485. zSavedAuthContext = pParse->zAuthContext;
  115486. pParse->zAuthContext = pItem->zName;
  115487. /* Generate code to implement the subquery
  115488. **
  115489. ** The subquery is implemented as a co-routine if the subquery is
  115490. ** guaranteed to be the outer loop (so that it does not need to be
  115491. ** computed more than once)
  115492. **
  115493. ** TODO: Are there other reasons beside (1) to use a co-routine
  115494. ** implementation?
  115495. */
  115496. if( i==0
  115497. && (pTabList->nSrc==1
  115498. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  115499. ){
  115500. /* Implement a co-routine that will return a single row of the result
  115501. ** set on each invocation.
  115502. */
  115503. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  115504. pItem->regReturn = ++pParse->nMem;
  115505. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  115506. VdbeComment((v, "%s", pItem->pTab->zName));
  115507. pItem->addrFillSub = addrTop;
  115508. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  115509. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  115510. sqlite3Select(pParse, pSub, &dest);
  115511. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  115512. pItem->fg.viaCoroutine = 1;
  115513. pItem->regResult = dest.iSdst;
  115514. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  115515. sqlite3VdbeJumpHere(v, addrTop-1);
  115516. sqlite3ClearTempRegCache(pParse);
  115517. }else{
  115518. /* Generate a subroutine that will fill an ephemeral table with
  115519. ** the content of this subquery. pItem->addrFillSub will point
  115520. ** to the address of the generated subroutine. pItem->regReturn
  115521. ** is a register allocated to hold the subroutine return address
  115522. */
  115523. int topAddr;
  115524. int onceAddr = 0;
  115525. int retAddr;
  115526. struct SrcList_item *pPrior;
  115527. assert( pItem->addrFillSub==0 );
  115528. pItem->regReturn = ++pParse->nMem;
  115529. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  115530. pItem->addrFillSub = topAddr+1;
  115531. if( pItem->fg.isCorrelated==0 ){
  115532. /* If the subquery is not correlated and if we are not inside of
  115533. ** a trigger, then we only need to compute the value of the subquery
  115534. ** once. */
  115535. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  115536. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  115537. }else{
  115538. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  115539. }
  115540. pPrior = isSelfJoinView(pTabList, pItem);
  115541. if( pPrior ){
  115542. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  115543. explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
  115544. assert( pPrior->pSelect!=0 );
  115545. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  115546. }else{
  115547. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  115548. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  115549. sqlite3Select(pParse, pSub, &dest);
  115550. }
  115551. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  115552. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  115553. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  115554. VdbeComment((v, "end %s", pItem->pTab->zName));
  115555. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  115556. sqlite3ClearTempRegCache(pParse);
  115557. }
  115558. if( db->mallocFailed ) goto select_end;
  115559. pParse->nHeight -= sqlite3SelectExprHeight(p);
  115560. pParse->zAuthContext = zSavedAuthContext;
  115561. #endif
  115562. }
  115563. /* Various elements of the SELECT copied into local variables for
  115564. ** convenience */
  115565. pEList = p->pEList;
  115566. pWhere = p->pWhere;
  115567. pGroupBy = p->pGroupBy;
  115568. pHaving = p->pHaving;
  115569. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  115570. #if SELECTTRACE_ENABLED
  115571. if( sqlite3SelectTrace & 0x400 ){
  115572. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  115573. sqlite3TreeViewSelect(0, p, 0);
  115574. }
  115575. #endif
  115576. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  115577. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  115578. && countOfViewOptimization(pParse, p)
  115579. ){
  115580. if( db->mallocFailed ) goto select_end;
  115581. pEList = p->pEList;
  115582. pTabList = p->pSrc;
  115583. }
  115584. #endif
  115585. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  115586. ** if the select-list is the same as the ORDER BY list, then this query
  115587. ** can be rewritten as a GROUP BY. In other words, this:
  115588. **
  115589. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  115590. **
  115591. ** is transformed to:
  115592. **
  115593. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  115594. **
  115595. ** The second form is preferred as a single index (or temp-table) may be
  115596. ** used for both the ORDER BY and DISTINCT processing. As originally
  115597. ** written the query must use a temp-table for at least one of the ORDER
  115598. ** BY and DISTINCT, and an index or separate temp-table for the other.
  115599. */
  115600. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  115601. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  115602. ){
  115603. p->selFlags &= ~SF_Distinct;
  115604. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  115605. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  115606. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  115607. ** original setting of the SF_Distinct flag, not the current setting */
  115608. assert( sDistinct.isTnct );
  115609. #if SELECTTRACE_ENABLED
  115610. if( sqlite3SelectTrace & 0x400 ){
  115611. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  115612. sqlite3TreeViewSelect(0, p, 0);
  115613. }
  115614. #endif
  115615. }
  115616. /* If there is an ORDER BY clause, then create an ephemeral index to
  115617. ** do the sorting. But this sorting ephemeral index might end up
  115618. ** being unused if the data can be extracted in pre-sorted order.
  115619. ** If that is the case, then the OP_OpenEphemeral instruction will be
  115620. ** changed to an OP_Noop once we figure out that the sorting index is
  115621. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  115622. ** that change.
  115623. */
  115624. if( sSort.pOrderBy ){
  115625. KeyInfo *pKeyInfo;
  115626. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  115627. sSort.iECursor = pParse->nTab++;
  115628. sSort.addrSortIndex =
  115629. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  115630. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  115631. (char*)pKeyInfo, P4_KEYINFO
  115632. );
  115633. }else{
  115634. sSort.addrSortIndex = -1;
  115635. }
  115636. /* If the output is destined for a temporary table, open that table.
  115637. */
  115638. if( pDest->eDest==SRT_EphemTab ){
  115639. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  115640. }
  115641. /* Set the limiter.
  115642. */
  115643. iEnd = sqlite3VdbeMakeLabel(v);
  115644. if( (p->selFlags & SF_FixedLimit)==0 ){
  115645. p->nSelectRow = 320; /* 4 billion rows */
  115646. }
  115647. computeLimitRegisters(pParse, p, iEnd);
  115648. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  115649. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  115650. sSort.sortFlags |= SORTFLAG_UseSorter;
  115651. }
  115652. /* Open an ephemeral index to use for the distinct set.
  115653. */
  115654. if( p->selFlags & SF_Distinct ){
  115655. sDistinct.tabTnct = pParse->nTab++;
  115656. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  115657. sDistinct.tabTnct, 0, 0,
  115658. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  115659. P4_KEYINFO);
  115660. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  115661. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  115662. }else{
  115663. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  115664. }
  115665. if( !isAgg && pGroupBy==0 ){
  115666. /* No aggregate functions and no GROUP BY clause */
  115667. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  115668. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  115669. wctrlFlags |= p->selFlags & SF_FixedLimit;
  115670. /* Begin the database scan. */
  115671. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  115672. p->pEList, wctrlFlags, p->nSelectRow);
  115673. if( pWInfo==0 ) goto select_end;
  115674. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  115675. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  115676. }
  115677. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  115678. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  115679. }
  115680. if( sSort.pOrderBy ){
  115681. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  115682. sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
  115683. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  115684. sSort.pOrderBy = 0;
  115685. }
  115686. }
  115687. /* If sorting index that was created by a prior OP_OpenEphemeral
  115688. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  115689. ** into an OP_Noop.
  115690. */
  115691. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  115692. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  115693. }
  115694. /* Use the standard inner loop. */
  115695. assert( p->pEList==pEList );
  115696. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  115697. sqlite3WhereContinueLabel(pWInfo),
  115698. sqlite3WhereBreakLabel(pWInfo));
  115699. /* End the database scan loop.
  115700. */
  115701. sqlite3WhereEnd(pWInfo);
  115702. }else{
  115703. /* This case when there exist aggregate functions or a GROUP BY clause
  115704. ** or both */
  115705. NameContext sNC; /* Name context for processing aggregate information */
  115706. int iAMem; /* First Mem address for storing current GROUP BY */
  115707. int iBMem; /* First Mem address for previous GROUP BY */
  115708. int iUseFlag; /* Mem address holding flag indicating that at least
  115709. ** one row of the input to the aggregator has been
  115710. ** processed */
  115711. int iAbortFlag; /* Mem address which causes query abort if positive */
  115712. int groupBySort; /* Rows come from source in GROUP BY order */
  115713. int addrEnd; /* End of processing for this SELECT */
  115714. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  115715. int sortOut = 0; /* Output register from the sorter */
  115716. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  115717. /* Remove any and all aliases between the result set and the
  115718. ** GROUP BY clause.
  115719. */
  115720. if( pGroupBy ){
  115721. int k; /* Loop counter */
  115722. struct ExprList_item *pItem; /* For looping over expression in a list */
  115723. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  115724. pItem->u.x.iAlias = 0;
  115725. }
  115726. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  115727. pItem->u.x.iAlias = 0;
  115728. }
  115729. assert( 66==sqlite3LogEst(100) );
  115730. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  115731. }else{
  115732. assert( 0==sqlite3LogEst(1) );
  115733. p->nSelectRow = 0;
  115734. }
  115735. /* If there is both a GROUP BY and an ORDER BY clause and they are
  115736. ** identical, then it may be possible to disable the ORDER BY clause
  115737. ** on the grounds that the GROUP BY will cause elements to come out
  115738. ** in the correct order. It also may not - the GROUP BY might use a
  115739. ** database index that causes rows to be grouped together as required
  115740. ** but not actually sorted. Either way, record the fact that the
  115741. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  115742. ** variable. */
  115743. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  115744. orderByGrp = 1;
  115745. }
  115746. /* Create a label to jump to when we want to abort the query */
  115747. addrEnd = sqlite3VdbeMakeLabel(v);
  115748. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  115749. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  115750. ** SELECT statement.
  115751. */
  115752. memset(&sNC, 0, sizeof(sNC));
  115753. sNC.pParse = pParse;
  115754. sNC.pSrcList = pTabList;
  115755. sNC.pAggInfo = &sAggInfo;
  115756. sAggInfo.mnReg = pParse->nMem+1;
  115757. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  115758. sAggInfo.pGroupBy = pGroupBy;
  115759. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  115760. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  115761. if( pHaving ){
  115762. if( pGroupBy ){
  115763. assert( pWhere==p->pWhere );
  115764. havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
  115765. pWhere = p->pWhere;
  115766. }
  115767. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  115768. }
  115769. sAggInfo.nAccumulator = sAggInfo.nColumn;
  115770. for(i=0; i<sAggInfo.nFunc; i++){
  115771. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  115772. sNC.ncFlags |= NC_InAggFunc;
  115773. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  115774. sNC.ncFlags &= ~NC_InAggFunc;
  115775. }
  115776. sAggInfo.mxReg = pParse->nMem;
  115777. if( db->mallocFailed ) goto select_end;
  115778. /* Processing for aggregates with GROUP BY is very different and
  115779. ** much more complex than aggregates without a GROUP BY.
  115780. */
  115781. if( pGroupBy ){
  115782. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  115783. int addr1; /* A-vs-B comparision jump */
  115784. int addrOutputRow; /* Start of subroutine that outputs a result row */
  115785. int regOutputRow; /* Return address register for output subroutine */
  115786. int addrSetAbort; /* Set the abort flag and return */
  115787. int addrTopOfLoop; /* Top of the input loop */
  115788. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  115789. int addrReset; /* Subroutine for resetting the accumulator */
  115790. int regReset; /* Return address register for reset subroutine */
  115791. /* If there is a GROUP BY clause we might need a sorting index to
  115792. ** implement it. Allocate that sorting index now. If it turns out
  115793. ** that we do not need it after all, the OP_SorterOpen instruction
  115794. ** will be converted into a Noop.
  115795. */
  115796. sAggInfo.sortingIdx = pParse->nTab++;
  115797. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  115798. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  115799. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  115800. 0, (char*)pKeyInfo, P4_KEYINFO);
  115801. /* Initialize memory locations used by GROUP BY aggregate processing
  115802. */
  115803. iUseFlag = ++pParse->nMem;
  115804. iAbortFlag = ++pParse->nMem;
  115805. regOutputRow = ++pParse->nMem;
  115806. addrOutputRow = sqlite3VdbeMakeLabel(v);
  115807. regReset = ++pParse->nMem;
  115808. addrReset = sqlite3VdbeMakeLabel(v);
  115809. iAMem = pParse->nMem + 1;
  115810. pParse->nMem += pGroupBy->nExpr;
  115811. iBMem = pParse->nMem + 1;
  115812. pParse->nMem += pGroupBy->nExpr;
  115813. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  115814. VdbeComment((v, "clear abort flag"));
  115815. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  115816. VdbeComment((v, "indicate accumulator empty"));
  115817. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  115818. /* Begin a loop that will extract all source rows in GROUP BY order.
  115819. ** This might involve two separate loops with an OP_Sort in between, or
  115820. ** it might be a single loop that uses an index to extract information
  115821. ** in the right order to begin with.
  115822. */
  115823. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  115824. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  115825. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  115826. );
  115827. if( pWInfo==0 ) goto select_end;
  115828. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  115829. /* The optimizer is able to deliver rows in group by order so
  115830. ** we do not have to sort. The OP_OpenEphemeral table will be
  115831. ** cancelled later because we still need to use the pKeyInfo
  115832. */
  115833. groupBySort = 0;
  115834. }else{
  115835. /* Rows are coming out in undetermined order. We have to push
  115836. ** each row into a sorting index, terminate the first loop,
  115837. ** then loop over the sorting index in order to get the output
  115838. ** in sorted order
  115839. */
  115840. int regBase;
  115841. int regRecord;
  115842. int nCol;
  115843. int nGroupBy;
  115844. explainTempTable(pParse,
  115845. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  115846. "DISTINCT" : "GROUP BY");
  115847. groupBySort = 1;
  115848. nGroupBy = pGroupBy->nExpr;
  115849. nCol = nGroupBy;
  115850. j = nGroupBy;
  115851. for(i=0; i<sAggInfo.nColumn; i++){
  115852. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  115853. nCol++;
  115854. j++;
  115855. }
  115856. }
  115857. regBase = sqlite3GetTempRange(pParse, nCol);
  115858. sqlite3ExprCacheClear(pParse);
  115859. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  115860. j = nGroupBy;
  115861. for(i=0; i<sAggInfo.nColumn; i++){
  115862. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  115863. if( pCol->iSorterColumn>=j ){
  115864. int r1 = j + regBase;
  115865. sqlite3ExprCodeGetColumnToReg(pParse,
  115866. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  115867. j++;
  115868. }
  115869. }
  115870. regRecord = sqlite3GetTempReg(pParse);
  115871. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  115872. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  115873. sqlite3ReleaseTempReg(pParse, regRecord);
  115874. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  115875. sqlite3WhereEnd(pWInfo);
  115876. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  115877. sortOut = sqlite3GetTempReg(pParse);
  115878. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  115879. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  115880. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  115881. sAggInfo.useSortingIdx = 1;
  115882. sqlite3ExprCacheClear(pParse);
  115883. }
  115884. /* If the index or temporary table used by the GROUP BY sort
  115885. ** will naturally deliver rows in the order required by the ORDER BY
  115886. ** clause, cancel the ephemeral table open coded earlier.
  115887. **
  115888. ** This is an optimization - the correct answer should result regardless.
  115889. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  115890. ** disable this optimization for testing purposes. */
  115891. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  115892. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  115893. ){
  115894. sSort.pOrderBy = 0;
  115895. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  115896. }
  115897. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  115898. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  115899. ** Then compare the current GROUP BY terms against the GROUP BY terms
  115900. ** from the previous row currently stored in a0, a1, a2...
  115901. */
  115902. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  115903. sqlite3ExprCacheClear(pParse);
  115904. if( groupBySort ){
  115905. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  115906. sortOut, sortPTab);
  115907. }
  115908. for(j=0; j<pGroupBy->nExpr; j++){
  115909. if( groupBySort ){
  115910. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  115911. }else{
  115912. sAggInfo.directMode = 1;
  115913. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  115914. }
  115915. }
  115916. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  115917. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  115918. addr1 = sqlite3VdbeCurrentAddr(v);
  115919. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  115920. /* Generate code that runs whenever the GROUP BY changes.
  115921. ** Changes in the GROUP BY are detected by the previous code
  115922. ** block. If there were no changes, this block is skipped.
  115923. **
  115924. ** This code copies current group by terms in b0,b1,b2,...
  115925. ** over to a0,a1,a2. It then calls the output subroutine
  115926. ** and resets the aggregate accumulator registers in preparation
  115927. ** for the next GROUP BY batch.
  115928. */
  115929. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  115930. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  115931. VdbeComment((v, "output one row"));
  115932. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  115933. VdbeComment((v, "check abort flag"));
  115934. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  115935. VdbeComment((v, "reset accumulator"));
  115936. /* Update the aggregate accumulators based on the content of
  115937. ** the current row
  115938. */
  115939. sqlite3VdbeJumpHere(v, addr1);
  115940. updateAccumulator(pParse, &sAggInfo);
  115941. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  115942. VdbeComment((v, "indicate data in accumulator"));
  115943. /* End of the loop
  115944. */
  115945. if( groupBySort ){
  115946. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  115947. VdbeCoverage(v);
  115948. }else{
  115949. sqlite3WhereEnd(pWInfo);
  115950. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  115951. }
  115952. /* Output the final row of result
  115953. */
  115954. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  115955. VdbeComment((v, "output final row"));
  115956. /* Jump over the subroutines
  115957. */
  115958. sqlite3VdbeGoto(v, addrEnd);
  115959. /* Generate a subroutine that outputs a single row of the result
  115960. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  115961. ** is less than or equal to zero, the subroutine is a no-op. If
  115962. ** the processing calls for the query to abort, this subroutine
  115963. ** increments the iAbortFlag memory location before returning in
  115964. ** order to signal the caller to abort.
  115965. */
  115966. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  115967. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  115968. VdbeComment((v, "set abort flag"));
  115969. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  115970. sqlite3VdbeResolveLabel(v, addrOutputRow);
  115971. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  115972. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  115973. VdbeCoverage(v);
  115974. VdbeComment((v, "Groupby result generator entry point"));
  115975. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  115976. finalizeAggFunctions(pParse, &sAggInfo);
  115977. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  115978. selectInnerLoop(pParse, p, -1, &sSort,
  115979. &sDistinct, pDest,
  115980. addrOutputRow+1, addrSetAbort);
  115981. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  115982. VdbeComment((v, "end groupby result generator"));
  115983. /* Generate a subroutine that will reset the group-by accumulator
  115984. */
  115985. sqlite3VdbeResolveLabel(v, addrReset);
  115986. resetAccumulator(pParse, &sAggInfo);
  115987. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  115988. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  115989. else {
  115990. ExprList *pDel = 0;
  115991. #ifndef SQLITE_OMIT_BTREECOUNT
  115992. Table *pTab;
  115993. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  115994. /* If isSimpleCount() returns a pointer to a Table structure, then
  115995. ** the SQL statement is of the form:
  115996. **
  115997. ** SELECT count(*) FROM <tbl>
  115998. **
  115999. ** where the Table structure returned represents table <tbl>.
  116000. **
  116001. ** This statement is so common that it is optimized specially. The
  116002. ** OP_Count instruction is executed either on the intkey table that
  116003. ** contains the data for table <tbl> or on one of its indexes. It
  116004. ** is better to execute the op on an index, as indexes are almost
  116005. ** always spread across less pages than their corresponding tables.
  116006. */
  116007. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  116008. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  116009. Index *pIdx; /* Iterator variable */
  116010. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  116011. Index *pBest = 0; /* Best index found so far */
  116012. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  116013. sqlite3CodeVerifySchema(pParse, iDb);
  116014. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  116015. /* Search for the index that has the lowest scan cost.
  116016. **
  116017. ** (2011-04-15) Do not do a full scan of an unordered index.
  116018. **
  116019. ** (2013-10-03) Do not count the entries in a partial index.
  116020. **
  116021. ** In practice the KeyInfo structure will not be used. It is only
  116022. ** passed to keep OP_OpenRead happy.
  116023. */
  116024. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  116025. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  116026. if( pIdx->bUnordered==0
  116027. && pIdx->szIdxRow<pTab->szTabRow
  116028. && pIdx->pPartIdxWhere==0
  116029. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  116030. ){
  116031. pBest = pIdx;
  116032. }
  116033. }
  116034. if( pBest ){
  116035. iRoot = pBest->tnum;
  116036. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  116037. }
  116038. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  116039. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  116040. if( pKeyInfo ){
  116041. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  116042. }
  116043. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  116044. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  116045. explainSimpleCount(pParse, pTab, pBest);
  116046. }else
  116047. #endif /* SQLITE_OMIT_BTREECOUNT */
  116048. {
  116049. /* Check if the query is of one of the following forms:
  116050. **
  116051. ** SELECT min(x) FROM ...
  116052. ** SELECT max(x) FROM ...
  116053. **
  116054. ** If it is, then ask the code in where.c to attempt to sort results
  116055. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  116056. ** If where.c is able to produce results sorted in this order, then
  116057. ** add vdbe code to break out of the processing loop after the
  116058. ** first iteration (since the first iteration of the loop is
  116059. ** guaranteed to operate on the row with the minimum or maximum
  116060. ** value of x, the only row required).
  116061. **
  116062. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  116063. ** modify behavior as follows:
  116064. **
  116065. ** + If the query is a "SELECT min(x)", then the loop coded by
  116066. ** where.c should not iterate over any values with a NULL value
  116067. ** for x.
  116068. **
  116069. ** + The optimizer code in where.c (the thing that decides which
  116070. ** index or indices to use) should place a different priority on
  116071. ** satisfying the 'ORDER BY' clause than it does in other cases.
  116072. ** Refer to code and comments in where.c for details.
  116073. */
  116074. ExprList *pMinMax = 0;
  116075. u8 flag = WHERE_ORDERBY_NORMAL;
  116076. assert( p->pGroupBy==0 );
  116077. assert( flag==0 );
  116078. if( p->pHaving==0 ){
  116079. flag = minMaxQuery(&sAggInfo, &pMinMax);
  116080. }
  116081. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  116082. if( flag ){
  116083. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  116084. pDel = pMinMax;
  116085. assert( db->mallocFailed || pMinMax!=0 );
  116086. if( !db->mallocFailed ){
  116087. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  116088. pMinMax->a[0].pExpr->op = TK_COLUMN;
  116089. }
  116090. }
  116091. /* This case runs if the aggregate has no GROUP BY clause. The
  116092. ** processing is much simpler since there is only a single row
  116093. ** of output.
  116094. */
  116095. resetAccumulator(pParse, &sAggInfo);
  116096. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
  116097. if( pWInfo==0 ){
  116098. sqlite3ExprListDelete(db, pDel);
  116099. goto select_end;
  116100. }
  116101. updateAccumulator(pParse, &sAggInfo);
  116102. assert( pMinMax==0 || pMinMax->nExpr==1 );
  116103. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  116104. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  116105. VdbeComment((v, "%s() by index",
  116106. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  116107. }
  116108. sqlite3WhereEnd(pWInfo);
  116109. finalizeAggFunctions(pParse, &sAggInfo);
  116110. }
  116111. sSort.pOrderBy = 0;
  116112. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  116113. selectInnerLoop(pParse, p, -1, 0, 0,
  116114. pDest, addrEnd, addrEnd);
  116115. sqlite3ExprListDelete(db, pDel);
  116116. }
  116117. sqlite3VdbeResolveLabel(v, addrEnd);
  116118. } /* endif aggregate query */
  116119. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  116120. explainTempTable(pParse, "DISTINCT");
  116121. }
  116122. /* If there is an ORDER BY clause, then we need to sort the results
  116123. ** and send them to the callback one by one.
  116124. */
  116125. if( sSort.pOrderBy ){
  116126. explainTempTable(pParse,
  116127. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  116128. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  116129. }
  116130. /* Jump here to skip this query
  116131. */
  116132. sqlite3VdbeResolveLabel(v, iEnd);
  116133. /* The SELECT has been coded. If there is an error in the Parse structure,
  116134. ** set the return code to 1. Otherwise 0. */
  116135. rc = (pParse->nErr>0);
  116136. /* Control jumps to here if an error is encountered above, or upon
  116137. ** successful coding of the SELECT.
  116138. */
  116139. select_end:
  116140. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  116141. sqlite3DbFree(db, sAggInfo.aCol);
  116142. sqlite3DbFree(db, sAggInfo.aFunc);
  116143. #if SELECTTRACE_ENABLED
  116144. SELECTTRACE(1,pParse,p,("end processing\n"));
  116145. pParse->nSelectIndent--;
  116146. #endif
  116147. return rc;
  116148. }
  116149. /************** End of select.c **********************************************/
  116150. /************** Begin file table.c *******************************************/
  116151. /*
  116152. ** 2001 September 15
  116153. **
  116154. ** The author disclaims copyright to this source code. In place of
  116155. ** a legal notice, here is a blessing:
  116156. **
  116157. ** May you do good and not evil.
  116158. ** May you find forgiveness for yourself and forgive others.
  116159. ** May you share freely, never taking more than you give.
  116160. **
  116161. *************************************************************************
  116162. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  116163. ** interface routines. These are just wrappers around the main
  116164. ** interface routine of sqlite3_exec().
  116165. **
  116166. ** These routines are in a separate files so that they will not be linked
  116167. ** if they are not used.
  116168. */
  116169. /* #include "sqliteInt.h" */
  116170. #ifndef SQLITE_OMIT_GET_TABLE
  116171. /*
  116172. ** This structure is used to pass data from sqlite3_get_table() through
  116173. ** to the callback function is uses to build the result.
  116174. */
  116175. typedef struct TabResult {
  116176. char **azResult; /* Accumulated output */
  116177. char *zErrMsg; /* Error message text, if an error occurs */
  116178. u32 nAlloc; /* Slots allocated for azResult[] */
  116179. u32 nRow; /* Number of rows in the result */
  116180. u32 nColumn; /* Number of columns in the result */
  116181. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  116182. int rc; /* Return code from sqlite3_exec() */
  116183. } TabResult;
  116184. /*
  116185. ** This routine is called once for each row in the result table. Its job
  116186. ** is to fill in the TabResult structure appropriately, allocating new
  116187. ** memory as necessary.
  116188. */
  116189. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  116190. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  116191. int need; /* Slots needed in p->azResult[] */
  116192. int i; /* Loop counter */
  116193. char *z; /* A single column of result */
  116194. /* Make sure there is enough space in p->azResult to hold everything
  116195. ** we need to remember from this invocation of the callback.
  116196. */
  116197. if( p->nRow==0 && argv!=0 ){
  116198. need = nCol*2;
  116199. }else{
  116200. need = nCol;
  116201. }
  116202. if( p->nData + need > p->nAlloc ){
  116203. char **azNew;
  116204. p->nAlloc = p->nAlloc*2 + need;
  116205. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  116206. if( azNew==0 ) goto malloc_failed;
  116207. p->azResult = azNew;
  116208. }
  116209. /* If this is the first row, then generate an extra row containing
  116210. ** the names of all columns.
  116211. */
  116212. if( p->nRow==0 ){
  116213. p->nColumn = nCol;
  116214. for(i=0; i<nCol; i++){
  116215. z = sqlite3_mprintf("%s", colv[i]);
  116216. if( z==0 ) goto malloc_failed;
  116217. p->azResult[p->nData++] = z;
  116218. }
  116219. }else if( (int)p->nColumn!=nCol ){
  116220. sqlite3_free(p->zErrMsg);
  116221. p->zErrMsg = sqlite3_mprintf(
  116222. "sqlite3_get_table() called with two or more incompatible queries"
  116223. );
  116224. p->rc = SQLITE_ERROR;
  116225. return 1;
  116226. }
  116227. /* Copy over the row data
  116228. */
  116229. if( argv!=0 ){
  116230. for(i=0; i<nCol; i++){
  116231. if( argv[i]==0 ){
  116232. z = 0;
  116233. }else{
  116234. int n = sqlite3Strlen30(argv[i])+1;
  116235. z = sqlite3_malloc64( n );
  116236. if( z==0 ) goto malloc_failed;
  116237. memcpy(z, argv[i], n);
  116238. }
  116239. p->azResult[p->nData++] = z;
  116240. }
  116241. p->nRow++;
  116242. }
  116243. return 0;
  116244. malloc_failed:
  116245. p->rc = SQLITE_NOMEM_BKPT;
  116246. return 1;
  116247. }
  116248. /*
  116249. ** Query the database. But instead of invoking a callback for each row,
  116250. ** malloc() for space to hold the result and return the entire results
  116251. ** at the conclusion of the call.
  116252. **
  116253. ** The result that is written to ***pazResult is held in memory obtained
  116254. ** from malloc(). But the caller cannot free this memory directly.
  116255. ** Instead, the entire table should be passed to sqlite3_free_table() when
  116256. ** the calling procedure is finished using it.
  116257. */
  116258. SQLITE_API int sqlite3_get_table(
  116259. sqlite3 *db, /* The database on which the SQL executes */
  116260. const char *zSql, /* The SQL to be executed */
  116261. char ***pazResult, /* Write the result table here */
  116262. int *pnRow, /* Write the number of rows in the result here */
  116263. int *pnColumn, /* Write the number of columns of result here */
  116264. char **pzErrMsg /* Write error messages here */
  116265. ){
  116266. int rc;
  116267. TabResult res;
  116268. #ifdef SQLITE_ENABLE_API_ARMOR
  116269. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  116270. #endif
  116271. *pazResult = 0;
  116272. if( pnColumn ) *pnColumn = 0;
  116273. if( pnRow ) *pnRow = 0;
  116274. if( pzErrMsg ) *pzErrMsg = 0;
  116275. res.zErrMsg = 0;
  116276. res.nRow = 0;
  116277. res.nColumn = 0;
  116278. res.nData = 1;
  116279. res.nAlloc = 20;
  116280. res.rc = SQLITE_OK;
  116281. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  116282. if( res.azResult==0 ){
  116283. db->errCode = SQLITE_NOMEM;
  116284. return SQLITE_NOMEM_BKPT;
  116285. }
  116286. res.azResult[0] = 0;
  116287. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  116288. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  116289. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  116290. if( (rc&0xff)==SQLITE_ABORT ){
  116291. sqlite3_free_table(&res.azResult[1]);
  116292. if( res.zErrMsg ){
  116293. if( pzErrMsg ){
  116294. sqlite3_free(*pzErrMsg);
  116295. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  116296. }
  116297. sqlite3_free(res.zErrMsg);
  116298. }
  116299. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  116300. return res.rc;
  116301. }
  116302. sqlite3_free(res.zErrMsg);
  116303. if( rc!=SQLITE_OK ){
  116304. sqlite3_free_table(&res.azResult[1]);
  116305. return rc;
  116306. }
  116307. if( res.nAlloc>res.nData ){
  116308. char **azNew;
  116309. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  116310. if( azNew==0 ){
  116311. sqlite3_free_table(&res.azResult[1]);
  116312. db->errCode = SQLITE_NOMEM;
  116313. return SQLITE_NOMEM_BKPT;
  116314. }
  116315. res.azResult = azNew;
  116316. }
  116317. *pazResult = &res.azResult[1];
  116318. if( pnColumn ) *pnColumn = res.nColumn;
  116319. if( pnRow ) *pnRow = res.nRow;
  116320. return rc;
  116321. }
  116322. /*
  116323. ** This routine frees the space the sqlite3_get_table() malloced.
  116324. */
  116325. SQLITE_API void sqlite3_free_table(
  116326. char **azResult /* Result returned from sqlite3_get_table() */
  116327. ){
  116328. if( azResult ){
  116329. int i, n;
  116330. azResult--;
  116331. assert( azResult!=0 );
  116332. n = SQLITE_PTR_TO_INT(azResult[0]);
  116333. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  116334. sqlite3_free(azResult);
  116335. }
  116336. }
  116337. #endif /* SQLITE_OMIT_GET_TABLE */
  116338. /************** End of table.c ***********************************************/
  116339. /************** Begin file trigger.c *****************************************/
  116340. /*
  116341. **
  116342. ** The author disclaims copyright to this source code. In place of
  116343. ** a legal notice, here is a blessing:
  116344. **
  116345. ** May you do good and not evil.
  116346. ** May you find forgiveness for yourself and forgive others.
  116347. ** May you share freely, never taking more than you give.
  116348. **
  116349. *************************************************************************
  116350. ** This file contains the implementation for TRIGGERs
  116351. */
  116352. /* #include "sqliteInt.h" */
  116353. #ifndef SQLITE_OMIT_TRIGGER
  116354. /*
  116355. ** Delete a linked list of TriggerStep structures.
  116356. */
  116357. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  116358. while( pTriggerStep ){
  116359. TriggerStep * pTmp = pTriggerStep;
  116360. pTriggerStep = pTriggerStep->pNext;
  116361. sqlite3ExprDelete(db, pTmp->pWhere);
  116362. sqlite3ExprListDelete(db, pTmp->pExprList);
  116363. sqlite3SelectDelete(db, pTmp->pSelect);
  116364. sqlite3IdListDelete(db, pTmp->pIdList);
  116365. sqlite3DbFree(db, pTmp);
  116366. }
  116367. }
  116368. /*
  116369. ** Given table pTab, return a list of all the triggers attached to
  116370. ** the table. The list is connected by Trigger.pNext pointers.
  116371. **
  116372. ** All of the triggers on pTab that are in the same database as pTab
  116373. ** are already attached to pTab->pTrigger. But there might be additional
  116374. ** triggers on pTab in the TEMP schema. This routine prepends all
  116375. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  116376. ** and returns the combined list.
  116377. **
  116378. ** To state it another way: This routine returns a list of all triggers
  116379. ** that fire off of pTab. The list will include any TEMP triggers on
  116380. ** pTab as well as the triggers lised in pTab->pTrigger.
  116381. */
  116382. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  116383. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  116384. Trigger *pList = 0; /* List of triggers to return */
  116385. if( pParse->disableTriggers ){
  116386. return 0;
  116387. }
  116388. if( pTmpSchema!=pTab->pSchema ){
  116389. HashElem *p;
  116390. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  116391. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  116392. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  116393. if( pTrig->pTabSchema==pTab->pSchema
  116394. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  116395. ){
  116396. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  116397. pList = pTrig;
  116398. }
  116399. }
  116400. }
  116401. return (pList ? pList : pTab->pTrigger);
  116402. }
  116403. /*
  116404. ** This is called by the parser when it sees a CREATE TRIGGER statement
  116405. ** up to the point of the BEGIN before the trigger actions. A Trigger
  116406. ** structure is generated based on the information available and stored
  116407. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  116408. ** sqlite3FinishTrigger() function is called to complete the trigger
  116409. ** construction process.
  116410. */
  116411. SQLITE_PRIVATE void sqlite3BeginTrigger(
  116412. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  116413. Token *pName1, /* The name of the trigger */
  116414. Token *pName2, /* The name of the trigger */
  116415. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  116416. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  116417. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  116418. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  116419. Expr *pWhen, /* WHEN clause */
  116420. int isTemp, /* True if the TEMPORARY keyword is present */
  116421. int noErr /* Suppress errors if the trigger already exists */
  116422. ){
  116423. Trigger *pTrigger = 0; /* The new trigger */
  116424. Table *pTab; /* Table that the trigger fires off of */
  116425. char *zName = 0; /* Name of the trigger */
  116426. sqlite3 *db = pParse->db; /* The database connection */
  116427. int iDb; /* The database to store the trigger in */
  116428. Token *pName; /* The unqualified db name */
  116429. DbFixer sFix; /* State vector for the DB fixer */
  116430. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  116431. assert( pName2!=0 );
  116432. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  116433. assert( op>0 && op<0xff );
  116434. if( isTemp ){
  116435. /* If TEMP was specified, then the trigger name may not be qualified. */
  116436. if( pName2->n>0 ){
  116437. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  116438. goto trigger_cleanup;
  116439. }
  116440. iDb = 1;
  116441. pName = pName1;
  116442. }else{
  116443. /* Figure out the db that the trigger will be created in */
  116444. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  116445. if( iDb<0 ){
  116446. goto trigger_cleanup;
  116447. }
  116448. }
  116449. if( !pTableName || db->mallocFailed ){
  116450. goto trigger_cleanup;
  116451. }
  116452. /* A long-standing parser bug is that this syntax was allowed:
  116453. **
  116454. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  116455. ** ^^^^^^^^
  116456. **
  116457. ** To maintain backwards compatibility, ignore the database
  116458. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  116459. */
  116460. if( db->init.busy && iDb!=1 ){
  116461. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  116462. pTableName->a[0].zDatabase = 0;
  116463. }
  116464. /* If the trigger name was unqualified, and the table is a temp table,
  116465. ** then set iDb to 1 to create the trigger in the temporary database.
  116466. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  116467. ** exist, the error is caught by the block below.
  116468. */
  116469. pTab = sqlite3SrcListLookup(pParse, pTableName);
  116470. if( db->init.busy==0 && pName2->n==0 && pTab
  116471. && pTab->pSchema==db->aDb[1].pSchema ){
  116472. iDb = 1;
  116473. }
  116474. /* Ensure the table name matches database name and that the table exists */
  116475. if( db->mallocFailed ) goto trigger_cleanup;
  116476. assert( pTableName->nSrc==1 );
  116477. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  116478. if( sqlite3FixSrcList(&sFix, pTableName) ){
  116479. goto trigger_cleanup;
  116480. }
  116481. pTab = sqlite3SrcListLookup(pParse, pTableName);
  116482. if( !pTab ){
  116483. /* The table does not exist. */
  116484. if( db->init.iDb==1 ){
  116485. /* Ticket #3810.
  116486. ** Normally, whenever a table is dropped, all associated triggers are
  116487. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  116488. ** and the table is dropped by a different database connection, the
  116489. ** trigger is not visible to the database connection that does the
  116490. ** drop so the trigger cannot be dropped. This results in an
  116491. ** "orphaned trigger" - a trigger whose associated table is missing.
  116492. */
  116493. db->init.orphanTrigger = 1;
  116494. }
  116495. goto trigger_cleanup;
  116496. }
  116497. if( IsVirtual(pTab) ){
  116498. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  116499. goto trigger_cleanup;
  116500. }
  116501. /* Check that the trigger name is not reserved and that no trigger of the
  116502. ** specified name exists */
  116503. zName = sqlite3NameFromToken(db, pName);
  116504. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  116505. goto trigger_cleanup;
  116506. }
  116507. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  116508. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  116509. if( !noErr ){
  116510. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  116511. }else{
  116512. assert( !db->init.busy );
  116513. sqlite3CodeVerifySchema(pParse, iDb);
  116514. }
  116515. goto trigger_cleanup;
  116516. }
  116517. /* Do not create a trigger on a system table */
  116518. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  116519. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  116520. goto trigger_cleanup;
  116521. }
  116522. /* INSTEAD of triggers are only for views and views only support INSTEAD
  116523. ** of triggers.
  116524. */
  116525. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  116526. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  116527. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  116528. goto trigger_cleanup;
  116529. }
  116530. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  116531. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  116532. " trigger on table: %S", pTableName, 0);
  116533. goto trigger_cleanup;
  116534. }
  116535. #ifndef SQLITE_OMIT_AUTHORIZATION
  116536. {
  116537. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  116538. int code = SQLITE_CREATE_TRIGGER;
  116539. const char *zDb = db->aDb[iTabDb].zDbSName;
  116540. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  116541. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  116542. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  116543. goto trigger_cleanup;
  116544. }
  116545. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  116546. goto trigger_cleanup;
  116547. }
  116548. }
  116549. #endif
  116550. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  116551. ** cannot appear on views. So we might as well translate every
  116552. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  116553. ** elsewhere.
  116554. */
  116555. if (tr_tm == TK_INSTEAD){
  116556. tr_tm = TK_BEFORE;
  116557. }
  116558. /* Build the Trigger object */
  116559. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  116560. if( pTrigger==0 ) goto trigger_cleanup;
  116561. pTrigger->zName = zName;
  116562. zName = 0;
  116563. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  116564. pTrigger->pSchema = db->aDb[iDb].pSchema;
  116565. pTrigger->pTabSchema = pTab->pSchema;
  116566. pTrigger->op = (u8)op;
  116567. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  116568. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  116569. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  116570. assert( pParse->pNewTrigger==0 );
  116571. pParse->pNewTrigger = pTrigger;
  116572. trigger_cleanup:
  116573. sqlite3DbFree(db, zName);
  116574. sqlite3SrcListDelete(db, pTableName);
  116575. sqlite3IdListDelete(db, pColumns);
  116576. sqlite3ExprDelete(db, pWhen);
  116577. if( !pParse->pNewTrigger ){
  116578. sqlite3DeleteTrigger(db, pTrigger);
  116579. }else{
  116580. assert( pParse->pNewTrigger==pTrigger );
  116581. }
  116582. }
  116583. /*
  116584. ** This routine is called after all of the trigger actions have been parsed
  116585. ** in order to complete the process of building the trigger.
  116586. */
  116587. SQLITE_PRIVATE void sqlite3FinishTrigger(
  116588. Parse *pParse, /* Parser context */
  116589. TriggerStep *pStepList, /* The triggered program */
  116590. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  116591. ){
  116592. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  116593. char *zName; /* Name of trigger */
  116594. sqlite3 *db = pParse->db; /* The database */
  116595. DbFixer sFix; /* Fixer object */
  116596. int iDb; /* Database containing the trigger */
  116597. Token nameToken; /* Trigger name for error reporting */
  116598. pParse->pNewTrigger = 0;
  116599. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  116600. zName = pTrig->zName;
  116601. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  116602. pTrig->step_list = pStepList;
  116603. while( pStepList ){
  116604. pStepList->pTrig = pTrig;
  116605. pStepList = pStepList->pNext;
  116606. }
  116607. sqlite3TokenInit(&nameToken, pTrig->zName);
  116608. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  116609. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  116610. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  116611. ){
  116612. goto triggerfinish_cleanup;
  116613. }
  116614. /* if we are not initializing,
  116615. ** build the sqlite_master entry
  116616. */
  116617. if( !db->init.busy ){
  116618. Vdbe *v;
  116619. char *z;
  116620. /* Make an entry in the sqlite_master table */
  116621. v = sqlite3GetVdbe(pParse);
  116622. if( v==0 ) goto triggerfinish_cleanup;
  116623. sqlite3BeginWriteOperation(pParse, 0, iDb);
  116624. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  116625. testcase( z==0 );
  116626. sqlite3NestedParse(pParse,
  116627. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  116628. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  116629. pTrig->table, z);
  116630. sqlite3DbFree(db, z);
  116631. sqlite3ChangeCookie(pParse, iDb);
  116632. sqlite3VdbeAddParseSchemaOp(v, iDb,
  116633. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  116634. }
  116635. if( db->init.busy ){
  116636. Trigger *pLink = pTrig;
  116637. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  116638. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  116639. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  116640. if( pTrig ){
  116641. sqlite3OomFault(db);
  116642. }else if( pLink->pSchema==pLink->pTabSchema ){
  116643. Table *pTab;
  116644. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  116645. assert( pTab!=0 );
  116646. pLink->pNext = pTab->pTrigger;
  116647. pTab->pTrigger = pLink;
  116648. }
  116649. }
  116650. triggerfinish_cleanup:
  116651. sqlite3DeleteTrigger(db, pTrig);
  116652. assert( !pParse->pNewTrigger );
  116653. sqlite3DeleteTriggerStep(db, pStepList);
  116654. }
  116655. /*
  116656. ** Turn a SELECT statement (that the pSelect parameter points to) into
  116657. ** a trigger step. Return a pointer to a TriggerStep structure.
  116658. **
  116659. ** The parser calls this routine when it finds a SELECT statement in
  116660. ** body of a TRIGGER.
  116661. */
  116662. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  116663. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  116664. if( pTriggerStep==0 ) {
  116665. sqlite3SelectDelete(db, pSelect);
  116666. return 0;
  116667. }
  116668. pTriggerStep->op = TK_SELECT;
  116669. pTriggerStep->pSelect = pSelect;
  116670. pTriggerStep->orconf = OE_Default;
  116671. return pTriggerStep;
  116672. }
  116673. /*
  116674. ** Allocate space to hold a new trigger step. The allocated space
  116675. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  116676. **
  116677. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  116678. */
  116679. static TriggerStep *triggerStepAllocate(
  116680. sqlite3 *db, /* Database connection */
  116681. u8 op, /* Trigger opcode */
  116682. Token *pName /* The target name */
  116683. ){
  116684. TriggerStep *pTriggerStep;
  116685. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  116686. if( pTriggerStep ){
  116687. char *z = (char*)&pTriggerStep[1];
  116688. memcpy(z, pName->z, pName->n);
  116689. sqlite3Dequote(z);
  116690. pTriggerStep->zTarget = z;
  116691. pTriggerStep->op = op;
  116692. }
  116693. return pTriggerStep;
  116694. }
  116695. /*
  116696. ** Build a trigger step out of an INSERT statement. Return a pointer
  116697. ** to the new trigger step.
  116698. **
  116699. ** The parser calls this routine when it sees an INSERT inside the
  116700. ** body of a trigger.
  116701. */
  116702. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  116703. sqlite3 *db, /* The database connection */
  116704. Token *pTableName, /* Name of the table into which we insert */
  116705. IdList *pColumn, /* List of columns in pTableName to insert into */
  116706. Select *pSelect, /* A SELECT statement that supplies values */
  116707. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  116708. ){
  116709. TriggerStep *pTriggerStep;
  116710. assert(pSelect != 0 || db->mallocFailed);
  116711. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  116712. if( pTriggerStep ){
  116713. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  116714. pTriggerStep->pIdList = pColumn;
  116715. pTriggerStep->orconf = orconf;
  116716. }else{
  116717. sqlite3IdListDelete(db, pColumn);
  116718. }
  116719. sqlite3SelectDelete(db, pSelect);
  116720. return pTriggerStep;
  116721. }
  116722. /*
  116723. ** Construct a trigger step that implements an UPDATE statement and return
  116724. ** a pointer to that trigger step. The parser calls this routine when it
  116725. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  116726. */
  116727. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  116728. sqlite3 *db, /* The database connection */
  116729. Token *pTableName, /* Name of the table to be updated */
  116730. ExprList *pEList, /* The SET clause: list of column and new values */
  116731. Expr *pWhere, /* The WHERE clause */
  116732. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  116733. ){
  116734. TriggerStep *pTriggerStep;
  116735. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  116736. if( pTriggerStep ){
  116737. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  116738. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  116739. pTriggerStep->orconf = orconf;
  116740. }
  116741. sqlite3ExprListDelete(db, pEList);
  116742. sqlite3ExprDelete(db, pWhere);
  116743. return pTriggerStep;
  116744. }
  116745. /*
  116746. ** Construct a trigger step that implements a DELETE statement and return
  116747. ** a pointer to that trigger step. The parser calls this routine when it
  116748. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  116749. */
  116750. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  116751. sqlite3 *db, /* Database connection */
  116752. Token *pTableName, /* The table from which rows are deleted */
  116753. Expr *pWhere /* The WHERE clause */
  116754. ){
  116755. TriggerStep *pTriggerStep;
  116756. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  116757. if( pTriggerStep ){
  116758. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  116759. pTriggerStep->orconf = OE_Default;
  116760. }
  116761. sqlite3ExprDelete(db, pWhere);
  116762. return pTriggerStep;
  116763. }
  116764. /*
  116765. ** Recursively delete a Trigger structure
  116766. */
  116767. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  116768. if( pTrigger==0 ) return;
  116769. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  116770. sqlite3DbFree(db, pTrigger->zName);
  116771. sqlite3DbFree(db, pTrigger->table);
  116772. sqlite3ExprDelete(db, pTrigger->pWhen);
  116773. sqlite3IdListDelete(db, pTrigger->pColumns);
  116774. sqlite3DbFree(db, pTrigger);
  116775. }
  116776. /*
  116777. ** This function is called to drop a trigger from the database schema.
  116778. **
  116779. ** This may be called directly from the parser and therefore identifies
  116780. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  116781. ** same job as this routine except it takes a pointer to the trigger
  116782. ** instead of the trigger name.
  116783. **/
  116784. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  116785. Trigger *pTrigger = 0;
  116786. int i;
  116787. const char *zDb;
  116788. const char *zName;
  116789. sqlite3 *db = pParse->db;
  116790. if( db->mallocFailed ) goto drop_trigger_cleanup;
  116791. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  116792. goto drop_trigger_cleanup;
  116793. }
  116794. assert( pName->nSrc==1 );
  116795. zDb = pName->a[0].zDatabase;
  116796. zName = pName->a[0].zName;
  116797. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  116798. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  116799. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  116800. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  116801. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  116802. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  116803. if( pTrigger ) break;
  116804. }
  116805. if( !pTrigger ){
  116806. if( !noErr ){
  116807. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  116808. }else{
  116809. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  116810. }
  116811. pParse->checkSchema = 1;
  116812. goto drop_trigger_cleanup;
  116813. }
  116814. sqlite3DropTriggerPtr(pParse, pTrigger);
  116815. drop_trigger_cleanup:
  116816. sqlite3SrcListDelete(db, pName);
  116817. }
  116818. /*
  116819. ** Return a pointer to the Table structure for the table that a trigger
  116820. ** is set on.
  116821. */
  116822. static Table *tableOfTrigger(Trigger *pTrigger){
  116823. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  116824. }
  116825. /*
  116826. ** Drop a trigger given a pointer to that trigger.
  116827. */
  116828. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  116829. Table *pTable;
  116830. Vdbe *v;
  116831. sqlite3 *db = pParse->db;
  116832. int iDb;
  116833. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  116834. assert( iDb>=0 && iDb<db->nDb );
  116835. pTable = tableOfTrigger(pTrigger);
  116836. assert( pTable );
  116837. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  116838. #ifndef SQLITE_OMIT_AUTHORIZATION
  116839. {
  116840. int code = SQLITE_DROP_TRIGGER;
  116841. const char *zDb = db->aDb[iDb].zDbSName;
  116842. const char *zTab = SCHEMA_TABLE(iDb);
  116843. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  116844. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  116845. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  116846. return;
  116847. }
  116848. }
  116849. #endif
  116850. /* Generate code to destroy the database record of the trigger.
  116851. */
  116852. assert( pTable!=0 );
  116853. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  116854. sqlite3NestedParse(pParse,
  116855. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  116856. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  116857. );
  116858. sqlite3ChangeCookie(pParse, iDb);
  116859. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  116860. }
  116861. }
  116862. /*
  116863. ** Remove a trigger from the hash tables of the sqlite* pointer.
  116864. */
  116865. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  116866. Trigger *pTrigger;
  116867. Hash *pHash;
  116868. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  116869. pHash = &(db->aDb[iDb].pSchema->trigHash);
  116870. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  116871. if( ALWAYS(pTrigger) ){
  116872. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  116873. Table *pTab = tableOfTrigger(pTrigger);
  116874. Trigger **pp;
  116875. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  116876. *pp = (*pp)->pNext;
  116877. }
  116878. sqlite3DeleteTrigger(db, pTrigger);
  116879. db->mDbFlags |= DBFLAG_SchemaChange;
  116880. }
  116881. }
  116882. /*
  116883. ** pEList is the SET clause of an UPDATE statement. Each entry
  116884. ** in pEList is of the format <id>=<expr>. If any of the entries
  116885. ** in pEList have an <id> which matches an identifier in pIdList,
  116886. ** then return TRUE. If pIdList==NULL, then it is considered a
  116887. ** wildcard that matches anything. Likewise if pEList==NULL then
  116888. ** it matches anything so always return true. Return false only
  116889. ** if there is no match.
  116890. */
  116891. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  116892. int e;
  116893. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  116894. for(e=0; e<pEList->nExpr; e++){
  116895. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  116896. }
  116897. return 0;
  116898. }
  116899. /*
  116900. ** Return a list of all triggers on table pTab if there exists at least
  116901. ** one trigger that must be fired when an operation of type 'op' is
  116902. ** performed on the table, and, if that operation is an UPDATE, if at
  116903. ** least one of the columns in pChanges is being modified.
  116904. */
  116905. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  116906. Parse *pParse, /* Parse context */
  116907. Table *pTab, /* The table the contains the triggers */
  116908. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  116909. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  116910. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  116911. ){
  116912. int mask = 0;
  116913. Trigger *pList = 0;
  116914. Trigger *p;
  116915. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  116916. pList = sqlite3TriggerList(pParse, pTab);
  116917. }
  116918. assert( pList==0 || IsVirtual(pTab)==0 );
  116919. for(p=pList; p; p=p->pNext){
  116920. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  116921. mask |= p->tr_tm;
  116922. }
  116923. }
  116924. if( pMask ){
  116925. *pMask = mask;
  116926. }
  116927. return (mask ? pList : 0);
  116928. }
  116929. /*
  116930. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  116931. ** to that SrcList.
  116932. **
  116933. ** This routine adds a specific database name, if needed, to the target when
  116934. ** forming the SrcList. This prevents a trigger in one database from
  116935. ** referring to a target in another database. An exception is when the
  116936. ** trigger is in TEMP in which case it can refer to any other database it
  116937. ** wants.
  116938. */
  116939. static SrcList *targetSrcList(
  116940. Parse *pParse, /* The parsing context */
  116941. TriggerStep *pStep /* The trigger containing the target token */
  116942. ){
  116943. sqlite3 *db = pParse->db;
  116944. int iDb; /* Index of the database to use */
  116945. SrcList *pSrc; /* SrcList to be returned */
  116946. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  116947. if( pSrc ){
  116948. assert( pSrc->nSrc>0 );
  116949. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  116950. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  116951. if( iDb==0 || iDb>=2 ){
  116952. const char *zDb;
  116953. assert( iDb<db->nDb );
  116954. zDb = db->aDb[iDb].zDbSName;
  116955. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  116956. }
  116957. }
  116958. return pSrc;
  116959. }
  116960. /*
  116961. ** Generate VDBE code for the statements inside the body of a single
  116962. ** trigger.
  116963. */
  116964. static int codeTriggerProgram(
  116965. Parse *pParse, /* The parser context */
  116966. TriggerStep *pStepList, /* List of statements inside the trigger body */
  116967. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  116968. ){
  116969. TriggerStep *pStep;
  116970. Vdbe *v = pParse->pVdbe;
  116971. sqlite3 *db = pParse->db;
  116972. assert( pParse->pTriggerTab && pParse->pToplevel );
  116973. assert( pStepList );
  116974. assert( v!=0 );
  116975. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  116976. /* Figure out the ON CONFLICT policy that will be used for this step
  116977. ** of the trigger program. If the statement that caused this trigger
  116978. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  116979. ** the ON CONFLICT policy that was specified as part of the trigger
  116980. ** step statement. Example:
  116981. **
  116982. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  116983. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  116984. ** END;
  116985. **
  116986. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  116987. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  116988. */
  116989. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  116990. assert( pParse->okConstFactor==0 );
  116991. switch( pStep->op ){
  116992. case TK_UPDATE: {
  116993. sqlite3Update(pParse,
  116994. targetSrcList(pParse, pStep),
  116995. sqlite3ExprListDup(db, pStep->pExprList, 0),
  116996. sqlite3ExprDup(db, pStep->pWhere, 0),
  116997. pParse->eOrconf
  116998. );
  116999. break;
  117000. }
  117001. case TK_INSERT: {
  117002. sqlite3Insert(pParse,
  117003. targetSrcList(pParse, pStep),
  117004. sqlite3SelectDup(db, pStep->pSelect, 0),
  117005. sqlite3IdListDup(db, pStep->pIdList),
  117006. pParse->eOrconf
  117007. );
  117008. break;
  117009. }
  117010. case TK_DELETE: {
  117011. sqlite3DeleteFrom(pParse,
  117012. targetSrcList(pParse, pStep),
  117013. sqlite3ExprDup(db, pStep->pWhere, 0)
  117014. );
  117015. break;
  117016. }
  117017. default: assert( pStep->op==TK_SELECT ); {
  117018. SelectDest sDest;
  117019. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  117020. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  117021. sqlite3Select(pParse, pSelect, &sDest);
  117022. sqlite3SelectDelete(db, pSelect);
  117023. break;
  117024. }
  117025. }
  117026. if( pStep->op!=TK_SELECT ){
  117027. sqlite3VdbeAddOp0(v, OP_ResetCount);
  117028. }
  117029. }
  117030. return 0;
  117031. }
  117032. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  117033. /*
  117034. ** This function is used to add VdbeComment() annotations to a VDBE
  117035. ** program. It is not used in production code, only for debugging.
  117036. */
  117037. static const char *onErrorText(int onError){
  117038. switch( onError ){
  117039. case OE_Abort: return "abort";
  117040. case OE_Rollback: return "rollback";
  117041. case OE_Fail: return "fail";
  117042. case OE_Replace: return "replace";
  117043. case OE_Ignore: return "ignore";
  117044. case OE_Default: return "default";
  117045. }
  117046. return "n/a";
  117047. }
  117048. #endif
  117049. /*
  117050. ** Parse context structure pFrom has just been used to create a sub-vdbe
  117051. ** (trigger program). If an error has occurred, transfer error information
  117052. ** from pFrom to pTo.
  117053. */
  117054. static void transferParseError(Parse *pTo, Parse *pFrom){
  117055. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  117056. assert( pTo->zErrMsg==0 || pTo->nErr );
  117057. if( pTo->nErr==0 ){
  117058. pTo->zErrMsg = pFrom->zErrMsg;
  117059. pTo->nErr = pFrom->nErr;
  117060. pTo->rc = pFrom->rc;
  117061. }else{
  117062. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  117063. }
  117064. }
  117065. /*
  117066. ** Create and populate a new TriggerPrg object with a sub-program
  117067. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  117068. */
  117069. static TriggerPrg *codeRowTrigger(
  117070. Parse *pParse, /* Current parse context */
  117071. Trigger *pTrigger, /* Trigger to code */
  117072. Table *pTab, /* The table pTrigger is attached to */
  117073. int orconf /* ON CONFLICT policy to code trigger program with */
  117074. ){
  117075. Parse *pTop = sqlite3ParseToplevel(pParse);
  117076. sqlite3 *db = pParse->db; /* Database handle */
  117077. TriggerPrg *pPrg; /* Value to return */
  117078. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  117079. Vdbe *v; /* Temporary VM */
  117080. NameContext sNC; /* Name context for sub-vdbe */
  117081. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  117082. Parse *pSubParse; /* Parse context for sub-vdbe */
  117083. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  117084. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  117085. assert( pTop->pVdbe );
  117086. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  117087. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  117088. ** list of the top-level Parse object sooner rather than later. */
  117089. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  117090. if( !pPrg ) return 0;
  117091. pPrg->pNext = pTop->pTriggerPrg;
  117092. pTop->pTriggerPrg = pPrg;
  117093. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  117094. if( !pProgram ) return 0;
  117095. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  117096. pPrg->pTrigger = pTrigger;
  117097. pPrg->orconf = orconf;
  117098. pPrg->aColmask[0] = 0xffffffff;
  117099. pPrg->aColmask[1] = 0xffffffff;
  117100. /* Allocate and populate a new Parse context to use for coding the
  117101. ** trigger sub-program. */
  117102. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  117103. if( !pSubParse ) return 0;
  117104. memset(&sNC, 0, sizeof(sNC));
  117105. sNC.pParse = pSubParse;
  117106. pSubParse->db = db;
  117107. pSubParse->pTriggerTab = pTab;
  117108. pSubParse->pToplevel = pTop;
  117109. pSubParse->zAuthContext = pTrigger->zName;
  117110. pSubParse->eTriggerOp = pTrigger->op;
  117111. pSubParse->nQueryLoop = pParse->nQueryLoop;
  117112. v = sqlite3GetVdbe(pSubParse);
  117113. if( v ){
  117114. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  117115. pTrigger->zName, onErrorText(orconf),
  117116. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  117117. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  117118. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  117119. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  117120. pTab->zName
  117121. ));
  117122. #ifndef SQLITE_OMIT_TRACE
  117123. sqlite3VdbeChangeP4(v, -1,
  117124. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  117125. );
  117126. #endif
  117127. /* If one was specified, code the WHEN clause. If it evaluates to false
  117128. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  117129. ** OP_Halt inserted at the end of the program. */
  117130. if( pTrigger->pWhen ){
  117131. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  117132. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  117133. && db->mallocFailed==0
  117134. ){
  117135. iEndTrigger = sqlite3VdbeMakeLabel(v);
  117136. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  117137. }
  117138. sqlite3ExprDelete(db, pWhen);
  117139. }
  117140. /* Code the trigger program into the sub-vdbe. */
  117141. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  117142. /* Insert an OP_Halt at the end of the sub-program. */
  117143. if( iEndTrigger ){
  117144. sqlite3VdbeResolveLabel(v, iEndTrigger);
  117145. }
  117146. sqlite3VdbeAddOp0(v, OP_Halt);
  117147. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  117148. transferParseError(pParse, pSubParse);
  117149. if( db->mallocFailed==0 ){
  117150. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  117151. }
  117152. pProgram->nMem = pSubParse->nMem;
  117153. pProgram->nCsr = pSubParse->nTab;
  117154. pProgram->token = (void *)pTrigger;
  117155. pPrg->aColmask[0] = pSubParse->oldmask;
  117156. pPrg->aColmask[1] = pSubParse->newmask;
  117157. sqlite3VdbeDelete(v);
  117158. }
  117159. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  117160. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  117161. sqlite3ParserReset(pSubParse);
  117162. sqlite3StackFree(db, pSubParse);
  117163. return pPrg;
  117164. }
  117165. /*
  117166. ** Return a pointer to a TriggerPrg object containing the sub-program for
  117167. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  117168. ** TriggerPrg object exists, a new object is allocated and populated before
  117169. ** being returned.
  117170. */
  117171. static TriggerPrg *getRowTrigger(
  117172. Parse *pParse, /* Current parse context */
  117173. Trigger *pTrigger, /* Trigger to code */
  117174. Table *pTab, /* The table trigger pTrigger is attached to */
  117175. int orconf /* ON CONFLICT algorithm. */
  117176. ){
  117177. Parse *pRoot = sqlite3ParseToplevel(pParse);
  117178. TriggerPrg *pPrg;
  117179. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  117180. /* It may be that this trigger has already been coded (or is in the
  117181. ** process of being coded). If this is the case, then an entry with
  117182. ** a matching TriggerPrg.pTrigger field will be present somewhere
  117183. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  117184. for(pPrg=pRoot->pTriggerPrg;
  117185. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  117186. pPrg=pPrg->pNext
  117187. );
  117188. /* If an existing TriggerPrg could not be located, create a new one. */
  117189. if( !pPrg ){
  117190. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  117191. }
  117192. return pPrg;
  117193. }
  117194. /*
  117195. ** Generate code for the trigger program associated with trigger p on
  117196. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  117197. ** function are the same as those described in the header function for
  117198. ** sqlite3CodeRowTrigger()
  117199. */
  117200. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  117201. Parse *pParse, /* Parse context */
  117202. Trigger *p, /* Trigger to code */
  117203. Table *pTab, /* The table to code triggers from */
  117204. int reg, /* Reg array containing OLD.* and NEW.* values */
  117205. int orconf, /* ON CONFLICT policy */
  117206. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  117207. ){
  117208. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  117209. TriggerPrg *pPrg;
  117210. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  117211. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  117212. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  117213. ** is a pointer to the sub-vdbe containing the trigger program. */
  117214. if( pPrg ){
  117215. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  117216. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  117217. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  117218. VdbeComment(
  117219. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  117220. /* Set the P5 operand of the OP_Program instruction to non-zero if
  117221. ** recursive invocation of this trigger program is disallowed. Recursive
  117222. ** invocation is disallowed if (a) the sub-program is really a trigger,
  117223. ** not a foreign key action, and (b) the flag to enable recursive triggers
  117224. ** is clear. */
  117225. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  117226. }
  117227. }
  117228. /*
  117229. ** This is called to code the required FOR EACH ROW triggers for an operation
  117230. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  117231. ** is given by the op parameter. The tr_tm parameter determines whether the
  117232. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  117233. ** parameter pChanges is passed the list of columns being modified.
  117234. **
  117235. ** If there are no triggers that fire at the specified time for the specified
  117236. ** operation on pTab, this function is a no-op.
  117237. **
  117238. ** The reg argument is the address of the first in an array of registers
  117239. ** that contain the values substituted for the new.* and old.* references
  117240. ** in the trigger program. If N is the number of columns in table pTab
  117241. ** (a copy of pTab->nCol), then registers are populated as follows:
  117242. **
  117243. ** Register Contains
  117244. ** ------------------------------------------------------
  117245. ** reg+0 OLD.rowid
  117246. ** reg+1 OLD.* value of left-most column of pTab
  117247. ** ... ...
  117248. ** reg+N OLD.* value of right-most column of pTab
  117249. ** reg+N+1 NEW.rowid
  117250. ** reg+N+2 OLD.* value of left-most column of pTab
  117251. ** ... ...
  117252. ** reg+N+N+1 NEW.* value of right-most column of pTab
  117253. **
  117254. ** For ON DELETE triggers, the registers containing the NEW.* values will
  117255. ** never be accessed by the trigger program, so they are not allocated or
  117256. ** populated by the caller (there is no data to populate them with anyway).
  117257. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  117258. ** are never accessed, and so are not allocated by the caller. So, for an
  117259. ** ON INSERT trigger, the value passed to this function as parameter reg
  117260. ** is not a readable register, although registers (reg+N) through
  117261. ** (reg+N+N+1) are.
  117262. **
  117263. ** Parameter orconf is the default conflict resolution algorithm for the
  117264. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  117265. ** is the instruction that control should jump to if a trigger program
  117266. ** raises an IGNORE exception.
  117267. */
  117268. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  117269. Parse *pParse, /* Parse context */
  117270. Trigger *pTrigger, /* List of triggers on table pTab */
  117271. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  117272. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  117273. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  117274. Table *pTab, /* The table to code triggers from */
  117275. int reg, /* The first in an array of registers (see above) */
  117276. int orconf, /* ON CONFLICT policy */
  117277. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  117278. ){
  117279. Trigger *p; /* Used to iterate through pTrigger list */
  117280. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  117281. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  117282. assert( (op==TK_UPDATE)==(pChanges!=0) );
  117283. for(p=pTrigger; p; p=p->pNext){
  117284. /* Sanity checking: The schema for the trigger and for the table are
  117285. ** always defined. The trigger must be in the same schema as the table
  117286. ** or else it must be a TEMP trigger. */
  117287. assert( p->pSchema!=0 );
  117288. assert( p->pTabSchema!=0 );
  117289. assert( p->pSchema==p->pTabSchema
  117290. || p->pSchema==pParse->db->aDb[1].pSchema );
  117291. /* Determine whether we should code this trigger */
  117292. if( p->op==op
  117293. && p->tr_tm==tr_tm
  117294. && checkColumnOverlap(p->pColumns, pChanges)
  117295. ){
  117296. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  117297. }
  117298. }
  117299. }
  117300. /*
  117301. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  117302. ** This function returns a 32-bit bitmask indicating which columns of the
  117303. ** old.* or new.* tables actually are used by triggers. This information
  117304. ** may be used by the caller, for example, to avoid having to load the entire
  117305. ** old.* record into memory when executing an UPDATE or DELETE command.
  117306. **
  117307. ** Bit 0 of the returned mask is set if the left-most column of the
  117308. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  117309. ** the second leftmost column value is required, and so on. If there
  117310. ** are more than 32 columns in the table, and at least one of the columns
  117311. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  117312. **
  117313. ** It is not possible to determine if the old.rowid or new.rowid column is
  117314. ** accessed by triggers. The caller must always assume that it is.
  117315. **
  117316. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  117317. ** applies to the old.* table. If 1, the new.* table.
  117318. **
  117319. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  117320. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  117321. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  117322. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  117323. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  117324. */
  117325. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  117326. Parse *pParse, /* Parse context */
  117327. Trigger *pTrigger, /* List of triggers on table pTab */
  117328. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  117329. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  117330. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  117331. Table *pTab, /* The table to code triggers from */
  117332. int orconf /* Default ON CONFLICT policy for trigger steps */
  117333. ){
  117334. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  117335. u32 mask = 0;
  117336. Trigger *p;
  117337. assert( isNew==1 || isNew==0 );
  117338. for(p=pTrigger; p; p=p->pNext){
  117339. if( p->op==op && (tr_tm&p->tr_tm)
  117340. && checkColumnOverlap(p->pColumns,pChanges)
  117341. ){
  117342. TriggerPrg *pPrg;
  117343. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  117344. if( pPrg ){
  117345. mask |= pPrg->aColmask[isNew];
  117346. }
  117347. }
  117348. }
  117349. return mask;
  117350. }
  117351. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  117352. /************** End of trigger.c *********************************************/
  117353. /************** Begin file update.c ******************************************/
  117354. /*
  117355. ** 2001 September 15
  117356. **
  117357. ** The author disclaims copyright to this source code. In place of
  117358. ** a legal notice, here is a blessing:
  117359. **
  117360. ** May you do good and not evil.
  117361. ** May you find forgiveness for yourself and forgive others.
  117362. ** May you share freely, never taking more than you give.
  117363. **
  117364. *************************************************************************
  117365. ** This file contains C code routines that are called by the parser
  117366. ** to handle UPDATE statements.
  117367. */
  117368. /* #include "sqliteInt.h" */
  117369. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117370. /* Forward declaration */
  117371. static void updateVirtualTable(
  117372. Parse *pParse, /* The parsing context */
  117373. SrcList *pSrc, /* The virtual table to be modified */
  117374. Table *pTab, /* The virtual table */
  117375. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  117376. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  117377. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  117378. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  117379. int onError /* ON CONFLICT strategy */
  117380. );
  117381. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  117382. /*
  117383. ** The most recently coded instruction was an OP_Column to retrieve the
  117384. ** i-th column of table pTab. This routine sets the P4 parameter of the
  117385. ** OP_Column to the default value, if any.
  117386. **
  117387. ** The default value of a column is specified by a DEFAULT clause in the
  117388. ** column definition. This was either supplied by the user when the table
  117389. ** was created, or added later to the table definition by an ALTER TABLE
  117390. ** command. If the latter, then the row-records in the table btree on disk
  117391. ** may not contain a value for the column and the default value, taken
  117392. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  117393. ** If the former, then all row-records are guaranteed to include a value
  117394. ** for the column and the P4 value is not required.
  117395. **
  117396. ** Column definitions created by an ALTER TABLE command may only have
  117397. ** literal default values specified: a number, null or a string. (If a more
  117398. ** complicated default expression value was provided, it is evaluated
  117399. ** when the ALTER TABLE is executed and one of the literal values written
  117400. ** into the sqlite_master table.)
  117401. **
  117402. ** Therefore, the P4 parameter is only required if the default value for
  117403. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  117404. ** function is capable of transforming these types of expressions into
  117405. ** sqlite3_value objects.
  117406. **
  117407. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  117408. ** on register iReg. This is used when an equivalent integer value is
  117409. ** stored in place of an 8-byte floating point value in order to save
  117410. ** space.
  117411. */
  117412. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  117413. assert( pTab!=0 );
  117414. if( !pTab->pSelect ){
  117415. sqlite3_value *pValue = 0;
  117416. u8 enc = ENC(sqlite3VdbeDb(v));
  117417. Column *pCol = &pTab->aCol[i];
  117418. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  117419. assert( i<pTab->nCol );
  117420. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  117421. pCol->affinity, &pValue);
  117422. if( pValue ){
  117423. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  117424. }
  117425. }
  117426. #ifndef SQLITE_OMIT_FLOATING_POINT
  117427. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  117428. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  117429. }
  117430. #endif
  117431. }
  117432. /*
  117433. ** Process an UPDATE statement.
  117434. **
  117435. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  117436. ** \_______/ \________/ \______/ \________________/
  117437. * onError pTabList pChanges pWhere
  117438. */
  117439. SQLITE_PRIVATE void sqlite3Update(
  117440. Parse *pParse, /* The parser context */
  117441. SrcList *pTabList, /* The table in which we should change things */
  117442. ExprList *pChanges, /* Things to be changed */
  117443. Expr *pWhere, /* The WHERE clause. May be null */
  117444. int onError /* How to handle constraint errors */
  117445. ){
  117446. int i, j; /* Loop counters */
  117447. Table *pTab; /* The table to be updated */
  117448. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  117449. WhereInfo *pWInfo; /* Information about the WHERE clause */
  117450. Vdbe *v; /* The virtual database engine */
  117451. Index *pIdx; /* For looping over indices */
  117452. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  117453. int nIdx; /* Number of indices that need updating */
  117454. int iBaseCur; /* Base cursor number */
  117455. int iDataCur; /* Cursor for the canonical data btree */
  117456. int iIdxCur; /* Cursor for the first index */
  117457. sqlite3 *db; /* The database structure */
  117458. int *aRegIdx = 0; /* First register in array assigned to each index */
  117459. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  117460. ** an expression for the i-th column of the table.
  117461. ** aXRef[i]==-1 if the i-th column is not changed. */
  117462. u8 *aToOpen; /* 1 for tables and indices to be opened */
  117463. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  117464. u8 chngRowid; /* Rowid changed in a normal table */
  117465. u8 chngKey; /* Either chngPk or chngRowid */
  117466. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  117467. AuthContext sContext; /* The authorization context */
  117468. NameContext sNC; /* The name-context to resolve expressions in */
  117469. int iDb; /* Database containing the table being updated */
  117470. int eOnePass; /* ONEPASS_XXX value from where.c */
  117471. int hasFK; /* True if foreign key processing is required */
  117472. int labelBreak; /* Jump here to break out of UPDATE loop */
  117473. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  117474. int flags; /* Flags for sqlite3WhereBegin() */
  117475. #ifndef SQLITE_OMIT_TRIGGER
  117476. int isView; /* True when updating a view (INSTEAD OF trigger) */
  117477. Trigger *pTrigger; /* List of triggers on pTab, if required */
  117478. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  117479. #endif
  117480. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  117481. int iEph = 0; /* Ephemeral table holding all primary key values */
  117482. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  117483. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  117484. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  117485. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  117486. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  117487. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  117488. /* Register Allocations */
  117489. int regRowCount = 0; /* A count of rows changed */
  117490. int regOldRowid = 0; /* The old rowid */
  117491. int regNewRowid = 0; /* The new rowid */
  117492. int regNew = 0; /* Content of the NEW.* table in triggers */
  117493. int regOld = 0; /* Content of OLD.* table in triggers */
  117494. int regRowSet = 0; /* Rowset of rows to be updated */
  117495. int regKey = 0; /* composite PRIMARY KEY value */
  117496. memset(&sContext, 0, sizeof(sContext));
  117497. db = pParse->db;
  117498. if( pParse->nErr || db->mallocFailed ){
  117499. goto update_cleanup;
  117500. }
  117501. assert( pTabList->nSrc==1 );
  117502. /* Locate the table which we want to update.
  117503. */
  117504. pTab = sqlite3SrcListLookup(pParse, pTabList);
  117505. if( pTab==0 ) goto update_cleanup;
  117506. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  117507. /* Figure out if we have any triggers and if the table being
  117508. ** updated is a view.
  117509. */
  117510. #ifndef SQLITE_OMIT_TRIGGER
  117511. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  117512. isView = pTab->pSelect!=0;
  117513. assert( pTrigger || tmask==0 );
  117514. #else
  117515. # define pTrigger 0
  117516. # define isView 0
  117517. # define tmask 0
  117518. #endif
  117519. #ifdef SQLITE_OMIT_VIEW
  117520. # undef isView
  117521. # define isView 0
  117522. #endif
  117523. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  117524. goto update_cleanup;
  117525. }
  117526. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  117527. goto update_cleanup;
  117528. }
  117529. /* Allocate a cursors for the main database table and for all indices.
  117530. ** The index cursors might not be used, but if they are used they
  117531. ** need to occur right after the database cursor. So go ahead and
  117532. ** allocate enough space, just in case.
  117533. */
  117534. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  117535. iIdxCur = iDataCur+1;
  117536. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  117537. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  117538. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  117539. iDataCur = pParse->nTab;
  117540. pTabList->a[0].iCursor = iDataCur;
  117541. }
  117542. pParse->nTab++;
  117543. }
  117544. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  117545. ** Initialize aXRef[] and aToOpen[] to their default values.
  117546. */
  117547. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  117548. if( aXRef==0 ) goto update_cleanup;
  117549. aRegIdx = aXRef+pTab->nCol;
  117550. aToOpen = (u8*)(aRegIdx+nIdx);
  117551. memset(aToOpen, 1, nIdx+1);
  117552. aToOpen[nIdx+1] = 0;
  117553. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  117554. /* Initialize the name-context */
  117555. memset(&sNC, 0, sizeof(sNC));
  117556. sNC.pParse = pParse;
  117557. sNC.pSrcList = pTabList;
  117558. /* Resolve the column names in all the expressions of the
  117559. ** of the UPDATE statement. Also find the column index
  117560. ** for each column to be updated in the pChanges array. For each
  117561. ** column to be updated, make sure we have authorization to change
  117562. ** that column.
  117563. */
  117564. chngRowid = chngPk = 0;
  117565. for(i=0; i<pChanges->nExpr; i++){
  117566. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  117567. goto update_cleanup;
  117568. }
  117569. for(j=0; j<pTab->nCol; j++){
  117570. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  117571. if( j==pTab->iPKey ){
  117572. chngRowid = 1;
  117573. pRowidExpr = pChanges->a[i].pExpr;
  117574. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  117575. chngPk = 1;
  117576. }
  117577. aXRef[j] = i;
  117578. break;
  117579. }
  117580. }
  117581. if( j>=pTab->nCol ){
  117582. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  117583. j = -1;
  117584. chngRowid = 1;
  117585. pRowidExpr = pChanges->a[i].pExpr;
  117586. }else{
  117587. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  117588. pParse->checkSchema = 1;
  117589. goto update_cleanup;
  117590. }
  117591. }
  117592. #ifndef SQLITE_OMIT_AUTHORIZATION
  117593. {
  117594. int rc;
  117595. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  117596. j<0 ? "ROWID" : pTab->aCol[j].zName,
  117597. db->aDb[iDb].zDbSName);
  117598. if( rc==SQLITE_DENY ){
  117599. goto update_cleanup;
  117600. }else if( rc==SQLITE_IGNORE ){
  117601. aXRef[j] = -1;
  117602. }
  117603. }
  117604. #endif
  117605. }
  117606. assert( (chngRowid & chngPk)==0 );
  117607. assert( chngRowid==0 || chngRowid==1 );
  117608. assert( chngPk==0 || chngPk==1 );
  117609. chngKey = chngRowid + chngPk;
  117610. /* The SET expressions are not actually used inside the WHERE loop.
  117611. ** So reset the colUsed mask. Unless this is a virtual table. In that
  117612. ** case, set all bits of the colUsed mask (to ensure that the virtual
  117613. ** table implementation makes all columns available).
  117614. */
  117615. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  117616. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  117617. /* There is one entry in the aRegIdx[] array for each index on the table
  117618. ** being updated. Fill in aRegIdx[] with a register number that will hold
  117619. ** the key for accessing each index.
  117620. **
  117621. ** FIXME: Be smarter about omitting indexes that use expressions.
  117622. */
  117623. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  117624. int reg;
  117625. if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
  117626. reg = ++pParse->nMem;
  117627. pParse->nMem += pIdx->nColumn;
  117628. }else{
  117629. reg = 0;
  117630. for(i=0; i<pIdx->nKeyCol; i++){
  117631. i16 iIdxCol = pIdx->aiColumn[i];
  117632. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  117633. reg = ++pParse->nMem;
  117634. pParse->nMem += pIdx->nColumn;
  117635. if( (onError==OE_Replace)
  117636. || (onError==OE_Default && pIdx->onError==OE_Replace)
  117637. ){
  117638. bReplace = 1;
  117639. }
  117640. break;
  117641. }
  117642. }
  117643. }
  117644. if( reg==0 ) aToOpen[j+1] = 0;
  117645. aRegIdx[j] = reg;
  117646. }
  117647. if( bReplace ){
  117648. /* If REPLACE conflict resolution might be invoked, open cursors on all
  117649. ** indexes in case they are needed to delete records. */
  117650. memset(aToOpen, 1, nIdx+1);
  117651. }
  117652. /* Begin generating code. */
  117653. v = sqlite3GetVdbe(pParse);
  117654. if( v==0 ) goto update_cleanup;
  117655. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  117656. sqlite3BeginWriteOperation(pParse, 1, iDb);
  117657. /* Allocate required registers. */
  117658. if( !IsVirtual(pTab) ){
  117659. regRowSet = ++pParse->nMem;
  117660. regOldRowid = regNewRowid = ++pParse->nMem;
  117661. if( chngPk || pTrigger || hasFK ){
  117662. regOld = pParse->nMem + 1;
  117663. pParse->nMem += pTab->nCol;
  117664. }
  117665. if( chngKey || pTrigger || hasFK ){
  117666. regNewRowid = ++pParse->nMem;
  117667. }
  117668. regNew = pParse->nMem + 1;
  117669. pParse->nMem += pTab->nCol;
  117670. }
  117671. /* Start the view context. */
  117672. if( isView ){
  117673. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  117674. }
  117675. /* If we are trying to update a view, realize that view into
  117676. ** an ephemeral table.
  117677. */
  117678. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  117679. if( isView ){
  117680. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  117681. }
  117682. #endif
  117683. /* Resolve the column names in all the expressions in the
  117684. ** WHERE clause.
  117685. */
  117686. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  117687. goto update_cleanup;
  117688. }
  117689. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117690. /* Virtual tables must be handled separately */
  117691. if( IsVirtual(pTab) ){
  117692. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  117693. pWhere, onError);
  117694. goto update_cleanup;
  117695. }
  117696. #endif
  117697. /* Initialize the count of updated rows */
  117698. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  117699. regRowCount = ++pParse->nMem;
  117700. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  117701. }
  117702. if( HasRowid(pTab) ){
  117703. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  117704. }else{
  117705. assert( pPk!=0 );
  117706. nPk = pPk->nKeyCol;
  117707. iPk = pParse->nMem+1;
  117708. pParse->nMem += nPk;
  117709. regKey = ++pParse->nMem;
  117710. iEph = pParse->nTab++;
  117711. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  117712. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  117713. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  117714. }
  117715. /* Begin the database scan.
  117716. **
  117717. ** Do not consider a single-pass strategy for a multi-row update if
  117718. ** there are any triggers or foreign keys to process, or rows may
  117719. ** be deleted as a result of REPLACE conflict handling. Any of these
  117720. ** things might disturb a cursor being used to scan through the table
  117721. ** or index, causing a single-pass approach to malfunction. */
  117722. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  117723. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  117724. flags |= WHERE_ONEPASS_MULTIROW;
  117725. }
  117726. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  117727. if( pWInfo==0 ) goto update_cleanup;
  117728. /* A one-pass strategy that might update more than one row may not
  117729. ** be used if any column of the index used for the scan is being
  117730. ** updated. Otherwise, if there is an index on "b", statements like
  117731. ** the following could create an infinite loop:
  117732. **
  117733. ** UPDATE t1 SET b=b+1 WHERE b>?
  117734. **
  117735. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  117736. ** strategy that uses an index for which one or more columns are being
  117737. ** updated. */
  117738. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  117739. if( eOnePass==ONEPASS_MULTI ){
  117740. int iCur = aiCurOnePass[1];
  117741. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  117742. eOnePass = ONEPASS_OFF;
  117743. }
  117744. assert( iCur!=iDataCur || !HasRowid(pTab) );
  117745. }
  117746. if( HasRowid(pTab) ){
  117747. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  117748. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  117749. ** leave it in register regOldRowid. */
  117750. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  117751. if( eOnePass==ONEPASS_OFF ){
  117752. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  117753. }
  117754. }else{
  117755. /* Read the PK of the current row into an array of registers. In
  117756. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  117757. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  117758. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  117759. ** is not required) and leave the PK fields in the array of registers. */
  117760. for(i=0; i<nPk; i++){
  117761. assert( pPk->aiColumn[i]>=0 );
  117762. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  117763. }
  117764. if( eOnePass ){
  117765. sqlite3VdbeChangeToNoop(v, addrOpen);
  117766. nKey = nPk;
  117767. regKey = iPk;
  117768. }else{
  117769. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  117770. sqlite3IndexAffinityStr(db, pPk), nPk);
  117771. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  117772. }
  117773. }
  117774. if( eOnePass!=ONEPASS_MULTI ){
  117775. sqlite3WhereEnd(pWInfo);
  117776. }
  117777. labelBreak = sqlite3VdbeMakeLabel(v);
  117778. if( !isView ){
  117779. int addrOnce = 0;
  117780. /* Open every index that needs updating. */
  117781. if( eOnePass!=ONEPASS_OFF ){
  117782. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  117783. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  117784. }
  117785. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  117786. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  117787. }
  117788. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  117789. 0, 0);
  117790. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  117791. }
  117792. /* Top of the update loop */
  117793. if( eOnePass!=ONEPASS_OFF ){
  117794. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  117795. assert( pPk );
  117796. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  117797. VdbeCoverageNeverTaken(v);
  117798. }
  117799. if( eOnePass==ONEPASS_SINGLE ){
  117800. labelContinue = labelBreak;
  117801. }else{
  117802. labelContinue = sqlite3VdbeMakeLabel(v);
  117803. }
  117804. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  117805. VdbeCoverageIf(v, pPk==0);
  117806. VdbeCoverageIf(v, pPk!=0);
  117807. }else if( pPk ){
  117808. labelContinue = sqlite3VdbeMakeLabel(v);
  117809. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  117810. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  117811. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  117812. VdbeCoverage(v);
  117813. }else{
  117814. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  117815. regOldRowid);
  117816. VdbeCoverage(v);
  117817. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  117818. VdbeCoverage(v);
  117819. }
  117820. /* If the record number will change, set register regNewRowid to
  117821. ** contain the new value. If the record number is not being modified,
  117822. ** then regNewRowid is the same register as regOldRowid, which is
  117823. ** already populated. */
  117824. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  117825. if( chngRowid ){
  117826. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  117827. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  117828. }
  117829. /* Compute the old pre-UPDATE content of the row being changed, if that
  117830. ** information is needed */
  117831. if( chngPk || hasFK || pTrigger ){
  117832. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  117833. oldmask |= sqlite3TriggerColmask(pParse,
  117834. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  117835. );
  117836. for(i=0; i<pTab->nCol; i++){
  117837. if( oldmask==0xffffffff
  117838. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  117839. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  117840. ){
  117841. testcase( oldmask!=0xffffffff && i==31 );
  117842. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  117843. }else{
  117844. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  117845. }
  117846. }
  117847. if( chngRowid==0 && pPk==0 ){
  117848. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  117849. }
  117850. }
  117851. /* Populate the array of registers beginning at regNew with the new
  117852. ** row data. This array is used to check constants, create the new
  117853. ** table and index records, and as the values for any new.* references
  117854. ** made by triggers.
  117855. **
  117856. ** If there are one or more BEFORE triggers, then do not populate the
  117857. ** registers associated with columns that are (a) not modified by
  117858. ** this UPDATE statement and (b) not accessed by new.* references. The
  117859. ** values for registers not modified by the UPDATE must be reloaded from
  117860. ** the database after the BEFORE triggers are fired anyway (as the trigger
  117861. ** may have modified them). So not loading those that are not going to
  117862. ** be used eliminates some redundant opcodes.
  117863. */
  117864. newmask = sqlite3TriggerColmask(
  117865. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  117866. );
  117867. for(i=0; i<pTab->nCol; i++){
  117868. if( i==pTab->iPKey ){
  117869. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  117870. }else{
  117871. j = aXRef[i];
  117872. if( j>=0 ){
  117873. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  117874. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  117875. /* This branch loads the value of a column that will not be changed
  117876. ** into a register. This is done if there are no BEFORE triggers, or
  117877. ** if there are one or more BEFORE triggers that use this value via
  117878. ** a new.* reference in a trigger program.
  117879. */
  117880. testcase( i==31 );
  117881. testcase( i==32 );
  117882. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  117883. }else{
  117884. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  117885. }
  117886. }
  117887. }
  117888. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  117889. ** verified. One could argue that this is wrong.
  117890. */
  117891. if( tmask&TRIGGER_BEFORE ){
  117892. sqlite3TableAffinity(v, pTab, regNew);
  117893. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  117894. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  117895. /* The row-trigger may have deleted the row being updated. In this
  117896. ** case, jump to the next row. No updates or AFTER triggers are
  117897. ** required. This behavior - what happens when the row being updated
  117898. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  117899. ** documentation.
  117900. */
  117901. if( pPk ){
  117902. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  117903. VdbeCoverage(v);
  117904. }else{
  117905. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  117906. VdbeCoverage(v);
  117907. }
  117908. /* If it did not delete it, the row-trigger may still have modified
  117909. ** some of the columns of the row being updated. Load the values for
  117910. ** all columns not modified by the update statement into their
  117911. ** registers in case this has happened.
  117912. */
  117913. for(i=0; i<pTab->nCol; i++){
  117914. if( aXRef[i]<0 && i!=pTab->iPKey ){
  117915. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  117916. }
  117917. }
  117918. }
  117919. if( !isView ){
  117920. int addr1 = 0; /* Address of jump instruction */
  117921. /* Do constraint checks. */
  117922. assert( regOldRowid>0 );
  117923. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  117924. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  117925. aXRef);
  117926. /* Do FK constraint checks. */
  117927. if( hasFK ){
  117928. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  117929. }
  117930. /* Delete the index entries associated with the current record. */
  117931. if( bReplace || chngKey ){
  117932. if( pPk ){
  117933. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  117934. }else{
  117935. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  117936. }
  117937. VdbeCoverageNeverTaken(v);
  117938. }
  117939. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  117940. /* If changing the rowid value, or if there are foreign key constraints
  117941. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  117942. ** to invoke the pre-update hook.
  117943. **
  117944. ** That (regNew==regnewRowid+1) is true is also important for the
  117945. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  117946. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  117947. ** is the column index supplied by the user.
  117948. */
  117949. assert( regNew==regNewRowid+1 );
  117950. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  117951. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  117952. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  117953. regNewRowid
  117954. );
  117955. if( eOnePass==ONEPASS_MULTI ){
  117956. assert( hasFK==0 && chngKey==0 );
  117957. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  117958. }
  117959. if( !pParse->nested ){
  117960. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  117961. }
  117962. #else
  117963. if( hasFK>1 || chngKey ){
  117964. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  117965. }
  117966. #endif
  117967. if( bReplace || chngKey ){
  117968. sqlite3VdbeJumpHere(v, addr1);
  117969. }
  117970. if( hasFK ){
  117971. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  117972. }
  117973. /* Insert the new index entries and the new record. */
  117974. sqlite3CompleteInsertion(
  117975. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  117976. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  117977. 0, 0
  117978. );
  117979. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  117980. ** handle rows (possibly in other tables) that refer via a foreign key
  117981. ** to the row just updated. */
  117982. if( hasFK ){
  117983. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  117984. }
  117985. }
  117986. /* Increment the row counter
  117987. */
  117988. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  117989. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  117990. }
  117991. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  117992. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  117993. /* Repeat the above with the next record to be updated, until
  117994. ** all record selected by the WHERE clause have been updated.
  117995. */
  117996. if( eOnePass==ONEPASS_SINGLE ){
  117997. /* Nothing to do at end-of-loop for a single-pass */
  117998. }else if( eOnePass==ONEPASS_MULTI ){
  117999. sqlite3VdbeResolveLabel(v, labelContinue);
  118000. sqlite3WhereEnd(pWInfo);
  118001. }else if( pPk ){
  118002. sqlite3VdbeResolveLabel(v, labelContinue);
  118003. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  118004. }else{
  118005. sqlite3VdbeGoto(v, labelContinue);
  118006. }
  118007. sqlite3VdbeResolveLabel(v, labelBreak);
  118008. /* Update the sqlite_sequence table by storing the content of the
  118009. ** maximum rowid counter values recorded while inserting into
  118010. ** autoincrement tables.
  118011. */
  118012. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  118013. sqlite3AutoincrementEnd(pParse);
  118014. }
  118015. /*
  118016. ** Return the number of rows that were changed. If this routine is
  118017. ** generating code because of a call to sqlite3NestedParse(), do not
  118018. ** invoke the callback function.
  118019. */
  118020. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  118021. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  118022. sqlite3VdbeSetNumCols(v, 1);
  118023. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  118024. }
  118025. update_cleanup:
  118026. sqlite3AuthContextPop(&sContext);
  118027. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  118028. sqlite3SrcListDelete(db, pTabList);
  118029. sqlite3ExprListDelete(db, pChanges);
  118030. sqlite3ExprDelete(db, pWhere);
  118031. return;
  118032. }
  118033. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  118034. ** they may interfere with compilation of other functions in this file
  118035. ** (or in another file, if this file becomes part of the amalgamation). */
  118036. #ifdef isView
  118037. #undef isView
  118038. #endif
  118039. #ifdef pTrigger
  118040. #undef pTrigger
  118041. #endif
  118042. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118043. /*
  118044. ** Generate code for an UPDATE of a virtual table.
  118045. **
  118046. ** There are two possible strategies - the default and the special
  118047. ** "onepass" strategy. Onepass is only used if the virtual table
  118048. ** implementation indicates that pWhere may match at most one row.
  118049. **
  118050. ** The default strategy is to create an ephemeral table that contains
  118051. ** for each row to be changed:
  118052. **
  118053. ** (A) The original rowid of that row.
  118054. ** (B) The revised rowid for the row.
  118055. ** (C) The content of every column in the row.
  118056. **
  118057. ** Then loop through the contents of this ephemeral table executing a
  118058. ** VUpdate for each row. When finished, drop the ephemeral table.
  118059. **
  118060. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  118061. ** stores the same values (A, B and C above) in a register array and
  118062. ** makes a single invocation of VUpdate.
  118063. */
  118064. static void updateVirtualTable(
  118065. Parse *pParse, /* The parsing context */
  118066. SrcList *pSrc, /* The virtual table to be modified */
  118067. Table *pTab, /* The virtual table */
  118068. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  118069. Expr *pRowid, /* Expression used to recompute the rowid */
  118070. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  118071. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  118072. int onError /* ON CONFLICT strategy */
  118073. ){
  118074. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  118075. int ephemTab; /* Table holding the result of the SELECT */
  118076. int i; /* Loop counter */
  118077. sqlite3 *db = pParse->db; /* Database connection */
  118078. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  118079. WhereInfo *pWInfo;
  118080. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  118081. int regArg; /* First register in VUpdate arg array */
  118082. int regRec; /* Register in which to assemble record */
  118083. int regRowid; /* Register for ephem table rowid */
  118084. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  118085. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  118086. int bOnePass; /* True to use onepass strategy */
  118087. int addr; /* Address of OP_OpenEphemeral */
  118088. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  118089. ** create and open the ephemeral table in which the records created from
  118090. ** these arguments will be temporarily stored. */
  118091. assert( v );
  118092. ephemTab = pParse->nTab++;
  118093. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  118094. regArg = pParse->nMem + 1;
  118095. pParse->nMem += nArg;
  118096. regRec = ++pParse->nMem;
  118097. regRowid = ++pParse->nMem;
  118098. /* Start scanning the virtual table */
  118099. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  118100. if( pWInfo==0 ) return;
  118101. /* Populate the argument registers. */
  118102. for(i=0; i<pTab->nCol; i++){
  118103. if( aXRef[i]>=0 ){
  118104. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  118105. }else{
  118106. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  118107. }
  118108. }
  118109. if( HasRowid(pTab) ){
  118110. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  118111. if( pRowid ){
  118112. sqlite3ExprCode(pParse, pRowid, regArg+1);
  118113. }else{
  118114. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  118115. }
  118116. }else{
  118117. Index *pPk; /* PRIMARY KEY index */
  118118. i16 iPk; /* PRIMARY KEY column */
  118119. pPk = sqlite3PrimaryKeyIndex(pTab);
  118120. assert( pPk!=0 );
  118121. assert( pPk->nKeyCol==1 );
  118122. iPk = pPk->aiColumn[0];
  118123. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  118124. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  118125. }
  118126. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  118127. if( bOnePass ){
  118128. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  118129. ** above. Also, if this is a top-level parse (not a trigger), clear the
  118130. ** multi-write flag so that the VM does not open a statement journal */
  118131. sqlite3VdbeChangeToNoop(v, addr);
  118132. if( sqlite3IsToplevel(pParse) ){
  118133. pParse->isMultiWrite = 0;
  118134. }
  118135. }else{
  118136. /* Create a record from the argument register contents and insert it into
  118137. ** the ephemeral table. */
  118138. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  118139. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  118140. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  118141. }
  118142. if( bOnePass==0 ){
  118143. /* End the virtual table scan */
  118144. sqlite3WhereEnd(pWInfo);
  118145. /* Begin scannning through the ephemeral table. */
  118146. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  118147. /* Extract arguments from the current row of the ephemeral table and
  118148. ** invoke the VUpdate method. */
  118149. for(i=0; i<nArg; i++){
  118150. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  118151. }
  118152. }
  118153. sqlite3VtabMakeWritable(pParse, pTab);
  118154. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  118155. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  118156. sqlite3MayAbort(pParse);
  118157. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  118158. ** jump to here if the scan visited zero rows. */
  118159. if( bOnePass==0 ){
  118160. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  118161. sqlite3VdbeJumpHere(v, addr);
  118162. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  118163. }else{
  118164. sqlite3WhereEnd(pWInfo);
  118165. }
  118166. }
  118167. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  118168. /************** End of update.c **********************************************/
  118169. /************** Begin file vacuum.c ******************************************/
  118170. /*
  118171. ** 2003 April 6
  118172. **
  118173. ** The author disclaims copyright to this source code. In place of
  118174. ** a legal notice, here is a blessing:
  118175. **
  118176. ** May you do good and not evil.
  118177. ** May you find forgiveness for yourself and forgive others.
  118178. ** May you share freely, never taking more than you give.
  118179. **
  118180. *************************************************************************
  118181. ** This file contains code used to implement the VACUUM command.
  118182. **
  118183. ** Most of the code in this file may be omitted by defining the
  118184. ** SQLITE_OMIT_VACUUM macro.
  118185. */
  118186. /* #include "sqliteInt.h" */
  118187. /* #include "vdbeInt.h" */
  118188. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  118189. /*
  118190. ** Execute zSql on database db.
  118191. **
  118192. ** If zSql returns rows, then each row will have exactly one
  118193. ** column. (This will only happen if zSql begins with "SELECT".)
  118194. ** Take each row of result and call execSql() again recursively.
  118195. **
  118196. ** The execSqlF() routine does the same thing, except it accepts
  118197. ** a format string as its third argument
  118198. */
  118199. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  118200. sqlite3_stmt *pStmt;
  118201. int rc;
  118202. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  118203. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  118204. if( rc!=SQLITE_OK ) return rc;
  118205. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  118206. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  118207. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  118208. if( zSubSql ){
  118209. assert( zSubSql[0]!='S' );
  118210. rc = execSql(db, pzErrMsg, zSubSql);
  118211. if( rc!=SQLITE_OK ) break;
  118212. }
  118213. }
  118214. assert( rc!=SQLITE_ROW );
  118215. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  118216. if( rc ){
  118217. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  118218. }
  118219. (void)sqlite3_finalize(pStmt);
  118220. return rc;
  118221. }
  118222. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  118223. char *z;
  118224. va_list ap;
  118225. int rc;
  118226. va_start(ap, zSql);
  118227. z = sqlite3VMPrintf(db, zSql, ap);
  118228. va_end(ap);
  118229. if( z==0 ) return SQLITE_NOMEM;
  118230. rc = execSql(db, pzErrMsg, z);
  118231. sqlite3DbFree(db, z);
  118232. return rc;
  118233. }
  118234. /*
  118235. ** The VACUUM command is used to clean up the database,
  118236. ** collapse free space, etc. It is modelled after the VACUUM command
  118237. ** in PostgreSQL. The VACUUM command works as follows:
  118238. **
  118239. ** (1) Create a new transient database file
  118240. ** (2) Copy all content from the database being vacuumed into
  118241. ** the new transient database file
  118242. ** (3) Copy content from the transient database back into the
  118243. ** original database.
  118244. **
  118245. ** The transient database requires temporary disk space approximately
  118246. ** equal to the size of the original database. The copy operation of
  118247. ** step (3) requires additional temporary disk space approximately equal
  118248. ** to the size of the original database for the rollback journal.
  118249. ** Hence, temporary disk space that is approximately 2x the size of the
  118250. ** original database is required. Every page of the database is written
  118251. ** approximately 3 times: Once for step (2) and twice for step (3).
  118252. ** Two writes per page are required in step (3) because the original
  118253. ** database content must be written into the rollback journal prior to
  118254. ** overwriting the database with the vacuumed content.
  118255. **
  118256. ** Only 1x temporary space and only 1x writes would be required if
  118257. ** the copy of step (3) were replaced by deleting the original database
  118258. ** and renaming the transient database as the original. But that will
  118259. ** not work if other processes are attached to the original database.
  118260. ** And a power loss in between deleting the original and renaming the
  118261. ** transient would cause the database file to appear to be deleted
  118262. ** following reboot.
  118263. */
  118264. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  118265. Vdbe *v = sqlite3GetVdbe(pParse);
  118266. int iDb = 0;
  118267. if( v==0 ) return;
  118268. if( pNm ){
  118269. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  118270. /* Default behavior: Report an error if the argument to VACUUM is
  118271. ** not recognized */
  118272. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  118273. if( iDb<0 ) return;
  118274. #else
  118275. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  118276. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  118277. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  118278. ** The buggy behavior is required for binary compatibility with some
  118279. ** legacy applications. */
  118280. iDb = sqlite3FindDb(pParse->db, pNm);
  118281. if( iDb<0 ) iDb = 0;
  118282. #endif
  118283. }
  118284. if( iDb!=1 ){
  118285. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  118286. sqlite3VdbeUsesBtree(v, iDb);
  118287. }
  118288. return;
  118289. }
  118290. /*
  118291. ** This routine implements the OP_Vacuum opcode of the VDBE.
  118292. */
  118293. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  118294. int rc = SQLITE_OK; /* Return code from service routines */
  118295. Btree *pMain; /* The database being vacuumed */
  118296. Btree *pTemp; /* The temporary database we vacuum into */
  118297. u16 saved_mDbFlags; /* Saved value of db->mDbFlags */
  118298. u32 saved_flags; /* Saved value of db->flags */
  118299. int saved_nChange; /* Saved value of db->nChange */
  118300. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  118301. u8 saved_mTrace; /* Saved trace settings */
  118302. Db *pDb = 0; /* Database to detach at end of vacuum */
  118303. int isMemDb; /* True if vacuuming a :memory: database */
  118304. int nRes; /* Bytes of reserved space at the end of each page */
  118305. int nDb; /* Number of attached databases */
  118306. const char *zDbMain; /* Schema name of database to vacuum */
  118307. if( !db->autoCommit ){
  118308. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  118309. return SQLITE_ERROR;
  118310. }
  118311. if( db->nVdbeActive>1 ){
  118312. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  118313. return SQLITE_ERROR;
  118314. }
  118315. /* Save the current value of the database flags so that it can be
  118316. ** restored before returning. Then set the writable-schema flag, and
  118317. ** disable CHECK and foreign key constraints. */
  118318. saved_flags = db->flags;
  118319. saved_mDbFlags = db->mDbFlags;
  118320. saved_nChange = db->nChange;
  118321. saved_nTotalChange = db->nTotalChange;
  118322. saved_mTrace = db->mTrace;
  118323. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  118324. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  118325. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
  118326. db->mTrace = 0;
  118327. zDbMain = db->aDb[iDb].zDbSName;
  118328. pMain = db->aDb[iDb].pBt;
  118329. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  118330. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  118331. ** can be set to 'off' for this file, as it is not recovered if a crash
  118332. ** occurs anyway. The integrity of the database is maintained by a
  118333. ** (possibly synchronous) transaction opened on the main database before
  118334. ** sqlite3BtreeCopyFile() is called.
  118335. **
  118336. ** An optimisation would be to use a non-journaled pager.
  118337. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  118338. ** that actually made the VACUUM run slower. Very little journalling
  118339. ** actually occurs when doing a vacuum since the vacuum_db is initially
  118340. ** empty. Only the journal header is written. Apparently it takes more
  118341. ** time to parse and run the PRAGMA to turn journalling off than it does
  118342. ** to write the journal header file.
  118343. */
  118344. nDb = db->nDb;
  118345. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  118346. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118347. assert( (db->nDb-1)==nDb );
  118348. pDb = &db->aDb[nDb];
  118349. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  118350. pTemp = pDb->pBt;
  118351. /* The call to execSql() to attach the temp database has left the file
  118352. ** locked (as there was more than one active statement when the transaction
  118353. ** to read the schema was concluded. Unlock it here so that this doesn't
  118354. ** cause problems for the call to BtreeSetPageSize() below. */
  118355. sqlite3BtreeCommit(pTemp);
  118356. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  118357. /* A VACUUM cannot change the pagesize of an encrypted database. */
  118358. #ifdef SQLITE_HAS_CODEC
  118359. if( db->nextPagesize ){
  118360. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  118361. int nKey;
  118362. char *zKey;
  118363. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  118364. if( nKey ) db->nextPagesize = 0;
  118365. }
  118366. #endif
  118367. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  118368. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  118369. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  118370. /* Begin a transaction and take an exclusive lock on the main database
  118371. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  118372. ** to ensure that we do not try to change the page-size on a WAL database.
  118373. */
  118374. rc = execSql(db, pzErrMsg, "BEGIN");
  118375. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118376. rc = sqlite3BtreeBeginTrans(pMain, 2);
  118377. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118378. /* Do not attempt to change the page size for a WAL database */
  118379. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  118380. ==PAGER_JOURNALMODE_WAL ){
  118381. db->nextPagesize = 0;
  118382. }
  118383. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  118384. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  118385. || NEVER(db->mallocFailed)
  118386. ){
  118387. rc = SQLITE_NOMEM_BKPT;
  118388. goto end_of_vacuum;
  118389. }
  118390. #ifndef SQLITE_OMIT_AUTOVACUUM
  118391. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  118392. sqlite3BtreeGetAutoVacuum(pMain));
  118393. #endif
  118394. /* Query the schema of the main database. Create a mirror schema
  118395. ** in the temporary database.
  118396. */
  118397. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  118398. rc = execSqlF(db, pzErrMsg,
  118399. "SELECT sql FROM \"%w\".sqlite_master"
  118400. " WHERE type='table'AND name<>'sqlite_sequence'"
  118401. " AND coalesce(rootpage,1)>0",
  118402. zDbMain
  118403. );
  118404. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118405. rc = execSqlF(db, pzErrMsg,
  118406. "SELECT sql FROM \"%w\".sqlite_master"
  118407. " WHERE type='index' AND length(sql)>10",
  118408. zDbMain
  118409. );
  118410. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118411. db->init.iDb = 0;
  118412. /* Loop through the tables in the main database. For each, do
  118413. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  118414. ** the contents to the temporary database.
  118415. */
  118416. rc = execSqlF(db, pzErrMsg,
  118417. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  118418. "||' SELECT*FROM\"%w\".'||quote(name)"
  118419. "FROM vacuum_db.sqlite_master "
  118420. "WHERE type='table'AND coalesce(rootpage,1)>0",
  118421. zDbMain
  118422. );
  118423. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  118424. db->mDbFlags &= ~DBFLAG_Vacuum;
  118425. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118426. /* Copy the triggers, views, and virtual tables from the main database
  118427. ** over to the temporary database. None of these objects has any
  118428. ** associated storage, so all we have to do is copy their entries
  118429. ** from the SQLITE_MASTER table.
  118430. */
  118431. rc = execSqlF(db, pzErrMsg,
  118432. "INSERT INTO vacuum_db.sqlite_master"
  118433. " SELECT*FROM \"%w\".sqlite_master"
  118434. " WHERE type IN('view','trigger')"
  118435. " OR(type='table'AND rootpage=0)",
  118436. zDbMain
  118437. );
  118438. if( rc ) goto end_of_vacuum;
  118439. /* At this point, there is a write transaction open on both the
  118440. ** vacuum database and the main database. Assuming no error occurs,
  118441. ** both transactions are closed by this block - the main database
  118442. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  118443. ** call to sqlite3BtreeCommit().
  118444. */
  118445. {
  118446. u32 meta;
  118447. int i;
  118448. /* This array determines which meta meta values are preserved in the
  118449. ** vacuum. Even entries are the meta value number and odd entries
  118450. ** are an increment to apply to the meta value after the vacuum.
  118451. ** The increment is used to increase the schema cookie so that other
  118452. ** connections to the same database will know to reread the schema.
  118453. */
  118454. static const unsigned char aCopy[] = {
  118455. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  118456. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  118457. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  118458. BTREE_USER_VERSION, 0, /* Preserve the user version */
  118459. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  118460. };
  118461. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  118462. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  118463. /* Copy Btree meta values */
  118464. for(i=0; i<ArraySize(aCopy); i+=2){
  118465. /* GetMeta() and UpdateMeta() cannot fail in this context because
  118466. ** we already have page 1 loaded into cache and marked dirty. */
  118467. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  118468. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  118469. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  118470. }
  118471. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  118472. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118473. rc = sqlite3BtreeCommit(pTemp);
  118474. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  118475. #ifndef SQLITE_OMIT_AUTOVACUUM
  118476. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  118477. #endif
  118478. }
  118479. assert( rc==SQLITE_OK );
  118480. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  118481. end_of_vacuum:
  118482. /* Restore the original value of db->flags */
  118483. db->init.iDb = 0;
  118484. db->mDbFlags = saved_mDbFlags;
  118485. db->flags = saved_flags;
  118486. db->nChange = saved_nChange;
  118487. db->nTotalChange = saved_nTotalChange;
  118488. db->mTrace = saved_mTrace;
  118489. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  118490. /* Currently there is an SQL level transaction open on the vacuum
  118491. ** database. No locks are held on any other files (since the main file
  118492. ** was committed at the btree level). So it safe to end the transaction
  118493. ** by manually setting the autoCommit flag to true and detaching the
  118494. ** vacuum database. The vacuum_db journal file is deleted when the pager
  118495. ** is closed by the DETACH.
  118496. */
  118497. db->autoCommit = 1;
  118498. if( pDb ){
  118499. sqlite3BtreeClose(pDb->pBt);
  118500. pDb->pBt = 0;
  118501. pDb->pSchema = 0;
  118502. }
  118503. /* This both clears the schemas and reduces the size of the db->aDb[]
  118504. ** array. */
  118505. sqlite3ResetAllSchemasOfConnection(db);
  118506. return rc;
  118507. }
  118508. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  118509. /************** End of vacuum.c **********************************************/
  118510. /************** Begin file vtab.c ********************************************/
  118511. /*
  118512. ** 2006 June 10
  118513. **
  118514. ** The author disclaims copyright to this source code. In place of
  118515. ** a legal notice, here is a blessing:
  118516. **
  118517. ** May you do good and not evil.
  118518. ** May you find forgiveness for yourself and forgive others.
  118519. ** May you share freely, never taking more than you give.
  118520. **
  118521. *************************************************************************
  118522. ** This file contains code used to help implement virtual tables.
  118523. */
  118524. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118525. /* #include "sqliteInt.h" */
  118526. /*
  118527. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  118528. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  118529. ** this struct allocated on the stack. It is used by the implementation of
  118530. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  118531. ** are invoked only from within xCreate and xConnect methods.
  118532. */
  118533. struct VtabCtx {
  118534. VTable *pVTable; /* The virtual table being constructed */
  118535. Table *pTab; /* The Table object to which the virtual table belongs */
  118536. VtabCtx *pPrior; /* Parent context (if any) */
  118537. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  118538. };
  118539. /*
  118540. ** Construct and install a Module object for a virtual table. When this
  118541. ** routine is called, it is guaranteed that all appropriate locks are held
  118542. ** and the module is not already part of the connection.
  118543. */
  118544. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  118545. sqlite3 *db, /* Database in which module is registered */
  118546. const char *zName, /* Name assigned to this module */
  118547. const sqlite3_module *pModule, /* The definition of the module */
  118548. void *pAux, /* Context pointer for xCreate/xConnect */
  118549. void (*xDestroy)(void *) /* Module destructor function */
  118550. ){
  118551. Module *pMod;
  118552. int nName = sqlite3Strlen30(zName);
  118553. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  118554. if( pMod==0 ){
  118555. sqlite3OomFault(db);
  118556. }else{
  118557. Module *pDel;
  118558. char *zCopy = (char *)(&pMod[1]);
  118559. memcpy(zCopy, zName, nName+1);
  118560. pMod->zName = zCopy;
  118561. pMod->pModule = pModule;
  118562. pMod->pAux = pAux;
  118563. pMod->xDestroy = xDestroy;
  118564. pMod->pEpoTab = 0;
  118565. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  118566. assert( pDel==0 || pDel==pMod );
  118567. if( pDel ){
  118568. sqlite3OomFault(db);
  118569. sqlite3DbFree(db, pDel);
  118570. pMod = 0;
  118571. }
  118572. }
  118573. return pMod;
  118574. }
  118575. /*
  118576. ** The actual function that does the work of creating a new module.
  118577. ** This function implements the sqlite3_create_module() and
  118578. ** sqlite3_create_module_v2() interfaces.
  118579. */
  118580. static int createModule(
  118581. sqlite3 *db, /* Database in which module is registered */
  118582. const char *zName, /* Name assigned to this module */
  118583. const sqlite3_module *pModule, /* The definition of the module */
  118584. void *pAux, /* Context pointer for xCreate/xConnect */
  118585. void (*xDestroy)(void *) /* Module destructor function */
  118586. ){
  118587. int rc = SQLITE_OK;
  118588. sqlite3_mutex_enter(db->mutex);
  118589. if( sqlite3HashFind(&db->aModule, zName) ){
  118590. rc = SQLITE_MISUSE_BKPT;
  118591. }else{
  118592. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  118593. }
  118594. rc = sqlite3ApiExit(db, rc);
  118595. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  118596. sqlite3_mutex_leave(db->mutex);
  118597. return rc;
  118598. }
  118599. /*
  118600. ** External API function used to create a new virtual-table module.
  118601. */
  118602. SQLITE_API int sqlite3_create_module(
  118603. sqlite3 *db, /* Database in which module is registered */
  118604. const char *zName, /* Name assigned to this module */
  118605. const sqlite3_module *pModule, /* The definition of the module */
  118606. void *pAux /* Context pointer for xCreate/xConnect */
  118607. ){
  118608. #ifdef SQLITE_ENABLE_API_ARMOR
  118609. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  118610. #endif
  118611. return createModule(db, zName, pModule, pAux, 0);
  118612. }
  118613. /*
  118614. ** External API function used to create a new virtual-table module.
  118615. */
  118616. SQLITE_API int sqlite3_create_module_v2(
  118617. sqlite3 *db, /* Database in which module is registered */
  118618. const char *zName, /* Name assigned to this module */
  118619. const sqlite3_module *pModule, /* The definition of the module */
  118620. void *pAux, /* Context pointer for xCreate/xConnect */
  118621. void (*xDestroy)(void *) /* Module destructor function */
  118622. ){
  118623. #ifdef SQLITE_ENABLE_API_ARMOR
  118624. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  118625. #endif
  118626. return createModule(db, zName, pModule, pAux, xDestroy);
  118627. }
  118628. /*
  118629. ** Lock the virtual table so that it cannot be disconnected.
  118630. ** Locks nest. Every lock should have a corresponding unlock.
  118631. ** If an unlock is omitted, resources leaks will occur.
  118632. **
  118633. ** If a disconnect is attempted while a virtual table is locked,
  118634. ** the disconnect is deferred until all locks have been removed.
  118635. */
  118636. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  118637. pVTab->nRef++;
  118638. }
  118639. /*
  118640. ** pTab is a pointer to a Table structure representing a virtual-table.
  118641. ** Return a pointer to the VTable object used by connection db to access
  118642. ** this virtual-table, if one has been created, or NULL otherwise.
  118643. */
  118644. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  118645. VTable *pVtab;
  118646. assert( IsVirtual(pTab) );
  118647. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  118648. return pVtab;
  118649. }
  118650. /*
  118651. ** Decrement the ref-count on a virtual table object. When the ref-count
  118652. ** reaches zero, call the xDisconnect() method to delete the object.
  118653. */
  118654. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  118655. sqlite3 *db = pVTab->db;
  118656. assert( db );
  118657. assert( pVTab->nRef>0 );
  118658. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  118659. pVTab->nRef--;
  118660. if( pVTab->nRef==0 ){
  118661. sqlite3_vtab *p = pVTab->pVtab;
  118662. if( p ){
  118663. p->pModule->xDisconnect(p);
  118664. }
  118665. sqlite3DbFree(db, pVTab);
  118666. }
  118667. }
  118668. /*
  118669. ** Table p is a virtual table. This function moves all elements in the
  118670. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  118671. ** database connections to be disconnected at the next opportunity.
  118672. ** Except, if argument db is not NULL, then the entry associated with
  118673. ** connection db is left in the p->pVTable list.
  118674. */
  118675. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  118676. VTable *pRet = 0;
  118677. VTable *pVTable = p->pVTable;
  118678. p->pVTable = 0;
  118679. /* Assert that the mutex (if any) associated with the BtShared database
  118680. ** that contains table p is held by the caller. See header comments
  118681. ** above function sqlite3VtabUnlockList() for an explanation of why
  118682. ** this makes it safe to access the sqlite3.pDisconnect list of any
  118683. ** database connection that may have an entry in the p->pVTable list.
  118684. */
  118685. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  118686. while( pVTable ){
  118687. sqlite3 *db2 = pVTable->db;
  118688. VTable *pNext = pVTable->pNext;
  118689. assert( db2 );
  118690. if( db2==db ){
  118691. pRet = pVTable;
  118692. p->pVTable = pRet;
  118693. pRet->pNext = 0;
  118694. }else{
  118695. pVTable->pNext = db2->pDisconnect;
  118696. db2->pDisconnect = pVTable;
  118697. }
  118698. pVTable = pNext;
  118699. }
  118700. assert( !db || pRet );
  118701. return pRet;
  118702. }
  118703. /*
  118704. ** Table *p is a virtual table. This function removes the VTable object
  118705. ** for table *p associated with database connection db from the linked
  118706. ** list in p->pVTab. It also decrements the VTable ref count. This is
  118707. ** used when closing database connection db to free all of its VTable
  118708. ** objects without disturbing the rest of the Schema object (which may
  118709. ** be being used by other shared-cache connections).
  118710. */
  118711. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  118712. VTable **ppVTab;
  118713. assert( IsVirtual(p) );
  118714. assert( sqlite3BtreeHoldsAllMutexes(db) );
  118715. assert( sqlite3_mutex_held(db->mutex) );
  118716. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  118717. if( (*ppVTab)->db==db ){
  118718. VTable *pVTab = *ppVTab;
  118719. *ppVTab = pVTab->pNext;
  118720. sqlite3VtabUnlock(pVTab);
  118721. break;
  118722. }
  118723. }
  118724. }
  118725. /*
  118726. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  118727. **
  118728. ** This function may only be called when the mutexes associated with all
  118729. ** shared b-tree databases opened using connection db are held by the
  118730. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  118731. ** sqlite3.pDisconnect list is accessed only as follows:
  118732. **
  118733. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  118734. ** associated with the database handle itself must be held.
  118735. **
  118736. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  118737. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  118738. ** associated with the database the virtual table is stored in is held
  118739. ** or, if the virtual table is stored in a non-sharable database, then
  118740. ** the database handle mutex is held.
  118741. **
  118742. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  118743. ** by multiple threads. It is thread-safe.
  118744. */
  118745. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  118746. VTable *p = db->pDisconnect;
  118747. db->pDisconnect = 0;
  118748. assert( sqlite3BtreeHoldsAllMutexes(db) );
  118749. assert( sqlite3_mutex_held(db->mutex) );
  118750. if( p ){
  118751. sqlite3ExpirePreparedStatements(db);
  118752. do {
  118753. VTable *pNext = p->pNext;
  118754. sqlite3VtabUnlock(p);
  118755. p = pNext;
  118756. }while( p );
  118757. }
  118758. }
  118759. /*
  118760. ** Clear any and all virtual-table information from the Table record.
  118761. ** This routine is called, for example, just before deleting the Table
  118762. ** record.
  118763. **
  118764. ** Since it is a virtual-table, the Table structure contains a pointer
  118765. ** to the head of a linked list of VTable structures. Each VTable
  118766. ** structure is associated with a single sqlite3* user of the schema.
  118767. ** The reference count of the VTable structure associated with database
  118768. ** connection db is decremented immediately (which may lead to the
  118769. ** structure being xDisconnected and free). Any other VTable structures
  118770. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  118771. ** database connection.
  118772. */
  118773. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  118774. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  118775. if( p->azModuleArg ){
  118776. int i;
  118777. for(i=0; i<p->nModuleArg; i++){
  118778. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  118779. }
  118780. sqlite3DbFree(db, p->azModuleArg);
  118781. }
  118782. }
  118783. /*
  118784. ** Add a new module argument to pTable->azModuleArg[].
  118785. ** The string is not copied - the pointer is stored. The
  118786. ** string will be freed automatically when the table is
  118787. ** deleted.
  118788. */
  118789. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  118790. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  118791. char **azModuleArg;
  118792. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  118793. if( azModuleArg==0 ){
  118794. sqlite3DbFree(db, zArg);
  118795. }else{
  118796. int i = pTable->nModuleArg++;
  118797. azModuleArg[i] = zArg;
  118798. azModuleArg[i+1] = 0;
  118799. pTable->azModuleArg = azModuleArg;
  118800. }
  118801. }
  118802. /*
  118803. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  118804. ** statement. The module name has been parsed, but the optional list
  118805. ** of parameters that follow the module name are still pending.
  118806. */
  118807. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  118808. Parse *pParse, /* Parsing context */
  118809. Token *pName1, /* Name of new table, or database name */
  118810. Token *pName2, /* Name of new table or NULL */
  118811. Token *pModuleName, /* Name of the module for the virtual table */
  118812. int ifNotExists /* No error if the table already exists */
  118813. ){
  118814. int iDb; /* The database the table is being created in */
  118815. Table *pTable; /* The new virtual table */
  118816. sqlite3 *db; /* Database connection */
  118817. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  118818. pTable = pParse->pNewTable;
  118819. if( pTable==0 ) return;
  118820. assert( 0==pTable->pIndex );
  118821. db = pParse->db;
  118822. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  118823. assert( iDb>=0 );
  118824. assert( pTable->nModuleArg==0 );
  118825. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  118826. addModuleArgument(db, pTable, 0);
  118827. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  118828. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  118829. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  118830. );
  118831. pParse->sNameToken.n = (int)(
  118832. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  118833. );
  118834. #ifndef SQLITE_OMIT_AUTHORIZATION
  118835. /* Creating a virtual table invokes the authorization callback twice.
  118836. ** The first invocation, to obtain permission to INSERT a row into the
  118837. ** sqlite_master table, has already been made by sqlite3StartTable().
  118838. ** The second call, to obtain permission to create the table, is made now.
  118839. */
  118840. if( pTable->azModuleArg ){
  118841. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  118842. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  118843. }
  118844. #endif
  118845. }
  118846. /*
  118847. ** This routine takes the module argument that has been accumulating
  118848. ** in pParse->zArg[] and appends it to the list of arguments on the
  118849. ** virtual table currently under construction in pParse->pTable.
  118850. */
  118851. static void addArgumentToVtab(Parse *pParse){
  118852. if( pParse->sArg.z && pParse->pNewTable ){
  118853. const char *z = (const char*)pParse->sArg.z;
  118854. int n = pParse->sArg.n;
  118855. sqlite3 *db = pParse->db;
  118856. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  118857. }
  118858. }
  118859. /*
  118860. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  118861. ** has been completely parsed.
  118862. */
  118863. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  118864. Table *pTab = pParse->pNewTable; /* The table being constructed */
  118865. sqlite3 *db = pParse->db; /* The database connection */
  118866. if( pTab==0 ) return;
  118867. addArgumentToVtab(pParse);
  118868. pParse->sArg.z = 0;
  118869. if( pTab->nModuleArg<1 ) return;
  118870. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  118871. ** first time (in other words if the virtual table is actually being
  118872. ** created now instead of just being read out of sqlite_master) then
  118873. ** do additional initialization work and store the statement text
  118874. ** in the sqlite_master table.
  118875. */
  118876. if( !db->init.busy ){
  118877. char *zStmt;
  118878. char *zWhere;
  118879. int iDb;
  118880. int iReg;
  118881. Vdbe *v;
  118882. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  118883. if( pEnd ){
  118884. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  118885. }
  118886. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  118887. /* A slot for the record has already been allocated in the
  118888. ** SQLITE_MASTER table. We just need to update that slot with all
  118889. ** the information we've collected.
  118890. **
  118891. ** The VM register number pParse->regRowid holds the rowid of an
  118892. ** entry in the sqlite_master table tht was created for this vtab
  118893. ** by sqlite3StartTable().
  118894. */
  118895. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  118896. sqlite3NestedParse(pParse,
  118897. "UPDATE %Q.%s "
  118898. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  118899. "WHERE rowid=#%d",
  118900. db->aDb[iDb].zDbSName, MASTER_NAME,
  118901. pTab->zName,
  118902. pTab->zName,
  118903. zStmt,
  118904. pParse->regRowid
  118905. );
  118906. sqlite3DbFree(db, zStmt);
  118907. v = sqlite3GetVdbe(pParse);
  118908. sqlite3ChangeCookie(pParse, iDb);
  118909. sqlite3VdbeAddOp0(v, OP_Expire);
  118910. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  118911. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  118912. iReg = ++pParse->nMem;
  118913. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  118914. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  118915. }
  118916. /* If we are rereading the sqlite_master table create the in-memory
  118917. ** record of the table. The xConnect() method is not called until
  118918. ** the first time the virtual table is used in an SQL statement. This
  118919. ** allows a schema that contains virtual tables to be loaded before
  118920. ** the required virtual table implementations are registered. */
  118921. else {
  118922. Table *pOld;
  118923. Schema *pSchema = pTab->pSchema;
  118924. const char *zName = pTab->zName;
  118925. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  118926. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  118927. if( pOld ){
  118928. sqlite3OomFault(db);
  118929. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  118930. return;
  118931. }
  118932. pParse->pNewTable = 0;
  118933. }
  118934. }
  118935. /*
  118936. ** The parser calls this routine when it sees the first token
  118937. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  118938. */
  118939. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  118940. addArgumentToVtab(pParse);
  118941. pParse->sArg.z = 0;
  118942. pParse->sArg.n = 0;
  118943. }
  118944. /*
  118945. ** The parser calls this routine for each token after the first token
  118946. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  118947. */
  118948. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  118949. Token *pArg = &pParse->sArg;
  118950. if( pArg->z==0 ){
  118951. pArg->z = p->z;
  118952. pArg->n = p->n;
  118953. }else{
  118954. assert(pArg->z <= p->z);
  118955. pArg->n = (int)(&p->z[p->n] - pArg->z);
  118956. }
  118957. }
  118958. /*
  118959. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  118960. ** pointer to the function to invoke is passed as the fourth parameter
  118961. ** to this procedure.
  118962. */
  118963. static int vtabCallConstructor(
  118964. sqlite3 *db,
  118965. Table *pTab,
  118966. Module *pMod,
  118967. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  118968. char **pzErr
  118969. ){
  118970. VtabCtx sCtx;
  118971. VTable *pVTable;
  118972. int rc;
  118973. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  118974. int nArg = pTab->nModuleArg;
  118975. char *zErr = 0;
  118976. char *zModuleName;
  118977. int iDb;
  118978. VtabCtx *pCtx;
  118979. /* Check that the virtual-table is not already being initialized */
  118980. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  118981. if( pCtx->pTab==pTab ){
  118982. *pzErr = sqlite3MPrintf(db,
  118983. "vtable constructor called recursively: %s", pTab->zName
  118984. );
  118985. return SQLITE_LOCKED;
  118986. }
  118987. }
  118988. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  118989. if( !zModuleName ){
  118990. return SQLITE_NOMEM_BKPT;
  118991. }
  118992. pVTable = sqlite3MallocZero(sizeof(VTable));
  118993. if( !pVTable ){
  118994. sqlite3OomFault(db);
  118995. sqlite3DbFree(db, zModuleName);
  118996. return SQLITE_NOMEM_BKPT;
  118997. }
  118998. pVTable->db = db;
  118999. pVTable->pMod = pMod;
  119000. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119001. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  119002. /* Invoke the virtual table constructor */
  119003. assert( &db->pVtabCtx );
  119004. assert( xConstruct );
  119005. sCtx.pTab = pTab;
  119006. sCtx.pVTable = pVTable;
  119007. sCtx.pPrior = db->pVtabCtx;
  119008. sCtx.bDeclared = 0;
  119009. db->pVtabCtx = &sCtx;
  119010. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  119011. db->pVtabCtx = sCtx.pPrior;
  119012. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  119013. assert( sCtx.pTab==pTab );
  119014. if( SQLITE_OK!=rc ){
  119015. if( zErr==0 ){
  119016. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  119017. }else {
  119018. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  119019. sqlite3_free(zErr);
  119020. }
  119021. sqlite3DbFree(db, pVTable);
  119022. }else if( ALWAYS(pVTable->pVtab) ){
  119023. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  119024. ** the sqlite3_vtab object if successful. */
  119025. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  119026. pVTable->pVtab->pModule = pMod->pModule;
  119027. pVTable->nRef = 1;
  119028. if( sCtx.bDeclared==0 ){
  119029. const char *zFormat = "vtable constructor did not declare schema: %s";
  119030. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  119031. sqlite3VtabUnlock(pVTable);
  119032. rc = SQLITE_ERROR;
  119033. }else{
  119034. int iCol;
  119035. u8 oooHidden = 0;
  119036. /* If everything went according to plan, link the new VTable structure
  119037. ** into the linked list headed by pTab->pVTable. Then loop through the
  119038. ** columns of the table to see if any of them contain the token "hidden".
  119039. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  119040. ** the type string. */
  119041. pVTable->pNext = pTab->pVTable;
  119042. pTab->pVTable = pVTable;
  119043. for(iCol=0; iCol<pTab->nCol; iCol++){
  119044. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  119045. int nType;
  119046. int i = 0;
  119047. nType = sqlite3Strlen30(zType);
  119048. for(i=0; i<nType; i++){
  119049. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  119050. && (i==0 || zType[i-1]==' ')
  119051. && (zType[i+6]=='\0' || zType[i+6]==' ')
  119052. ){
  119053. break;
  119054. }
  119055. }
  119056. if( i<nType ){
  119057. int j;
  119058. int nDel = 6 + (zType[i+6] ? 1 : 0);
  119059. for(j=i; (j+nDel)<=nType; j++){
  119060. zType[j] = zType[j+nDel];
  119061. }
  119062. if( zType[i]=='\0' && i>0 ){
  119063. assert(zType[i-1]==' ');
  119064. zType[i-1] = '\0';
  119065. }
  119066. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  119067. oooHidden = TF_OOOHidden;
  119068. }else{
  119069. pTab->tabFlags |= oooHidden;
  119070. }
  119071. }
  119072. }
  119073. }
  119074. sqlite3DbFree(db, zModuleName);
  119075. return rc;
  119076. }
  119077. /*
  119078. ** This function is invoked by the parser to call the xConnect() method
  119079. ** of the virtual table pTab. If an error occurs, an error code is returned
  119080. ** and an error left in pParse.
  119081. **
  119082. ** This call is a no-op if table pTab is not a virtual table.
  119083. */
  119084. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  119085. sqlite3 *db = pParse->db;
  119086. const char *zMod;
  119087. Module *pMod;
  119088. int rc;
  119089. assert( pTab );
  119090. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  119091. return SQLITE_OK;
  119092. }
  119093. /* Locate the required virtual table module */
  119094. zMod = pTab->azModuleArg[0];
  119095. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  119096. if( !pMod ){
  119097. const char *zModule = pTab->azModuleArg[0];
  119098. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  119099. rc = SQLITE_ERROR;
  119100. }else{
  119101. char *zErr = 0;
  119102. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  119103. if( rc!=SQLITE_OK ){
  119104. sqlite3ErrorMsg(pParse, "%s", zErr);
  119105. pParse->rc = rc;
  119106. }
  119107. sqlite3DbFree(db, zErr);
  119108. }
  119109. return rc;
  119110. }
  119111. /*
  119112. ** Grow the db->aVTrans[] array so that there is room for at least one
  119113. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  119114. */
  119115. static int growVTrans(sqlite3 *db){
  119116. const int ARRAY_INCR = 5;
  119117. /* Grow the sqlite3.aVTrans array if required */
  119118. if( (db->nVTrans%ARRAY_INCR)==0 ){
  119119. VTable **aVTrans;
  119120. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  119121. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  119122. if( !aVTrans ){
  119123. return SQLITE_NOMEM_BKPT;
  119124. }
  119125. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  119126. db->aVTrans = aVTrans;
  119127. }
  119128. return SQLITE_OK;
  119129. }
  119130. /*
  119131. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  119132. ** have already been reserved using growVTrans().
  119133. */
  119134. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  119135. /* Add pVtab to the end of sqlite3.aVTrans */
  119136. db->aVTrans[db->nVTrans++] = pVTab;
  119137. sqlite3VtabLock(pVTab);
  119138. }
  119139. /*
  119140. ** This function is invoked by the vdbe to call the xCreate method
  119141. ** of the virtual table named zTab in database iDb.
  119142. **
  119143. ** If an error occurs, *pzErr is set to point to an English language
  119144. ** description of the error and an SQLITE_XXX error code is returned.
  119145. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  119146. */
  119147. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  119148. int rc = SQLITE_OK;
  119149. Table *pTab;
  119150. Module *pMod;
  119151. const char *zMod;
  119152. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  119153. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  119154. /* Locate the required virtual table module */
  119155. zMod = pTab->azModuleArg[0];
  119156. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  119157. /* If the module has been registered and includes a Create method,
  119158. ** invoke it now. If the module has not been registered, return an
  119159. ** error. Otherwise, do nothing.
  119160. */
  119161. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  119162. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  119163. rc = SQLITE_ERROR;
  119164. }else{
  119165. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  119166. }
  119167. /* Justification of ALWAYS(): The xConstructor method is required to
  119168. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  119169. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  119170. rc = growVTrans(db);
  119171. if( rc==SQLITE_OK ){
  119172. addToVTrans(db, sqlite3GetVTable(db, pTab));
  119173. }
  119174. }
  119175. return rc;
  119176. }
  119177. /*
  119178. ** This function is used to set the schema of a virtual table. It is only
  119179. ** valid to call this function from within the xCreate() or xConnect() of a
  119180. ** virtual table module.
  119181. */
  119182. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  119183. VtabCtx *pCtx;
  119184. int rc = SQLITE_OK;
  119185. Table *pTab;
  119186. char *zErr = 0;
  119187. Parse sParse;
  119188. #ifdef SQLITE_ENABLE_API_ARMOR
  119189. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  119190. return SQLITE_MISUSE_BKPT;
  119191. }
  119192. #endif
  119193. sqlite3_mutex_enter(db->mutex);
  119194. pCtx = db->pVtabCtx;
  119195. if( !pCtx || pCtx->bDeclared ){
  119196. sqlite3Error(db, SQLITE_MISUSE);
  119197. sqlite3_mutex_leave(db->mutex);
  119198. return SQLITE_MISUSE_BKPT;
  119199. }
  119200. pTab = pCtx->pTab;
  119201. assert( IsVirtual(pTab) );
  119202. memset(&sParse, 0, sizeof(sParse));
  119203. sParse.declareVtab = 1;
  119204. sParse.db = db;
  119205. sParse.nQueryLoop = 1;
  119206. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  119207. && sParse.pNewTable
  119208. && !db->mallocFailed
  119209. && !sParse.pNewTable->pSelect
  119210. && !IsVirtual(sParse.pNewTable)
  119211. ){
  119212. if( !pTab->aCol ){
  119213. Table *pNew = sParse.pNewTable;
  119214. Index *pIdx;
  119215. pTab->aCol = pNew->aCol;
  119216. pTab->nCol = pNew->nCol;
  119217. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  119218. pNew->nCol = 0;
  119219. pNew->aCol = 0;
  119220. assert( pTab->pIndex==0 );
  119221. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  119222. if( !HasRowid(pNew)
  119223. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  119224. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  119225. ){
  119226. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  119227. ** or else must have a single-column PRIMARY KEY */
  119228. rc = SQLITE_ERROR;
  119229. }
  119230. pIdx = pNew->pIndex;
  119231. if( pIdx ){
  119232. assert( pIdx->pNext==0 );
  119233. pTab->pIndex = pIdx;
  119234. pNew->pIndex = 0;
  119235. pIdx->pTable = pTab;
  119236. }
  119237. }
  119238. pCtx->bDeclared = 1;
  119239. }else{
  119240. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  119241. sqlite3DbFree(db, zErr);
  119242. rc = SQLITE_ERROR;
  119243. }
  119244. sParse.declareVtab = 0;
  119245. if( sParse.pVdbe ){
  119246. sqlite3VdbeFinalize(sParse.pVdbe);
  119247. }
  119248. sqlite3DeleteTable(db, sParse.pNewTable);
  119249. sqlite3ParserReset(&sParse);
  119250. assert( (rc&0xff)==rc );
  119251. rc = sqlite3ApiExit(db, rc);
  119252. sqlite3_mutex_leave(db->mutex);
  119253. return rc;
  119254. }
  119255. /*
  119256. ** This function is invoked by the vdbe to call the xDestroy method
  119257. ** of the virtual table named zTab in database iDb. This occurs
  119258. ** when a DROP TABLE is mentioned.
  119259. **
  119260. ** This call is a no-op if zTab is not a virtual table.
  119261. */
  119262. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  119263. int rc = SQLITE_OK;
  119264. Table *pTab;
  119265. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  119266. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  119267. VTable *p;
  119268. int (*xDestroy)(sqlite3_vtab *);
  119269. for(p=pTab->pVTable; p; p=p->pNext){
  119270. assert( p->pVtab );
  119271. if( p->pVtab->nRef>0 ){
  119272. return SQLITE_LOCKED;
  119273. }
  119274. }
  119275. p = vtabDisconnectAll(db, pTab);
  119276. xDestroy = p->pMod->pModule->xDestroy;
  119277. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  119278. rc = xDestroy(p->pVtab);
  119279. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  119280. if( rc==SQLITE_OK ){
  119281. assert( pTab->pVTable==p && p->pNext==0 );
  119282. p->pVtab = 0;
  119283. pTab->pVTable = 0;
  119284. sqlite3VtabUnlock(p);
  119285. }
  119286. }
  119287. return rc;
  119288. }
  119289. /*
  119290. ** This function invokes either the xRollback or xCommit method
  119291. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  119292. ** called is identified by the second argument, "offset", which is
  119293. ** the offset of the method to call in the sqlite3_module structure.
  119294. **
  119295. ** The array is cleared after invoking the callbacks.
  119296. */
  119297. static void callFinaliser(sqlite3 *db, int offset){
  119298. int i;
  119299. if( db->aVTrans ){
  119300. VTable **aVTrans = db->aVTrans;
  119301. db->aVTrans = 0;
  119302. for(i=0; i<db->nVTrans; i++){
  119303. VTable *pVTab = aVTrans[i];
  119304. sqlite3_vtab *p = pVTab->pVtab;
  119305. if( p ){
  119306. int (*x)(sqlite3_vtab *);
  119307. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  119308. if( x ) x(p);
  119309. }
  119310. pVTab->iSavepoint = 0;
  119311. sqlite3VtabUnlock(pVTab);
  119312. }
  119313. sqlite3DbFree(db, aVTrans);
  119314. db->nVTrans = 0;
  119315. }
  119316. }
  119317. /*
  119318. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  119319. ** array. Return the error code for the first error that occurs, or
  119320. ** SQLITE_OK if all xSync operations are successful.
  119321. **
  119322. ** If an error message is available, leave it in p->zErrMsg.
  119323. */
  119324. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  119325. int i;
  119326. int rc = SQLITE_OK;
  119327. VTable **aVTrans = db->aVTrans;
  119328. db->aVTrans = 0;
  119329. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  119330. int (*x)(sqlite3_vtab *);
  119331. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  119332. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  119333. rc = x(pVtab);
  119334. sqlite3VtabImportErrmsg(p, pVtab);
  119335. }
  119336. }
  119337. db->aVTrans = aVTrans;
  119338. return rc;
  119339. }
  119340. /*
  119341. ** Invoke the xRollback method of all virtual tables in the
  119342. ** sqlite3.aVTrans array. Then clear the array itself.
  119343. */
  119344. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  119345. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  119346. return SQLITE_OK;
  119347. }
  119348. /*
  119349. ** Invoke the xCommit method of all virtual tables in the
  119350. ** sqlite3.aVTrans array. Then clear the array itself.
  119351. */
  119352. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  119353. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  119354. return SQLITE_OK;
  119355. }
  119356. /*
  119357. ** If the virtual table pVtab supports the transaction interface
  119358. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  119359. ** not currently open, invoke the xBegin method now.
  119360. **
  119361. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  119362. ** in the sqlite3.aVTrans array.
  119363. */
  119364. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  119365. int rc = SQLITE_OK;
  119366. const sqlite3_module *pModule;
  119367. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  119368. ** than zero, then this function is being called from within a
  119369. ** virtual module xSync() callback. It is illegal to write to
  119370. ** virtual module tables in this case, so return SQLITE_LOCKED.
  119371. */
  119372. if( sqlite3VtabInSync(db) ){
  119373. return SQLITE_LOCKED;
  119374. }
  119375. if( !pVTab ){
  119376. return SQLITE_OK;
  119377. }
  119378. pModule = pVTab->pVtab->pModule;
  119379. if( pModule->xBegin ){
  119380. int i;
  119381. /* If pVtab is already in the aVTrans array, return early */
  119382. for(i=0; i<db->nVTrans; i++){
  119383. if( db->aVTrans[i]==pVTab ){
  119384. return SQLITE_OK;
  119385. }
  119386. }
  119387. /* Invoke the xBegin method. If successful, add the vtab to the
  119388. ** sqlite3.aVTrans[] array. */
  119389. rc = growVTrans(db);
  119390. if( rc==SQLITE_OK ){
  119391. rc = pModule->xBegin(pVTab->pVtab);
  119392. if( rc==SQLITE_OK ){
  119393. int iSvpt = db->nStatement + db->nSavepoint;
  119394. addToVTrans(db, pVTab);
  119395. if( iSvpt && pModule->xSavepoint ){
  119396. pVTab->iSavepoint = iSvpt;
  119397. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  119398. }
  119399. }
  119400. }
  119401. }
  119402. return rc;
  119403. }
  119404. /*
  119405. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  119406. ** virtual tables that currently have an open transaction. Pass iSavepoint
  119407. ** as the second argument to the virtual table method invoked.
  119408. **
  119409. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  119410. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  119411. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  119412. ** an open transaction is invoked.
  119413. **
  119414. ** If any virtual table method returns an error code other than SQLITE_OK,
  119415. ** processing is abandoned and the error returned to the caller of this
  119416. ** function immediately. If all calls to virtual table methods are successful,
  119417. ** SQLITE_OK is returned.
  119418. */
  119419. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  119420. int rc = SQLITE_OK;
  119421. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  119422. assert( iSavepoint>=-1 );
  119423. if( db->aVTrans ){
  119424. int i;
  119425. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  119426. VTable *pVTab = db->aVTrans[i];
  119427. const sqlite3_module *pMod = pVTab->pMod->pModule;
  119428. if( pVTab->pVtab && pMod->iVersion>=2 ){
  119429. int (*xMethod)(sqlite3_vtab *, int);
  119430. switch( op ){
  119431. case SAVEPOINT_BEGIN:
  119432. xMethod = pMod->xSavepoint;
  119433. pVTab->iSavepoint = iSavepoint+1;
  119434. break;
  119435. case SAVEPOINT_ROLLBACK:
  119436. xMethod = pMod->xRollbackTo;
  119437. break;
  119438. default:
  119439. xMethod = pMod->xRelease;
  119440. break;
  119441. }
  119442. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  119443. rc = xMethod(pVTab->pVtab, iSavepoint);
  119444. }
  119445. }
  119446. }
  119447. }
  119448. return rc;
  119449. }
  119450. /*
  119451. ** The first parameter (pDef) is a function implementation. The
  119452. ** second parameter (pExpr) is the first argument to this function.
  119453. ** If pExpr is a column in a virtual table, then let the virtual
  119454. ** table implementation have an opportunity to overload the function.
  119455. **
  119456. ** This routine is used to allow virtual table implementations to
  119457. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  119458. **
  119459. ** Return either the pDef argument (indicating no change) or a
  119460. ** new FuncDef structure that is marked as ephemeral using the
  119461. ** SQLITE_FUNC_EPHEM flag.
  119462. */
  119463. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  119464. sqlite3 *db, /* Database connection for reporting malloc problems */
  119465. FuncDef *pDef, /* Function to possibly overload */
  119466. int nArg, /* Number of arguments to the function */
  119467. Expr *pExpr /* First argument to the function */
  119468. ){
  119469. Table *pTab;
  119470. sqlite3_vtab *pVtab;
  119471. sqlite3_module *pMod;
  119472. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  119473. void *pArg = 0;
  119474. FuncDef *pNew;
  119475. int rc = 0;
  119476. char *zLowerName;
  119477. unsigned char *z;
  119478. /* Check to see the left operand is a column in a virtual table */
  119479. if( NEVER(pExpr==0) ) return pDef;
  119480. if( pExpr->op!=TK_COLUMN ) return pDef;
  119481. pTab = pExpr->pTab;
  119482. if( pTab==0 ) return pDef;
  119483. if( !IsVirtual(pTab) ) return pDef;
  119484. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  119485. assert( pVtab!=0 );
  119486. assert( pVtab->pModule!=0 );
  119487. pMod = (sqlite3_module *)pVtab->pModule;
  119488. if( pMod->xFindFunction==0 ) return pDef;
  119489. /* Call the xFindFunction method on the virtual table implementation
  119490. ** to see if the implementation wants to overload this function
  119491. */
  119492. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  119493. if( zLowerName ){
  119494. for(z=(unsigned char*)zLowerName; *z; z++){
  119495. *z = sqlite3UpperToLower[*z];
  119496. }
  119497. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
  119498. sqlite3DbFree(db, zLowerName);
  119499. }
  119500. if( rc==0 ){
  119501. return pDef;
  119502. }
  119503. /* Create a new ephemeral function definition for the overloaded
  119504. ** function */
  119505. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  119506. + sqlite3Strlen30(pDef->zName) + 1);
  119507. if( pNew==0 ){
  119508. return pDef;
  119509. }
  119510. *pNew = *pDef;
  119511. pNew->zName = (const char*)&pNew[1];
  119512. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  119513. pNew->xSFunc = xSFunc;
  119514. pNew->pUserData = pArg;
  119515. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  119516. return pNew;
  119517. }
  119518. /*
  119519. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  119520. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  119521. ** array if it is missing. If pTab is already in the array, this routine
  119522. ** is a no-op.
  119523. */
  119524. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  119525. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  119526. int i, n;
  119527. Table **apVtabLock;
  119528. assert( IsVirtual(pTab) );
  119529. for(i=0; i<pToplevel->nVtabLock; i++){
  119530. if( pTab==pToplevel->apVtabLock[i] ) return;
  119531. }
  119532. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  119533. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  119534. if( apVtabLock ){
  119535. pToplevel->apVtabLock = apVtabLock;
  119536. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  119537. }else{
  119538. sqlite3OomFault(pToplevel->db);
  119539. }
  119540. }
  119541. /*
  119542. ** Check to see if virtual table module pMod can be have an eponymous
  119543. ** virtual table instance. If it can, create one if one does not already
  119544. ** exist. Return non-zero if the eponymous virtual table instance exists
  119545. ** when this routine returns, and return zero if it does not exist.
  119546. **
  119547. ** An eponymous virtual table instance is one that is named after its
  119548. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  119549. ** statement in order to come into existance. Eponymous virtual table
  119550. ** instances always exist. They cannot be DROP-ed.
  119551. **
  119552. ** Any virtual table module for which xConnect and xCreate are the same
  119553. ** method can have an eponymous virtual table instance.
  119554. */
  119555. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  119556. const sqlite3_module *pModule = pMod->pModule;
  119557. Table *pTab;
  119558. char *zErr = 0;
  119559. int rc;
  119560. sqlite3 *db = pParse->db;
  119561. if( pMod->pEpoTab ) return 1;
  119562. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  119563. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  119564. if( pTab==0 ) return 0;
  119565. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  119566. if( pTab->zName==0 ){
  119567. sqlite3DbFree(db, pTab);
  119568. return 0;
  119569. }
  119570. pMod->pEpoTab = pTab;
  119571. pTab->nTabRef = 1;
  119572. pTab->pSchema = db->aDb[0].pSchema;
  119573. assert( pTab->nModuleArg==0 );
  119574. pTab->iPKey = -1;
  119575. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  119576. addModuleArgument(db, pTab, 0);
  119577. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  119578. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  119579. if( rc ){
  119580. sqlite3ErrorMsg(pParse, "%s", zErr);
  119581. sqlite3DbFree(db, zErr);
  119582. sqlite3VtabEponymousTableClear(db, pMod);
  119583. return 0;
  119584. }
  119585. return 1;
  119586. }
  119587. /*
  119588. ** Erase the eponymous virtual table instance associated with
  119589. ** virtual table module pMod, if it exists.
  119590. */
  119591. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  119592. Table *pTab = pMod->pEpoTab;
  119593. if( pTab!=0 ){
  119594. /* Mark the table as Ephemeral prior to deleting it, so that the
  119595. ** sqlite3DeleteTable() routine will know that it is not stored in
  119596. ** the schema. */
  119597. pTab->tabFlags |= TF_Ephemeral;
  119598. sqlite3DeleteTable(db, pTab);
  119599. pMod->pEpoTab = 0;
  119600. }
  119601. }
  119602. /*
  119603. ** Return the ON CONFLICT resolution mode in effect for the virtual
  119604. ** table update operation currently in progress.
  119605. **
  119606. ** The results of this routine are undefined unless it is called from
  119607. ** within an xUpdate method.
  119608. */
  119609. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  119610. static const unsigned char aMap[] = {
  119611. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  119612. };
  119613. #ifdef SQLITE_ENABLE_API_ARMOR
  119614. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  119615. #endif
  119616. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  119617. assert( OE_Ignore==4 && OE_Replace==5 );
  119618. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  119619. return (int)aMap[db->vtabOnConflict-1];
  119620. }
  119621. /*
  119622. ** Call from within the xCreate() or xConnect() methods to provide
  119623. ** the SQLite core with additional information about the behavior
  119624. ** of the virtual table being implemented.
  119625. */
  119626. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  119627. va_list ap;
  119628. int rc = SQLITE_OK;
  119629. #ifdef SQLITE_ENABLE_API_ARMOR
  119630. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  119631. #endif
  119632. sqlite3_mutex_enter(db->mutex);
  119633. va_start(ap, op);
  119634. switch( op ){
  119635. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  119636. VtabCtx *p = db->pVtabCtx;
  119637. if( !p ){
  119638. rc = SQLITE_MISUSE_BKPT;
  119639. }else{
  119640. assert( p->pTab==0 || IsVirtual(p->pTab) );
  119641. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  119642. }
  119643. break;
  119644. }
  119645. default:
  119646. rc = SQLITE_MISUSE_BKPT;
  119647. break;
  119648. }
  119649. va_end(ap);
  119650. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  119651. sqlite3_mutex_leave(db->mutex);
  119652. return rc;
  119653. }
  119654. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  119655. /************** End of vtab.c ************************************************/
  119656. /************** Begin file wherecode.c ***************************************/
  119657. /*
  119658. ** 2015-06-06
  119659. **
  119660. ** The author disclaims copyright to this source code. In place of
  119661. ** a legal notice, here is a blessing:
  119662. **
  119663. ** May you do good and not evil.
  119664. ** May you find forgiveness for yourself and forgive others.
  119665. ** May you share freely, never taking more than you give.
  119666. **
  119667. *************************************************************************
  119668. ** This module contains C code that generates VDBE code used to process
  119669. ** the WHERE clause of SQL statements.
  119670. **
  119671. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  119672. ** size of where.c and make it easier to edit. This file contains the routines
  119673. ** that actually generate the bulk of the WHERE loop code. The original where.c
  119674. ** file retains the code that does query planning and analysis.
  119675. */
  119676. /* #include "sqliteInt.h" */
  119677. /************** Include whereInt.h in the middle of wherecode.c **************/
  119678. /************** Begin file whereInt.h ****************************************/
  119679. /*
  119680. ** 2013-11-12
  119681. **
  119682. ** The author disclaims copyright to this source code. In place of
  119683. ** a legal notice, here is a blessing:
  119684. **
  119685. ** May you do good and not evil.
  119686. ** May you find forgiveness for yourself and forgive others.
  119687. ** May you share freely, never taking more than you give.
  119688. **
  119689. *************************************************************************
  119690. **
  119691. ** This file contains structure and macro definitions for the query
  119692. ** planner logic in "where.c". These definitions are broken out into
  119693. ** a separate source file for easier editing.
  119694. */
  119695. /*
  119696. ** Trace output macros
  119697. */
  119698. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  119699. /***/ int sqlite3WhereTrace;
  119700. #endif
  119701. #if defined(SQLITE_DEBUG) \
  119702. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  119703. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  119704. # define WHERETRACE_ENABLED 1
  119705. #else
  119706. # define WHERETRACE(K,X)
  119707. #endif
  119708. /* Forward references
  119709. */
  119710. typedef struct WhereClause WhereClause;
  119711. typedef struct WhereMaskSet WhereMaskSet;
  119712. typedef struct WhereOrInfo WhereOrInfo;
  119713. typedef struct WhereAndInfo WhereAndInfo;
  119714. typedef struct WhereLevel WhereLevel;
  119715. typedef struct WhereLoop WhereLoop;
  119716. typedef struct WherePath WherePath;
  119717. typedef struct WhereTerm WhereTerm;
  119718. typedef struct WhereLoopBuilder WhereLoopBuilder;
  119719. typedef struct WhereScan WhereScan;
  119720. typedef struct WhereOrCost WhereOrCost;
  119721. typedef struct WhereOrSet WhereOrSet;
  119722. /*
  119723. ** This object contains information needed to implement a single nested
  119724. ** loop in WHERE clause.
  119725. **
  119726. ** Contrast this object with WhereLoop. This object describes the
  119727. ** implementation of the loop. WhereLoop describes the algorithm.
  119728. ** This object contains a pointer to the WhereLoop algorithm as one of
  119729. ** its elements.
  119730. **
  119731. ** The WhereInfo object contains a single instance of this object for
  119732. ** each term in the FROM clause (which is to say, for each of the
  119733. ** nested loops as implemented). The order of WhereLevel objects determines
  119734. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  119735. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  119736. */
  119737. struct WhereLevel {
  119738. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  119739. int iTabCur; /* The VDBE cursor used to access the table */
  119740. int iIdxCur; /* The VDBE cursor used to access pIdx */
  119741. int addrBrk; /* Jump here to break out of the loop */
  119742. int addrNxt; /* Jump here to start the next IN combination */
  119743. int addrSkip; /* Jump here for next iteration of skip-scan */
  119744. int addrCont; /* Jump here to continue with the next loop cycle */
  119745. int addrFirst; /* First instruction of interior of the loop */
  119746. int addrBody; /* Beginning of the body of this loop */
  119747. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  119748. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  119749. int addrLikeRep; /* LIKE range processing address */
  119750. #endif
  119751. u8 iFrom; /* Which entry in the FROM clause */
  119752. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  119753. int p1, p2; /* Operands of the opcode used to ends the loop */
  119754. union { /* Information that depends on pWLoop->wsFlags */
  119755. struct {
  119756. int nIn; /* Number of entries in aInLoop[] */
  119757. struct InLoop {
  119758. int iCur; /* The VDBE cursor used by this IN operator */
  119759. int addrInTop; /* Top of the IN loop */
  119760. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  119761. } *aInLoop; /* Information about each nested IN operator */
  119762. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  119763. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  119764. } u;
  119765. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  119766. Bitmask notReady; /* FROM entries not usable at this level */
  119767. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  119768. int addrVisit; /* Address at which row is visited */
  119769. #endif
  119770. };
  119771. /*
  119772. ** Each instance of this object represents an algorithm for evaluating one
  119773. ** term of a join. Every term of the FROM clause will have at least
  119774. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  119775. ** prevent a query solution - which is an error) and many terms of the
  119776. ** FROM clause will have multiple WhereLoop objects, each describing a
  119777. ** potential way of implementing that FROM-clause term, together with
  119778. ** dependencies and cost estimates for using the chosen algorithm.
  119779. **
  119780. ** Query planning consists of building up a collection of these WhereLoop
  119781. ** objects, then computing a particular sequence of WhereLoop objects, with
  119782. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  119783. ** and that minimize the overall cost.
  119784. */
  119785. struct WhereLoop {
  119786. Bitmask prereq; /* Bitmask of other loops that must run first */
  119787. Bitmask maskSelf; /* Bitmask identifying table iTab */
  119788. #ifdef SQLITE_DEBUG
  119789. char cId; /* Symbolic ID of this loop for debugging use */
  119790. #endif
  119791. u8 iTab; /* Position in FROM clause of table for this loop */
  119792. u8 iSortIdx; /* Sorting index number. 0==None */
  119793. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  119794. LogEst rRun; /* Cost of running each loop */
  119795. LogEst nOut; /* Estimated number of output rows */
  119796. union {
  119797. struct { /* Information for internal btree tables */
  119798. u16 nEq; /* Number of equality constraints */
  119799. u16 nBtm; /* Size of BTM vector */
  119800. u16 nTop; /* Size of TOP vector */
  119801. u16 nIdxCol; /* Index column used for ORDER BY */
  119802. Index *pIndex; /* Index used, or NULL */
  119803. } btree;
  119804. struct { /* Information for virtual tables */
  119805. int idxNum; /* Index number */
  119806. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  119807. i8 isOrdered; /* True if satisfies ORDER BY */
  119808. u16 omitMask; /* Terms that may be omitted */
  119809. char *idxStr; /* Index identifier string */
  119810. } vtab;
  119811. } u;
  119812. u32 wsFlags; /* WHERE_* flags describing the plan */
  119813. u16 nLTerm; /* Number of entries in aLTerm[] */
  119814. u16 nSkip; /* Number of NULL aLTerm[] entries */
  119815. /**** whereLoopXfer() copies fields above ***********************/
  119816. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  119817. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  119818. WhereTerm **aLTerm; /* WhereTerms used */
  119819. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  119820. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  119821. };
  119822. /* This object holds the prerequisites and the cost of running a
  119823. ** subquery on one operand of an OR operator in the WHERE clause.
  119824. ** See WhereOrSet for additional information
  119825. */
  119826. struct WhereOrCost {
  119827. Bitmask prereq; /* Prerequisites */
  119828. LogEst rRun; /* Cost of running this subquery */
  119829. LogEst nOut; /* Number of outputs for this subquery */
  119830. };
  119831. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  119832. ** correspond to the subquery(s) of OR-clause processing. Only the
  119833. ** best N_OR_COST elements are retained.
  119834. */
  119835. #define N_OR_COST 3
  119836. struct WhereOrSet {
  119837. u16 n; /* Number of valid a[] entries */
  119838. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  119839. };
  119840. /*
  119841. ** Each instance of this object holds a sequence of WhereLoop objects
  119842. ** that implement some or all of a query plan.
  119843. **
  119844. ** Think of each WhereLoop object as a node in a graph with arcs
  119845. ** showing dependencies and costs for travelling between nodes. (That is
  119846. ** not a completely accurate description because WhereLoop costs are a
  119847. ** vector, not a scalar, and because dependencies are many-to-one, not
  119848. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  119849. ** Then a WherePath object is a path through the graph that visits some
  119850. ** or all of the WhereLoop objects once.
  119851. **
  119852. ** The "solver" works by creating the N best WherePath objects of length
  119853. ** 1. Then using those as a basis to compute the N best WherePath objects
  119854. ** of length 2. And so forth until the length of WherePaths equals the
  119855. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  119856. ** at the end is the chosen query plan.
  119857. */
  119858. struct WherePath {
  119859. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  119860. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  119861. LogEst nRow; /* Estimated number of rows generated by this path */
  119862. LogEst rCost; /* Total cost of this path */
  119863. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  119864. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  119865. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  119866. };
  119867. /*
  119868. ** The query generator uses an array of instances of this structure to
  119869. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  119870. ** clause subexpression is separated from the others by AND operators,
  119871. ** usually, or sometimes subexpressions separated by OR.
  119872. **
  119873. ** All WhereTerms are collected into a single WhereClause structure.
  119874. ** The following identity holds:
  119875. **
  119876. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  119877. **
  119878. ** When a term is of the form:
  119879. **
  119880. ** X <op> <expr>
  119881. **
  119882. ** where X is a column name and <op> is one of certain operators,
  119883. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  119884. ** cursor number and column number for X. WhereTerm.eOperator records
  119885. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  119886. ** use of a bitmask encoding for the operator allows us to search
  119887. ** quickly for terms that match any of several different operators.
  119888. **
  119889. ** A WhereTerm might also be two or more subterms connected by OR:
  119890. **
  119891. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  119892. **
  119893. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  119894. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  119895. ** is collected about the OR clause.
  119896. **
  119897. ** If a term in the WHERE clause does not match either of the two previous
  119898. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  119899. ** to the original subexpression content and wtFlags is set up appropriately
  119900. ** but no other fields in the WhereTerm object are meaningful.
  119901. **
  119902. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  119903. ** but they do so indirectly. A single WhereMaskSet structure translates
  119904. ** cursor number into bits and the translated bit is stored in the prereq
  119905. ** fields. The translation is used in order to maximize the number of
  119906. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  119907. ** spread out over the non-negative integers. For example, the cursor
  119908. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  119909. ** translates these sparse cursor numbers into consecutive integers
  119910. ** beginning with 0 in order to make the best possible use of the available
  119911. ** bits in the Bitmask. So, in the example above, the cursor numbers
  119912. ** would be mapped into integers 0 through 7.
  119913. **
  119914. ** The number of terms in a join is limited by the number of bits
  119915. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  119916. ** is only able to process joins with 64 or fewer tables.
  119917. */
  119918. struct WhereTerm {
  119919. Expr *pExpr; /* Pointer to the subexpression that is this term */
  119920. WhereClause *pWC; /* The clause this term is part of */
  119921. LogEst truthProb; /* Probability of truth for this expression */
  119922. u16 wtFlags; /* TERM_xxx bit flags. See below */
  119923. u16 eOperator; /* A WO_xx value describing <op> */
  119924. u8 nChild; /* Number of children that must disable us */
  119925. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  119926. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  119927. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  119928. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  119929. union {
  119930. int leftColumn; /* Column number of X in "X <op> <expr>" */
  119931. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  119932. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  119933. } u;
  119934. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  119935. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  119936. };
  119937. /*
  119938. ** Allowed values of WhereTerm.wtFlags
  119939. */
  119940. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  119941. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  119942. #define TERM_CODED 0x04 /* This term is already coded */
  119943. #define TERM_COPIED 0x08 /* Has a child */
  119944. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  119945. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  119946. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  119947. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  119948. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  119949. #else
  119950. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  119951. #endif
  119952. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  119953. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  119954. #define TERM_LIKE 0x400 /* The original LIKE operator */
  119955. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  119956. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  119957. /*
  119958. ** An instance of the WhereScan object is used as an iterator for locating
  119959. ** terms in the WHERE clause that are useful to the query planner.
  119960. */
  119961. struct WhereScan {
  119962. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  119963. WhereClause *pWC; /* WhereClause currently being scanned */
  119964. const char *zCollName; /* Required collating sequence, if not NULL */
  119965. Expr *pIdxExpr; /* Search for this index expression */
  119966. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  119967. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  119968. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  119969. u32 opMask; /* Acceptable operators */
  119970. int k; /* Resume scanning at this->pWC->a[this->k] */
  119971. int aiCur[11]; /* Cursors in the equivalence class */
  119972. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  119973. };
  119974. /*
  119975. ** An instance of the following structure holds all information about a
  119976. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  119977. **
  119978. ** Explanation of pOuter: For a WHERE clause of the form
  119979. **
  119980. ** a AND ((b AND c) OR (d AND e)) AND f
  119981. **
  119982. ** There are separate WhereClause objects for the whole clause and for
  119983. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  119984. ** subclauses points to the WhereClause object for the whole clause.
  119985. */
  119986. struct WhereClause {
  119987. WhereInfo *pWInfo; /* WHERE clause processing context */
  119988. WhereClause *pOuter; /* Outer conjunction */
  119989. u8 op; /* Split operator. TK_AND or TK_OR */
  119990. int nTerm; /* Number of terms */
  119991. int nSlot; /* Number of entries in a[] */
  119992. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  119993. #if defined(SQLITE_SMALL_STACK)
  119994. WhereTerm aStatic[1]; /* Initial static space for a[] */
  119995. #else
  119996. WhereTerm aStatic[8]; /* Initial static space for a[] */
  119997. #endif
  119998. };
  119999. /*
  120000. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  120001. ** a dynamically allocated instance of the following structure.
  120002. */
  120003. struct WhereOrInfo {
  120004. WhereClause wc; /* Decomposition into subterms */
  120005. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  120006. };
  120007. /*
  120008. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  120009. ** a dynamically allocated instance of the following structure.
  120010. */
  120011. struct WhereAndInfo {
  120012. WhereClause wc; /* The subexpression broken out */
  120013. };
  120014. /*
  120015. ** An instance of the following structure keeps track of a mapping
  120016. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  120017. **
  120018. ** The VDBE cursor numbers are small integers contained in
  120019. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  120020. ** clause, the cursor numbers might not begin with 0 and they might
  120021. ** contain gaps in the numbering sequence. But we want to make maximum
  120022. ** use of the bits in our bitmasks. This structure provides a mapping
  120023. ** from the sparse cursor numbers into consecutive integers beginning
  120024. ** with 0.
  120025. **
  120026. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  120027. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  120028. **
  120029. ** For example, if the WHERE clause expression used these VDBE
  120030. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  120031. ** would map those cursor numbers into bits 0 through 5.
  120032. **
  120033. ** Note that the mapping is not necessarily ordered. In the example
  120034. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  120035. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  120036. ** does not really matter. What is important is that sparse cursor
  120037. ** numbers all get mapped into bit numbers that begin with 0 and contain
  120038. ** no gaps.
  120039. */
  120040. struct WhereMaskSet {
  120041. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  120042. int n; /* Number of assigned cursor values */
  120043. int ix[BMS]; /* Cursor assigned to each bit */
  120044. };
  120045. /*
  120046. ** Initialize a WhereMaskSet object
  120047. */
  120048. #define initMaskSet(P) (P)->n=0
  120049. /*
  120050. ** This object is a convenience wrapper holding all information needed
  120051. ** to construct WhereLoop objects for a particular query.
  120052. */
  120053. struct WhereLoopBuilder {
  120054. WhereInfo *pWInfo; /* Information about this WHERE */
  120055. WhereClause *pWC; /* WHERE clause terms */
  120056. ExprList *pOrderBy; /* ORDER BY clause */
  120057. WhereLoop *pNew; /* Template WhereLoop */
  120058. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  120059. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  120060. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  120061. int nRecValid; /* Number of valid fields currently in pRec */
  120062. #endif
  120063. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  120064. };
  120065. /* Allowed values for WhereLoopBuider.bldFlags */
  120066. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  120067. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  120068. /*
  120069. ** The WHERE clause processing routine has two halves. The
  120070. ** first part does the start of the WHERE loop and the second
  120071. ** half does the tail of the WHERE loop. An instance of
  120072. ** this structure is returned by the first half and passed
  120073. ** into the second half to give some continuity.
  120074. **
  120075. ** An instance of this object holds the complete state of the query
  120076. ** planner.
  120077. */
  120078. struct WhereInfo {
  120079. Parse *pParse; /* Parsing and code generating context */
  120080. SrcList *pTabList; /* List of tables in the join */
  120081. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  120082. ExprList *pResultSet; /* Result set of the query */
  120083. Expr *pWhere; /* The complete WHERE clause */
  120084. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  120085. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  120086. int iContinue; /* Jump here to continue with next record */
  120087. int iBreak; /* Jump here to break out of the loop */
  120088. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  120089. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  120090. u8 nLevel; /* Number of nested loop */
  120091. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  120092. u8 sorted; /* True if really sorted (not just grouped) */
  120093. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  120094. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  120095. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  120096. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  120097. int iTop; /* The very beginning of the WHERE loop */
  120098. WhereLoop *pLoops; /* List of all WhereLoop objects */
  120099. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  120100. LogEst nRowOut; /* Estimated number of output rows */
  120101. WhereClause sWC; /* Decomposition of the WHERE clause */
  120102. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  120103. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  120104. };
  120105. /*
  120106. ** Private interfaces - callable only by other where.c routines.
  120107. **
  120108. ** where.c:
  120109. */
  120110. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  120111. #ifdef WHERETRACE_ENABLED
  120112. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  120113. #endif
  120114. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  120115. WhereClause *pWC, /* The WHERE clause to be searched */
  120116. int iCur, /* Cursor number of LHS */
  120117. int iColumn, /* Column number of LHS */
  120118. Bitmask notReady, /* RHS must not overlap with this mask */
  120119. u32 op, /* Mask of WO_xx values describing operator */
  120120. Index *pIdx /* Must be compatible with this index, if not NULL */
  120121. );
  120122. /* wherecode.c: */
  120123. #ifndef SQLITE_OMIT_EXPLAIN
  120124. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  120125. Parse *pParse, /* Parse context */
  120126. SrcList *pTabList, /* Table list this loop refers to */
  120127. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  120128. int iLevel, /* Value for "level" column of output */
  120129. int iFrom, /* Value for "from" column of output */
  120130. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  120131. );
  120132. #else
  120133. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  120134. #endif /* SQLITE_OMIT_EXPLAIN */
  120135. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  120136. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  120137. Vdbe *v, /* Vdbe to add scanstatus entry to */
  120138. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  120139. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  120140. int addrExplain /* Address of OP_Explain (or 0) */
  120141. );
  120142. #else
  120143. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  120144. #endif
  120145. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  120146. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  120147. int iLevel, /* Which level of pWInfo->a[] should be coded */
  120148. Bitmask notReady /* Which tables are currently available */
  120149. );
  120150. /* whereexpr.c: */
  120151. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  120152. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  120153. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  120154. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  120155. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  120156. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  120157. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  120158. /*
  120159. ** Bitmasks for the operators on WhereTerm objects. These are all
  120160. ** operators that are of interest to the query planner. An
  120161. ** OR-ed combination of these values can be used when searching for
  120162. ** particular WhereTerms within a WhereClause.
  120163. **
  120164. ** Value constraints:
  120165. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  120166. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  120167. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  120168. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  120169. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  120170. */
  120171. #define WO_IN 0x0001
  120172. #define WO_EQ 0x0002
  120173. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  120174. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  120175. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  120176. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  120177. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  120178. #define WO_IS 0x0080
  120179. #define WO_ISNULL 0x0100
  120180. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  120181. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  120182. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  120183. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  120184. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  120185. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  120186. /*
  120187. ** These are definitions of bits in the WhereLoop.wsFlags field.
  120188. ** The particular combination of bits in each WhereLoop help to
  120189. ** determine the algorithm that WhereLoop represents.
  120190. */
  120191. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  120192. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  120193. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  120194. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  120195. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  120196. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  120197. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  120198. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  120199. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  120200. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  120201. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  120202. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  120203. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  120204. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  120205. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  120206. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  120207. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  120208. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  120209. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  120210. /************** End of whereInt.h ********************************************/
  120211. /************** Continuing where we left off in wherecode.c ******************/
  120212. #ifndef SQLITE_OMIT_EXPLAIN
  120213. /*
  120214. ** Return the name of the i-th column of the pIdx index.
  120215. */
  120216. static const char *explainIndexColumnName(Index *pIdx, int i){
  120217. i = pIdx->aiColumn[i];
  120218. if( i==XN_EXPR ) return "<expr>";
  120219. if( i==XN_ROWID ) return "rowid";
  120220. return pIdx->pTable->aCol[i].zName;
  120221. }
  120222. /*
  120223. ** This routine is a helper for explainIndexRange() below
  120224. **
  120225. ** pStr holds the text of an expression that we are building up one term
  120226. ** at a time. This routine adds a new term to the end of the expression.
  120227. ** Terms are separated by AND so add the "AND" text for second and subsequent
  120228. ** terms only.
  120229. */
  120230. static void explainAppendTerm(
  120231. StrAccum *pStr, /* The text expression being built */
  120232. Index *pIdx, /* Index to read column names from */
  120233. int nTerm, /* Number of terms */
  120234. int iTerm, /* Zero-based index of first term. */
  120235. int bAnd, /* Non-zero to append " AND " */
  120236. const char *zOp /* Name of the operator */
  120237. ){
  120238. int i;
  120239. assert( nTerm>=1 );
  120240. if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  120241. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  120242. for(i=0; i<nTerm; i++){
  120243. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  120244. sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
  120245. }
  120246. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  120247. sqlite3StrAccumAppend(pStr, zOp, 1);
  120248. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  120249. for(i=0; i<nTerm; i++){
  120250. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  120251. sqlite3StrAccumAppend(pStr, "?", 1);
  120252. }
  120253. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  120254. }
  120255. /*
  120256. ** Argument pLevel describes a strategy for scanning table pTab. This
  120257. ** function appends text to pStr that describes the subset of table
  120258. ** rows scanned by the strategy in the form of an SQL expression.
  120259. **
  120260. ** For example, if the query:
  120261. **
  120262. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  120263. **
  120264. ** is run and there is an index on (a, b), then this function returns a
  120265. ** string similar to:
  120266. **
  120267. ** "a=? AND b>?"
  120268. */
  120269. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  120270. Index *pIndex = pLoop->u.btree.pIndex;
  120271. u16 nEq = pLoop->u.btree.nEq;
  120272. u16 nSkip = pLoop->nSkip;
  120273. int i, j;
  120274. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  120275. sqlite3StrAccumAppend(pStr, " (", 2);
  120276. for(i=0; i<nEq; i++){
  120277. const char *z = explainIndexColumnName(pIndex, i);
  120278. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  120279. sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  120280. }
  120281. j = i;
  120282. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  120283. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  120284. i = 1;
  120285. }
  120286. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  120287. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  120288. }
  120289. sqlite3StrAccumAppend(pStr, ")", 1);
  120290. }
  120291. /*
  120292. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  120293. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  120294. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  120295. ** is added to the output to describe the table scan strategy in pLevel.
  120296. **
  120297. ** If an OP_Explain opcode is added to the VM, its address is returned.
  120298. ** Otherwise, if no OP_Explain is coded, zero is returned.
  120299. */
  120300. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  120301. Parse *pParse, /* Parse context */
  120302. SrcList *pTabList, /* Table list this loop refers to */
  120303. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  120304. int iLevel, /* Value for "level" column of output */
  120305. int iFrom, /* Value for "from" column of output */
  120306. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  120307. ){
  120308. int ret = 0;
  120309. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  120310. if( pParse->explain==2 )
  120311. #endif
  120312. {
  120313. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  120314. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  120315. sqlite3 *db = pParse->db; /* Database handle */
  120316. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  120317. int isSearch; /* True for a SEARCH. False for SCAN. */
  120318. WhereLoop *pLoop; /* The controlling WhereLoop object */
  120319. u32 flags; /* Flags that describe this loop */
  120320. char *zMsg; /* Text to add to EQP output */
  120321. StrAccum str; /* EQP output string */
  120322. char zBuf[100]; /* Initial space for EQP output string */
  120323. pLoop = pLevel->pWLoop;
  120324. flags = pLoop->wsFlags;
  120325. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  120326. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  120327. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  120328. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  120329. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  120330. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  120331. if( pItem->pSelect ){
  120332. sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
  120333. }else{
  120334. sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
  120335. }
  120336. if( pItem->zAlias ){
  120337. sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
  120338. }
  120339. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  120340. const char *zFmt = 0;
  120341. Index *pIdx;
  120342. assert( pLoop->u.btree.pIndex!=0 );
  120343. pIdx = pLoop->u.btree.pIndex;
  120344. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  120345. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  120346. if( isSearch ){
  120347. zFmt = "PRIMARY KEY";
  120348. }
  120349. }else if( flags & WHERE_PARTIALIDX ){
  120350. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  120351. }else if( flags & WHERE_AUTO_INDEX ){
  120352. zFmt = "AUTOMATIC COVERING INDEX";
  120353. }else if( flags & WHERE_IDX_ONLY ){
  120354. zFmt = "COVERING INDEX %s";
  120355. }else{
  120356. zFmt = "INDEX %s";
  120357. }
  120358. if( zFmt ){
  120359. sqlite3StrAccumAppend(&str, " USING ", 7);
  120360. sqlite3XPrintf(&str, zFmt, pIdx->zName);
  120361. explainIndexRange(&str, pLoop);
  120362. }
  120363. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  120364. const char *zRangeOp;
  120365. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  120366. zRangeOp = "=";
  120367. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  120368. zRangeOp = ">? AND rowid<";
  120369. }else if( flags&WHERE_BTM_LIMIT ){
  120370. zRangeOp = ">";
  120371. }else{
  120372. assert( flags&WHERE_TOP_LIMIT);
  120373. zRangeOp = "<";
  120374. }
  120375. sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  120376. }
  120377. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120378. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  120379. sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
  120380. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  120381. }
  120382. #endif
  120383. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  120384. if( pLoop->nOut>=10 ){
  120385. sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  120386. }else{
  120387. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  120388. }
  120389. #endif
  120390. zMsg = sqlite3StrAccumFinish(&str);
  120391. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  120392. }
  120393. return ret;
  120394. }
  120395. #endif /* SQLITE_OMIT_EXPLAIN */
  120396. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  120397. /*
  120398. ** Configure the VM passed as the first argument with an
  120399. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  120400. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  120401. ** clause that the scan reads data from.
  120402. **
  120403. ** If argument addrExplain is not 0, it must be the address of an
  120404. ** OP_Explain instruction that describes the same loop.
  120405. */
  120406. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  120407. Vdbe *v, /* Vdbe to add scanstatus entry to */
  120408. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  120409. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  120410. int addrExplain /* Address of OP_Explain (or 0) */
  120411. ){
  120412. const char *zObj = 0;
  120413. WhereLoop *pLoop = pLvl->pWLoop;
  120414. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  120415. zObj = pLoop->u.btree.pIndex->zName;
  120416. }else{
  120417. zObj = pSrclist->a[pLvl->iFrom].zName;
  120418. }
  120419. sqlite3VdbeScanStatus(
  120420. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  120421. );
  120422. }
  120423. #endif
  120424. /*
  120425. ** Disable a term in the WHERE clause. Except, do not disable the term
  120426. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  120427. ** or USING clause of that join.
  120428. **
  120429. ** Consider the term t2.z='ok' in the following queries:
  120430. **
  120431. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  120432. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  120433. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  120434. **
  120435. ** The t2.z='ok' is disabled in the in (2) because it originates
  120436. ** in the ON clause. The term is disabled in (3) because it is not part
  120437. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  120438. **
  120439. ** Disabling a term causes that term to not be tested in the inner loop
  120440. ** of the join. Disabling is an optimization. When terms are satisfied
  120441. ** by indices, we disable them to prevent redundant tests in the inner
  120442. ** loop. We would get the correct results if nothing were ever disabled,
  120443. ** but joins might run a little slower. The trick is to disable as much
  120444. ** as we can without disabling too much. If we disabled in (1), we'd get
  120445. ** the wrong answer. See ticket #813.
  120446. **
  120447. ** If all the children of a term are disabled, then that term is also
  120448. ** automatically disabled. In this way, terms get disabled if derived
  120449. ** virtual terms are tested first. For example:
  120450. **
  120451. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  120452. ** \___________/ \______/ \_____/
  120453. ** parent child1 child2
  120454. **
  120455. ** Only the parent term was in the original WHERE clause. The child1
  120456. ** and child2 terms were added by the LIKE optimization. If both of
  120457. ** the virtual child terms are valid, then testing of the parent can be
  120458. ** skipped.
  120459. **
  120460. ** Usually the parent term is marked as TERM_CODED. But if the parent
  120461. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  120462. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  120463. ** a conditional such that is only evaluated on the second pass of a
  120464. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  120465. */
  120466. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  120467. int nLoop = 0;
  120468. while( ALWAYS(pTerm!=0)
  120469. && (pTerm->wtFlags & TERM_CODED)==0
  120470. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  120471. && (pLevel->notReady & pTerm->prereqAll)==0
  120472. ){
  120473. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  120474. pTerm->wtFlags |= TERM_LIKECOND;
  120475. }else{
  120476. pTerm->wtFlags |= TERM_CODED;
  120477. }
  120478. if( pTerm->iParent<0 ) break;
  120479. pTerm = &pTerm->pWC->a[pTerm->iParent];
  120480. pTerm->nChild--;
  120481. if( pTerm->nChild!=0 ) break;
  120482. nLoop++;
  120483. }
  120484. }
  120485. /*
  120486. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  120487. ** to the n registers starting at base.
  120488. **
  120489. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  120490. ** beginning and end of zAff are ignored. If all entries in zAff are
  120491. ** SQLITE_AFF_BLOB, then no code gets generated.
  120492. **
  120493. ** This routine makes its own copy of zAff so that the caller is free
  120494. ** to modify zAff after this routine returns.
  120495. */
  120496. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  120497. Vdbe *v = pParse->pVdbe;
  120498. if( zAff==0 ){
  120499. assert( pParse->db->mallocFailed );
  120500. return;
  120501. }
  120502. assert( v!=0 );
  120503. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  120504. ** and end of the affinity string.
  120505. */
  120506. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  120507. n--;
  120508. base++;
  120509. zAff++;
  120510. }
  120511. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  120512. n--;
  120513. }
  120514. /* Code the OP_Affinity opcode if there is anything left to do. */
  120515. if( n>0 ){
  120516. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  120517. sqlite3ExprCacheAffinityChange(pParse, base, n);
  120518. }
  120519. }
  120520. /*
  120521. ** Expression pRight, which is the RHS of a comparison operation, is
  120522. ** either a vector of n elements or, if n==1, a scalar expression.
  120523. ** Before the comparison operation, affinity zAff is to be applied
  120524. ** to the pRight values. This function modifies characters within the
  120525. ** affinity string to SQLITE_AFF_BLOB if either:
  120526. **
  120527. ** * the comparison will be performed with no affinity, or
  120528. ** * the affinity change in zAff is guaranteed not to change the value.
  120529. */
  120530. static void updateRangeAffinityStr(
  120531. Expr *pRight, /* RHS of comparison */
  120532. int n, /* Number of vector elements in comparison */
  120533. char *zAff /* Affinity string to modify */
  120534. ){
  120535. int i;
  120536. for(i=0; i<n; i++){
  120537. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  120538. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  120539. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  120540. ){
  120541. zAff[i] = SQLITE_AFF_BLOB;
  120542. }
  120543. }
  120544. }
  120545. /*
  120546. ** Generate code for a single equality term of the WHERE clause. An equality
  120547. ** term can be either X=expr or X IN (...). pTerm is the term to be
  120548. ** coded.
  120549. **
  120550. ** The current value for the constraint is left in a register, the index
  120551. ** of which is returned. An attempt is made store the result in iTarget but
  120552. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  120553. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  120554. ** some other register and it is the caller's responsibility to compensate.
  120555. **
  120556. ** For a constraint of the form X=expr, the expression is evaluated in
  120557. ** straight-line code. For constraints of the form X IN (...)
  120558. ** this routine sets up a loop that will iterate over all values of X.
  120559. */
  120560. static int codeEqualityTerm(
  120561. Parse *pParse, /* The parsing context */
  120562. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  120563. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  120564. int iEq, /* Index of the equality term within this level */
  120565. int bRev, /* True for reverse-order IN operations */
  120566. int iTarget /* Attempt to leave results in this register */
  120567. ){
  120568. Expr *pX = pTerm->pExpr;
  120569. Vdbe *v = pParse->pVdbe;
  120570. int iReg; /* Register holding results */
  120571. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  120572. assert( iTarget>0 );
  120573. if( pX->op==TK_EQ || pX->op==TK_IS ){
  120574. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  120575. }else if( pX->op==TK_ISNULL ){
  120576. iReg = iTarget;
  120577. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  120578. #ifndef SQLITE_OMIT_SUBQUERY
  120579. }else{
  120580. int eType = IN_INDEX_NOOP;
  120581. int iTab;
  120582. struct InLoop *pIn;
  120583. WhereLoop *pLoop = pLevel->pWLoop;
  120584. int i;
  120585. int nEq = 0;
  120586. int *aiMap = 0;
  120587. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  120588. && pLoop->u.btree.pIndex!=0
  120589. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  120590. ){
  120591. testcase( iEq==0 );
  120592. testcase( bRev );
  120593. bRev = !bRev;
  120594. }
  120595. assert( pX->op==TK_IN );
  120596. iReg = iTarget;
  120597. for(i=0; i<iEq; i++){
  120598. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  120599. disableTerm(pLevel, pTerm);
  120600. return iTarget;
  120601. }
  120602. }
  120603. for(i=iEq;i<pLoop->nLTerm; i++){
  120604. if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  120605. }
  120606. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  120607. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  120608. }else{
  120609. Select *pSelect = pX->x.pSelect;
  120610. sqlite3 *db = pParse->db;
  120611. u16 savedDbOptFlags = db->dbOptFlags;
  120612. ExprList *pOrigRhs = pSelect->pEList;
  120613. ExprList *pOrigLhs = pX->pLeft->x.pList;
  120614. ExprList *pRhs = 0; /* New Select.pEList for RHS */
  120615. ExprList *pLhs = 0; /* New pX->pLeft vector */
  120616. for(i=iEq;i<pLoop->nLTerm; i++){
  120617. if( pLoop->aLTerm[i]->pExpr==pX ){
  120618. int iField = pLoop->aLTerm[i]->iField - 1;
  120619. Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
  120620. Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
  120621. pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
  120622. pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
  120623. }
  120624. }
  120625. if( !db->mallocFailed ){
  120626. Expr *pLeft = pX->pLeft;
  120627. if( pSelect->pOrderBy ){
  120628. /* If the SELECT statement has an ORDER BY clause, zero the
  120629. ** iOrderByCol variables. These are set to non-zero when an
  120630. ** ORDER BY term exactly matches one of the terms of the
  120631. ** result-set. Since the result-set of the SELECT statement may
  120632. ** have been modified or reordered, these variables are no longer
  120633. ** set correctly. Since setting them is just an optimization,
  120634. ** it's easiest just to zero them here. */
  120635. ExprList *pOrderBy = pSelect->pOrderBy;
  120636. for(i=0; i<pOrderBy->nExpr; i++){
  120637. pOrderBy->a[i].u.x.iOrderByCol = 0;
  120638. }
  120639. }
  120640. /* Take care here not to generate a TK_VECTOR containing only a
  120641. ** single value. Since the parser never creates such a vector, some
  120642. ** of the subroutines do not handle this case. */
  120643. if( pLhs->nExpr==1 ){
  120644. pX->pLeft = pLhs->a[0].pExpr;
  120645. }else{
  120646. pLeft->x.pList = pLhs;
  120647. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
  120648. testcase( aiMap==0 );
  120649. }
  120650. pSelect->pEList = pRhs;
  120651. db->dbOptFlags |= SQLITE_QueryFlattener;
  120652. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  120653. db->dbOptFlags = savedDbOptFlags;
  120654. testcase( aiMap!=0 && aiMap[0]!=0 );
  120655. pSelect->pEList = pOrigRhs;
  120656. pLeft->x.pList = pOrigLhs;
  120657. pX->pLeft = pLeft;
  120658. }
  120659. sqlite3ExprListDelete(pParse->db, pLhs);
  120660. sqlite3ExprListDelete(pParse->db, pRhs);
  120661. }
  120662. if( eType==IN_INDEX_INDEX_DESC ){
  120663. testcase( bRev );
  120664. bRev = !bRev;
  120665. }
  120666. iTab = pX->iTable;
  120667. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  120668. VdbeCoverageIf(v, bRev);
  120669. VdbeCoverageIf(v, !bRev);
  120670. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  120671. pLoop->wsFlags |= WHERE_IN_ABLE;
  120672. if( pLevel->u.in.nIn==0 ){
  120673. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  120674. }
  120675. i = pLevel->u.in.nIn;
  120676. pLevel->u.in.nIn += nEq;
  120677. pLevel->u.in.aInLoop =
  120678. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  120679. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  120680. pIn = pLevel->u.in.aInLoop;
  120681. if( pIn ){
  120682. int iMap = 0; /* Index in aiMap[] */
  120683. pIn += i;
  120684. for(i=iEq;i<pLoop->nLTerm; i++){
  120685. if( pLoop->aLTerm[i]->pExpr==pX ){
  120686. int iOut = iReg + i - iEq;
  120687. if( eType==IN_INDEX_ROWID ){
  120688. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  120689. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  120690. }else{
  120691. int iCol = aiMap ? aiMap[iMap++] : 0;
  120692. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  120693. }
  120694. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  120695. if( i==iEq ){
  120696. pIn->iCur = iTab;
  120697. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  120698. }else{
  120699. pIn->eEndLoopOp = OP_Noop;
  120700. }
  120701. pIn++;
  120702. }
  120703. }
  120704. }else{
  120705. pLevel->u.in.nIn = 0;
  120706. }
  120707. sqlite3DbFree(pParse->db, aiMap);
  120708. #endif
  120709. }
  120710. disableTerm(pLevel, pTerm);
  120711. return iReg;
  120712. }
  120713. /*
  120714. ** Generate code that will evaluate all == and IN constraints for an
  120715. ** index scan.
  120716. **
  120717. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  120718. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  120719. ** The index has as many as three equality constraints, but in this
  120720. ** example, the third "c" value is an inequality. So only two
  120721. ** constraints are coded. This routine will generate code to evaluate
  120722. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  120723. ** in consecutive registers and the index of the first register is returned.
  120724. **
  120725. ** In the example above nEq==2. But this subroutine works for any value
  120726. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  120727. ** The only thing it does is allocate the pLevel->iMem memory cell and
  120728. ** compute the affinity string.
  120729. **
  120730. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  120731. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  120732. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  120733. ** occurs after the nEq quality constraints.
  120734. **
  120735. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  120736. ** the index of the first memory cell in that range. The code that
  120737. ** calls this routine will use that memory range to store keys for
  120738. ** start and termination conditions of the loop.
  120739. ** key value of the loop. If one or more IN operators appear, then
  120740. ** this routine allocates an additional nEq memory cells for internal
  120741. ** use.
  120742. **
  120743. ** Before returning, *pzAff is set to point to a buffer containing a
  120744. ** copy of the column affinity string of the index allocated using
  120745. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  120746. ** with equality constraints that use BLOB or NONE affinity are set to
  120747. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  120748. **
  120749. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  120750. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  120751. **
  120752. ** In the example above, the index on t1(a) has TEXT affinity. But since
  120753. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  120754. ** no conversion should be attempted before using a t2.b value as part of
  120755. ** a key to search the index. Hence the first byte in the returned affinity
  120756. ** string in this example would be set to SQLITE_AFF_BLOB.
  120757. */
  120758. static int codeAllEqualityTerms(
  120759. Parse *pParse, /* Parsing context */
  120760. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  120761. int bRev, /* Reverse the order of IN operators */
  120762. int nExtraReg, /* Number of extra registers to allocate */
  120763. char **pzAff /* OUT: Set to point to affinity string */
  120764. ){
  120765. u16 nEq; /* The number of == or IN constraints to code */
  120766. u16 nSkip; /* Number of left-most columns to skip */
  120767. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  120768. Index *pIdx; /* The index being used for this loop */
  120769. WhereTerm *pTerm; /* A single constraint term */
  120770. WhereLoop *pLoop; /* The WhereLoop object */
  120771. int j; /* Loop counter */
  120772. int regBase; /* Base register */
  120773. int nReg; /* Number of registers to allocate */
  120774. char *zAff; /* Affinity string to return */
  120775. /* This module is only called on query plans that use an index. */
  120776. pLoop = pLevel->pWLoop;
  120777. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  120778. nEq = pLoop->u.btree.nEq;
  120779. nSkip = pLoop->nSkip;
  120780. pIdx = pLoop->u.btree.pIndex;
  120781. assert( pIdx!=0 );
  120782. /* Figure out how many memory cells we will need then allocate them.
  120783. */
  120784. regBase = pParse->nMem + 1;
  120785. nReg = pLoop->u.btree.nEq + nExtraReg;
  120786. pParse->nMem += nReg;
  120787. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  120788. assert( zAff!=0 || pParse->db->mallocFailed );
  120789. if( nSkip ){
  120790. int iIdxCur = pLevel->iIdxCur;
  120791. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  120792. VdbeCoverageIf(v, bRev==0);
  120793. VdbeCoverageIf(v, bRev!=0);
  120794. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  120795. j = sqlite3VdbeAddOp0(v, OP_Goto);
  120796. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  120797. iIdxCur, 0, regBase, nSkip);
  120798. VdbeCoverageIf(v, bRev==0);
  120799. VdbeCoverageIf(v, bRev!=0);
  120800. sqlite3VdbeJumpHere(v, j);
  120801. for(j=0; j<nSkip; j++){
  120802. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  120803. testcase( pIdx->aiColumn[j]==XN_EXPR );
  120804. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  120805. }
  120806. }
  120807. /* Evaluate the equality constraints
  120808. */
  120809. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  120810. for(j=nSkip; j<nEq; j++){
  120811. int r1;
  120812. pTerm = pLoop->aLTerm[j];
  120813. assert( pTerm!=0 );
  120814. /* The following testcase is true for indices with redundant columns.
  120815. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  120816. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  120817. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120818. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  120819. if( r1!=regBase+j ){
  120820. if( nReg==1 ){
  120821. sqlite3ReleaseTempReg(pParse, regBase);
  120822. regBase = r1;
  120823. }else{
  120824. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  120825. }
  120826. }
  120827. if( pTerm->eOperator & WO_IN ){
  120828. if( pTerm->pExpr->flags & EP_xIsSelect ){
  120829. /* No affinity ever needs to be (or should be) applied to a value
  120830. ** from the RHS of an "? IN (SELECT ...)" expression. The
  120831. ** sqlite3FindInIndex() routine has already ensured that the
  120832. ** affinity of the comparison has been applied to the value. */
  120833. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  120834. }
  120835. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  120836. Expr *pRight = pTerm->pExpr->pRight;
  120837. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  120838. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  120839. VdbeCoverage(v);
  120840. }
  120841. if( zAff ){
  120842. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  120843. zAff[j] = SQLITE_AFF_BLOB;
  120844. }
  120845. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  120846. zAff[j] = SQLITE_AFF_BLOB;
  120847. }
  120848. }
  120849. }
  120850. }
  120851. *pzAff = zAff;
  120852. return regBase;
  120853. }
  120854. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120855. /*
  120856. ** If the most recently coded instruction is a constant range constraint
  120857. ** (a string literal) that originated from the LIKE optimization, then
  120858. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  120859. ** to a BLOB at appropriate times.
  120860. **
  120861. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  120862. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  120863. ** scan loop run twice, once for strings and a second time for BLOBs.
  120864. ** The OP_String opcodes on the second pass convert the upper and lower
  120865. ** bound string constants to blobs. This routine makes the necessary changes
  120866. ** to the OP_String opcodes for that to happen.
  120867. **
  120868. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  120869. ** only the one pass through the string space is required, so this routine
  120870. ** becomes a no-op.
  120871. */
  120872. static void whereLikeOptimizationStringFixup(
  120873. Vdbe *v, /* prepared statement under construction */
  120874. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  120875. WhereTerm *pTerm /* The upper or lower bound just coded */
  120876. ){
  120877. if( pTerm->wtFlags & TERM_LIKEOPT ){
  120878. VdbeOp *pOp;
  120879. assert( pLevel->iLikeRepCntr>0 );
  120880. pOp = sqlite3VdbeGetOp(v, -1);
  120881. assert( pOp!=0 );
  120882. assert( pOp->opcode==OP_String8
  120883. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  120884. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  120885. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  120886. }
  120887. }
  120888. #else
  120889. # define whereLikeOptimizationStringFixup(A,B,C)
  120890. #endif
  120891. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  120892. /*
  120893. ** Information is passed from codeCursorHint() down to individual nodes of
  120894. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  120895. ** structure.
  120896. */
  120897. struct CCurHint {
  120898. int iTabCur; /* Cursor for the main table */
  120899. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  120900. Index *pIdx; /* The index used to access the table */
  120901. };
  120902. /*
  120903. ** This function is called for every node of an expression that is a candidate
  120904. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  120905. ** the table CCurHint.iTabCur, verify that the same column can be
  120906. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  120907. */
  120908. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  120909. struct CCurHint *pHint = pWalker->u.pCCurHint;
  120910. assert( pHint->pIdx!=0 );
  120911. if( pExpr->op==TK_COLUMN
  120912. && pExpr->iTable==pHint->iTabCur
  120913. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  120914. ){
  120915. pWalker->eCode = 1;
  120916. }
  120917. return WRC_Continue;
  120918. }
  120919. /*
  120920. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  120921. ** should be included in the cursor-hint for a table that is on the rhs
  120922. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  120923. ** expression is not suitable.
  120924. **
  120925. ** An expression is unsuitable if it might evaluate to non NULL even if
  120926. ** a TK_COLUMN node that does affect the value of the expression is set
  120927. ** to NULL. For example:
  120928. **
  120929. ** col IS NULL
  120930. ** col IS NOT NULL
  120931. ** coalesce(col, 1)
  120932. ** CASE WHEN col THEN 0 ELSE 1 END
  120933. */
  120934. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  120935. if( pExpr->op==TK_IS
  120936. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  120937. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  120938. ){
  120939. pWalker->eCode = 1;
  120940. }else if( pExpr->op==TK_FUNCTION ){
  120941. int d1;
  120942. char d2[4];
  120943. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  120944. pWalker->eCode = 1;
  120945. }
  120946. }
  120947. return WRC_Continue;
  120948. }
  120949. /*
  120950. ** This function is called on every node of an expression tree used as an
  120951. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  120952. ** that accesses any table other than the one identified by
  120953. ** CCurHint.iTabCur, then do the following:
  120954. **
  120955. ** 1) allocate a register and code an OP_Column instruction to read
  120956. ** the specified column into the new register, and
  120957. **
  120958. ** 2) transform the expression node to a TK_REGISTER node that reads
  120959. ** from the newly populated register.
  120960. **
  120961. ** Also, if the node is a TK_COLUMN that does access the table idenified
  120962. ** by pCCurHint.iTabCur, and an index is being used (which we will
  120963. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  120964. ** an access of the index rather than the original table.
  120965. */
  120966. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  120967. int rc = WRC_Continue;
  120968. struct CCurHint *pHint = pWalker->u.pCCurHint;
  120969. if( pExpr->op==TK_COLUMN ){
  120970. if( pExpr->iTable!=pHint->iTabCur ){
  120971. Vdbe *v = pWalker->pParse->pVdbe;
  120972. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  120973. sqlite3ExprCodeGetColumnOfTable(
  120974. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  120975. );
  120976. pExpr->op = TK_REGISTER;
  120977. pExpr->iTable = reg;
  120978. }else if( pHint->pIdx!=0 ){
  120979. pExpr->iTable = pHint->iIdxCur;
  120980. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  120981. assert( pExpr->iColumn>=0 );
  120982. }
  120983. }else if( pExpr->op==TK_AGG_FUNCTION ){
  120984. /* An aggregate function in the WHERE clause of a query means this must
  120985. ** be a correlated sub-query, and expression pExpr is an aggregate from
  120986. ** the parent context. Do not walk the function arguments in this case.
  120987. **
  120988. ** todo: It should be possible to replace this node with a TK_REGISTER
  120989. ** expression, as the result of the expression must be stored in a
  120990. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  120991. rc = WRC_Prune;
  120992. }
  120993. return rc;
  120994. }
  120995. /*
  120996. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  120997. */
  120998. static void codeCursorHint(
  120999. struct SrcList_item *pTabItem, /* FROM clause item */
  121000. WhereInfo *pWInfo, /* The where clause */
  121001. WhereLevel *pLevel, /* Which loop to provide hints for */
  121002. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  121003. ){
  121004. Parse *pParse = pWInfo->pParse;
  121005. sqlite3 *db = pParse->db;
  121006. Vdbe *v = pParse->pVdbe;
  121007. Expr *pExpr = 0;
  121008. WhereLoop *pLoop = pLevel->pWLoop;
  121009. int iCur;
  121010. WhereClause *pWC;
  121011. WhereTerm *pTerm;
  121012. int i, j;
  121013. struct CCurHint sHint;
  121014. Walker sWalker;
  121015. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  121016. iCur = pLevel->iTabCur;
  121017. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  121018. sHint.iTabCur = iCur;
  121019. sHint.iIdxCur = pLevel->iIdxCur;
  121020. sHint.pIdx = pLoop->u.btree.pIndex;
  121021. memset(&sWalker, 0, sizeof(sWalker));
  121022. sWalker.pParse = pParse;
  121023. sWalker.u.pCCurHint = &sHint;
  121024. pWC = &pWInfo->sWC;
  121025. for(i=0; i<pWC->nTerm; i++){
  121026. pTerm = &pWC->a[i];
  121027. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  121028. if( pTerm->prereqAll & pLevel->notReady ) continue;
  121029. /* Any terms specified as part of the ON(...) clause for any LEFT
  121030. ** JOIN for which the current table is not the rhs are omitted
  121031. ** from the cursor-hint.
  121032. **
  121033. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  121034. ** that were specified as part of the WHERE clause must be excluded.
  121035. ** This is to address the following:
  121036. **
  121037. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  121038. **
  121039. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  121040. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  121041. ** pushed down to the cursor, this row is filtered out, causing
  121042. ** SQLite to synthesize a row of NULL values. Which does match the
  121043. ** WHERE clause, and so the query returns a row. Which is incorrect.
  121044. **
  121045. ** For the same reason, WHERE terms such as:
  121046. **
  121047. ** WHERE 1 = (t2.c IS NULL)
  121048. **
  121049. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  121050. */
  121051. if( pTabItem->fg.jointype & JT_LEFT ){
  121052. Expr *pExpr = pTerm->pExpr;
  121053. if( !ExprHasProperty(pExpr, EP_FromJoin)
  121054. || pExpr->iRightJoinTable!=pTabItem->iCursor
  121055. ){
  121056. sWalker.eCode = 0;
  121057. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  121058. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  121059. if( sWalker.eCode ) continue;
  121060. }
  121061. }else{
  121062. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  121063. }
  121064. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  121065. ** the cursor. These terms are not needed as hints for a pure range
  121066. ** scan (that has no == terms) so omit them. */
  121067. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  121068. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  121069. if( j<pLoop->nLTerm ) continue;
  121070. }
  121071. /* No subqueries or non-deterministic functions allowed */
  121072. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  121073. /* For an index scan, make sure referenced columns are actually in
  121074. ** the index. */
  121075. if( sHint.pIdx!=0 ){
  121076. sWalker.eCode = 0;
  121077. sWalker.xExprCallback = codeCursorHintCheckExpr;
  121078. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  121079. if( sWalker.eCode ) continue;
  121080. }
  121081. /* If we survive all prior tests, that means this term is worth hinting */
  121082. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  121083. }
  121084. if( pExpr!=0 ){
  121085. sWalker.xExprCallback = codeCursorHintFixExpr;
  121086. sqlite3WalkExpr(&sWalker, pExpr);
  121087. sqlite3VdbeAddOp4(v, OP_CursorHint,
  121088. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  121089. (const char*)pExpr, P4_EXPR);
  121090. }
  121091. }
  121092. #else
  121093. # define codeCursorHint(A,B,C,D) /* No-op */
  121094. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  121095. /*
  121096. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  121097. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  121098. ** function generates code to do a deferred seek of cursor iCur to the
  121099. ** rowid stored in register iRowid.
  121100. **
  121101. ** Normally, this is just:
  121102. **
  121103. ** OP_DeferredSeek $iCur $iRowid
  121104. **
  121105. ** However, if the scan currently being coded is a branch of an OR-loop and
  121106. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  121107. ** is set to iIdxCur and P4 is set to point to an array of integers
  121108. ** containing one entry for each column of the table cursor iCur is open
  121109. ** on. For each table column, if the column is the i'th column of the
  121110. ** index, then the corresponding array entry is set to (i+1). If the column
  121111. ** does not appear in the index at all, the array entry is set to 0.
  121112. */
  121113. static void codeDeferredSeek(
  121114. WhereInfo *pWInfo, /* Where clause context */
  121115. Index *pIdx, /* Index scan is using */
  121116. int iCur, /* Cursor for IPK b-tree */
  121117. int iIdxCur /* Index cursor */
  121118. ){
  121119. Parse *pParse = pWInfo->pParse; /* Parse context */
  121120. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  121121. assert( iIdxCur>0 );
  121122. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  121123. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  121124. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  121125. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  121126. ){
  121127. int i;
  121128. Table *pTab = pIdx->pTable;
  121129. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  121130. if( ai ){
  121131. ai[0] = pTab->nCol;
  121132. for(i=0; i<pIdx->nColumn-1; i++){
  121133. assert( pIdx->aiColumn[i]<pTab->nCol );
  121134. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  121135. }
  121136. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  121137. }
  121138. }
  121139. }
  121140. /*
  121141. ** If the expression passed as the second argument is a vector, generate
  121142. ** code to write the first nReg elements of the vector into an array
  121143. ** of registers starting with iReg.
  121144. **
  121145. ** If the expression is not a vector, then nReg must be passed 1. In
  121146. ** this case, generate code to evaluate the expression and leave the
  121147. ** result in register iReg.
  121148. */
  121149. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  121150. assert( nReg>0 );
  121151. if( p && sqlite3ExprIsVector(p) ){
  121152. #ifndef SQLITE_OMIT_SUBQUERY
  121153. if( (p->flags & EP_xIsSelect) ){
  121154. Vdbe *v = pParse->pVdbe;
  121155. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  121156. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  121157. }else
  121158. #endif
  121159. {
  121160. int i;
  121161. ExprList *pList = p->x.pList;
  121162. assert( nReg<=pList->nExpr );
  121163. for(i=0; i<nReg; i++){
  121164. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  121165. }
  121166. }
  121167. }else{
  121168. assert( nReg==1 );
  121169. sqlite3ExprCode(pParse, p, iReg);
  121170. }
  121171. }
  121172. /* An instance of the IdxExprTrans object carries information about a
  121173. ** mapping from an expression on table columns into a column in an index
  121174. ** down through the Walker.
  121175. */
  121176. typedef struct IdxExprTrans {
  121177. Expr *pIdxExpr; /* The index expression */
  121178. int iTabCur; /* The cursor of the corresponding table */
  121179. int iIdxCur; /* The cursor for the index */
  121180. int iIdxCol; /* The column for the index */
  121181. } IdxExprTrans;
  121182. /* The walker node callback used to transform matching expressions into
  121183. ** a reference to an index column for an index on an expression.
  121184. **
  121185. ** If pExpr matches, then transform it into a reference to the index column
  121186. ** that contains the value of pExpr.
  121187. */
  121188. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  121189. IdxExprTrans *pX = p->u.pIdxTrans;
  121190. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  121191. pExpr->op = TK_COLUMN;
  121192. pExpr->iTable = pX->iIdxCur;
  121193. pExpr->iColumn = pX->iIdxCol;
  121194. pExpr->pTab = 0;
  121195. return WRC_Prune;
  121196. }else{
  121197. return WRC_Continue;
  121198. }
  121199. }
  121200. /*
  121201. ** For an indexes on expression X, locate every instance of expression X
  121202. ** in pExpr and change that subexpression into a reference to the appropriate
  121203. ** column of the index.
  121204. */
  121205. static void whereIndexExprTrans(
  121206. Index *pIdx, /* The Index */
  121207. int iTabCur, /* Cursor of the table that is being indexed */
  121208. int iIdxCur, /* Cursor of the index itself */
  121209. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  121210. ){
  121211. int iIdxCol; /* Column number of the index */
  121212. ExprList *aColExpr; /* Expressions that are indexed */
  121213. Walker w;
  121214. IdxExprTrans x;
  121215. aColExpr = pIdx->aColExpr;
  121216. if( aColExpr==0 ) return; /* Not an index on expressions */
  121217. memset(&w, 0, sizeof(w));
  121218. w.xExprCallback = whereIndexExprTransNode;
  121219. w.u.pIdxTrans = &x;
  121220. x.iTabCur = iTabCur;
  121221. x.iIdxCur = iIdxCur;
  121222. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  121223. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  121224. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  121225. x.iIdxCol = iIdxCol;
  121226. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  121227. sqlite3WalkExpr(&w, pWInfo->pWhere);
  121228. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  121229. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  121230. }
  121231. }
  121232. /*
  121233. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  121234. ** implementation described by pWInfo.
  121235. */
  121236. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  121237. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  121238. int iLevel, /* Which level of pWInfo->a[] should be coded */
  121239. Bitmask notReady /* Which tables are currently available */
  121240. ){
  121241. int j, k; /* Loop counters */
  121242. int iCur; /* The VDBE cursor for the table */
  121243. int addrNxt; /* Where to jump to continue with the next IN case */
  121244. int omitTable; /* True if we use the index only */
  121245. int bRev; /* True if we need to scan in reverse order */
  121246. WhereLevel *pLevel; /* The where level to be coded */
  121247. WhereLoop *pLoop; /* The WhereLoop object being coded */
  121248. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  121249. WhereTerm *pTerm; /* A WHERE clause term */
  121250. Parse *pParse; /* Parsing context */
  121251. sqlite3 *db; /* Database connection */
  121252. Vdbe *v; /* The prepared stmt under constructions */
  121253. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  121254. int addrBrk; /* Jump here to break out of the loop */
  121255. int addrHalt; /* addrBrk for the outermost loop */
  121256. int addrCont; /* Jump here to continue with next cycle */
  121257. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  121258. int iReleaseReg = 0; /* Temp register to free before returning */
  121259. Index *pIdx = 0; /* Index used by loop (if any) */
  121260. int iLoop; /* Iteration of constraint generator loop */
  121261. pParse = pWInfo->pParse;
  121262. v = pParse->pVdbe;
  121263. pWC = &pWInfo->sWC;
  121264. db = pParse->db;
  121265. pLevel = &pWInfo->a[iLevel];
  121266. pLoop = pLevel->pWLoop;
  121267. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  121268. iCur = pTabItem->iCursor;
  121269. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  121270. bRev = (pWInfo->revMask>>iLevel)&1;
  121271. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  121272. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  121273. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  121274. /* Create labels for the "break" and "continue" instructions
  121275. ** for the current loop. Jump to addrBrk to break out of a loop.
  121276. ** Jump to cont to go immediately to the next iteration of the
  121277. ** loop.
  121278. **
  121279. ** When there is an IN operator, we also have a "addrNxt" label that
  121280. ** means to continue with the next IN value combination. When
  121281. ** there are no IN operators in the constraints, the "addrNxt" label
  121282. ** is the same as "addrBrk".
  121283. */
  121284. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  121285. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  121286. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  121287. ** initialize a memory cell that records if this table matches any
  121288. ** row of the left table of the join.
  121289. */
  121290. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  121291. pLevel->iLeftJoin = ++pParse->nMem;
  121292. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  121293. VdbeComment((v, "init LEFT JOIN no-match flag"));
  121294. }
  121295. /* Compute a safe address to jump to if we discover that the table for
  121296. ** this loop is empty and can never contribute content. */
  121297. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  121298. addrHalt = pWInfo->a[j].addrBrk;
  121299. /* Special case of a FROM clause subquery implemented as a co-routine */
  121300. if( pTabItem->fg.viaCoroutine ){
  121301. int regYield = pTabItem->regReturn;
  121302. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  121303. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  121304. VdbeCoverage(v);
  121305. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  121306. pLevel->op = OP_Goto;
  121307. }else
  121308. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121309. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  121310. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  121311. ** to access the data.
  121312. */
  121313. int iReg; /* P3 Value for OP_VFilter */
  121314. int addrNotFound;
  121315. int nConstraint = pLoop->nLTerm;
  121316. int iIn; /* Counter for IN constraints */
  121317. sqlite3ExprCachePush(pParse);
  121318. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  121319. addrNotFound = pLevel->addrBrk;
  121320. for(j=0; j<nConstraint; j++){
  121321. int iTarget = iReg+j+2;
  121322. pTerm = pLoop->aLTerm[j];
  121323. if( NEVER(pTerm==0) ) continue;
  121324. if( pTerm->eOperator & WO_IN ){
  121325. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  121326. addrNotFound = pLevel->addrNxt;
  121327. }else{
  121328. Expr *pRight = pTerm->pExpr->pRight;
  121329. codeExprOrVector(pParse, pRight, iTarget, 1);
  121330. }
  121331. }
  121332. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  121333. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  121334. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  121335. pLoop->u.vtab.idxStr,
  121336. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  121337. VdbeCoverage(v);
  121338. pLoop->u.vtab.needFree = 0;
  121339. pLevel->p1 = iCur;
  121340. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  121341. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  121342. iIn = pLevel->u.in.nIn;
  121343. for(j=nConstraint-1; j>=0; j--){
  121344. pTerm = pLoop->aLTerm[j];
  121345. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  121346. disableTerm(pLevel, pTerm);
  121347. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  121348. Expr *pCompare; /* The comparison operator */
  121349. Expr *pRight; /* RHS of the comparison */
  121350. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  121351. /* Reload the constraint value into reg[iReg+j+2]. The same value
  121352. ** was loaded into the same register prior to the OP_VFilter, but
  121353. ** the xFilter implementation might have changed the datatype or
  121354. ** encoding of the value in the register, so it *must* be reloaded. */
  121355. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  121356. if( !db->mallocFailed ){
  121357. assert( iIn>0 );
  121358. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  121359. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  121360. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  121361. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  121362. testcase( pOp->opcode==OP_Rowid );
  121363. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  121364. }
  121365. /* Generate code that will continue to the next row if
  121366. ** the IN constraint is not satisfied */
  121367. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  121368. assert( pCompare!=0 || db->mallocFailed );
  121369. if( pCompare ){
  121370. pCompare->pLeft = pTerm->pExpr->pLeft;
  121371. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  121372. if( pRight ){
  121373. pRight->iTable = iReg+j+2;
  121374. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  121375. }
  121376. pCompare->pLeft = 0;
  121377. sqlite3ExprDelete(db, pCompare);
  121378. }
  121379. }
  121380. }
  121381. /* These registers need to be preserved in case there is an IN operator
  121382. ** loop. So we could deallocate the registers here (and potentially
  121383. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  121384. ** simpler and safer to simply not reuse the registers.
  121385. **
  121386. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  121387. */
  121388. sqlite3ExprCachePop(pParse);
  121389. }else
  121390. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  121391. if( (pLoop->wsFlags & WHERE_IPK)!=0
  121392. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  121393. ){
  121394. /* Case 2: We can directly reference a single row using an
  121395. ** equality comparison against the ROWID field. Or
  121396. ** we reference multiple rows using a "rowid IN (...)"
  121397. ** construct.
  121398. */
  121399. assert( pLoop->u.btree.nEq==1 );
  121400. pTerm = pLoop->aLTerm[0];
  121401. assert( pTerm!=0 );
  121402. assert( pTerm->pExpr!=0 );
  121403. assert( omitTable==0 );
  121404. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  121405. iReleaseReg = ++pParse->nMem;
  121406. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  121407. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  121408. addrNxt = pLevel->addrNxt;
  121409. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  121410. VdbeCoverage(v);
  121411. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  121412. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  121413. VdbeComment((v, "pk"));
  121414. pLevel->op = OP_Noop;
  121415. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  121416. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  121417. ){
  121418. /* Case 3: We have an inequality comparison against the ROWID field.
  121419. */
  121420. int testOp = OP_Noop;
  121421. int start;
  121422. int memEndValue = 0;
  121423. WhereTerm *pStart, *pEnd;
  121424. assert( omitTable==0 );
  121425. j = 0;
  121426. pStart = pEnd = 0;
  121427. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  121428. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  121429. assert( pStart!=0 || pEnd!=0 );
  121430. if( bRev ){
  121431. pTerm = pStart;
  121432. pStart = pEnd;
  121433. pEnd = pTerm;
  121434. }
  121435. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  121436. if( pStart ){
  121437. Expr *pX; /* The expression that defines the start bound */
  121438. int r1, rTemp; /* Registers for holding the start boundary */
  121439. int op; /* Cursor seek operation */
  121440. /* The following constant maps TK_xx codes into corresponding
  121441. ** seek opcodes. It depends on a particular ordering of TK_xx
  121442. */
  121443. const u8 aMoveOp[] = {
  121444. /* TK_GT */ OP_SeekGT,
  121445. /* TK_LE */ OP_SeekLE,
  121446. /* TK_LT */ OP_SeekLT,
  121447. /* TK_GE */ OP_SeekGE
  121448. };
  121449. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  121450. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  121451. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  121452. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  121453. testcase( pStart->wtFlags & TERM_VIRTUAL );
  121454. pX = pStart->pExpr;
  121455. assert( pX!=0 );
  121456. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  121457. if( sqlite3ExprIsVector(pX->pRight) ){
  121458. r1 = rTemp = sqlite3GetTempReg(pParse);
  121459. codeExprOrVector(pParse, pX->pRight, r1, 1);
  121460. op = aMoveOp[(pX->op - TK_GT) | 0x0001];
  121461. }else{
  121462. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  121463. disableTerm(pLevel, pStart);
  121464. op = aMoveOp[(pX->op - TK_GT)];
  121465. }
  121466. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  121467. VdbeComment((v, "pk"));
  121468. VdbeCoverageIf(v, pX->op==TK_GT);
  121469. VdbeCoverageIf(v, pX->op==TK_LE);
  121470. VdbeCoverageIf(v, pX->op==TK_LT);
  121471. VdbeCoverageIf(v, pX->op==TK_GE);
  121472. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  121473. sqlite3ReleaseTempReg(pParse, rTemp);
  121474. }else{
  121475. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  121476. VdbeCoverageIf(v, bRev==0);
  121477. VdbeCoverageIf(v, bRev!=0);
  121478. }
  121479. if( pEnd ){
  121480. Expr *pX;
  121481. pX = pEnd->pExpr;
  121482. assert( pX!=0 );
  121483. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  121484. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  121485. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  121486. memEndValue = ++pParse->nMem;
  121487. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  121488. if( 0==sqlite3ExprIsVector(pX->pRight)
  121489. && (pX->op==TK_LT || pX->op==TK_GT)
  121490. ){
  121491. testOp = bRev ? OP_Le : OP_Ge;
  121492. }else{
  121493. testOp = bRev ? OP_Lt : OP_Gt;
  121494. }
  121495. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  121496. disableTerm(pLevel, pEnd);
  121497. }
  121498. }
  121499. start = sqlite3VdbeCurrentAddr(v);
  121500. pLevel->op = bRev ? OP_Prev : OP_Next;
  121501. pLevel->p1 = iCur;
  121502. pLevel->p2 = start;
  121503. assert( pLevel->p5==0 );
  121504. if( testOp!=OP_Noop ){
  121505. iRowidReg = ++pParse->nMem;
  121506. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  121507. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  121508. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  121509. VdbeCoverageIf(v, testOp==OP_Le);
  121510. VdbeCoverageIf(v, testOp==OP_Lt);
  121511. VdbeCoverageIf(v, testOp==OP_Ge);
  121512. VdbeCoverageIf(v, testOp==OP_Gt);
  121513. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  121514. }
  121515. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  121516. /* Case 4: A scan using an index.
  121517. **
  121518. ** The WHERE clause may contain zero or more equality
  121519. ** terms ("==" or "IN" operators) that refer to the N
  121520. ** left-most columns of the index. It may also contain
  121521. ** inequality constraints (>, <, >= or <=) on the indexed
  121522. ** column that immediately follows the N equalities. Only
  121523. ** the right-most column can be an inequality - the rest must
  121524. ** use the "==" and "IN" operators. For example, if the
  121525. ** index is on (x,y,z), then the following clauses are all
  121526. ** optimized:
  121527. **
  121528. ** x=5
  121529. ** x=5 AND y=10
  121530. ** x=5 AND y<10
  121531. ** x=5 AND y>5 AND y<10
  121532. ** x=5 AND y=5 AND z<=10
  121533. **
  121534. ** The z<10 term of the following cannot be used, only
  121535. ** the x=5 term:
  121536. **
  121537. ** x=5 AND z<10
  121538. **
  121539. ** N may be zero if there are inequality constraints.
  121540. ** If there are no inequality constraints, then N is at
  121541. ** least one.
  121542. **
  121543. ** This case is also used when there are no WHERE clause
  121544. ** constraints but an index is selected anyway, in order
  121545. ** to force the output order to conform to an ORDER BY.
  121546. */
  121547. static const u8 aStartOp[] = {
  121548. 0,
  121549. 0,
  121550. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  121551. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  121552. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  121553. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  121554. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  121555. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  121556. };
  121557. static const u8 aEndOp[] = {
  121558. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  121559. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  121560. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  121561. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  121562. };
  121563. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  121564. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  121565. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  121566. int regBase; /* Base register holding constraint values */
  121567. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  121568. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  121569. int startEq; /* True if range start uses ==, >= or <= */
  121570. int endEq; /* True if range end uses ==, >= or <= */
  121571. int start_constraints; /* Start of range is constrained */
  121572. int nConstraint; /* Number of constraint terms */
  121573. int iIdxCur; /* The VDBE cursor for the index */
  121574. int nExtraReg = 0; /* Number of extra registers needed */
  121575. int op; /* Instruction opcode */
  121576. char *zStartAff; /* Affinity for start of range constraint */
  121577. char *zEndAff = 0; /* Affinity for end of range constraint */
  121578. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  121579. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  121580. pIdx = pLoop->u.btree.pIndex;
  121581. iIdxCur = pLevel->iIdxCur;
  121582. assert( nEq>=pLoop->nSkip );
  121583. /* If this loop satisfies a sort order (pOrderBy) request that
  121584. ** was passed to this function to implement a "SELECT min(x) ..."
  121585. ** query, then the caller will only allow the loop to run for
  121586. ** a single iteration. This means that the first row returned
  121587. ** should not have a NULL value stored in 'x'. If column 'x' is
  121588. ** the first one after the nEq equality constraints in the index,
  121589. ** this requires some special handling.
  121590. */
  121591. assert( pWInfo->pOrderBy==0
  121592. || pWInfo->pOrderBy->nExpr==1
  121593. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  121594. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  121595. && pWInfo->nOBSat>0
  121596. && (pIdx->nKeyCol>nEq)
  121597. ){
  121598. assert( pLoop->nSkip==0 );
  121599. bSeekPastNull = 1;
  121600. nExtraReg = 1;
  121601. }
  121602. /* Find any inequality constraint terms for the start and end
  121603. ** of the range.
  121604. */
  121605. j = nEq;
  121606. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  121607. pRangeStart = pLoop->aLTerm[j++];
  121608. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  121609. /* Like optimization range constraints always occur in pairs */
  121610. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  121611. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  121612. }
  121613. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  121614. pRangeEnd = pLoop->aLTerm[j++];
  121615. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  121616. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  121617. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  121618. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  121619. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  121620. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  121621. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  121622. VdbeComment((v, "LIKE loop counter"));
  121623. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  121624. /* iLikeRepCntr actually stores 2x the counter register number. The
  121625. ** bottom bit indicates whether the search order is ASC or DESC. */
  121626. testcase( bRev );
  121627. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  121628. assert( (bRev & ~1)==0 );
  121629. pLevel->iLikeRepCntr <<=1;
  121630. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  121631. }
  121632. #endif
  121633. if( pRangeStart==0 ){
  121634. j = pIdx->aiColumn[nEq];
  121635. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  121636. bSeekPastNull = 1;
  121637. }
  121638. }
  121639. }
  121640. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  121641. /* If we are doing a reverse order scan on an ascending index, or
  121642. ** a forward order scan on a descending index, interchange the
  121643. ** start and end terms (pRangeStart and pRangeEnd).
  121644. */
  121645. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  121646. || (bRev && pIdx->nKeyCol==nEq)
  121647. ){
  121648. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  121649. SWAP(u8, bSeekPastNull, bStopAtNull);
  121650. SWAP(u8, nBtm, nTop);
  121651. }
  121652. /* Generate code to evaluate all constraint terms using == or IN
  121653. ** and store the values of those terms in an array of registers
  121654. ** starting at regBase.
  121655. */
  121656. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  121657. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  121658. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  121659. if( zStartAff && nTop ){
  121660. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  121661. }
  121662. addrNxt = pLevel->addrNxt;
  121663. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  121664. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  121665. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  121666. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  121667. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  121668. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  121669. start_constraints = pRangeStart || nEq>0;
  121670. /* Seek the index cursor to the start of the range. */
  121671. nConstraint = nEq;
  121672. if( pRangeStart ){
  121673. Expr *pRight = pRangeStart->pExpr->pRight;
  121674. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  121675. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  121676. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  121677. && sqlite3ExprCanBeNull(pRight)
  121678. ){
  121679. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  121680. VdbeCoverage(v);
  121681. }
  121682. if( zStartAff ){
  121683. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  121684. }
  121685. nConstraint += nBtm;
  121686. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  121687. if( sqlite3ExprIsVector(pRight)==0 ){
  121688. disableTerm(pLevel, pRangeStart);
  121689. }else{
  121690. startEq = 1;
  121691. }
  121692. bSeekPastNull = 0;
  121693. }else if( bSeekPastNull ){
  121694. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  121695. nConstraint++;
  121696. startEq = 0;
  121697. start_constraints = 1;
  121698. }
  121699. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  121700. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  121701. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  121702. ** above has already left the cursor sitting on the correct row,
  121703. ** so no further seeking is needed */
  121704. }else{
  121705. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  121706. assert( op!=0 );
  121707. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  121708. VdbeCoverage(v);
  121709. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  121710. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  121711. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  121712. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  121713. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  121714. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  121715. }
  121716. /* Load the value for the inequality constraint at the end of the
  121717. ** range (if any).
  121718. */
  121719. nConstraint = nEq;
  121720. if( pRangeEnd ){
  121721. Expr *pRight = pRangeEnd->pExpr->pRight;
  121722. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  121723. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  121724. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  121725. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  121726. && sqlite3ExprCanBeNull(pRight)
  121727. ){
  121728. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  121729. VdbeCoverage(v);
  121730. }
  121731. if( zEndAff ){
  121732. updateRangeAffinityStr(pRight, nTop, zEndAff);
  121733. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  121734. }else{
  121735. assert( pParse->db->mallocFailed );
  121736. }
  121737. nConstraint += nTop;
  121738. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  121739. if( sqlite3ExprIsVector(pRight)==0 ){
  121740. disableTerm(pLevel, pRangeEnd);
  121741. }else{
  121742. endEq = 1;
  121743. }
  121744. }else if( bStopAtNull ){
  121745. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  121746. endEq = 0;
  121747. nConstraint++;
  121748. }
  121749. sqlite3DbFree(db, zStartAff);
  121750. sqlite3DbFree(db, zEndAff);
  121751. /* Top of the loop body */
  121752. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  121753. /* Check if the index cursor is past the end of the range. */
  121754. if( nConstraint ){
  121755. op = aEndOp[bRev*2 + endEq];
  121756. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  121757. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  121758. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  121759. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  121760. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  121761. }
  121762. /* Seek the table cursor, if required */
  121763. if( omitTable ){
  121764. /* pIdx is a covering index. No need to access the main table. */
  121765. }else if( HasRowid(pIdx->pTable) ){
  121766. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  121767. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  121768. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  121769. )){
  121770. iRowidReg = ++pParse->nMem;
  121771. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  121772. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  121773. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  121774. VdbeCoverage(v);
  121775. }else{
  121776. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  121777. }
  121778. }else if( iCur!=iIdxCur ){
  121779. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  121780. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  121781. for(j=0; j<pPk->nKeyCol; j++){
  121782. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  121783. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  121784. }
  121785. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  121786. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  121787. }
  121788. /* If pIdx is an index on one or more expressions, then look through
  121789. ** all the expressions in pWInfo and try to transform matching expressions
  121790. ** into reference to index columns.
  121791. */
  121792. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  121793. /* Record the instruction used to terminate the loop. */
  121794. if( pLoop->wsFlags & WHERE_ONEROW ){
  121795. pLevel->op = OP_Noop;
  121796. }else if( bRev ){
  121797. pLevel->op = OP_Prev;
  121798. }else{
  121799. pLevel->op = OP_Next;
  121800. }
  121801. pLevel->p1 = iIdxCur;
  121802. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  121803. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  121804. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  121805. }else{
  121806. assert( pLevel->p5==0 );
  121807. }
  121808. if( omitTable ) pIdx = 0;
  121809. }else
  121810. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  121811. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  121812. /* Case 5: Two or more separately indexed terms connected by OR
  121813. **
  121814. ** Example:
  121815. **
  121816. ** CREATE TABLE t1(a,b,c,d);
  121817. ** CREATE INDEX i1 ON t1(a);
  121818. ** CREATE INDEX i2 ON t1(b);
  121819. ** CREATE INDEX i3 ON t1(c);
  121820. **
  121821. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  121822. **
  121823. ** In the example, there are three indexed terms connected by OR.
  121824. ** The top of the loop looks like this:
  121825. **
  121826. ** Null 1 # Zero the rowset in reg 1
  121827. **
  121828. ** Then, for each indexed term, the following. The arguments to
  121829. ** RowSetTest are such that the rowid of the current row is inserted
  121830. ** into the RowSet. If it is already present, control skips the
  121831. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  121832. **
  121833. ** sqlite3WhereBegin(<term>)
  121834. ** RowSetTest # Insert rowid into rowset
  121835. ** Gosub 2 A
  121836. ** sqlite3WhereEnd()
  121837. **
  121838. ** Following the above, code to terminate the loop. Label A, the target
  121839. ** of the Gosub above, jumps to the instruction right after the Goto.
  121840. **
  121841. ** Null 1 # Zero the rowset in reg 1
  121842. ** Goto B # The loop is finished.
  121843. **
  121844. ** A: <loop body> # Return data, whatever.
  121845. **
  121846. ** Return 2 # Jump back to the Gosub
  121847. **
  121848. ** B: <after the loop>
  121849. **
  121850. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  121851. ** use an ephemeral index instead of a RowSet to record the primary
  121852. ** keys of the rows we have already seen.
  121853. **
  121854. */
  121855. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  121856. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  121857. Index *pCov = 0; /* Potential covering index (or NULL) */
  121858. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  121859. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  121860. int regRowset = 0; /* Register for RowSet object */
  121861. int regRowid = 0; /* Register holding rowid */
  121862. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  121863. int iRetInit; /* Address of regReturn init */
  121864. int untestedTerms = 0; /* Some terms not completely tested */
  121865. int ii; /* Loop counter */
  121866. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  121867. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  121868. Table *pTab = pTabItem->pTab;
  121869. pTerm = pLoop->aLTerm[0];
  121870. assert( pTerm!=0 );
  121871. assert( pTerm->eOperator & WO_OR );
  121872. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  121873. pOrWc = &pTerm->u.pOrInfo->wc;
  121874. pLevel->op = OP_Return;
  121875. pLevel->p1 = regReturn;
  121876. /* Set up a new SrcList in pOrTab containing the table being scanned
  121877. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  121878. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  121879. */
  121880. if( pWInfo->nLevel>1 ){
  121881. int nNotReady; /* The number of notReady tables */
  121882. struct SrcList_item *origSrc; /* Original list of tables */
  121883. nNotReady = pWInfo->nLevel - iLevel - 1;
  121884. pOrTab = sqlite3StackAllocRaw(db,
  121885. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  121886. if( pOrTab==0 ) return notReady;
  121887. pOrTab->nAlloc = (u8)(nNotReady + 1);
  121888. pOrTab->nSrc = pOrTab->nAlloc;
  121889. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  121890. origSrc = pWInfo->pTabList->a;
  121891. for(k=1; k<=nNotReady; k++){
  121892. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  121893. }
  121894. }else{
  121895. pOrTab = pWInfo->pTabList;
  121896. }
  121897. /* Initialize the rowset register to contain NULL. An SQL NULL is
  121898. ** equivalent to an empty rowset. Or, create an ephemeral index
  121899. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  121900. **
  121901. ** Also initialize regReturn to contain the address of the instruction
  121902. ** immediately following the OP_Return at the bottom of the loop. This
  121903. ** is required in a few obscure LEFT JOIN cases where control jumps
  121904. ** over the top of the loop into the body of it. In this case the
  121905. ** correct response for the end-of-loop code (the OP_Return) is to
  121906. ** fall through to the next instruction, just as an OP_Next does if
  121907. ** called on an uninitialized cursor.
  121908. */
  121909. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  121910. if( HasRowid(pTab) ){
  121911. regRowset = ++pParse->nMem;
  121912. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  121913. }else{
  121914. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  121915. regRowset = pParse->nTab++;
  121916. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  121917. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  121918. }
  121919. regRowid = ++pParse->nMem;
  121920. }
  121921. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  121922. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  121923. ** Then for every term xN, evaluate as the subexpression: xN AND z
  121924. ** That way, terms in y that are factored into the disjunction will
  121925. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  121926. **
  121927. ** Actually, each subexpression is converted to "xN AND w" where w is
  121928. ** the "interesting" terms of z - terms that did not originate in the
  121929. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  121930. ** indices.
  121931. **
  121932. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  121933. ** is not contained in the ON clause of a LEFT JOIN.
  121934. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  121935. */
  121936. if( pWC->nTerm>1 ){
  121937. int iTerm;
  121938. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  121939. Expr *pExpr = pWC->a[iTerm].pExpr;
  121940. if( &pWC->a[iTerm] == pTerm ) continue;
  121941. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  121942. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  121943. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  121944. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  121945. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  121946. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  121947. pExpr = sqlite3ExprDup(db, pExpr, 0);
  121948. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  121949. }
  121950. if( pAndExpr ){
  121951. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  121952. }
  121953. }
  121954. /* Run a separate WHERE clause for each term of the OR clause. After
  121955. ** eliminating duplicates from other WHERE clauses, the action for each
  121956. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  121957. */
  121958. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  121959. for(ii=0; ii<pOrWc->nTerm; ii++){
  121960. WhereTerm *pOrTerm = &pOrWc->a[ii];
  121961. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  121962. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  121963. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  121964. int jmp1 = 0; /* Address of jump operation */
  121965. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  121966. pAndExpr->pLeft = pOrExpr;
  121967. pOrExpr = pAndExpr;
  121968. }
  121969. /* Loop through table entries that match term pOrTerm. */
  121970. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  121971. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  121972. wctrlFlags, iCovCur);
  121973. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  121974. if( pSubWInfo ){
  121975. WhereLoop *pSubLoop;
  121976. int addrExplain = sqlite3WhereExplainOneScan(
  121977. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  121978. );
  121979. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  121980. /* This is the sub-WHERE clause body. First skip over
  121981. ** duplicate rows from prior sub-WHERE clauses, and record the
  121982. ** rowid (or PRIMARY KEY) for the current row so that the same
  121983. ** row will be skipped in subsequent sub-WHERE clauses.
  121984. */
  121985. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  121986. int r;
  121987. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  121988. if( HasRowid(pTab) ){
  121989. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  121990. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  121991. r,iSet);
  121992. VdbeCoverage(v);
  121993. }else{
  121994. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  121995. int nPk = pPk->nKeyCol;
  121996. int iPk;
  121997. /* Read the PK into an array of temp registers. */
  121998. r = sqlite3GetTempRange(pParse, nPk);
  121999. for(iPk=0; iPk<nPk; iPk++){
  122000. int iCol = pPk->aiColumn[iPk];
  122001. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  122002. }
  122003. /* Check if the temp table already contains this key. If so,
  122004. ** the row has already been included in the result set and
  122005. ** can be ignored (by jumping past the Gosub below). Otherwise,
  122006. ** insert the key into the temp table and proceed with processing
  122007. ** the row.
  122008. **
  122009. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  122010. ** is zero, assume that the key cannot already be present in
  122011. ** the temp table. And if iSet is -1, assume that there is no
  122012. ** need to insert the key into the temp table, as it will never
  122013. ** be tested for. */
  122014. if( iSet ){
  122015. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  122016. VdbeCoverage(v);
  122017. }
  122018. if( iSet>=0 ){
  122019. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  122020. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  122021. r, nPk);
  122022. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  122023. }
  122024. /* Release the array of temp registers */
  122025. sqlite3ReleaseTempRange(pParse, r, nPk);
  122026. }
  122027. }
  122028. /* Invoke the main loop body as a subroutine */
  122029. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  122030. /* Jump here (skipping the main loop body subroutine) if the
  122031. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  122032. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  122033. /* The pSubWInfo->untestedTerms flag means that this OR term
  122034. ** contained one or more AND term from a notReady table. The
  122035. ** terms from the notReady table could not be tested and will
  122036. ** need to be tested later.
  122037. */
  122038. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  122039. /* If all of the OR-connected terms are optimized using the same
  122040. ** index, and the index is opened using the same cursor number
  122041. ** by each call to sqlite3WhereBegin() made by this loop, it may
  122042. ** be possible to use that index as a covering index.
  122043. **
  122044. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  122045. ** uses an index, and this is either the first OR-connected term
  122046. ** processed or the index is the same as that used by all previous
  122047. ** terms, set pCov to the candidate covering index. Otherwise, set
  122048. ** pCov to NULL to indicate that no candidate covering index will
  122049. ** be available.
  122050. */
  122051. pSubLoop = pSubWInfo->a[0].pWLoop;
  122052. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  122053. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  122054. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  122055. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  122056. ){
  122057. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  122058. pCov = pSubLoop->u.btree.pIndex;
  122059. }else{
  122060. pCov = 0;
  122061. }
  122062. /* Finish the loop through table entries that match term pOrTerm. */
  122063. sqlite3WhereEnd(pSubWInfo);
  122064. }
  122065. }
  122066. }
  122067. pLevel->u.pCovidx = pCov;
  122068. if( pCov ) pLevel->iIdxCur = iCovCur;
  122069. if( pAndExpr ){
  122070. pAndExpr->pLeft = 0;
  122071. sqlite3ExprDelete(db, pAndExpr);
  122072. }
  122073. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  122074. sqlite3VdbeGoto(v, pLevel->addrBrk);
  122075. sqlite3VdbeResolveLabel(v, iLoopBody);
  122076. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  122077. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  122078. }else
  122079. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  122080. {
  122081. /* Case 6: There is no usable index. We must do a complete
  122082. ** scan of the entire table.
  122083. */
  122084. static const u8 aStep[] = { OP_Next, OP_Prev };
  122085. static const u8 aStart[] = { OP_Rewind, OP_Last };
  122086. assert( bRev==0 || bRev==1 );
  122087. if( pTabItem->fg.isRecursive ){
  122088. /* Tables marked isRecursive have only a single row that is stored in
  122089. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  122090. pLevel->op = OP_Noop;
  122091. }else{
  122092. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  122093. pLevel->op = aStep[bRev];
  122094. pLevel->p1 = iCur;
  122095. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  122096. VdbeCoverageIf(v, bRev==0);
  122097. VdbeCoverageIf(v, bRev!=0);
  122098. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  122099. }
  122100. }
  122101. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  122102. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  122103. #endif
  122104. /* Insert code to test every subexpression that can be completely
  122105. ** computed using the current set of tables.
  122106. **
  122107. ** This loop may run between one and three times, depending on the
  122108. ** constraints to be generated. The value of stack variable iLoop
  122109. ** determines the constraints coded by each iteration, as follows:
  122110. **
  122111. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  122112. ** iLoop==2: Code remaining expressions that do not contain correlated
  122113. ** sub-queries.
  122114. ** iLoop==3: Code all remaining expressions.
  122115. **
  122116. ** An effort is made to skip unnecessary iterations of the loop.
  122117. */
  122118. iLoop = (pIdx ? 1 : 2);
  122119. do{
  122120. int iNext = 0; /* Next value for iLoop */
  122121. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  122122. Expr *pE;
  122123. int skipLikeAddr = 0;
  122124. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  122125. testcase( pTerm->wtFlags & TERM_CODED );
  122126. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  122127. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  122128. testcase( pWInfo->untestedTerms==0
  122129. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  122130. pWInfo->untestedTerms = 1;
  122131. continue;
  122132. }
  122133. pE = pTerm->pExpr;
  122134. assert( pE!=0 );
  122135. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  122136. continue;
  122137. }
  122138. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  122139. iNext = 2;
  122140. continue;
  122141. }
  122142. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  122143. if( iNext==0 ) iNext = 3;
  122144. continue;
  122145. }
  122146. if( pTerm->wtFlags & TERM_LIKECOND ){
  122147. /* If the TERM_LIKECOND flag is set, that means that the range search
  122148. ** is sufficient to guarantee that the LIKE operator is true, so we
  122149. ** can skip the call to the like(A,B) function. But this only works
  122150. ** for strings. So do not skip the call to the function on the pass
  122151. ** that compares BLOBs. */
  122152. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  122153. continue;
  122154. #else
  122155. u32 x = pLevel->iLikeRepCntr;
  122156. assert( x>0 );
  122157. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
  122158. VdbeCoverage(v);
  122159. #endif
  122160. }
  122161. #ifdef WHERETRACE_ENABLED /* 0xffff */
  122162. if( sqlite3WhereTrace ){
  122163. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  122164. pWC->nTerm-j, pTerm, iLoop));
  122165. }
  122166. #endif
  122167. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  122168. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  122169. pTerm->wtFlags |= TERM_CODED;
  122170. }
  122171. iLoop = iNext;
  122172. }while( iLoop>0 );
  122173. /* Insert code to test for implied constraints based on transitivity
  122174. ** of the "==" operator.
  122175. **
  122176. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  122177. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  122178. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  122179. ** the implied "t1.a=123" constraint.
  122180. */
  122181. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  122182. Expr *pE, sEAlt;
  122183. WhereTerm *pAlt;
  122184. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  122185. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  122186. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  122187. if( pTerm->leftCursor!=iCur ) continue;
  122188. if( pLevel->iLeftJoin ) continue;
  122189. pE = pTerm->pExpr;
  122190. assert( !ExprHasProperty(pE, EP_FromJoin) );
  122191. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  122192. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  122193. WO_EQ|WO_IN|WO_IS, 0);
  122194. if( pAlt==0 ) continue;
  122195. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  122196. testcase( pAlt->eOperator & WO_EQ );
  122197. testcase( pAlt->eOperator & WO_IS );
  122198. testcase( pAlt->eOperator & WO_IN );
  122199. VdbeModuleComment((v, "begin transitive constraint"));
  122200. sEAlt = *pAlt->pExpr;
  122201. sEAlt.pLeft = pE->pLeft;
  122202. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  122203. }
  122204. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  122205. ** at least one row of the right table has matched the left table.
  122206. */
  122207. if( pLevel->iLeftJoin ){
  122208. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  122209. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  122210. VdbeComment((v, "record LEFT JOIN hit"));
  122211. sqlite3ExprCacheClear(pParse);
  122212. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  122213. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  122214. testcase( pTerm->wtFlags & TERM_CODED );
  122215. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  122216. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  122217. assert( pWInfo->untestedTerms );
  122218. continue;
  122219. }
  122220. assert( pTerm->pExpr );
  122221. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  122222. pTerm->wtFlags |= TERM_CODED;
  122223. }
  122224. }
  122225. return pLevel->notReady;
  122226. }
  122227. /************** End of wherecode.c *******************************************/
  122228. /************** Begin file whereexpr.c ***************************************/
  122229. /*
  122230. ** 2015-06-08
  122231. **
  122232. ** The author disclaims copyright to this source code. In place of
  122233. ** a legal notice, here is a blessing:
  122234. **
  122235. ** May you do good and not evil.
  122236. ** May you find forgiveness for yourself and forgive others.
  122237. ** May you share freely, never taking more than you give.
  122238. **
  122239. *************************************************************************
  122240. ** This module contains C code that generates VDBE code used to process
  122241. ** the WHERE clause of SQL statements.
  122242. **
  122243. ** This file was originally part of where.c but was split out to improve
  122244. ** readability and editabiliity. This file contains utility routines for
  122245. ** analyzing Expr objects in the WHERE clause.
  122246. */
  122247. /* #include "sqliteInt.h" */
  122248. /* #include "whereInt.h" */
  122249. /* Forward declarations */
  122250. static void exprAnalyze(SrcList*, WhereClause*, int);
  122251. /*
  122252. ** Deallocate all memory associated with a WhereOrInfo object.
  122253. */
  122254. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  122255. sqlite3WhereClauseClear(&p->wc);
  122256. sqlite3DbFree(db, p);
  122257. }
  122258. /*
  122259. ** Deallocate all memory associated with a WhereAndInfo object.
  122260. */
  122261. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  122262. sqlite3WhereClauseClear(&p->wc);
  122263. sqlite3DbFree(db, p);
  122264. }
  122265. /*
  122266. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  122267. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  122268. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  122269. ** 0 is returned if the new WhereTerm could not be added due to a memory
  122270. ** allocation error. The memory allocation failure will be recorded in
  122271. ** the db->mallocFailed flag so that higher-level functions can detect it.
  122272. **
  122273. ** This routine will increase the size of the pWC->a[] array as necessary.
  122274. **
  122275. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  122276. ** for freeing the expression p is assumed by the WhereClause object pWC.
  122277. ** This is true even if this routine fails to allocate a new WhereTerm.
  122278. **
  122279. ** WARNING: This routine might reallocate the space used to store
  122280. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  122281. ** calling this routine. Such pointers may be reinitialized by referencing
  122282. ** the pWC->a[] array.
  122283. */
  122284. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  122285. WhereTerm *pTerm;
  122286. int idx;
  122287. testcase( wtFlags & TERM_VIRTUAL );
  122288. if( pWC->nTerm>=pWC->nSlot ){
  122289. WhereTerm *pOld = pWC->a;
  122290. sqlite3 *db = pWC->pWInfo->pParse->db;
  122291. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  122292. if( pWC->a==0 ){
  122293. if( wtFlags & TERM_DYNAMIC ){
  122294. sqlite3ExprDelete(db, p);
  122295. }
  122296. pWC->a = pOld;
  122297. return 0;
  122298. }
  122299. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  122300. if( pOld!=pWC->aStatic ){
  122301. sqlite3DbFree(db, pOld);
  122302. }
  122303. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  122304. }
  122305. pTerm = &pWC->a[idx = pWC->nTerm++];
  122306. if( p && ExprHasProperty(p, EP_Unlikely) ){
  122307. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  122308. }else{
  122309. pTerm->truthProb = 1;
  122310. }
  122311. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  122312. pTerm->wtFlags = wtFlags;
  122313. pTerm->pWC = pWC;
  122314. pTerm->iParent = -1;
  122315. memset(&pTerm->eOperator, 0,
  122316. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  122317. return idx;
  122318. }
  122319. /*
  122320. ** Return TRUE if the given operator is one of the operators that is
  122321. ** allowed for an indexable WHERE clause term. The allowed operators are
  122322. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  122323. */
  122324. static int allowedOp(int op){
  122325. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  122326. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  122327. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  122328. assert( TK_GE==TK_EQ+4 );
  122329. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  122330. }
  122331. /*
  122332. ** Commute a comparison operator. Expressions of the form "X op Y"
  122333. ** are converted into "Y op X".
  122334. **
  122335. ** If left/right precedence rules come into play when determining the
  122336. ** collating sequence, then COLLATE operators are adjusted to ensure
  122337. ** that the collating sequence does not change. For example:
  122338. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  122339. ** the left hand side of a comparison overrides any collation sequence
  122340. ** attached to the right. For the same reason the EP_Collate flag
  122341. ** is not commuted.
  122342. */
  122343. static void exprCommute(Parse *pParse, Expr *pExpr){
  122344. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  122345. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  122346. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  122347. if( expRight==expLeft ){
  122348. /* Either X and Y both have COLLATE operator or neither do */
  122349. if( expRight ){
  122350. /* Both X and Y have COLLATE operators. Make sure X is always
  122351. ** used by clearing the EP_Collate flag from Y. */
  122352. pExpr->pRight->flags &= ~EP_Collate;
  122353. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  122354. /* Neither X nor Y have COLLATE operators, but X has a non-default
  122355. ** collating sequence. So add the EP_Collate marker on X to cause
  122356. ** it to be searched first. */
  122357. pExpr->pLeft->flags |= EP_Collate;
  122358. }
  122359. }
  122360. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  122361. if( pExpr->op>=TK_GT ){
  122362. assert( TK_LT==TK_GT+2 );
  122363. assert( TK_GE==TK_LE+2 );
  122364. assert( TK_GT>TK_EQ );
  122365. assert( TK_GT<TK_LE );
  122366. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  122367. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  122368. }
  122369. }
  122370. /*
  122371. ** Translate from TK_xx operator to WO_xx bitmask.
  122372. */
  122373. static u16 operatorMask(int op){
  122374. u16 c;
  122375. assert( allowedOp(op) );
  122376. if( op==TK_IN ){
  122377. c = WO_IN;
  122378. }else if( op==TK_ISNULL ){
  122379. c = WO_ISNULL;
  122380. }else if( op==TK_IS ){
  122381. c = WO_IS;
  122382. }else{
  122383. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  122384. c = (u16)(WO_EQ<<(op-TK_EQ));
  122385. }
  122386. assert( op!=TK_ISNULL || c==WO_ISNULL );
  122387. assert( op!=TK_IN || c==WO_IN );
  122388. assert( op!=TK_EQ || c==WO_EQ );
  122389. assert( op!=TK_LT || c==WO_LT );
  122390. assert( op!=TK_LE || c==WO_LE );
  122391. assert( op!=TK_GT || c==WO_GT );
  122392. assert( op!=TK_GE || c==WO_GE );
  122393. assert( op!=TK_IS || c==WO_IS );
  122394. return c;
  122395. }
  122396. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  122397. /*
  122398. ** Check to see if the given expression is a LIKE or GLOB operator that
  122399. ** can be optimized using inequality constraints. Return TRUE if it is
  122400. ** so and false if not.
  122401. **
  122402. ** In order for the operator to be optimizible, the RHS must be a string
  122403. ** literal that does not begin with a wildcard. The LHS must be a column
  122404. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  122405. ** that virtual tables cannot participate in the LIKE optimization.) The
  122406. ** collating sequence for the column on the LHS must be appropriate for
  122407. ** the operator.
  122408. */
  122409. static int isLikeOrGlob(
  122410. Parse *pParse, /* Parsing and code generating context */
  122411. Expr *pExpr, /* Test this expression */
  122412. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  122413. int *pisComplete, /* True if the only wildcard is % in the last character */
  122414. int *pnoCase /* True if uppercase is equivalent to lowercase */
  122415. ){
  122416. const u8 *z = 0; /* String on RHS of LIKE operator */
  122417. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  122418. ExprList *pList; /* List of operands to the LIKE operator */
  122419. int c; /* One character in z[] */
  122420. int cnt; /* Number of non-wildcard prefix characters */
  122421. char wc[4]; /* Wildcard characters */
  122422. sqlite3 *db = pParse->db; /* Database connection */
  122423. sqlite3_value *pVal = 0;
  122424. int op; /* Opcode of pRight */
  122425. int rc; /* Result code to return */
  122426. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  122427. return 0;
  122428. }
  122429. #ifdef SQLITE_EBCDIC
  122430. if( *pnoCase ) return 0;
  122431. #endif
  122432. pList = pExpr->x.pList;
  122433. pLeft = pList->a[1].pExpr;
  122434. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  122435. op = pRight->op;
  122436. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  122437. Vdbe *pReprepare = pParse->pReprepare;
  122438. int iCol = pRight->iColumn;
  122439. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  122440. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  122441. z = sqlite3_value_text(pVal);
  122442. }
  122443. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  122444. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  122445. }else if( op==TK_STRING ){
  122446. z = (u8*)pRight->u.zToken;
  122447. }
  122448. if( z ){
  122449. /* If the RHS begins with a digit or a minus sign, then the LHS must
  122450. ** be an ordinary column (not a virtual table column) with TEXT affinity.
  122451. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  122452. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  122453. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  122454. ** the LHS is numeric and so the optimization still works.
  122455. */
  122456. if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
  122457. if( pLeft->op!=TK_COLUMN
  122458. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  122459. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  122460. ){
  122461. sqlite3ValueFree(pVal);
  122462. return 0;
  122463. }
  122464. }
  122465. /* Count the number of prefix characters prior to the first wildcard */
  122466. cnt = 0;
  122467. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  122468. cnt++;
  122469. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  122470. }
  122471. /* The optimization is possible only if (1) the pattern does not begin
  122472. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  122473. ** an (illegal 0xff) character. The second condition is necessary so
  122474. ** that we can increment the prefix key to find an upper bound for the
  122475. ** range search.
  122476. */
  122477. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  122478. Expr *pPrefix;
  122479. /* A "complete" match if the pattern ends with "*" or "%" */
  122480. *pisComplete = c==wc[0] && z[cnt+1]==0;
  122481. /* Get the pattern prefix. Remove all escapes from the prefix. */
  122482. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  122483. if( pPrefix ){
  122484. int iFrom, iTo;
  122485. char *zNew = pPrefix->u.zToken;
  122486. zNew[cnt] = 0;
  122487. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  122488. if( zNew[iFrom]==wc[3] ) iFrom++;
  122489. zNew[iTo++] = zNew[iFrom];
  122490. }
  122491. zNew[iTo] = 0;
  122492. }
  122493. *ppPrefix = pPrefix;
  122494. /* If the RHS pattern is a bound parameter, make arrangements to
  122495. ** reprepare the statement when that parameter is rebound */
  122496. if( op==TK_VARIABLE ){
  122497. Vdbe *v = pParse->pVdbe;
  122498. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  122499. if( *pisComplete && pRight->u.zToken[1] ){
  122500. /* If the rhs of the LIKE expression is a variable, and the current
  122501. ** value of the variable means there is no need to invoke the LIKE
  122502. ** function, then no OP_Variable will be added to the program.
  122503. ** This causes problems for the sqlite3_bind_parameter_name()
  122504. ** API. To work around them, add a dummy OP_Variable here.
  122505. */
  122506. int r1 = sqlite3GetTempReg(pParse);
  122507. sqlite3ExprCodeTarget(pParse, pRight, r1);
  122508. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  122509. sqlite3ReleaseTempReg(pParse, r1);
  122510. }
  122511. }
  122512. }else{
  122513. z = 0;
  122514. }
  122515. }
  122516. rc = (z!=0);
  122517. sqlite3ValueFree(pVal);
  122518. return rc;
  122519. }
  122520. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  122521. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122522. /*
  122523. ** Check to see if the pExpr expression is a form that needs to be passed
  122524. ** to the xBestIndex method of virtual tables. Forms of interest include:
  122525. **
  122526. ** Expression Virtual Table Operator
  122527. ** ----------------------- ---------------------------------
  122528. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  122529. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  122530. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  122531. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  122532. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  122533. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  122534. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  122535. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  122536. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  122537. **
  122538. ** In every case, "column" must be a column of a virtual table. If there
  122539. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  122540. ** "expr" expression (even though in forms (6) and (8) the column is on the
  122541. ** right and the expression is on the left). Also set *peOp2 to the
  122542. ** appropriate virtual table operator. The return value is 1 or 2 if there
  122543. ** is a match. The usual return is 1, but if the RHS is also a column
  122544. ** of virtual table in forms (5) or (7) then return 2.
  122545. **
  122546. ** If the expression matches none of the patterns above, return 0.
  122547. */
  122548. static int isAuxiliaryVtabOperator(
  122549. Expr *pExpr, /* Test this expression */
  122550. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  122551. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  122552. Expr **ppRight /* Expression to left of MATCH/op2 */
  122553. ){
  122554. if( pExpr->op==TK_FUNCTION ){
  122555. static const struct Op2 {
  122556. const char *zOp;
  122557. unsigned char eOp2;
  122558. } aOp[] = {
  122559. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  122560. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  122561. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  122562. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  122563. };
  122564. ExprList *pList;
  122565. Expr *pCol; /* Column reference */
  122566. int i;
  122567. pList = pExpr->x.pList;
  122568. if( pList==0 || pList->nExpr!=2 ){
  122569. return 0;
  122570. }
  122571. pCol = pList->a[1].pExpr;
  122572. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  122573. return 0;
  122574. }
  122575. for(i=0; i<ArraySize(aOp); i++){
  122576. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  122577. *peOp2 = aOp[i].eOp2;
  122578. *ppRight = pList->a[0].pExpr;
  122579. *ppLeft = pCol;
  122580. return 1;
  122581. }
  122582. }
  122583. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  122584. int res = 0;
  122585. Expr *pLeft = pExpr->pLeft;
  122586. Expr *pRight = pExpr->pRight;
  122587. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
  122588. res++;
  122589. }
  122590. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
  122591. res++;
  122592. SWAP(Expr*, pLeft, pRight);
  122593. }
  122594. *ppLeft = pLeft;
  122595. *ppRight = pRight;
  122596. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  122597. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  122598. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  122599. return res;
  122600. }
  122601. return 0;
  122602. }
  122603. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  122604. /*
  122605. ** If the pBase expression originated in the ON or USING clause of
  122606. ** a join, then transfer the appropriate markings over to derived.
  122607. */
  122608. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  122609. if( pDerived ){
  122610. pDerived->flags |= pBase->flags & EP_FromJoin;
  122611. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  122612. }
  122613. }
  122614. /*
  122615. ** Mark term iChild as being a child of term iParent
  122616. */
  122617. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  122618. pWC->a[iChild].iParent = iParent;
  122619. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  122620. pWC->a[iParent].nChild++;
  122621. }
  122622. /*
  122623. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  122624. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  122625. ** the number of available subterms, return NULL.
  122626. */
  122627. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  122628. if( pTerm->eOperator!=WO_AND ){
  122629. return N==0 ? pTerm : 0;
  122630. }
  122631. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  122632. return &pTerm->u.pAndInfo->wc.a[N];
  122633. }
  122634. return 0;
  122635. }
  122636. /*
  122637. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  122638. ** two subterms are in disjunction - they are OR-ed together.
  122639. **
  122640. ** If these two terms are both of the form: "A op B" with the same
  122641. ** A and B values but different operators and if the operators are
  122642. ** compatible (if one is = and the other is <, for example) then
  122643. ** add a new virtual AND term to pWC that is the combination of the
  122644. ** two.
  122645. **
  122646. ** Some examples:
  122647. **
  122648. ** x<y OR x=y --> x<=y
  122649. ** x=y OR x=y --> x=y
  122650. ** x<=y OR x<y --> x<=y
  122651. **
  122652. ** The following is NOT generated:
  122653. **
  122654. ** x<y OR x>y --> x!=y
  122655. */
  122656. static void whereCombineDisjuncts(
  122657. SrcList *pSrc, /* the FROM clause */
  122658. WhereClause *pWC, /* The complete WHERE clause */
  122659. WhereTerm *pOne, /* First disjunct */
  122660. WhereTerm *pTwo /* Second disjunct */
  122661. ){
  122662. u16 eOp = pOne->eOperator | pTwo->eOperator;
  122663. sqlite3 *db; /* Database connection (for malloc) */
  122664. Expr *pNew; /* New virtual expression */
  122665. int op; /* Operator for the combined expression */
  122666. int idxNew; /* Index in pWC of the next virtual term */
  122667. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  122668. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  122669. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  122670. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  122671. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  122672. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  122673. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  122674. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  122675. /* If we reach this point, it means the two subterms can be combined */
  122676. if( (eOp & (eOp-1))!=0 ){
  122677. if( eOp & (WO_LT|WO_LE) ){
  122678. eOp = WO_LE;
  122679. }else{
  122680. assert( eOp & (WO_GT|WO_GE) );
  122681. eOp = WO_GE;
  122682. }
  122683. }
  122684. db = pWC->pWInfo->pParse->db;
  122685. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  122686. if( pNew==0 ) return;
  122687. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  122688. pNew->op = op;
  122689. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  122690. exprAnalyze(pSrc, pWC, idxNew);
  122691. }
  122692. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  122693. /*
  122694. ** Analyze a term that consists of two or more OR-connected
  122695. ** subterms. So in:
  122696. **
  122697. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  122698. ** ^^^^^^^^^^^^^^^^^^^^
  122699. **
  122700. ** This routine analyzes terms such as the middle term in the above example.
  122701. ** A WhereOrTerm object is computed and attached to the term under
  122702. ** analysis, regardless of the outcome of the analysis. Hence:
  122703. **
  122704. ** WhereTerm.wtFlags |= TERM_ORINFO
  122705. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  122706. **
  122707. ** The term being analyzed must have two or more of OR-connected subterms.
  122708. ** A single subterm might be a set of AND-connected sub-subterms.
  122709. ** Examples of terms under analysis:
  122710. **
  122711. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  122712. ** (B) x=expr1 OR expr2=x OR x=expr3
  122713. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  122714. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  122715. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  122716. ** (F) x>A OR (x=A AND y>=B)
  122717. **
  122718. ** CASE 1:
  122719. **
  122720. ** If all subterms are of the form T.C=expr for some single column of C and
  122721. ** a single table T (as shown in example B above) then create a new virtual
  122722. ** term that is an equivalent IN expression. In other words, if the term
  122723. ** being analyzed is:
  122724. **
  122725. ** x = expr1 OR expr2 = x OR x = expr3
  122726. **
  122727. ** then create a new virtual term like this:
  122728. **
  122729. ** x IN (expr1,expr2,expr3)
  122730. **
  122731. ** CASE 2:
  122732. **
  122733. ** If there are exactly two disjuncts and one side has x>A and the other side
  122734. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  122735. ** WHERE clause of the form "x>=A". Example:
  122736. **
  122737. ** x>A OR (x=A AND y>B) adds: x>=A
  122738. **
  122739. ** The added conjunct can sometimes be helpful in query planning.
  122740. **
  122741. ** CASE 3:
  122742. **
  122743. ** If all subterms are indexable by a single table T, then set
  122744. **
  122745. ** WhereTerm.eOperator = WO_OR
  122746. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  122747. **
  122748. ** A subterm is "indexable" if it is of the form
  122749. ** "T.C <op> <expr>" where C is any column of table T and
  122750. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  122751. ** A subterm is also indexable if it is an AND of two or more
  122752. ** subsubterms at least one of which is indexable. Indexable AND
  122753. ** subterms have their eOperator set to WO_AND and they have
  122754. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  122755. **
  122756. ** From another point of view, "indexable" means that the subterm could
  122757. ** potentially be used with an index if an appropriate index exists.
  122758. ** This analysis does not consider whether or not the index exists; that
  122759. ** is decided elsewhere. This analysis only looks at whether subterms
  122760. ** appropriate for indexing exist.
  122761. **
  122762. ** All examples A through E above satisfy case 3. But if a term
  122763. ** also satisfies case 1 (such as B) we know that the optimizer will
  122764. ** always prefer case 1, so in that case we pretend that case 3 is not
  122765. ** satisfied.
  122766. **
  122767. ** It might be the case that multiple tables are indexable. For example,
  122768. ** (E) above is indexable on tables P, Q, and R.
  122769. **
  122770. ** Terms that satisfy case 3 are candidates for lookup by using
  122771. ** separate indices to find rowids for each subterm and composing
  122772. ** the union of all rowids using a RowSet object. This is similar
  122773. ** to "bitmap indices" in other database engines.
  122774. **
  122775. ** OTHERWISE:
  122776. **
  122777. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  122778. ** zero. This term is not useful for search.
  122779. */
  122780. static void exprAnalyzeOrTerm(
  122781. SrcList *pSrc, /* the FROM clause */
  122782. WhereClause *pWC, /* the complete WHERE clause */
  122783. int idxTerm /* Index of the OR-term to be analyzed */
  122784. ){
  122785. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  122786. Parse *pParse = pWInfo->pParse; /* Parser context */
  122787. sqlite3 *db = pParse->db; /* Database connection */
  122788. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  122789. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  122790. int i; /* Loop counters */
  122791. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  122792. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  122793. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  122794. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  122795. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  122796. /*
  122797. ** Break the OR clause into its separate subterms. The subterms are
  122798. ** stored in a WhereClause structure containing within the WhereOrInfo
  122799. ** object that is attached to the original OR clause term.
  122800. */
  122801. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  122802. assert( pExpr->op==TK_OR );
  122803. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  122804. if( pOrInfo==0 ) return;
  122805. pTerm->wtFlags |= TERM_ORINFO;
  122806. pOrWc = &pOrInfo->wc;
  122807. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  122808. sqlite3WhereClauseInit(pOrWc, pWInfo);
  122809. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  122810. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  122811. if( db->mallocFailed ) return;
  122812. assert( pOrWc->nTerm>=2 );
  122813. /*
  122814. ** Compute the set of tables that might satisfy cases 1 or 3.
  122815. */
  122816. indexable = ~(Bitmask)0;
  122817. chngToIN = ~(Bitmask)0;
  122818. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  122819. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  122820. WhereAndInfo *pAndInfo;
  122821. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  122822. chngToIN = 0;
  122823. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  122824. if( pAndInfo ){
  122825. WhereClause *pAndWC;
  122826. WhereTerm *pAndTerm;
  122827. int j;
  122828. Bitmask b = 0;
  122829. pOrTerm->u.pAndInfo = pAndInfo;
  122830. pOrTerm->wtFlags |= TERM_ANDINFO;
  122831. pOrTerm->eOperator = WO_AND;
  122832. pAndWC = &pAndInfo->wc;
  122833. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  122834. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  122835. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  122836. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  122837. pAndWC->pOuter = pWC;
  122838. if( !db->mallocFailed ){
  122839. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  122840. assert( pAndTerm->pExpr );
  122841. if( allowedOp(pAndTerm->pExpr->op)
  122842. || pAndTerm->eOperator==WO_AUX
  122843. ){
  122844. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  122845. }
  122846. }
  122847. }
  122848. indexable &= b;
  122849. }
  122850. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  122851. /* Skip this term for now. We revisit it when we process the
  122852. ** corresponding TERM_VIRTUAL term */
  122853. }else{
  122854. Bitmask b;
  122855. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  122856. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  122857. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  122858. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  122859. }
  122860. indexable &= b;
  122861. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  122862. chngToIN = 0;
  122863. }else{
  122864. chngToIN &= b;
  122865. }
  122866. }
  122867. }
  122868. /*
  122869. ** Record the set of tables that satisfy case 3. The set might be
  122870. ** empty.
  122871. */
  122872. pOrInfo->indexable = indexable;
  122873. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  122874. /* For a two-way OR, attempt to implementation case 2.
  122875. */
  122876. if( indexable && pOrWc->nTerm==2 ){
  122877. int iOne = 0;
  122878. WhereTerm *pOne;
  122879. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  122880. int iTwo = 0;
  122881. WhereTerm *pTwo;
  122882. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  122883. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  122884. }
  122885. }
  122886. }
  122887. /*
  122888. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  122889. ** we have to do some additional checking to see if case 1 really
  122890. ** is satisfied.
  122891. **
  122892. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  122893. ** that there is no possibility of transforming the OR clause into an
  122894. ** IN operator because one or more terms in the OR clause contain
  122895. ** something other than == on a column in the single table. The 1-bit
  122896. ** case means that every term of the OR clause is of the form
  122897. ** "table.column=expr" for some single table. The one bit that is set
  122898. ** will correspond to the common table. We still need to check to make
  122899. ** sure the same column is used on all terms. The 2-bit case is when
  122900. ** the all terms are of the form "table1.column=table2.column". It
  122901. ** might be possible to form an IN operator with either table1.column
  122902. ** or table2.column as the LHS if either is common to every term of
  122903. ** the OR clause.
  122904. **
  122905. ** Note that terms of the form "table.column1=table.column2" (the
  122906. ** same table on both sizes of the ==) cannot be optimized.
  122907. */
  122908. if( chngToIN ){
  122909. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  122910. int iColumn = -1; /* Column index on lhs of IN operator */
  122911. int iCursor = -1; /* Table cursor common to all terms */
  122912. int j = 0; /* Loop counter */
  122913. /* Search for a table and column that appears on one side or the
  122914. ** other of the == operator in every subterm. That table and column
  122915. ** will be recorded in iCursor and iColumn. There might not be any
  122916. ** such table and column. Set okToChngToIN if an appropriate table
  122917. ** and column is found but leave okToChngToIN false if not found.
  122918. */
  122919. for(j=0; j<2 && !okToChngToIN; j++){
  122920. pOrTerm = pOrWc->a;
  122921. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  122922. assert( pOrTerm->eOperator & WO_EQ );
  122923. pOrTerm->wtFlags &= ~TERM_OR_OK;
  122924. if( pOrTerm->leftCursor==iCursor ){
  122925. /* This is the 2-bit case and we are on the second iteration and
  122926. ** current term is from the first iteration. So skip this term. */
  122927. assert( j==1 );
  122928. continue;
  122929. }
  122930. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  122931. pOrTerm->leftCursor))==0 ){
  122932. /* This term must be of the form t1.a==t2.b where t2 is in the
  122933. ** chngToIN set but t1 is not. This term will be either preceded
  122934. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  122935. ** and use its inversion. */
  122936. testcase( pOrTerm->wtFlags & TERM_COPIED );
  122937. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  122938. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  122939. continue;
  122940. }
  122941. iColumn = pOrTerm->u.leftColumn;
  122942. iCursor = pOrTerm->leftCursor;
  122943. break;
  122944. }
  122945. if( i<0 ){
  122946. /* No candidate table+column was found. This can only occur
  122947. ** on the second iteration */
  122948. assert( j==1 );
  122949. assert( IsPowerOfTwo(chngToIN) );
  122950. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  122951. break;
  122952. }
  122953. testcase( j==1 );
  122954. /* We have found a candidate table and column. Check to see if that
  122955. ** table and column is common to every term in the OR clause */
  122956. okToChngToIN = 1;
  122957. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  122958. assert( pOrTerm->eOperator & WO_EQ );
  122959. if( pOrTerm->leftCursor!=iCursor ){
  122960. pOrTerm->wtFlags &= ~TERM_OR_OK;
  122961. }else if( pOrTerm->u.leftColumn!=iColumn ){
  122962. okToChngToIN = 0;
  122963. }else{
  122964. int affLeft, affRight;
  122965. /* If the right-hand side is also a column, then the affinities
  122966. ** of both right and left sides must be such that no type
  122967. ** conversions are required on the right. (Ticket #2249)
  122968. */
  122969. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  122970. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  122971. if( affRight!=0 && affRight!=affLeft ){
  122972. okToChngToIN = 0;
  122973. }else{
  122974. pOrTerm->wtFlags |= TERM_OR_OK;
  122975. }
  122976. }
  122977. }
  122978. }
  122979. /* At this point, okToChngToIN is true if original pTerm satisfies
  122980. ** case 1. In that case, construct a new virtual term that is
  122981. ** pTerm converted into an IN operator.
  122982. */
  122983. if( okToChngToIN ){
  122984. Expr *pDup; /* A transient duplicate expression */
  122985. ExprList *pList = 0; /* The RHS of the IN operator */
  122986. Expr *pLeft = 0; /* The LHS of the IN operator */
  122987. Expr *pNew; /* The complete IN operator */
  122988. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  122989. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  122990. assert( pOrTerm->eOperator & WO_EQ );
  122991. assert( pOrTerm->leftCursor==iCursor );
  122992. assert( pOrTerm->u.leftColumn==iColumn );
  122993. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  122994. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  122995. pLeft = pOrTerm->pExpr->pLeft;
  122996. }
  122997. assert( pLeft!=0 );
  122998. pDup = sqlite3ExprDup(db, pLeft, 0);
  122999. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  123000. if( pNew ){
  123001. int idxNew;
  123002. transferJoinMarkings(pNew, pExpr);
  123003. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  123004. pNew->x.pList = pList;
  123005. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  123006. testcase( idxNew==0 );
  123007. exprAnalyze(pSrc, pWC, idxNew);
  123008. pTerm = &pWC->a[idxTerm];
  123009. markTermAsChild(pWC, idxNew, idxTerm);
  123010. }else{
  123011. sqlite3ExprListDelete(db, pList);
  123012. }
  123013. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  123014. }
  123015. }
  123016. }
  123017. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  123018. /*
  123019. ** We already know that pExpr is a binary operator where both operands are
  123020. ** column references. This routine checks to see if pExpr is an equivalence
  123021. ** relation:
  123022. ** 1. The SQLITE_Transitive optimization must be enabled
  123023. ** 2. Must be either an == or an IS operator
  123024. ** 3. Not originating in the ON clause of an OUTER JOIN
  123025. ** 4. The affinities of A and B must be compatible
  123026. ** 5a. Both operands use the same collating sequence OR
  123027. ** 5b. The overall collating sequence is BINARY
  123028. ** If this routine returns TRUE, that means that the RHS can be substituted
  123029. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  123030. ** This is an optimization. No harm comes from returning 0. But if 1 is
  123031. ** returned when it should not be, then incorrect answers might result.
  123032. */
  123033. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  123034. char aff1, aff2;
  123035. CollSeq *pColl;
  123036. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  123037. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  123038. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  123039. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  123040. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  123041. if( aff1!=aff2
  123042. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  123043. ){
  123044. return 0;
  123045. }
  123046. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  123047. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  123048. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  123049. }
  123050. /*
  123051. ** Recursively walk the expressions of a SELECT statement and generate
  123052. ** a bitmask indicating which tables are used in that expression
  123053. ** tree.
  123054. */
  123055. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  123056. Bitmask mask = 0;
  123057. while( pS ){
  123058. SrcList *pSrc = pS->pSrc;
  123059. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  123060. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  123061. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  123062. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  123063. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  123064. if( ALWAYS(pSrc!=0) ){
  123065. int i;
  123066. for(i=0; i<pSrc->nSrc; i++){
  123067. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  123068. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  123069. }
  123070. }
  123071. pS = pS->pPrior;
  123072. }
  123073. return mask;
  123074. }
  123075. /*
  123076. ** Expression pExpr is one operand of a comparison operator that might
  123077. ** be useful for indexing. This routine checks to see if pExpr appears
  123078. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  123079. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  123080. ** number of the table that is indexed and aiCurCol[1] to the column number
  123081. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  123082. ** indexed.
  123083. **
  123084. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  123085. ** true even if that particular column is not indexed, because the column
  123086. ** might be added to an automatic index later.
  123087. */
  123088. static SQLITE_NOINLINE int exprMightBeIndexed2(
  123089. SrcList *pFrom, /* The FROM clause */
  123090. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  123091. int *aiCurCol, /* Write the referenced table cursor and column here */
  123092. Expr *pExpr /* An operand of a comparison operator */
  123093. ){
  123094. Index *pIdx;
  123095. int i;
  123096. int iCur;
  123097. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  123098. iCur = pFrom->a[i].iCursor;
  123099. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  123100. if( pIdx->aColExpr==0 ) continue;
  123101. for(i=0; i<pIdx->nKeyCol; i++){
  123102. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  123103. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  123104. aiCurCol[0] = iCur;
  123105. aiCurCol[1] = XN_EXPR;
  123106. return 1;
  123107. }
  123108. }
  123109. }
  123110. return 0;
  123111. }
  123112. static int exprMightBeIndexed(
  123113. SrcList *pFrom, /* The FROM clause */
  123114. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  123115. int *aiCurCol, /* Write the referenced table cursor & column here */
  123116. Expr *pExpr, /* An operand of a comparison operator */
  123117. int op /* The specific comparison operator */
  123118. ){
  123119. /* If this expression is a vector to the left or right of a
  123120. ** inequality constraint (>, <, >= or <=), perform the processing
  123121. ** on the first element of the vector. */
  123122. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  123123. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  123124. assert( op<=TK_GE );
  123125. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  123126. pExpr = pExpr->x.pList->a[0].pExpr;
  123127. }
  123128. if( pExpr->op==TK_COLUMN ){
  123129. aiCurCol[0] = pExpr->iTable;
  123130. aiCurCol[1] = pExpr->iColumn;
  123131. return 1;
  123132. }
  123133. if( mPrereq==0 ) return 0; /* No table references */
  123134. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  123135. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  123136. }
  123137. /*
  123138. ** The input to this routine is an WhereTerm structure with only the
  123139. ** "pExpr" field filled in. The job of this routine is to analyze the
  123140. ** subexpression and populate all the other fields of the WhereTerm
  123141. ** structure.
  123142. **
  123143. ** If the expression is of the form "<expr> <op> X" it gets commuted
  123144. ** to the standard form of "X <op> <expr>".
  123145. **
  123146. ** If the expression is of the form "X <op> Y" where both X and Y are
  123147. ** columns, then the original expression is unchanged and a new virtual
  123148. ** term of the form "Y <op> X" is added to the WHERE clause and
  123149. ** analyzed separately. The original term is marked with TERM_COPIED
  123150. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  123151. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  123152. ** is a commuted copy of a prior term.) The original term has nChild=1
  123153. ** and the copy has idxParent set to the index of the original term.
  123154. */
  123155. static void exprAnalyze(
  123156. SrcList *pSrc, /* the FROM clause */
  123157. WhereClause *pWC, /* the WHERE clause */
  123158. int idxTerm /* Index of the term to be analyzed */
  123159. ){
  123160. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  123161. WhereTerm *pTerm; /* The term to be analyzed */
  123162. WhereMaskSet *pMaskSet; /* Set of table index masks */
  123163. Expr *pExpr; /* The expression to be analyzed */
  123164. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  123165. Bitmask prereqAll; /* Prerequesites of pExpr */
  123166. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  123167. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  123168. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  123169. int noCase = 0; /* uppercase equivalent to lowercase */
  123170. int op; /* Top-level operator. pExpr->op */
  123171. Parse *pParse = pWInfo->pParse; /* Parsing context */
  123172. sqlite3 *db = pParse->db; /* Database connection */
  123173. unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
  123174. int nLeft; /* Number of elements on left side vector */
  123175. if( db->mallocFailed ){
  123176. return;
  123177. }
  123178. pTerm = &pWC->a[idxTerm];
  123179. pMaskSet = &pWInfo->sMaskSet;
  123180. pExpr = pTerm->pExpr;
  123181. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  123182. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  123183. op = pExpr->op;
  123184. if( op==TK_IN ){
  123185. assert( pExpr->pRight==0 );
  123186. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  123187. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  123188. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  123189. }else{
  123190. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  123191. }
  123192. }else if( op==TK_ISNULL ){
  123193. pTerm->prereqRight = 0;
  123194. }else{
  123195. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  123196. }
  123197. pMaskSet->bVarSelect = 0;
  123198. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  123199. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  123200. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  123201. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  123202. prereqAll |= x;
  123203. extraRight = x-1; /* ON clause terms may not be used with an index
  123204. ** on left table of a LEFT JOIN. Ticket #3015 */
  123205. if( (prereqAll>>1)>=x ){
  123206. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  123207. return;
  123208. }
  123209. }
  123210. pTerm->prereqAll = prereqAll;
  123211. pTerm->leftCursor = -1;
  123212. pTerm->iParent = -1;
  123213. pTerm->eOperator = 0;
  123214. if( allowedOp(op) ){
  123215. int aiCurCol[2];
  123216. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  123217. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  123218. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  123219. if( pTerm->iField>0 ){
  123220. assert( op==TK_IN );
  123221. assert( pLeft->op==TK_VECTOR );
  123222. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  123223. }
  123224. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  123225. pTerm->leftCursor = aiCurCol[0];
  123226. pTerm->u.leftColumn = aiCurCol[1];
  123227. pTerm->eOperator = operatorMask(op) & opMask;
  123228. }
  123229. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  123230. if( pRight
  123231. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  123232. ){
  123233. WhereTerm *pNew;
  123234. Expr *pDup;
  123235. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  123236. assert( pTerm->iField==0 );
  123237. if( pTerm->leftCursor>=0 ){
  123238. int idxNew;
  123239. pDup = sqlite3ExprDup(db, pExpr, 0);
  123240. if( db->mallocFailed ){
  123241. sqlite3ExprDelete(db, pDup);
  123242. return;
  123243. }
  123244. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  123245. if( idxNew==0 ) return;
  123246. pNew = &pWC->a[idxNew];
  123247. markTermAsChild(pWC, idxNew, idxTerm);
  123248. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  123249. pTerm = &pWC->a[idxTerm];
  123250. pTerm->wtFlags |= TERM_COPIED;
  123251. if( termIsEquivalence(pParse, pDup) ){
  123252. pTerm->eOperator |= WO_EQUIV;
  123253. eExtraOp = WO_EQUIV;
  123254. }
  123255. }else{
  123256. pDup = pExpr;
  123257. pNew = pTerm;
  123258. }
  123259. exprCommute(pParse, pDup);
  123260. pNew->leftCursor = aiCurCol[0];
  123261. pNew->u.leftColumn = aiCurCol[1];
  123262. testcase( (prereqLeft | extraRight) != prereqLeft );
  123263. pNew->prereqRight = prereqLeft | extraRight;
  123264. pNew->prereqAll = prereqAll;
  123265. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  123266. }
  123267. }
  123268. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  123269. /* If a term is the BETWEEN operator, create two new virtual terms
  123270. ** that define the range that the BETWEEN implements. For example:
  123271. **
  123272. ** a BETWEEN b AND c
  123273. **
  123274. ** is converted into:
  123275. **
  123276. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  123277. **
  123278. ** The two new terms are added onto the end of the WhereClause object.
  123279. ** The new terms are "dynamic" and are children of the original BETWEEN
  123280. ** term. That means that if the BETWEEN term is coded, the children are
  123281. ** skipped. Or, if the children are satisfied by an index, the original
  123282. ** BETWEEN term is skipped.
  123283. */
  123284. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  123285. ExprList *pList = pExpr->x.pList;
  123286. int i;
  123287. static const u8 ops[] = {TK_GE, TK_LE};
  123288. assert( pList!=0 );
  123289. assert( pList->nExpr==2 );
  123290. for(i=0; i<2; i++){
  123291. Expr *pNewExpr;
  123292. int idxNew;
  123293. pNewExpr = sqlite3PExpr(pParse, ops[i],
  123294. sqlite3ExprDup(db, pExpr->pLeft, 0),
  123295. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  123296. transferJoinMarkings(pNewExpr, pExpr);
  123297. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  123298. testcase( idxNew==0 );
  123299. exprAnalyze(pSrc, pWC, idxNew);
  123300. pTerm = &pWC->a[idxTerm];
  123301. markTermAsChild(pWC, idxNew, idxTerm);
  123302. }
  123303. }
  123304. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  123305. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  123306. /* Analyze a term that is composed of two or more subterms connected by
  123307. ** an OR operator.
  123308. */
  123309. else if( pExpr->op==TK_OR ){
  123310. assert( pWC->op==TK_AND );
  123311. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  123312. pTerm = &pWC->a[idxTerm];
  123313. }
  123314. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  123315. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  123316. /* Add constraints to reduce the search space on a LIKE or GLOB
  123317. ** operator.
  123318. **
  123319. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  123320. **
  123321. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  123322. **
  123323. ** The last character of the prefix "abc" is incremented to form the
  123324. ** termination condition "abd". If case is not significant (the default
  123325. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  123326. ** bound is made all lowercase so that the bounds also work when comparing
  123327. ** BLOBs.
  123328. */
  123329. if( pWC->op==TK_AND
  123330. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  123331. ){
  123332. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  123333. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  123334. Expr *pNewExpr1;
  123335. Expr *pNewExpr2;
  123336. int idxNew1;
  123337. int idxNew2;
  123338. const char *zCollSeqName; /* Name of collating sequence */
  123339. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  123340. pLeft = pExpr->x.pList->a[1].pExpr;
  123341. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  123342. /* Convert the lower bound to upper-case and the upper bound to
  123343. ** lower-case (upper-case is less than lower-case in ASCII) so that
  123344. ** the range constraints also work for BLOBs
  123345. */
  123346. if( noCase && !pParse->db->mallocFailed ){
  123347. int i;
  123348. char c;
  123349. pTerm->wtFlags |= TERM_LIKE;
  123350. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  123351. pStr1->u.zToken[i] = sqlite3Toupper(c);
  123352. pStr2->u.zToken[i] = sqlite3Tolower(c);
  123353. }
  123354. }
  123355. if( !db->mallocFailed ){
  123356. u8 c, *pC; /* Last character before the first wildcard */
  123357. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  123358. c = *pC;
  123359. if( noCase ){
  123360. /* The point is to increment the last character before the first
  123361. ** wildcard. But if we increment '@', that will push it into the
  123362. ** alphabetic range where case conversions will mess up the
  123363. ** inequality. To avoid this, make sure to also run the full
  123364. ** LIKE on all candidate expressions by clearing the isComplete flag
  123365. */
  123366. if( c=='A'-1 ) isComplete = 0;
  123367. c = sqlite3UpperToLower[c];
  123368. }
  123369. *pC = c + 1;
  123370. }
  123371. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  123372. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  123373. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  123374. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  123375. pStr1);
  123376. transferJoinMarkings(pNewExpr1, pExpr);
  123377. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  123378. testcase( idxNew1==0 );
  123379. exprAnalyze(pSrc, pWC, idxNew1);
  123380. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  123381. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  123382. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  123383. pStr2);
  123384. transferJoinMarkings(pNewExpr2, pExpr);
  123385. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  123386. testcase( idxNew2==0 );
  123387. exprAnalyze(pSrc, pWC, idxNew2);
  123388. pTerm = &pWC->a[idxTerm];
  123389. if( isComplete ){
  123390. markTermAsChild(pWC, idxNew1, idxTerm);
  123391. markTermAsChild(pWC, idxNew2, idxTerm);
  123392. }
  123393. }
  123394. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  123395. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123396. /* Add a WO_AUX auxiliary term to the constraint set if the
  123397. ** current expression is of the form "column OP expr" where OP
  123398. ** is an operator that gets passed into virtual tables but which is
  123399. ** not normally optimized for ordinary tables. In other words, OP
  123400. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  123401. ** This information is used by the xBestIndex methods of
  123402. ** virtual tables. The native query optimizer does not attempt
  123403. ** to do anything with MATCH functions.
  123404. */
  123405. if( pWC->op==TK_AND ){
  123406. Expr *pRight, *pLeft;
  123407. int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
  123408. while( res-- > 0 ){
  123409. int idxNew;
  123410. WhereTerm *pNewTerm;
  123411. Bitmask prereqColumn, prereqExpr;
  123412. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  123413. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  123414. if( (prereqExpr & prereqColumn)==0 ){
  123415. Expr *pNewExpr;
  123416. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  123417. 0, sqlite3ExprDup(db, pRight, 0));
  123418. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  123419. ExprSetProperty(pNewExpr, EP_FromJoin);
  123420. }
  123421. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  123422. testcase( idxNew==0 );
  123423. pNewTerm = &pWC->a[idxNew];
  123424. pNewTerm->prereqRight = prereqExpr;
  123425. pNewTerm->leftCursor = pLeft->iTable;
  123426. pNewTerm->u.leftColumn = pLeft->iColumn;
  123427. pNewTerm->eOperator = WO_AUX;
  123428. pNewTerm->eMatchOp = eOp2;
  123429. markTermAsChild(pWC, idxNew, idxTerm);
  123430. pTerm = &pWC->a[idxTerm];
  123431. pTerm->wtFlags |= TERM_COPIED;
  123432. pNewTerm->prereqAll = pTerm->prereqAll;
  123433. }
  123434. SWAP(Expr*, pLeft, pRight);
  123435. }
  123436. }
  123437. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  123438. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  123439. ** new terms for each component comparison - "a = ?" and "b = ?". The
  123440. ** new terms completely replace the original vector comparison, which is
  123441. ** no longer used.
  123442. **
  123443. ** This is only required if at least one side of the comparison operation
  123444. ** is not a sub-select. */
  123445. if( pWC->op==TK_AND
  123446. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  123447. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  123448. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  123449. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  123450. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  123451. ){
  123452. int i;
  123453. for(i=0; i<nLeft; i++){
  123454. int idxNew;
  123455. Expr *pNew;
  123456. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  123457. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  123458. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  123459. transferJoinMarkings(pNew, pExpr);
  123460. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  123461. exprAnalyze(pSrc, pWC, idxNew);
  123462. }
  123463. pTerm = &pWC->a[idxTerm];
  123464. pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  123465. pTerm->eOperator = 0;
  123466. }
  123467. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  123468. ** a virtual term for each vector component. The expression object
  123469. ** used by each such virtual term is pExpr (the full vector IN(...)
  123470. ** expression). The WhereTerm.iField variable identifies the index within
  123471. ** the vector on the LHS that the virtual term represents.
  123472. **
  123473. ** This only works if the RHS is a simple SELECT, not a compound
  123474. */
  123475. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  123476. && pExpr->pLeft->op==TK_VECTOR
  123477. && pExpr->x.pSelect->pPrior==0
  123478. ){
  123479. int i;
  123480. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  123481. int idxNew;
  123482. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  123483. pWC->a[idxNew].iField = i+1;
  123484. exprAnalyze(pSrc, pWC, idxNew);
  123485. markTermAsChild(pWC, idxNew, idxTerm);
  123486. }
  123487. }
  123488. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123489. /* When sqlite_stat3 histogram data is available an operator of the
  123490. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  123491. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  123492. ** virtual term of that form.
  123493. **
  123494. ** Note that the virtual term must be tagged with TERM_VNULL.
  123495. */
  123496. if( pExpr->op==TK_NOTNULL
  123497. && pExpr->pLeft->op==TK_COLUMN
  123498. && pExpr->pLeft->iColumn>=0
  123499. && OptimizationEnabled(db, SQLITE_Stat34)
  123500. ){
  123501. Expr *pNewExpr;
  123502. Expr *pLeft = pExpr->pLeft;
  123503. int idxNew;
  123504. WhereTerm *pNewTerm;
  123505. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  123506. sqlite3ExprDup(db, pLeft, 0),
  123507. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  123508. idxNew = whereClauseInsert(pWC, pNewExpr,
  123509. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  123510. if( idxNew ){
  123511. pNewTerm = &pWC->a[idxNew];
  123512. pNewTerm->prereqRight = 0;
  123513. pNewTerm->leftCursor = pLeft->iTable;
  123514. pNewTerm->u.leftColumn = pLeft->iColumn;
  123515. pNewTerm->eOperator = WO_GT;
  123516. markTermAsChild(pWC, idxNew, idxTerm);
  123517. pTerm = &pWC->a[idxTerm];
  123518. pTerm->wtFlags |= TERM_COPIED;
  123519. pNewTerm->prereqAll = pTerm->prereqAll;
  123520. }
  123521. }
  123522. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123523. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  123524. ** an index for tables to the left of the join.
  123525. */
  123526. testcase( pTerm!=&pWC->a[idxTerm] );
  123527. pTerm = &pWC->a[idxTerm];
  123528. pTerm->prereqRight |= extraRight;
  123529. }
  123530. /***************************************************************************
  123531. ** Routines with file scope above. Interface to the rest of the where.c
  123532. ** subsystem follows.
  123533. ***************************************************************************/
  123534. /*
  123535. ** This routine identifies subexpressions in the WHERE clause where
  123536. ** each subexpression is separated by the AND operator or some other
  123537. ** operator specified in the op parameter. The WhereClause structure
  123538. ** is filled with pointers to subexpressions. For example:
  123539. **
  123540. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  123541. ** \________/ \_______________/ \________________/
  123542. ** slot[0] slot[1] slot[2]
  123543. **
  123544. ** The original WHERE clause in pExpr is unaltered. All this routine
  123545. ** does is make slot[] entries point to substructure within pExpr.
  123546. **
  123547. ** In the previous sentence and in the diagram, "slot[]" refers to
  123548. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  123549. ** all terms of the WHERE clause.
  123550. */
  123551. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  123552. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  123553. pWC->op = op;
  123554. if( pE2==0 ) return;
  123555. if( pE2->op!=op ){
  123556. whereClauseInsert(pWC, pExpr, 0);
  123557. }else{
  123558. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  123559. sqlite3WhereSplit(pWC, pE2->pRight, op);
  123560. }
  123561. }
  123562. /*
  123563. ** Initialize a preallocated WhereClause structure.
  123564. */
  123565. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  123566. WhereClause *pWC, /* The WhereClause to be initialized */
  123567. WhereInfo *pWInfo /* The WHERE processing context */
  123568. ){
  123569. pWC->pWInfo = pWInfo;
  123570. pWC->pOuter = 0;
  123571. pWC->nTerm = 0;
  123572. pWC->nSlot = ArraySize(pWC->aStatic);
  123573. pWC->a = pWC->aStatic;
  123574. }
  123575. /*
  123576. ** Deallocate a WhereClause structure. The WhereClause structure
  123577. ** itself is not freed. This routine is the inverse of
  123578. ** sqlite3WhereClauseInit().
  123579. */
  123580. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  123581. int i;
  123582. WhereTerm *a;
  123583. sqlite3 *db = pWC->pWInfo->pParse->db;
  123584. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  123585. if( a->wtFlags & TERM_DYNAMIC ){
  123586. sqlite3ExprDelete(db, a->pExpr);
  123587. }
  123588. if( a->wtFlags & TERM_ORINFO ){
  123589. whereOrInfoDelete(db, a->u.pOrInfo);
  123590. }else if( a->wtFlags & TERM_ANDINFO ){
  123591. whereAndInfoDelete(db, a->u.pAndInfo);
  123592. }
  123593. }
  123594. if( pWC->a!=pWC->aStatic ){
  123595. sqlite3DbFree(db, pWC->a);
  123596. }
  123597. }
  123598. /*
  123599. ** These routines walk (recursively) an expression tree and generate
  123600. ** a bitmask indicating which tables are used in that expression
  123601. ** tree.
  123602. */
  123603. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  123604. Bitmask mask;
  123605. if( p==0 ) return 0;
  123606. if( p->op==TK_COLUMN ){
  123607. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  123608. }
  123609. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  123610. assert( !ExprHasProperty(p, EP_TokenOnly) );
  123611. if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  123612. if( p->pRight ){
  123613. mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
  123614. assert( p->x.pList==0 );
  123615. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  123616. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  123617. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  123618. }else if( p->x.pList ){
  123619. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  123620. }
  123621. return mask;
  123622. }
  123623. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  123624. int i;
  123625. Bitmask mask = 0;
  123626. if( pList ){
  123627. for(i=0; i<pList->nExpr; i++){
  123628. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  123629. }
  123630. }
  123631. return mask;
  123632. }
  123633. /*
  123634. ** Call exprAnalyze on all terms in a WHERE clause.
  123635. **
  123636. ** Note that exprAnalyze() might add new virtual terms onto the
  123637. ** end of the WHERE clause. We do not want to analyze these new
  123638. ** virtual terms, so start analyzing at the end and work forward
  123639. ** so that the added virtual terms are never processed.
  123640. */
  123641. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  123642. SrcList *pTabList, /* the FROM clause */
  123643. WhereClause *pWC /* the WHERE clause to be analyzed */
  123644. ){
  123645. int i;
  123646. for(i=pWC->nTerm-1; i>=0; i--){
  123647. exprAnalyze(pTabList, pWC, i);
  123648. }
  123649. }
  123650. /*
  123651. ** For table-valued-functions, transform the function arguments into
  123652. ** new WHERE clause terms.
  123653. **
  123654. ** Each function argument translates into an equality constraint against
  123655. ** a HIDDEN column in the table.
  123656. */
  123657. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  123658. Parse *pParse, /* Parsing context */
  123659. struct SrcList_item *pItem, /* The FROM clause term to process */
  123660. WhereClause *pWC /* Xfer function arguments to here */
  123661. ){
  123662. Table *pTab;
  123663. int j, k;
  123664. ExprList *pArgs;
  123665. Expr *pColRef;
  123666. Expr *pTerm;
  123667. if( pItem->fg.isTabFunc==0 ) return;
  123668. pTab = pItem->pTab;
  123669. assert( pTab!=0 );
  123670. pArgs = pItem->u1.pFuncArg;
  123671. if( pArgs==0 ) return;
  123672. for(j=k=0; j<pArgs->nExpr; j++){
  123673. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  123674. if( k>=pTab->nCol ){
  123675. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  123676. pTab->zName, j);
  123677. return;
  123678. }
  123679. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  123680. if( pColRef==0 ) return;
  123681. pColRef->iTable = pItem->iCursor;
  123682. pColRef->iColumn = k++;
  123683. pColRef->pTab = pTab;
  123684. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  123685. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
  123686. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  123687. }
  123688. }
  123689. /************** End of whereexpr.c *******************************************/
  123690. /************** Begin file where.c *******************************************/
  123691. /*
  123692. ** 2001 September 15
  123693. **
  123694. ** The author disclaims copyright to this source code. In place of
  123695. ** a legal notice, here is a blessing:
  123696. **
  123697. ** May you do good and not evil.
  123698. ** May you find forgiveness for yourself and forgive others.
  123699. ** May you share freely, never taking more than you give.
  123700. **
  123701. *************************************************************************
  123702. ** This module contains C code that generates VDBE code used to process
  123703. ** the WHERE clause of SQL statements. This module is responsible for
  123704. ** generating the code that loops through a table looking for applicable
  123705. ** rows. Indices are selected and used to speed the search when doing
  123706. ** so is applicable. Because this module is responsible for selecting
  123707. ** indices, you might also think of this module as the "query optimizer".
  123708. */
  123709. /* #include "sqliteInt.h" */
  123710. /* #include "whereInt.h" */
  123711. /* Forward declaration of methods */
  123712. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  123713. /* Test variable that can be set to enable WHERE tracing */
  123714. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  123715. /***/ int sqlite3WhereTrace = 0;
  123716. #endif
  123717. /*
  123718. ** Return the estimated number of output rows from a WHERE clause
  123719. */
  123720. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  123721. return pWInfo->nRowOut;
  123722. }
  123723. /*
  123724. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  123725. ** WHERE clause returns outputs for DISTINCT processing.
  123726. */
  123727. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  123728. return pWInfo->eDistinct;
  123729. }
  123730. /*
  123731. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  123732. ** Return FALSE if the output needs to be sorted.
  123733. */
  123734. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  123735. return pWInfo->nOBSat;
  123736. }
  123737. /*
  123738. ** Return TRUE if the innermost loop of the WHERE clause implementation
  123739. ** returns rows in ORDER BY order for complete run of the inner loop.
  123740. **
  123741. ** Across multiple iterations of outer loops, the output rows need not be
  123742. ** sorted. As long as rows are sorted for just the innermost loop, this
  123743. ** routine can return TRUE.
  123744. */
  123745. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
  123746. return pWInfo->bOrderedInnerLoop;
  123747. }
  123748. /*
  123749. ** Return the VDBE address or label to jump to in order to continue
  123750. ** immediately with the next row of a WHERE clause.
  123751. */
  123752. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  123753. assert( pWInfo->iContinue!=0 );
  123754. return pWInfo->iContinue;
  123755. }
  123756. /*
  123757. ** Return the VDBE address or label to jump to in order to break
  123758. ** out of a WHERE loop.
  123759. */
  123760. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  123761. return pWInfo->iBreak;
  123762. }
  123763. /*
  123764. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  123765. ** operate directly on the rowis returned by a WHERE clause. Return
  123766. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  123767. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  123768. ** optimization can be used on multiple
  123769. **
  123770. ** If the ONEPASS optimization is used (if this routine returns true)
  123771. ** then also write the indices of open cursors used by ONEPASS
  123772. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  123773. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  123774. ** Either value may be -1, indicating that cursor is not used.
  123775. ** Any cursors returned will have been opened for writing.
  123776. **
  123777. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  123778. ** unable to use the ONEPASS optimization.
  123779. */
  123780. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  123781. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  123782. #ifdef WHERETRACE_ENABLED
  123783. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  123784. sqlite3DebugPrintf("%s cursors: %d %d\n",
  123785. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  123786. aiCur[0], aiCur[1]);
  123787. }
  123788. #endif
  123789. return pWInfo->eOnePass;
  123790. }
  123791. /*
  123792. ** Move the content of pSrc into pDest
  123793. */
  123794. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  123795. pDest->n = pSrc->n;
  123796. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  123797. }
  123798. /*
  123799. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  123800. **
  123801. ** The new entry might overwrite an existing entry, or it might be
  123802. ** appended, or it might be discarded. Do whatever is the right thing
  123803. ** so that pSet keeps the N_OR_COST best entries seen so far.
  123804. */
  123805. static int whereOrInsert(
  123806. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  123807. Bitmask prereq, /* Prerequisites of the new entry */
  123808. LogEst rRun, /* Run-cost of the new entry */
  123809. LogEst nOut /* Number of outputs for the new entry */
  123810. ){
  123811. u16 i;
  123812. WhereOrCost *p;
  123813. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  123814. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  123815. goto whereOrInsert_done;
  123816. }
  123817. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  123818. return 0;
  123819. }
  123820. }
  123821. if( pSet->n<N_OR_COST ){
  123822. p = &pSet->a[pSet->n++];
  123823. p->nOut = nOut;
  123824. }else{
  123825. p = pSet->a;
  123826. for(i=1; i<pSet->n; i++){
  123827. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  123828. }
  123829. if( p->rRun<=rRun ) return 0;
  123830. }
  123831. whereOrInsert_done:
  123832. p->prereq = prereq;
  123833. p->rRun = rRun;
  123834. if( p->nOut>nOut ) p->nOut = nOut;
  123835. return 1;
  123836. }
  123837. /*
  123838. ** Return the bitmask for the given cursor number. Return 0 if
  123839. ** iCursor is not in the set.
  123840. */
  123841. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  123842. int i;
  123843. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  123844. for(i=0; i<pMaskSet->n; i++){
  123845. if( pMaskSet->ix[i]==iCursor ){
  123846. return MASKBIT(i);
  123847. }
  123848. }
  123849. return 0;
  123850. }
  123851. /*
  123852. ** Create a new mask for cursor iCursor.
  123853. **
  123854. ** There is one cursor per table in the FROM clause. The number of
  123855. ** tables in the FROM clause is limited by a test early in the
  123856. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  123857. ** array will never overflow.
  123858. */
  123859. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  123860. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  123861. pMaskSet->ix[pMaskSet->n++] = iCursor;
  123862. }
  123863. /*
  123864. ** Advance to the next WhereTerm that matches according to the criteria
  123865. ** established when the pScan object was initialized by whereScanInit().
  123866. ** Return NULL if there are no more matching WhereTerms.
  123867. */
  123868. static WhereTerm *whereScanNext(WhereScan *pScan){
  123869. int iCur; /* The cursor on the LHS of the term */
  123870. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  123871. Expr *pX; /* An expression being tested */
  123872. WhereClause *pWC; /* Shorthand for pScan->pWC */
  123873. WhereTerm *pTerm; /* The term being tested */
  123874. int k = pScan->k; /* Where to start scanning */
  123875. assert( pScan->iEquiv<=pScan->nEquiv );
  123876. pWC = pScan->pWC;
  123877. while(1){
  123878. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  123879. iCur = pScan->aiCur[pScan->iEquiv-1];
  123880. assert( pWC!=0 );
  123881. do{
  123882. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  123883. if( pTerm->leftCursor==iCur
  123884. && pTerm->u.leftColumn==iColumn
  123885. && (iColumn!=XN_EXPR
  123886. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  123887. pScan->pIdxExpr,iCur)==0)
  123888. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  123889. ){
  123890. if( (pTerm->eOperator & WO_EQUIV)!=0
  123891. && pScan->nEquiv<ArraySize(pScan->aiCur)
  123892. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  123893. ){
  123894. int j;
  123895. for(j=0; j<pScan->nEquiv; j++){
  123896. if( pScan->aiCur[j]==pX->iTable
  123897. && pScan->aiColumn[j]==pX->iColumn ){
  123898. break;
  123899. }
  123900. }
  123901. if( j==pScan->nEquiv ){
  123902. pScan->aiCur[j] = pX->iTable;
  123903. pScan->aiColumn[j] = pX->iColumn;
  123904. pScan->nEquiv++;
  123905. }
  123906. }
  123907. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  123908. /* Verify the affinity and collating sequence match */
  123909. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  123910. CollSeq *pColl;
  123911. Parse *pParse = pWC->pWInfo->pParse;
  123912. pX = pTerm->pExpr;
  123913. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  123914. continue;
  123915. }
  123916. assert(pX->pLeft);
  123917. pColl = sqlite3BinaryCompareCollSeq(pParse,
  123918. pX->pLeft, pX->pRight);
  123919. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  123920. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  123921. continue;
  123922. }
  123923. }
  123924. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  123925. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  123926. && pX->iTable==pScan->aiCur[0]
  123927. && pX->iColumn==pScan->aiColumn[0]
  123928. ){
  123929. testcase( pTerm->eOperator & WO_IS );
  123930. continue;
  123931. }
  123932. pScan->pWC = pWC;
  123933. pScan->k = k+1;
  123934. return pTerm;
  123935. }
  123936. }
  123937. }
  123938. pWC = pWC->pOuter;
  123939. k = 0;
  123940. }while( pWC!=0 );
  123941. if( pScan->iEquiv>=pScan->nEquiv ) break;
  123942. pWC = pScan->pOrigWC;
  123943. k = 0;
  123944. pScan->iEquiv++;
  123945. }
  123946. return 0;
  123947. }
  123948. /*
  123949. ** Initialize a WHERE clause scanner object. Return a pointer to the
  123950. ** first match. Return NULL if there are no matches.
  123951. **
  123952. ** The scanner will be searching the WHERE clause pWC. It will look
  123953. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  123954. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  123955. ** must be one of the indexes of table iCur.
  123956. **
  123957. ** The <op> must be one of the operators described by opMask.
  123958. **
  123959. ** If the search is for X and the WHERE clause contains terms of the
  123960. ** form X=Y then this routine might also return terms of the form
  123961. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  123962. ** but is enough to handle most commonly occurring SQL statements.
  123963. **
  123964. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  123965. ** index pIdx.
  123966. */
  123967. static WhereTerm *whereScanInit(
  123968. WhereScan *pScan, /* The WhereScan object being initialized */
  123969. WhereClause *pWC, /* The WHERE clause to be scanned */
  123970. int iCur, /* Cursor to scan for */
  123971. int iColumn, /* Column to scan for */
  123972. u32 opMask, /* Operator(s) to scan for */
  123973. Index *pIdx /* Must be compatible with this index */
  123974. ){
  123975. pScan->pOrigWC = pWC;
  123976. pScan->pWC = pWC;
  123977. pScan->pIdxExpr = 0;
  123978. pScan->idxaff = 0;
  123979. pScan->zCollName = 0;
  123980. if( pIdx ){
  123981. int j = iColumn;
  123982. iColumn = pIdx->aiColumn[j];
  123983. if( iColumn==XN_EXPR ){
  123984. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  123985. pScan->zCollName = pIdx->azColl[j];
  123986. }else if( iColumn==pIdx->pTable->iPKey ){
  123987. iColumn = XN_ROWID;
  123988. }else if( iColumn>=0 ){
  123989. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  123990. pScan->zCollName = pIdx->azColl[j];
  123991. }
  123992. }else if( iColumn==XN_EXPR ){
  123993. return 0;
  123994. }
  123995. pScan->opMask = opMask;
  123996. pScan->k = 0;
  123997. pScan->aiCur[0] = iCur;
  123998. pScan->aiColumn[0] = iColumn;
  123999. pScan->nEquiv = 1;
  124000. pScan->iEquiv = 1;
  124001. return whereScanNext(pScan);
  124002. }
  124003. /*
  124004. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  124005. ** where X is a reference to the iColumn of table iCur or of index pIdx
  124006. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  124007. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  124008. **
  124009. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  124010. ** Search for terms matching the iColumn-th column of pIdx
  124011. ** rather than the iColumn-th column of table iCur.
  124012. **
  124013. ** The term returned might by Y=<expr> if there is another constraint in
  124014. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  124015. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  124016. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  124017. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  124018. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  124019. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  124020. **
  124021. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  124022. ** then try for the one with no dependencies on <expr> - in other words where
  124023. ** <expr> is a constant expression of some kind. Only return entries of
  124024. ** the form "X <op> Y" where Y is a column in another table if no terms of
  124025. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  124026. ** exist, try to return a term that does not use WO_EQUIV.
  124027. */
  124028. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  124029. WhereClause *pWC, /* The WHERE clause to be searched */
  124030. int iCur, /* Cursor number of LHS */
  124031. int iColumn, /* Column number of LHS */
  124032. Bitmask notReady, /* RHS must not overlap with this mask */
  124033. u32 op, /* Mask of WO_xx values describing operator */
  124034. Index *pIdx /* Must be compatible with this index, if not NULL */
  124035. ){
  124036. WhereTerm *pResult = 0;
  124037. WhereTerm *p;
  124038. WhereScan scan;
  124039. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  124040. op &= WO_EQ|WO_IS;
  124041. while( p ){
  124042. if( (p->prereqRight & notReady)==0 ){
  124043. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  124044. testcase( p->eOperator & WO_IS );
  124045. return p;
  124046. }
  124047. if( pResult==0 ) pResult = p;
  124048. }
  124049. p = whereScanNext(&scan);
  124050. }
  124051. return pResult;
  124052. }
  124053. /*
  124054. ** This function searches pList for an entry that matches the iCol-th column
  124055. ** of index pIdx.
  124056. **
  124057. ** If such an expression is found, its index in pList->a[] is returned. If
  124058. ** no expression is found, -1 is returned.
  124059. */
  124060. static int findIndexCol(
  124061. Parse *pParse, /* Parse context */
  124062. ExprList *pList, /* Expression list to search */
  124063. int iBase, /* Cursor for table associated with pIdx */
  124064. Index *pIdx, /* Index to match column of */
  124065. int iCol /* Column of index to match */
  124066. ){
  124067. int i;
  124068. const char *zColl = pIdx->azColl[iCol];
  124069. for(i=0; i<pList->nExpr; i++){
  124070. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  124071. if( p->op==TK_COLUMN
  124072. && p->iColumn==pIdx->aiColumn[iCol]
  124073. && p->iTable==iBase
  124074. ){
  124075. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  124076. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  124077. return i;
  124078. }
  124079. }
  124080. }
  124081. return -1;
  124082. }
  124083. /*
  124084. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  124085. */
  124086. static int indexColumnNotNull(Index *pIdx, int iCol){
  124087. int j;
  124088. assert( pIdx!=0 );
  124089. assert( iCol>=0 && iCol<pIdx->nColumn );
  124090. j = pIdx->aiColumn[iCol];
  124091. if( j>=0 ){
  124092. return pIdx->pTable->aCol[j].notNull;
  124093. }else if( j==(-1) ){
  124094. return 1;
  124095. }else{
  124096. assert( j==(-2) );
  124097. return 0; /* Assume an indexed expression can always yield a NULL */
  124098. }
  124099. }
  124100. /*
  124101. ** Return true if the DISTINCT expression-list passed as the third argument
  124102. ** is redundant.
  124103. **
  124104. ** A DISTINCT list is redundant if any subset of the columns in the
  124105. ** DISTINCT list are collectively unique and individually non-null.
  124106. */
  124107. static int isDistinctRedundant(
  124108. Parse *pParse, /* Parsing context */
  124109. SrcList *pTabList, /* The FROM clause */
  124110. WhereClause *pWC, /* The WHERE clause */
  124111. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  124112. ){
  124113. Table *pTab;
  124114. Index *pIdx;
  124115. int i;
  124116. int iBase;
  124117. /* If there is more than one table or sub-select in the FROM clause of
  124118. ** this query, then it will not be possible to show that the DISTINCT
  124119. ** clause is redundant. */
  124120. if( pTabList->nSrc!=1 ) return 0;
  124121. iBase = pTabList->a[0].iCursor;
  124122. pTab = pTabList->a[0].pTab;
  124123. /* If any of the expressions is an IPK column on table iBase, then return
  124124. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  124125. ** current SELECT is a correlated sub-query.
  124126. */
  124127. for(i=0; i<pDistinct->nExpr; i++){
  124128. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  124129. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  124130. }
  124131. /* Loop through all indices on the table, checking each to see if it makes
  124132. ** the DISTINCT qualifier redundant. It does so if:
  124133. **
  124134. ** 1. The index is itself UNIQUE, and
  124135. **
  124136. ** 2. All of the columns in the index are either part of the pDistinct
  124137. ** list, or else the WHERE clause contains a term of the form "col=X",
  124138. ** where X is a constant value. The collation sequences of the
  124139. ** comparison and select-list expressions must match those of the index.
  124140. **
  124141. ** 3. All of those index columns for which the WHERE clause does not
  124142. ** contain a "col=X" term are subject to a NOT NULL constraint.
  124143. */
  124144. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  124145. if( !IsUniqueIndex(pIdx) ) continue;
  124146. for(i=0; i<pIdx->nKeyCol; i++){
  124147. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  124148. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  124149. if( indexColumnNotNull(pIdx, i)==0 ) break;
  124150. }
  124151. }
  124152. if( i==pIdx->nKeyCol ){
  124153. /* This index implies that the DISTINCT qualifier is redundant. */
  124154. return 1;
  124155. }
  124156. }
  124157. return 0;
  124158. }
  124159. /*
  124160. ** Estimate the logarithm of the input value to base 2.
  124161. */
  124162. static LogEst estLog(LogEst N){
  124163. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  124164. }
  124165. /*
  124166. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  124167. **
  124168. ** This routine runs over generated VDBE code and translates OP_Column
  124169. ** opcodes into OP_Copy when the table is being accessed via co-routine
  124170. ** instead of via table lookup.
  124171. **
  124172. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  124173. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  124174. ** then each OP_Rowid is transformed into an instruction to increment the
  124175. ** value stored in its output register.
  124176. */
  124177. static void translateColumnToCopy(
  124178. Parse *pParse, /* Parsing context */
  124179. int iStart, /* Translate from this opcode to the end */
  124180. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  124181. int iRegister, /* The first column is in this register */
  124182. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  124183. ){
  124184. Vdbe *v = pParse->pVdbe;
  124185. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  124186. int iEnd = sqlite3VdbeCurrentAddr(v);
  124187. if( pParse->db->mallocFailed ) return;
  124188. for(; iStart<iEnd; iStart++, pOp++){
  124189. if( pOp->p1!=iTabCur ) continue;
  124190. if( pOp->opcode==OP_Column ){
  124191. pOp->opcode = OP_Copy;
  124192. pOp->p1 = pOp->p2 + iRegister;
  124193. pOp->p2 = pOp->p3;
  124194. pOp->p3 = 0;
  124195. }else if( pOp->opcode==OP_Rowid ){
  124196. if( bIncrRowid ){
  124197. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  124198. pOp->opcode = OP_AddImm;
  124199. pOp->p1 = pOp->p2;
  124200. pOp->p2 = 1;
  124201. }else{
  124202. pOp->opcode = OP_Null;
  124203. pOp->p1 = 0;
  124204. pOp->p3 = 0;
  124205. }
  124206. }
  124207. }
  124208. }
  124209. /*
  124210. ** Two routines for printing the content of an sqlite3_index_info
  124211. ** structure. Used for testing and debugging only. If neither
  124212. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  124213. ** are no-ops.
  124214. */
  124215. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  124216. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  124217. int i;
  124218. if( !sqlite3WhereTrace ) return;
  124219. for(i=0; i<p->nConstraint; i++){
  124220. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  124221. i,
  124222. p->aConstraint[i].iColumn,
  124223. p->aConstraint[i].iTermOffset,
  124224. p->aConstraint[i].op,
  124225. p->aConstraint[i].usable);
  124226. }
  124227. for(i=0; i<p->nOrderBy; i++){
  124228. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  124229. i,
  124230. p->aOrderBy[i].iColumn,
  124231. p->aOrderBy[i].desc);
  124232. }
  124233. }
  124234. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  124235. int i;
  124236. if( !sqlite3WhereTrace ) return;
  124237. for(i=0; i<p->nConstraint; i++){
  124238. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  124239. i,
  124240. p->aConstraintUsage[i].argvIndex,
  124241. p->aConstraintUsage[i].omit);
  124242. }
  124243. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  124244. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  124245. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  124246. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  124247. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  124248. }
  124249. #else
  124250. #define TRACE_IDX_INPUTS(A)
  124251. #define TRACE_IDX_OUTPUTS(A)
  124252. #endif
  124253. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  124254. /*
  124255. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  124256. ** could be used with an index to access pSrc, assuming an appropriate
  124257. ** index existed.
  124258. */
  124259. static int termCanDriveIndex(
  124260. WhereTerm *pTerm, /* WHERE clause term to check */
  124261. struct SrcList_item *pSrc, /* Table we are trying to access */
  124262. Bitmask notReady /* Tables in outer loops of the join */
  124263. ){
  124264. char aff;
  124265. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  124266. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  124267. if( (pSrc->fg.jointype & JT_LEFT)
  124268. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  124269. && (pTerm->eOperator & WO_IS)
  124270. ){
  124271. /* Cannot use an IS term from the WHERE clause as an index driver for
  124272. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  124273. ** the ON clause. */
  124274. return 0;
  124275. }
  124276. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  124277. if( pTerm->u.leftColumn<0 ) return 0;
  124278. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  124279. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  124280. testcase( pTerm->pExpr->op==TK_IS );
  124281. return 1;
  124282. }
  124283. #endif
  124284. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  124285. /*
  124286. ** Generate code to construct the Index object for an automatic index
  124287. ** and to set up the WhereLevel object pLevel so that the code generator
  124288. ** makes use of the automatic index.
  124289. */
  124290. static void constructAutomaticIndex(
  124291. Parse *pParse, /* The parsing context */
  124292. WhereClause *pWC, /* The WHERE clause */
  124293. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  124294. Bitmask notReady, /* Mask of cursors that are not available */
  124295. WhereLevel *pLevel /* Write new index here */
  124296. ){
  124297. int nKeyCol; /* Number of columns in the constructed index */
  124298. WhereTerm *pTerm; /* A single term of the WHERE clause */
  124299. WhereTerm *pWCEnd; /* End of pWC->a[] */
  124300. Index *pIdx; /* Object describing the transient index */
  124301. Vdbe *v; /* Prepared statement under construction */
  124302. int addrInit; /* Address of the initialization bypass jump */
  124303. Table *pTable; /* The table being indexed */
  124304. int addrTop; /* Top of the index fill loop */
  124305. int regRecord; /* Register holding an index record */
  124306. int n; /* Column counter */
  124307. int i; /* Loop counter */
  124308. int mxBitCol; /* Maximum column in pSrc->colUsed */
  124309. CollSeq *pColl; /* Collating sequence to on a column */
  124310. WhereLoop *pLoop; /* The Loop object */
  124311. char *zNotUsed; /* Extra space on the end of pIdx */
  124312. Bitmask idxCols; /* Bitmap of columns used for indexing */
  124313. Bitmask extraCols; /* Bitmap of additional columns */
  124314. u8 sentWarning = 0; /* True if a warnning has been issued */
  124315. Expr *pPartial = 0; /* Partial Index Expression */
  124316. int iContinue = 0; /* Jump here to skip excluded rows */
  124317. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  124318. int addrCounter = 0; /* Address where integer counter is initialized */
  124319. int regBase; /* Array of registers where record is assembled */
  124320. /* Generate code to skip over the creation and initialization of the
  124321. ** transient index on 2nd and subsequent iterations of the loop. */
  124322. v = pParse->pVdbe;
  124323. assert( v!=0 );
  124324. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  124325. /* Count the number of columns that will be added to the index
  124326. ** and used to match WHERE clause constraints */
  124327. nKeyCol = 0;
  124328. pTable = pSrc->pTab;
  124329. pWCEnd = &pWC->a[pWC->nTerm];
  124330. pLoop = pLevel->pWLoop;
  124331. idxCols = 0;
  124332. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  124333. Expr *pExpr = pTerm->pExpr;
  124334. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  124335. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  124336. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  124337. if( pLoop->prereq==0
  124338. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  124339. && !ExprHasProperty(pExpr, EP_FromJoin)
  124340. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  124341. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  124342. sqlite3ExprDup(pParse->db, pExpr, 0));
  124343. }
  124344. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  124345. int iCol = pTerm->u.leftColumn;
  124346. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  124347. testcase( iCol==BMS );
  124348. testcase( iCol==BMS-1 );
  124349. if( !sentWarning ){
  124350. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  124351. "automatic index on %s(%s)", pTable->zName,
  124352. pTable->aCol[iCol].zName);
  124353. sentWarning = 1;
  124354. }
  124355. if( (idxCols & cMask)==0 ){
  124356. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  124357. goto end_auto_index_create;
  124358. }
  124359. pLoop->aLTerm[nKeyCol++] = pTerm;
  124360. idxCols |= cMask;
  124361. }
  124362. }
  124363. }
  124364. assert( nKeyCol>0 );
  124365. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  124366. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  124367. | WHERE_AUTO_INDEX;
  124368. /* Count the number of additional columns needed to create a
  124369. ** covering index. A "covering index" is an index that contains all
  124370. ** columns that are needed by the query. With a covering index, the
  124371. ** original table never needs to be accessed. Automatic indices must
  124372. ** be a covering index because the index will not be updated if the
  124373. ** original table changes and the index and table cannot both be used
  124374. ** if they go out of sync.
  124375. */
  124376. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  124377. mxBitCol = MIN(BMS-1,pTable->nCol);
  124378. testcase( pTable->nCol==BMS-1 );
  124379. testcase( pTable->nCol==BMS-2 );
  124380. for(i=0; i<mxBitCol; i++){
  124381. if( extraCols & MASKBIT(i) ) nKeyCol++;
  124382. }
  124383. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  124384. nKeyCol += pTable->nCol - BMS + 1;
  124385. }
  124386. /* Construct the Index object to describe this index */
  124387. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  124388. if( pIdx==0 ) goto end_auto_index_create;
  124389. pLoop->u.btree.pIndex = pIdx;
  124390. pIdx->zName = "auto-index";
  124391. pIdx->pTable = pTable;
  124392. n = 0;
  124393. idxCols = 0;
  124394. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  124395. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  124396. int iCol = pTerm->u.leftColumn;
  124397. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  124398. testcase( iCol==BMS-1 );
  124399. testcase( iCol==BMS );
  124400. if( (idxCols & cMask)==0 ){
  124401. Expr *pX = pTerm->pExpr;
  124402. idxCols |= cMask;
  124403. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  124404. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  124405. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  124406. n++;
  124407. }
  124408. }
  124409. }
  124410. assert( (u32)n==pLoop->u.btree.nEq );
  124411. /* Add additional columns needed to make the automatic index into
  124412. ** a covering index */
  124413. for(i=0; i<mxBitCol; i++){
  124414. if( extraCols & MASKBIT(i) ){
  124415. pIdx->aiColumn[n] = i;
  124416. pIdx->azColl[n] = sqlite3StrBINARY;
  124417. n++;
  124418. }
  124419. }
  124420. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  124421. for(i=BMS-1; i<pTable->nCol; i++){
  124422. pIdx->aiColumn[n] = i;
  124423. pIdx->azColl[n] = sqlite3StrBINARY;
  124424. n++;
  124425. }
  124426. }
  124427. assert( n==nKeyCol );
  124428. pIdx->aiColumn[n] = XN_ROWID;
  124429. pIdx->azColl[n] = sqlite3StrBINARY;
  124430. /* Create the automatic index */
  124431. assert( pLevel->iIdxCur>=0 );
  124432. pLevel->iIdxCur = pParse->nTab++;
  124433. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  124434. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  124435. VdbeComment((v, "for %s", pTable->zName));
  124436. /* Fill the automatic index with content */
  124437. sqlite3ExprCachePush(pParse);
  124438. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  124439. if( pTabItem->fg.viaCoroutine ){
  124440. int regYield = pTabItem->regReturn;
  124441. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  124442. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  124443. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  124444. VdbeCoverage(v);
  124445. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  124446. }else{
  124447. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  124448. }
  124449. if( pPartial ){
  124450. iContinue = sqlite3VdbeMakeLabel(v);
  124451. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  124452. pLoop->wsFlags |= WHERE_PARTIALIDX;
  124453. }
  124454. regRecord = sqlite3GetTempReg(pParse);
  124455. regBase = sqlite3GenerateIndexKey(
  124456. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  124457. );
  124458. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  124459. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  124460. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  124461. if( pTabItem->fg.viaCoroutine ){
  124462. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  124463. testcase( pParse->db->mallocFailed );
  124464. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  124465. pTabItem->regResult, 1);
  124466. sqlite3VdbeGoto(v, addrTop);
  124467. pTabItem->fg.viaCoroutine = 0;
  124468. }else{
  124469. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  124470. }
  124471. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  124472. sqlite3VdbeJumpHere(v, addrTop);
  124473. sqlite3ReleaseTempReg(pParse, regRecord);
  124474. sqlite3ExprCachePop(pParse);
  124475. /* Jump here when skipping the initialization */
  124476. sqlite3VdbeJumpHere(v, addrInit);
  124477. end_auto_index_create:
  124478. sqlite3ExprDelete(pParse->db, pPartial);
  124479. }
  124480. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  124481. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124482. /*
  124483. ** Allocate and populate an sqlite3_index_info structure. It is the
  124484. ** responsibility of the caller to eventually release the structure
  124485. ** by passing the pointer returned by this function to sqlite3_free().
  124486. */
  124487. static sqlite3_index_info *allocateIndexInfo(
  124488. Parse *pParse,
  124489. WhereClause *pWC,
  124490. Bitmask mUnusable, /* Ignore terms with these prereqs */
  124491. struct SrcList_item *pSrc,
  124492. ExprList *pOrderBy,
  124493. u16 *pmNoOmit /* Mask of terms not to omit */
  124494. ){
  124495. int i, j;
  124496. int nTerm;
  124497. struct sqlite3_index_constraint *pIdxCons;
  124498. struct sqlite3_index_orderby *pIdxOrderBy;
  124499. struct sqlite3_index_constraint_usage *pUsage;
  124500. WhereTerm *pTerm;
  124501. int nOrderBy;
  124502. sqlite3_index_info *pIdxInfo;
  124503. u16 mNoOmit = 0;
  124504. /* Count the number of possible WHERE clause constraints referring
  124505. ** to this virtual table */
  124506. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  124507. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  124508. if( pTerm->prereqRight & mUnusable ) continue;
  124509. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  124510. testcase( pTerm->eOperator & WO_IN );
  124511. testcase( pTerm->eOperator & WO_ISNULL );
  124512. testcase( pTerm->eOperator & WO_IS );
  124513. testcase( pTerm->eOperator & WO_ALL );
  124514. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  124515. if( pTerm->wtFlags & TERM_VNULL ) continue;
  124516. assert( pTerm->u.leftColumn>=(-1) );
  124517. nTerm++;
  124518. }
  124519. /* If the ORDER BY clause contains only columns in the current
  124520. ** virtual table then allocate space for the aOrderBy part of
  124521. ** the sqlite3_index_info structure.
  124522. */
  124523. nOrderBy = 0;
  124524. if( pOrderBy ){
  124525. int n = pOrderBy->nExpr;
  124526. for(i=0; i<n; i++){
  124527. Expr *pExpr = pOrderBy->a[i].pExpr;
  124528. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  124529. }
  124530. if( i==n){
  124531. nOrderBy = n;
  124532. }
  124533. }
  124534. /* Allocate the sqlite3_index_info structure
  124535. */
  124536. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  124537. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  124538. + sizeof(*pIdxOrderBy)*nOrderBy );
  124539. if( pIdxInfo==0 ){
  124540. sqlite3ErrorMsg(pParse, "out of memory");
  124541. return 0;
  124542. }
  124543. /* Initialize the structure. The sqlite3_index_info structure contains
  124544. ** many fields that are declared "const" to prevent xBestIndex from
  124545. ** changing them. We have to do some funky casting in order to
  124546. ** initialize those fields.
  124547. */
  124548. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  124549. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  124550. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  124551. *(int*)&pIdxInfo->nConstraint = nTerm;
  124552. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  124553. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  124554. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  124555. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  124556. pUsage;
  124557. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  124558. u16 op;
  124559. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  124560. if( pTerm->prereqRight & mUnusable ) continue;
  124561. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  124562. testcase( pTerm->eOperator & WO_IN );
  124563. testcase( pTerm->eOperator & WO_IS );
  124564. testcase( pTerm->eOperator & WO_ISNULL );
  124565. testcase( pTerm->eOperator & WO_ALL );
  124566. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  124567. if( pTerm->wtFlags & TERM_VNULL ) continue;
  124568. assert( pTerm->u.leftColumn>=(-1) );
  124569. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  124570. pIdxCons[j].iTermOffset = i;
  124571. op = pTerm->eOperator & WO_ALL;
  124572. if( op==WO_IN ) op = WO_EQ;
  124573. if( op==WO_AUX ){
  124574. pIdxCons[j].op = pTerm->eMatchOp;
  124575. }else if( op & (WO_ISNULL|WO_IS) ){
  124576. if( op==WO_ISNULL ){
  124577. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  124578. }else{
  124579. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  124580. }
  124581. }else{
  124582. pIdxCons[j].op = (u8)op;
  124583. /* The direct assignment in the previous line is possible only because
  124584. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  124585. ** following asserts verify this fact. */
  124586. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  124587. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  124588. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  124589. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  124590. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  124591. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  124592. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  124593. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  124594. ){
  124595. if( i<16 ) mNoOmit |= (1 << i);
  124596. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  124597. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  124598. }
  124599. }
  124600. j++;
  124601. }
  124602. for(i=0; i<nOrderBy; i++){
  124603. Expr *pExpr = pOrderBy->a[i].pExpr;
  124604. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  124605. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  124606. }
  124607. *pmNoOmit = mNoOmit;
  124608. return pIdxInfo;
  124609. }
  124610. /*
  124611. ** The table object reference passed as the second argument to this function
  124612. ** must represent a virtual table. This function invokes the xBestIndex()
  124613. ** method of the virtual table with the sqlite3_index_info object that
  124614. ** comes in as the 3rd argument to this function.
  124615. **
  124616. ** If an error occurs, pParse is populated with an error message and a
  124617. ** non-zero value is returned. Otherwise, 0 is returned and the output
  124618. ** part of the sqlite3_index_info structure is left populated.
  124619. **
  124620. ** Whether or not an error is returned, it is the responsibility of the
  124621. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  124622. ** that this is required.
  124623. */
  124624. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  124625. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  124626. int rc;
  124627. TRACE_IDX_INPUTS(p);
  124628. rc = pVtab->pModule->xBestIndex(pVtab, p);
  124629. TRACE_IDX_OUTPUTS(p);
  124630. if( rc!=SQLITE_OK ){
  124631. if( rc==SQLITE_NOMEM ){
  124632. sqlite3OomFault(pParse->db);
  124633. }else if( !pVtab->zErrMsg ){
  124634. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  124635. }else{
  124636. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  124637. }
  124638. }
  124639. sqlite3_free(pVtab->zErrMsg);
  124640. pVtab->zErrMsg = 0;
  124641. #if 0
  124642. /* This error is now caught by the caller.
  124643. ** Search for "xBestIndex malfunction" below */
  124644. for(i=0; i<p->nConstraint; i++){
  124645. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  124646. sqlite3ErrorMsg(pParse,
  124647. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  124648. }
  124649. }
  124650. #endif
  124651. return pParse->nErr;
  124652. }
  124653. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  124654. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124655. /*
  124656. ** Estimate the location of a particular key among all keys in an
  124657. ** index. Store the results in aStat as follows:
  124658. **
  124659. ** aStat[0] Est. number of rows less than pRec
  124660. ** aStat[1] Est. number of rows equal to pRec
  124661. **
  124662. ** Return the index of the sample that is the smallest sample that
  124663. ** is greater than or equal to pRec. Note that this index is not an index
  124664. ** into the aSample[] array - it is an index into a virtual set of samples
  124665. ** based on the contents of aSample[] and the number of fields in record
  124666. ** pRec.
  124667. */
  124668. static int whereKeyStats(
  124669. Parse *pParse, /* Database connection */
  124670. Index *pIdx, /* Index to consider domain of */
  124671. UnpackedRecord *pRec, /* Vector of values to consider */
  124672. int roundUp, /* Round up if true. Round down if false */
  124673. tRowcnt *aStat /* OUT: stats written here */
  124674. ){
  124675. IndexSample *aSample = pIdx->aSample;
  124676. int iCol; /* Index of required stats in anEq[] etc. */
  124677. int i; /* Index of first sample >= pRec */
  124678. int iSample; /* Smallest sample larger than or equal to pRec */
  124679. int iMin = 0; /* Smallest sample not yet tested */
  124680. int iTest; /* Next sample to test */
  124681. int res; /* Result of comparison operation */
  124682. int nField; /* Number of fields in pRec */
  124683. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  124684. #ifndef SQLITE_DEBUG
  124685. UNUSED_PARAMETER( pParse );
  124686. #endif
  124687. assert( pRec!=0 );
  124688. assert( pIdx->nSample>0 );
  124689. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  124690. /* Do a binary search to find the first sample greater than or equal
  124691. ** to pRec. If pRec contains a single field, the set of samples to search
  124692. ** is simply the aSample[] array. If the samples in aSample[] contain more
  124693. ** than one fields, all fields following the first are ignored.
  124694. **
  124695. ** If pRec contains N fields, where N is more than one, then as well as the
  124696. ** samples in aSample[] (truncated to N fields), the search also has to
  124697. ** consider prefixes of those samples. For example, if the set of samples
  124698. ** in aSample is:
  124699. **
  124700. ** aSample[0] = (a, 5)
  124701. ** aSample[1] = (a, 10)
  124702. ** aSample[2] = (b, 5)
  124703. ** aSample[3] = (c, 100)
  124704. ** aSample[4] = (c, 105)
  124705. **
  124706. ** Then the search space should ideally be the samples above and the
  124707. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  124708. ** the code actually searches this set:
  124709. **
  124710. ** 0: (a)
  124711. ** 1: (a, 5)
  124712. ** 2: (a, 10)
  124713. ** 3: (a, 10)
  124714. ** 4: (b)
  124715. ** 5: (b, 5)
  124716. ** 6: (c)
  124717. ** 7: (c, 100)
  124718. ** 8: (c, 105)
  124719. ** 9: (c, 105)
  124720. **
  124721. ** For each sample in the aSample[] array, N samples are present in the
  124722. ** effective sample array. In the above, samples 0 and 1 are based on
  124723. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  124724. **
  124725. ** Often, sample i of each block of N effective samples has (i+1) fields.
  124726. ** Except, each sample may be extended to ensure that it is greater than or
  124727. ** equal to the previous sample in the array. For example, in the above,
  124728. ** sample 2 is the first sample of a block of N samples, so at first it
  124729. ** appears that it should be 1 field in size. However, that would make it
  124730. ** smaller than sample 1, so the binary search would not work. As a result,
  124731. ** it is extended to two fields. The duplicates that this creates do not
  124732. ** cause any problems.
  124733. */
  124734. nField = pRec->nField;
  124735. iCol = 0;
  124736. iSample = pIdx->nSample * nField;
  124737. do{
  124738. int iSamp; /* Index in aSample[] of test sample */
  124739. int n; /* Number of fields in test sample */
  124740. iTest = (iMin+iSample)/2;
  124741. iSamp = iTest / nField;
  124742. if( iSamp>0 ){
  124743. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  124744. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  124745. ** fields that is greater than the previous effective sample. */
  124746. for(n=(iTest % nField) + 1; n<nField; n++){
  124747. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  124748. }
  124749. }else{
  124750. n = iTest + 1;
  124751. }
  124752. pRec->nField = n;
  124753. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  124754. if( res<0 ){
  124755. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  124756. iMin = iTest+1;
  124757. }else if( res==0 && n<nField ){
  124758. iLower = aSample[iSamp].anLt[n-1];
  124759. iMin = iTest+1;
  124760. res = -1;
  124761. }else{
  124762. iSample = iTest;
  124763. iCol = n-1;
  124764. }
  124765. }while( res && iMin<iSample );
  124766. i = iSample / nField;
  124767. #ifdef SQLITE_DEBUG
  124768. /* The following assert statements check that the binary search code
  124769. ** above found the right answer. This block serves no purpose other
  124770. ** than to invoke the asserts. */
  124771. if( pParse->db->mallocFailed==0 ){
  124772. if( res==0 ){
  124773. /* If (res==0) is true, then pRec must be equal to sample i. */
  124774. assert( i<pIdx->nSample );
  124775. assert( iCol==nField-1 );
  124776. pRec->nField = nField;
  124777. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  124778. || pParse->db->mallocFailed
  124779. );
  124780. }else{
  124781. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  124782. ** all samples in the aSample[] array, pRec must be smaller than the
  124783. ** (iCol+1) field prefix of sample i. */
  124784. assert( i<=pIdx->nSample && i>=0 );
  124785. pRec->nField = iCol+1;
  124786. assert( i==pIdx->nSample
  124787. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  124788. || pParse->db->mallocFailed );
  124789. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  124790. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  124791. ** be greater than or equal to the (iCol) field prefix of sample i.
  124792. ** If (i>0), then pRec must also be greater than sample (i-1). */
  124793. if( iCol>0 ){
  124794. pRec->nField = iCol;
  124795. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  124796. || pParse->db->mallocFailed );
  124797. }
  124798. if( i>0 ){
  124799. pRec->nField = nField;
  124800. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  124801. || pParse->db->mallocFailed );
  124802. }
  124803. }
  124804. }
  124805. #endif /* ifdef SQLITE_DEBUG */
  124806. if( res==0 ){
  124807. /* Record pRec is equal to sample i */
  124808. assert( iCol==nField-1 );
  124809. aStat[0] = aSample[i].anLt[iCol];
  124810. aStat[1] = aSample[i].anEq[iCol];
  124811. }else{
  124812. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  124813. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  124814. ** is larger than all samples in the array. */
  124815. tRowcnt iUpper, iGap;
  124816. if( i>=pIdx->nSample ){
  124817. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  124818. }else{
  124819. iUpper = aSample[i].anLt[iCol];
  124820. }
  124821. if( iLower>=iUpper ){
  124822. iGap = 0;
  124823. }else{
  124824. iGap = iUpper - iLower;
  124825. }
  124826. if( roundUp ){
  124827. iGap = (iGap*2)/3;
  124828. }else{
  124829. iGap = iGap/3;
  124830. }
  124831. aStat[0] = iLower + iGap;
  124832. aStat[1] = pIdx->aAvgEq[nField-1];
  124833. }
  124834. /* Restore the pRec->nField value before returning. */
  124835. pRec->nField = nField;
  124836. return i;
  124837. }
  124838. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  124839. /*
  124840. ** If it is not NULL, pTerm is a term that provides an upper or lower
  124841. ** bound on a range scan. Without considering pTerm, it is estimated
  124842. ** that the scan will visit nNew rows. This function returns the number
  124843. ** estimated to be visited after taking pTerm into account.
  124844. **
  124845. ** If the user explicitly specified a likelihood() value for this term,
  124846. ** then the return value is the likelihood multiplied by the number of
  124847. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  124848. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  124849. */
  124850. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  124851. LogEst nRet = nNew;
  124852. if( pTerm ){
  124853. if( pTerm->truthProb<=0 ){
  124854. nRet += pTerm->truthProb;
  124855. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  124856. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  124857. }
  124858. }
  124859. return nRet;
  124860. }
  124861. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124862. /*
  124863. ** Return the affinity for a single column of an index.
  124864. */
  124865. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  124866. assert( iCol>=0 && iCol<pIdx->nColumn );
  124867. if( !pIdx->zColAff ){
  124868. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  124869. }
  124870. return pIdx->zColAff[iCol];
  124871. }
  124872. #endif
  124873. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124874. /*
  124875. ** This function is called to estimate the number of rows visited by a
  124876. ** range-scan on a skip-scan index. For example:
  124877. **
  124878. ** CREATE INDEX i1 ON t1(a, b, c);
  124879. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  124880. **
  124881. ** Value pLoop->nOut is currently set to the estimated number of rows
  124882. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  124883. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  124884. ** on the stat4 data for the index. this scan will be peformed multiple
  124885. ** times (once for each (a,b) combination that matches a=?) is dealt with
  124886. ** by the caller.
  124887. **
  124888. ** It does this by scanning through all stat4 samples, comparing values
  124889. ** extracted from pLower and pUpper with the corresponding column in each
  124890. ** sample. If L and U are the number of samples found to be less than or
  124891. ** equal to the values extracted from pLower and pUpper respectively, and
  124892. ** N is the total number of samples, the pLoop->nOut value is adjusted
  124893. ** as follows:
  124894. **
  124895. ** nOut = nOut * ( min(U - L, 1) / N )
  124896. **
  124897. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  124898. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  124899. ** U is set to N.
  124900. **
  124901. ** Normally, this function sets *pbDone to 1 before returning. However,
  124902. ** if no value can be extracted from either pLower or pUpper (and so the
  124903. ** estimate of the number of rows delivered remains unchanged), *pbDone
  124904. ** is left as is.
  124905. **
  124906. ** If an error occurs, an SQLite error code is returned. Otherwise,
  124907. ** SQLITE_OK.
  124908. */
  124909. static int whereRangeSkipScanEst(
  124910. Parse *pParse, /* Parsing & code generating context */
  124911. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  124912. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  124913. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  124914. int *pbDone /* Set to true if at least one expr. value extracted */
  124915. ){
  124916. Index *p = pLoop->u.btree.pIndex;
  124917. int nEq = pLoop->u.btree.nEq;
  124918. sqlite3 *db = pParse->db;
  124919. int nLower = -1;
  124920. int nUpper = p->nSample+1;
  124921. int rc = SQLITE_OK;
  124922. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  124923. CollSeq *pColl;
  124924. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  124925. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  124926. sqlite3_value *pVal = 0; /* Value extracted from record */
  124927. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  124928. if( pLower ){
  124929. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  124930. nLower = 0;
  124931. }
  124932. if( pUpper && rc==SQLITE_OK ){
  124933. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  124934. nUpper = p2 ? 0 : p->nSample;
  124935. }
  124936. if( p1 || p2 ){
  124937. int i;
  124938. int nDiff;
  124939. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  124940. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  124941. if( rc==SQLITE_OK && p1 ){
  124942. int res = sqlite3MemCompare(p1, pVal, pColl);
  124943. if( res>=0 ) nLower++;
  124944. }
  124945. if( rc==SQLITE_OK && p2 ){
  124946. int res = sqlite3MemCompare(p2, pVal, pColl);
  124947. if( res>=0 ) nUpper++;
  124948. }
  124949. }
  124950. nDiff = (nUpper - nLower);
  124951. if( nDiff<=0 ) nDiff = 1;
  124952. /* If there is both an upper and lower bound specified, and the
  124953. ** comparisons indicate that they are close together, use the fallback
  124954. ** method (assume that the scan visits 1/64 of the rows) for estimating
  124955. ** the number of rows visited. Otherwise, estimate the number of rows
  124956. ** using the method described in the header comment for this function. */
  124957. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  124958. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  124959. pLoop->nOut -= nAdjust;
  124960. *pbDone = 1;
  124961. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  124962. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  124963. }
  124964. }else{
  124965. assert( *pbDone==0 );
  124966. }
  124967. sqlite3ValueFree(p1);
  124968. sqlite3ValueFree(p2);
  124969. sqlite3ValueFree(pVal);
  124970. return rc;
  124971. }
  124972. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  124973. /*
  124974. ** This function is used to estimate the number of rows that will be visited
  124975. ** by scanning an index for a range of values. The range may have an upper
  124976. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  124977. ** and lower bounds are represented by pLower and pUpper respectively. For
  124978. ** example, assuming that index p is on t1(a):
  124979. **
  124980. ** ... FROM t1 WHERE a > ? AND a < ? ...
  124981. ** |_____| |_____|
  124982. ** | |
  124983. ** pLower pUpper
  124984. **
  124985. ** If either of the upper or lower bound is not present, then NULL is passed in
  124986. ** place of the corresponding WhereTerm.
  124987. **
  124988. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  124989. ** column subject to the range constraint. Or, equivalently, the number of
  124990. ** equality constraints optimized by the proposed index scan. For example,
  124991. ** assuming index p is on t1(a, b), and the SQL query is:
  124992. **
  124993. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  124994. **
  124995. ** then nEq is set to 1 (as the range restricted column, b, is the second
  124996. ** left-most column of the index). Or, if the query is:
  124997. **
  124998. ** ... FROM t1 WHERE a > ? AND a < ? ...
  124999. **
  125000. ** then nEq is set to 0.
  125001. **
  125002. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  125003. ** number of rows that the index scan is expected to visit without
  125004. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  125005. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  125006. ** to account for the range constraints pLower and pUpper.
  125007. **
  125008. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  125009. ** used, a single range inequality reduces the search space by a factor of 4.
  125010. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  125011. ** rows visited by a factor of 64.
  125012. */
  125013. static int whereRangeScanEst(
  125014. Parse *pParse, /* Parsing & code generating context */
  125015. WhereLoopBuilder *pBuilder,
  125016. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  125017. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  125018. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  125019. ){
  125020. int rc = SQLITE_OK;
  125021. int nOut = pLoop->nOut;
  125022. LogEst nNew;
  125023. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125024. Index *p = pLoop->u.btree.pIndex;
  125025. int nEq = pLoop->u.btree.nEq;
  125026. if( p->nSample>0 && nEq<p->nSampleCol ){
  125027. if( nEq==pBuilder->nRecValid ){
  125028. UnpackedRecord *pRec = pBuilder->pRec;
  125029. tRowcnt a[2];
  125030. int nBtm = pLoop->u.btree.nBtm;
  125031. int nTop = pLoop->u.btree.nTop;
  125032. /* Variable iLower will be set to the estimate of the number of rows in
  125033. ** the index that are less than the lower bound of the range query. The
  125034. ** lower bound being the concatenation of $P and $L, where $P is the
  125035. ** key-prefix formed by the nEq values matched against the nEq left-most
  125036. ** columns of the index, and $L is the value in pLower.
  125037. **
  125038. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  125039. ** is not a simple variable or literal value), the lower bound of the
  125040. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  125041. ** if $L is available, whereKeyStats() is called for both ($P) and
  125042. ** ($P:$L) and the larger of the two returned values is used.
  125043. **
  125044. ** Similarly, iUpper is to be set to the estimate of the number of rows
  125045. ** less than the upper bound of the range query. Where the upper bound
  125046. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  125047. ** of iUpper are requested of whereKeyStats() and the smaller used.
  125048. **
  125049. ** The number of rows between the two bounds is then just iUpper-iLower.
  125050. */
  125051. tRowcnt iLower; /* Rows less than the lower bound */
  125052. tRowcnt iUpper; /* Rows less than the upper bound */
  125053. int iLwrIdx = -2; /* aSample[] for the lower bound */
  125054. int iUprIdx = -1; /* aSample[] for the upper bound */
  125055. if( pRec ){
  125056. testcase( pRec->nField!=pBuilder->nRecValid );
  125057. pRec->nField = pBuilder->nRecValid;
  125058. }
  125059. /* Determine iLower and iUpper using ($P) only. */
  125060. if( nEq==0 ){
  125061. iLower = 0;
  125062. iUpper = p->nRowEst0;
  125063. }else{
  125064. /* Note: this call could be optimized away - since the same values must
  125065. ** have been requested when testing key $P in whereEqualScanEst(). */
  125066. whereKeyStats(pParse, p, pRec, 0, a);
  125067. iLower = a[0];
  125068. iUpper = a[0] + a[1];
  125069. }
  125070. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  125071. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  125072. assert( p->aSortOrder!=0 );
  125073. if( p->aSortOrder[nEq] ){
  125074. /* The roles of pLower and pUpper are swapped for a DESC index */
  125075. SWAP(WhereTerm*, pLower, pUpper);
  125076. SWAP(int, nBtm, nTop);
  125077. }
  125078. /* If possible, improve on the iLower estimate using ($P:$L). */
  125079. if( pLower ){
  125080. int n; /* Values extracted from pExpr */
  125081. Expr *pExpr = pLower->pExpr->pRight;
  125082. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  125083. if( rc==SQLITE_OK && n ){
  125084. tRowcnt iNew;
  125085. u16 mask = WO_GT|WO_LE;
  125086. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  125087. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  125088. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  125089. if( iNew>iLower ) iLower = iNew;
  125090. nOut--;
  125091. pLower = 0;
  125092. }
  125093. }
  125094. /* If possible, improve on the iUpper estimate using ($P:$U). */
  125095. if( pUpper ){
  125096. int n; /* Values extracted from pExpr */
  125097. Expr *pExpr = pUpper->pExpr->pRight;
  125098. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  125099. if( rc==SQLITE_OK && n ){
  125100. tRowcnt iNew;
  125101. u16 mask = WO_GT|WO_LE;
  125102. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  125103. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  125104. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  125105. if( iNew<iUpper ) iUpper = iNew;
  125106. nOut--;
  125107. pUpper = 0;
  125108. }
  125109. }
  125110. pBuilder->pRec = pRec;
  125111. if( rc==SQLITE_OK ){
  125112. if( iUpper>iLower ){
  125113. nNew = sqlite3LogEst(iUpper - iLower);
  125114. /* TUNING: If both iUpper and iLower are derived from the same
  125115. ** sample, then assume they are 4x more selective. This brings
  125116. ** the estimated selectivity more in line with what it would be
  125117. ** if estimated without the use of STAT3/4 tables. */
  125118. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  125119. }else{
  125120. nNew = 10; assert( 10==sqlite3LogEst(2) );
  125121. }
  125122. if( nNew<nOut ){
  125123. nOut = nNew;
  125124. }
  125125. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  125126. (u32)iLower, (u32)iUpper, nOut));
  125127. }
  125128. }else{
  125129. int bDone = 0;
  125130. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  125131. if( bDone ) return rc;
  125132. }
  125133. }
  125134. #else
  125135. UNUSED_PARAMETER(pParse);
  125136. UNUSED_PARAMETER(pBuilder);
  125137. assert( pLower || pUpper );
  125138. #endif
  125139. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  125140. nNew = whereRangeAdjust(pLower, nOut);
  125141. nNew = whereRangeAdjust(pUpper, nNew);
  125142. /* TUNING: If there is both an upper and lower limit and neither limit
  125143. ** has an application-defined likelihood(), assume the range is
  125144. ** reduced by an additional 75%. This means that, by default, an open-ended
  125145. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  125146. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  125147. ** match 1/64 of the index. */
  125148. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  125149. nNew -= 20;
  125150. }
  125151. nOut -= (pLower!=0) + (pUpper!=0);
  125152. if( nNew<10 ) nNew = 10;
  125153. if( nNew<nOut ) nOut = nNew;
  125154. #if defined(WHERETRACE_ENABLED)
  125155. if( pLoop->nOut>nOut ){
  125156. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  125157. pLoop->nOut, nOut));
  125158. }
  125159. #endif
  125160. pLoop->nOut = (LogEst)nOut;
  125161. return rc;
  125162. }
  125163. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125164. /*
  125165. ** Estimate the number of rows that will be returned based on
  125166. ** an equality constraint x=VALUE and where that VALUE occurs in
  125167. ** the histogram data. This only works when x is the left-most
  125168. ** column of an index and sqlite_stat3 histogram data is available
  125169. ** for that index. When pExpr==NULL that means the constraint is
  125170. ** "x IS NULL" instead of "x=VALUE".
  125171. **
  125172. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  125173. ** If unable to make an estimate, leave *pnRow unchanged and return
  125174. ** non-zero.
  125175. **
  125176. ** This routine can fail if it is unable to load a collating sequence
  125177. ** required for string comparison, or if unable to allocate memory
  125178. ** for a UTF conversion required for comparison. The error is stored
  125179. ** in the pParse structure.
  125180. */
  125181. static int whereEqualScanEst(
  125182. Parse *pParse, /* Parsing & code generating context */
  125183. WhereLoopBuilder *pBuilder,
  125184. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  125185. tRowcnt *pnRow /* Write the revised row estimate here */
  125186. ){
  125187. Index *p = pBuilder->pNew->u.btree.pIndex;
  125188. int nEq = pBuilder->pNew->u.btree.nEq;
  125189. UnpackedRecord *pRec = pBuilder->pRec;
  125190. int rc; /* Subfunction return code */
  125191. tRowcnt a[2]; /* Statistics */
  125192. int bOk;
  125193. assert( nEq>=1 );
  125194. assert( nEq<=p->nColumn );
  125195. assert( p->aSample!=0 );
  125196. assert( p->nSample>0 );
  125197. assert( pBuilder->nRecValid<nEq );
  125198. /* If values are not available for all fields of the index to the left
  125199. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  125200. if( pBuilder->nRecValid<(nEq-1) ){
  125201. return SQLITE_NOTFOUND;
  125202. }
  125203. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  125204. ** below would return the same value. */
  125205. if( nEq>=p->nColumn ){
  125206. *pnRow = 1;
  125207. return SQLITE_OK;
  125208. }
  125209. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  125210. pBuilder->pRec = pRec;
  125211. if( rc!=SQLITE_OK ) return rc;
  125212. if( bOk==0 ) return SQLITE_NOTFOUND;
  125213. pBuilder->nRecValid = nEq;
  125214. whereKeyStats(pParse, p, pRec, 0, a);
  125215. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  125216. p->zName, nEq-1, (int)a[1]));
  125217. *pnRow = a[1];
  125218. return rc;
  125219. }
  125220. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  125221. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125222. /*
  125223. ** Estimate the number of rows that will be returned based on
  125224. ** an IN constraint where the right-hand side of the IN operator
  125225. ** is a list of values. Example:
  125226. **
  125227. ** WHERE x IN (1,2,3,4)
  125228. **
  125229. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  125230. ** If unable to make an estimate, leave *pnRow unchanged and return
  125231. ** non-zero.
  125232. **
  125233. ** This routine can fail if it is unable to load a collating sequence
  125234. ** required for string comparison, or if unable to allocate memory
  125235. ** for a UTF conversion required for comparison. The error is stored
  125236. ** in the pParse structure.
  125237. */
  125238. static int whereInScanEst(
  125239. Parse *pParse, /* Parsing & code generating context */
  125240. WhereLoopBuilder *pBuilder,
  125241. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  125242. tRowcnt *pnRow /* Write the revised row estimate here */
  125243. ){
  125244. Index *p = pBuilder->pNew->u.btree.pIndex;
  125245. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  125246. int nRecValid = pBuilder->nRecValid;
  125247. int rc = SQLITE_OK; /* Subfunction return code */
  125248. tRowcnt nEst; /* Number of rows for a single term */
  125249. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  125250. int i; /* Loop counter */
  125251. assert( p->aSample!=0 );
  125252. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  125253. nEst = nRow0;
  125254. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  125255. nRowEst += nEst;
  125256. pBuilder->nRecValid = nRecValid;
  125257. }
  125258. if( rc==SQLITE_OK ){
  125259. if( nRowEst > nRow0 ) nRowEst = nRow0;
  125260. *pnRow = nRowEst;
  125261. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  125262. }
  125263. assert( pBuilder->nRecValid==nRecValid );
  125264. return rc;
  125265. }
  125266. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  125267. #ifdef WHERETRACE_ENABLED
  125268. /*
  125269. ** Print the content of a WhereTerm object
  125270. */
  125271. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  125272. if( pTerm==0 ){
  125273. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  125274. }else{
  125275. char zType[4];
  125276. char zLeft[50];
  125277. memcpy(zType, "...", 4);
  125278. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  125279. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  125280. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  125281. if( pTerm->eOperator & WO_SINGLE ){
  125282. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  125283. pTerm->leftCursor, pTerm->u.leftColumn);
  125284. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  125285. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  125286. pTerm->u.pOrInfo->indexable);
  125287. }else{
  125288. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  125289. }
  125290. sqlite3DebugPrintf(
  125291. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  125292. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  125293. pTerm->eOperator, pTerm->wtFlags);
  125294. if( pTerm->iField ){
  125295. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  125296. }else{
  125297. sqlite3DebugPrintf("\n");
  125298. }
  125299. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  125300. }
  125301. }
  125302. #endif
  125303. #ifdef WHERETRACE_ENABLED
  125304. /*
  125305. ** Show the complete content of a WhereClause
  125306. */
  125307. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  125308. int i;
  125309. for(i=0; i<pWC->nTerm; i++){
  125310. whereTermPrint(&pWC->a[i], i);
  125311. }
  125312. }
  125313. #endif
  125314. #ifdef WHERETRACE_ENABLED
  125315. /*
  125316. ** Print a WhereLoop object for debugging purposes
  125317. */
  125318. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  125319. WhereInfo *pWInfo = pWC->pWInfo;
  125320. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  125321. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  125322. Table *pTab = pItem->pTab;
  125323. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  125324. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  125325. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  125326. sqlite3DebugPrintf(" %12s",
  125327. pItem->zAlias ? pItem->zAlias : pTab->zName);
  125328. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  125329. const char *zName;
  125330. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  125331. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  125332. int i = sqlite3Strlen30(zName) - 1;
  125333. while( zName[i]!='_' ) i--;
  125334. zName += i;
  125335. }
  125336. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  125337. }else{
  125338. sqlite3DebugPrintf("%20s","");
  125339. }
  125340. }else{
  125341. char *z;
  125342. if( p->u.vtab.idxStr ){
  125343. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  125344. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  125345. }else{
  125346. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  125347. }
  125348. sqlite3DebugPrintf(" %-19s", z);
  125349. sqlite3_free(z);
  125350. }
  125351. if( p->wsFlags & WHERE_SKIPSCAN ){
  125352. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  125353. }else{
  125354. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  125355. }
  125356. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  125357. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  125358. int i;
  125359. for(i=0; i<p->nLTerm; i++){
  125360. whereTermPrint(p->aLTerm[i], i);
  125361. }
  125362. }
  125363. }
  125364. #endif
  125365. /*
  125366. ** Convert bulk memory into a valid WhereLoop that can be passed
  125367. ** to whereLoopClear harmlessly.
  125368. */
  125369. static void whereLoopInit(WhereLoop *p){
  125370. p->aLTerm = p->aLTermSpace;
  125371. p->nLTerm = 0;
  125372. p->nLSlot = ArraySize(p->aLTermSpace);
  125373. p->wsFlags = 0;
  125374. }
  125375. /*
  125376. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  125377. */
  125378. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  125379. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  125380. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  125381. sqlite3_free(p->u.vtab.idxStr);
  125382. p->u.vtab.needFree = 0;
  125383. p->u.vtab.idxStr = 0;
  125384. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  125385. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  125386. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  125387. p->u.btree.pIndex = 0;
  125388. }
  125389. }
  125390. }
  125391. /*
  125392. ** Deallocate internal memory used by a WhereLoop object
  125393. */
  125394. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  125395. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  125396. whereLoopClearUnion(db, p);
  125397. whereLoopInit(p);
  125398. }
  125399. /*
  125400. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  125401. */
  125402. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  125403. WhereTerm **paNew;
  125404. if( p->nLSlot>=n ) return SQLITE_OK;
  125405. n = (n+7)&~7;
  125406. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  125407. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  125408. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  125409. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  125410. p->aLTerm = paNew;
  125411. p->nLSlot = n;
  125412. return SQLITE_OK;
  125413. }
  125414. /*
  125415. ** Transfer content from the second pLoop into the first.
  125416. */
  125417. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  125418. whereLoopClearUnion(db, pTo);
  125419. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  125420. memset(&pTo->u, 0, sizeof(pTo->u));
  125421. return SQLITE_NOMEM_BKPT;
  125422. }
  125423. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  125424. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  125425. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  125426. pFrom->u.vtab.needFree = 0;
  125427. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  125428. pFrom->u.btree.pIndex = 0;
  125429. }
  125430. return SQLITE_OK;
  125431. }
  125432. /*
  125433. ** Delete a WhereLoop object
  125434. */
  125435. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  125436. whereLoopClear(db, p);
  125437. sqlite3DbFreeNN(db, p);
  125438. }
  125439. /*
  125440. ** Free a WhereInfo structure
  125441. */
  125442. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  125443. if( ALWAYS(pWInfo) ){
  125444. int i;
  125445. for(i=0; i<pWInfo->nLevel; i++){
  125446. WhereLevel *pLevel = &pWInfo->a[i];
  125447. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  125448. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  125449. }
  125450. }
  125451. sqlite3WhereClauseClear(&pWInfo->sWC);
  125452. while( pWInfo->pLoops ){
  125453. WhereLoop *p = pWInfo->pLoops;
  125454. pWInfo->pLoops = p->pNextLoop;
  125455. whereLoopDelete(db, p);
  125456. }
  125457. sqlite3DbFreeNN(db, pWInfo);
  125458. }
  125459. }
  125460. /*
  125461. ** Return TRUE if all of the following are true:
  125462. **
  125463. ** (1) X has the same or lower cost that Y
  125464. ** (2) X uses fewer WHERE clause terms than Y
  125465. ** (3) Every WHERE clause term used by X is also used by Y
  125466. ** (4) X skips at least as many columns as Y
  125467. ** (5) If X is a covering index, than Y is too
  125468. **
  125469. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  125470. ** If X is a proper subset of Y then Y is a better choice and ought
  125471. ** to have a lower cost. This routine returns TRUE when that cost
  125472. ** relationship is inverted and needs to be adjusted. Constraint (4)
  125473. ** was added because if X uses skip-scan less than Y it still might
  125474. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  125475. ** was added because a covering index probably deserves to have a lower cost
  125476. ** than a non-covering index even if it is a proper subset.
  125477. */
  125478. static int whereLoopCheaperProperSubset(
  125479. const WhereLoop *pX, /* First WhereLoop to compare */
  125480. const WhereLoop *pY /* Compare against this WhereLoop */
  125481. ){
  125482. int i, j;
  125483. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  125484. return 0; /* X is not a subset of Y */
  125485. }
  125486. if( pY->nSkip > pX->nSkip ) return 0;
  125487. if( pX->rRun >= pY->rRun ){
  125488. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  125489. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  125490. }
  125491. for(i=pX->nLTerm-1; i>=0; i--){
  125492. if( pX->aLTerm[i]==0 ) continue;
  125493. for(j=pY->nLTerm-1; j>=0; j--){
  125494. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  125495. }
  125496. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  125497. }
  125498. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  125499. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  125500. return 0; /* Constraint (5) */
  125501. }
  125502. return 1; /* All conditions meet */
  125503. }
  125504. /*
  125505. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  125506. ** that:
  125507. **
  125508. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  125509. ** subset of pTemplate
  125510. **
  125511. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  125512. ** is a proper subset.
  125513. **
  125514. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  125515. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  125516. ** also used by Y.
  125517. */
  125518. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  125519. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  125520. for(; p; p=p->pNextLoop){
  125521. if( p->iTab!=pTemplate->iTab ) continue;
  125522. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  125523. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  125524. /* Adjust pTemplate cost downward so that it is cheaper than its
  125525. ** subset p. */
  125526. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  125527. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  125528. pTemplate->rRun = p->rRun;
  125529. pTemplate->nOut = p->nOut - 1;
  125530. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  125531. /* Adjust pTemplate cost upward so that it is costlier than p since
  125532. ** pTemplate is a proper subset of p */
  125533. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  125534. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  125535. pTemplate->rRun = p->rRun;
  125536. pTemplate->nOut = p->nOut + 1;
  125537. }
  125538. }
  125539. }
  125540. /*
  125541. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  125542. ** replaced by pTemplate.
  125543. **
  125544. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  125545. ** In other words if pTemplate ought to be dropped from further consideration.
  125546. **
  125547. ** If pX is a WhereLoop that pTemplate can replace, then return the
  125548. ** link that points to pX.
  125549. **
  125550. ** If pTemplate cannot replace any existing element of the list but needs
  125551. ** to be added to the list as a new entry, then return a pointer to the
  125552. ** tail of the list.
  125553. */
  125554. static WhereLoop **whereLoopFindLesser(
  125555. WhereLoop **ppPrev,
  125556. const WhereLoop *pTemplate
  125557. ){
  125558. WhereLoop *p;
  125559. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  125560. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  125561. /* If either the iTab or iSortIdx values for two WhereLoop are different
  125562. ** then those WhereLoops need to be considered separately. Neither is
  125563. ** a candidate to replace the other. */
  125564. continue;
  125565. }
  125566. /* In the current implementation, the rSetup value is either zero
  125567. ** or the cost of building an automatic index (NlogN) and the NlogN
  125568. ** is the same for compatible WhereLoops. */
  125569. assert( p->rSetup==0 || pTemplate->rSetup==0
  125570. || p->rSetup==pTemplate->rSetup );
  125571. /* whereLoopAddBtree() always generates and inserts the automatic index
  125572. ** case first. Hence compatible candidate WhereLoops never have a larger
  125573. ** rSetup. Call this SETUP-INVARIANT */
  125574. assert( p->rSetup>=pTemplate->rSetup );
  125575. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  125576. ** UNIQUE constraint) with one or more == constraints is better
  125577. ** than an automatic index. Unless it is a skip-scan. */
  125578. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  125579. && (pTemplate->nSkip)==0
  125580. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  125581. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  125582. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  125583. ){
  125584. break;
  125585. }
  125586. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  125587. ** discarded. WhereLoop p is better if:
  125588. ** (1) p has no more dependencies than pTemplate, and
  125589. ** (2) p has an equal or lower cost than pTemplate
  125590. */
  125591. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  125592. && p->rSetup<=pTemplate->rSetup /* (2a) */
  125593. && p->rRun<=pTemplate->rRun /* (2b) */
  125594. && p->nOut<=pTemplate->nOut /* (2c) */
  125595. ){
  125596. return 0; /* Discard pTemplate */
  125597. }
  125598. /* If pTemplate is always better than p, then cause p to be overwritten
  125599. ** with pTemplate. pTemplate is better than p if:
  125600. ** (1) pTemplate has no more dependences than p, and
  125601. ** (2) pTemplate has an equal or lower cost than p.
  125602. */
  125603. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  125604. && p->rRun>=pTemplate->rRun /* (2a) */
  125605. && p->nOut>=pTemplate->nOut /* (2b) */
  125606. ){
  125607. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  125608. break; /* Cause p to be overwritten by pTemplate */
  125609. }
  125610. }
  125611. return ppPrev;
  125612. }
  125613. /*
  125614. ** Insert or replace a WhereLoop entry using the template supplied.
  125615. **
  125616. ** An existing WhereLoop entry might be overwritten if the new template
  125617. ** is better and has fewer dependencies. Or the template will be ignored
  125618. ** and no insert will occur if an existing WhereLoop is faster and has
  125619. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  125620. ** added based on the template.
  125621. **
  125622. ** If pBuilder->pOrSet is not NULL then we care about only the
  125623. ** prerequisites and rRun and nOut costs of the N best loops. That
  125624. ** information is gathered in the pBuilder->pOrSet object. This special
  125625. ** processing mode is used only for OR clause processing.
  125626. **
  125627. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  125628. ** still might overwrite similar loops with the new template if the
  125629. ** new template is better. Loops may be overwritten if the following
  125630. ** conditions are met:
  125631. **
  125632. ** (1) They have the same iTab.
  125633. ** (2) They have the same iSortIdx.
  125634. ** (3) The template has same or fewer dependencies than the current loop
  125635. ** (4) The template has the same or lower cost than the current loop
  125636. */
  125637. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  125638. WhereLoop **ppPrev, *p;
  125639. WhereInfo *pWInfo = pBuilder->pWInfo;
  125640. sqlite3 *db = pWInfo->pParse->db;
  125641. int rc;
  125642. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  125643. ** and prereqs.
  125644. */
  125645. if( pBuilder->pOrSet!=0 ){
  125646. if( pTemplate->nLTerm ){
  125647. #if WHERETRACE_ENABLED
  125648. u16 n = pBuilder->pOrSet->n;
  125649. int x =
  125650. #endif
  125651. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  125652. pTemplate->nOut);
  125653. #if WHERETRACE_ENABLED /* 0x8 */
  125654. if( sqlite3WhereTrace & 0x8 ){
  125655. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  125656. whereLoopPrint(pTemplate, pBuilder->pWC);
  125657. }
  125658. #endif
  125659. }
  125660. return SQLITE_OK;
  125661. }
  125662. /* Look for an existing WhereLoop to replace with pTemplate
  125663. */
  125664. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  125665. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  125666. if( ppPrev==0 ){
  125667. /* There already exists a WhereLoop on the list that is better
  125668. ** than pTemplate, so just ignore pTemplate */
  125669. #if WHERETRACE_ENABLED /* 0x8 */
  125670. if( sqlite3WhereTrace & 0x8 ){
  125671. sqlite3DebugPrintf(" skip: ");
  125672. whereLoopPrint(pTemplate, pBuilder->pWC);
  125673. }
  125674. #endif
  125675. return SQLITE_OK;
  125676. }else{
  125677. p = *ppPrev;
  125678. }
  125679. /* If we reach this point it means that either p[] should be overwritten
  125680. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  125681. ** WhereLoop and insert it.
  125682. */
  125683. #if WHERETRACE_ENABLED /* 0x8 */
  125684. if( sqlite3WhereTrace & 0x8 ){
  125685. if( p!=0 ){
  125686. sqlite3DebugPrintf("replace: ");
  125687. whereLoopPrint(p, pBuilder->pWC);
  125688. sqlite3DebugPrintf(" with: ");
  125689. }else{
  125690. sqlite3DebugPrintf(" add: ");
  125691. }
  125692. whereLoopPrint(pTemplate, pBuilder->pWC);
  125693. }
  125694. #endif
  125695. if( p==0 ){
  125696. /* Allocate a new WhereLoop to add to the end of the list */
  125697. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  125698. if( p==0 ) return SQLITE_NOMEM_BKPT;
  125699. whereLoopInit(p);
  125700. p->pNextLoop = 0;
  125701. }else{
  125702. /* We will be overwriting WhereLoop p[]. But before we do, first
  125703. ** go through the rest of the list and delete any other entries besides
  125704. ** p[] that are also supplated by pTemplate */
  125705. WhereLoop **ppTail = &p->pNextLoop;
  125706. WhereLoop *pToDel;
  125707. while( *ppTail ){
  125708. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  125709. if( ppTail==0 ) break;
  125710. pToDel = *ppTail;
  125711. if( pToDel==0 ) break;
  125712. *ppTail = pToDel->pNextLoop;
  125713. #if WHERETRACE_ENABLED /* 0x8 */
  125714. if( sqlite3WhereTrace & 0x8 ){
  125715. sqlite3DebugPrintf(" delete: ");
  125716. whereLoopPrint(pToDel, pBuilder->pWC);
  125717. }
  125718. #endif
  125719. whereLoopDelete(db, pToDel);
  125720. }
  125721. }
  125722. rc = whereLoopXfer(db, p, pTemplate);
  125723. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  125724. Index *pIndex = p->u.btree.pIndex;
  125725. if( pIndex && pIndex->tnum==0 ){
  125726. p->u.btree.pIndex = 0;
  125727. }
  125728. }
  125729. return rc;
  125730. }
  125731. /*
  125732. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  125733. ** WHERE clause that reference the loop but which are not used by an
  125734. ** index.
  125735. *
  125736. ** For every WHERE clause term that is not used by the index
  125737. ** and which has a truth probability assigned by one of the likelihood(),
  125738. ** likely(), or unlikely() SQL functions, reduce the estimated number
  125739. ** of output rows by the probability specified.
  125740. **
  125741. ** TUNING: For every WHERE clause term that is not used by the index
  125742. ** and which does not have an assigned truth probability, heuristics
  125743. ** described below are used to try to estimate the truth probability.
  125744. ** TODO --> Perhaps this is something that could be improved by better
  125745. ** table statistics.
  125746. **
  125747. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  125748. ** value corresponds to -1 in LogEst notation, so this means decrement
  125749. ** the WhereLoop.nOut field for every such WHERE clause term.
  125750. **
  125751. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  125752. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  125753. ** final output row estimate is no greater than 1/4 of the total number
  125754. ** of rows in the table. In other words, assume that x==EXPR will filter
  125755. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  125756. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  125757. ** on the "x" column and so in that case only cap the output row estimate
  125758. ** at 1/2 instead of 1/4.
  125759. */
  125760. static void whereLoopOutputAdjust(
  125761. WhereClause *pWC, /* The WHERE clause */
  125762. WhereLoop *pLoop, /* The loop to adjust downward */
  125763. LogEst nRow /* Number of rows in the entire table */
  125764. ){
  125765. WhereTerm *pTerm, *pX;
  125766. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  125767. int i, j, k;
  125768. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  125769. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  125770. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  125771. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  125772. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  125773. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  125774. for(j=pLoop->nLTerm-1; j>=0; j--){
  125775. pX = pLoop->aLTerm[j];
  125776. if( pX==0 ) continue;
  125777. if( pX==pTerm ) break;
  125778. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  125779. }
  125780. if( j<0 ){
  125781. if( pTerm->truthProb<=0 ){
  125782. /* If a truth probability is specified using the likelihood() hints,
  125783. ** then use the probability provided by the application. */
  125784. pLoop->nOut += pTerm->truthProb;
  125785. }else{
  125786. /* In the absence of explicit truth probabilities, use heuristics to
  125787. ** guess a reasonable truth probability. */
  125788. pLoop->nOut--;
  125789. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  125790. Expr *pRight = pTerm->pExpr->pRight;
  125791. testcase( pTerm->pExpr->op==TK_IS );
  125792. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  125793. k = 10;
  125794. }else{
  125795. k = 20;
  125796. }
  125797. if( iReduce<k ) iReduce = k;
  125798. }
  125799. }
  125800. }
  125801. }
  125802. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  125803. }
  125804. /*
  125805. ** Term pTerm is a vector range comparison operation. The first comparison
  125806. ** in the vector can be optimized using column nEq of the index. This
  125807. ** function returns the total number of vector elements that can be used
  125808. ** as part of the range comparison.
  125809. **
  125810. ** For example, if the query is:
  125811. **
  125812. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  125813. **
  125814. ** and the index:
  125815. **
  125816. ** CREATE INDEX ... ON (a, b, c, d, e)
  125817. **
  125818. ** then this function would be invoked with nEq=1. The value returned in
  125819. ** this case is 3.
  125820. */
  125821. static int whereRangeVectorLen(
  125822. Parse *pParse, /* Parsing context */
  125823. int iCur, /* Cursor open on pIdx */
  125824. Index *pIdx, /* The index to be used for a inequality constraint */
  125825. int nEq, /* Number of prior equality constraints on same index */
  125826. WhereTerm *pTerm /* The vector inequality constraint */
  125827. ){
  125828. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  125829. int i;
  125830. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  125831. for(i=1; i<nCmp; i++){
  125832. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  125833. ** of the index. If not, exit the loop. */
  125834. char aff; /* Comparison affinity */
  125835. char idxaff = 0; /* Indexed columns affinity */
  125836. CollSeq *pColl; /* Comparison collation sequence */
  125837. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  125838. Expr *pRhs = pTerm->pExpr->pRight;
  125839. if( pRhs->flags & EP_xIsSelect ){
  125840. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  125841. }else{
  125842. pRhs = pRhs->x.pList->a[i].pExpr;
  125843. }
  125844. /* Check that the LHS of the comparison is a column reference to
  125845. ** the right column of the right source table. And that the sort
  125846. ** order of the index column is the same as the sort order of the
  125847. ** leftmost index column. */
  125848. if( pLhs->op!=TK_COLUMN
  125849. || pLhs->iTable!=iCur
  125850. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  125851. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  125852. ){
  125853. break;
  125854. }
  125855. testcase( pLhs->iColumn==XN_ROWID );
  125856. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  125857. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  125858. if( aff!=idxaff ) break;
  125859. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  125860. if( pColl==0 ) break;
  125861. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  125862. }
  125863. return i;
  125864. }
  125865. /*
  125866. ** Adjust the cost C by the costMult facter T. This only occurs if
  125867. ** compiled with -DSQLITE_ENABLE_COSTMULT
  125868. */
  125869. #ifdef SQLITE_ENABLE_COSTMULT
  125870. # define ApplyCostMultiplier(C,T) C += T
  125871. #else
  125872. # define ApplyCostMultiplier(C,T)
  125873. #endif
  125874. /*
  125875. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  125876. ** index pIndex. Try to match one more.
  125877. **
  125878. ** When this function is called, pBuilder->pNew->nOut contains the
  125879. ** number of rows expected to be visited by filtering using the nEq
  125880. ** terms only. If it is modified, this value is restored before this
  125881. ** function returns.
  125882. **
  125883. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  125884. ** INTEGER PRIMARY KEY.
  125885. */
  125886. static int whereLoopAddBtreeIndex(
  125887. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  125888. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  125889. Index *pProbe, /* An index on pSrc */
  125890. LogEst nInMul /* log(Number of iterations due to IN) */
  125891. ){
  125892. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  125893. Parse *pParse = pWInfo->pParse; /* Parsing context */
  125894. sqlite3 *db = pParse->db; /* Database connection malloc context */
  125895. WhereLoop *pNew; /* Template WhereLoop under construction */
  125896. WhereTerm *pTerm; /* A WhereTerm under consideration */
  125897. int opMask; /* Valid operators for constraints */
  125898. WhereScan scan; /* Iterator for WHERE terms */
  125899. Bitmask saved_prereq; /* Original value of pNew->prereq */
  125900. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  125901. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  125902. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  125903. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  125904. u16 saved_nSkip; /* Original value of pNew->nSkip */
  125905. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  125906. LogEst saved_nOut; /* Original value of pNew->nOut */
  125907. int rc = SQLITE_OK; /* Return code */
  125908. LogEst rSize; /* Number of rows in the table */
  125909. LogEst rLogSize; /* Logarithm of table size */
  125910. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  125911. pNew = pBuilder->pNew;
  125912. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  125913. WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
  125914. pProbe->zName, pNew->u.btree.nEq));
  125915. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  125916. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  125917. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  125918. opMask = WO_LT|WO_LE;
  125919. }else{
  125920. assert( pNew->u.btree.nBtm==0 );
  125921. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  125922. }
  125923. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  125924. assert( pNew->u.btree.nEq<pProbe->nColumn );
  125925. saved_nEq = pNew->u.btree.nEq;
  125926. saved_nBtm = pNew->u.btree.nBtm;
  125927. saved_nTop = pNew->u.btree.nTop;
  125928. saved_nSkip = pNew->nSkip;
  125929. saved_nLTerm = pNew->nLTerm;
  125930. saved_wsFlags = pNew->wsFlags;
  125931. saved_prereq = pNew->prereq;
  125932. saved_nOut = pNew->nOut;
  125933. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  125934. opMask, pProbe);
  125935. pNew->rSetup = 0;
  125936. rSize = pProbe->aiRowLogEst[0];
  125937. rLogSize = estLog(rSize);
  125938. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  125939. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  125940. LogEst rCostIdx;
  125941. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  125942. int nIn = 0;
  125943. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125944. int nRecValid = pBuilder->nRecValid;
  125945. #endif
  125946. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  125947. && indexColumnNotNull(pProbe, saved_nEq)
  125948. ){
  125949. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  125950. }
  125951. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  125952. /* Do not allow the upper bound of a LIKE optimization range constraint
  125953. ** to mix with a lower range bound from some other source */
  125954. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  125955. /* Do not allow IS constraints from the WHERE clause to be used by the
  125956. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  125957. ** allowed */
  125958. if( (pSrc->fg.jointype & JT_LEFT)!=0
  125959. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  125960. && (eOp & (WO_IS|WO_ISNULL))!=0
  125961. ){
  125962. testcase( eOp & WO_IS );
  125963. testcase( eOp & WO_ISNULL );
  125964. continue;
  125965. }
  125966. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  125967. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  125968. }else{
  125969. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  125970. }
  125971. pNew->wsFlags = saved_wsFlags;
  125972. pNew->u.btree.nEq = saved_nEq;
  125973. pNew->u.btree.nBtm = saved_nBtm;
  125974. pNew->u.btree.nTop = saved_nTop;
  125975. pNew->nLTerm = saved_nLTerm;
  125976. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  125977. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  125978. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  125979. assert( nInMul==0
  125980. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  125981. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  125982. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  125983. );
  125984. if( eOp & WO_IN ){
  125985. Expr *pExpr = pTerm->pExpr;
  125986. pNew->wsFlags |= WHERE_COLUMN_IN;
  125987. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  125988. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  125989. int i;
  125990. nIn = 46; assert( 46==sqlite3LogEst(25) );
  125991. /* The expression may actually be of the form (x, y) IN (SELECT...).
  125992. ** In this case there is a separate term for each of (x) and (y).
  125993. ** However, the nIn multiplier should only be applied once, not once
  125994. ** for each such term. The following loop checks that pTerm is the
  125995. ** first such term in use, and sets nIn back to 0 if it is not. */
  125996. for(i=0; i<pNew->nLTerm-1; i++){
  125997. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  125998. }
  125999. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  126000. /* "x IN (value, value, ...)" */
  126001. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  126002. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  126003. ** changes "x IN (?)" into "x=?". */
  126004. }
  126005. }else if( eOp & (WO_EQ|WO_IS) ){
  126006. int iCol = pProbe->aiColumn[saved_nEq];
  126007. pNew->wsFlags |= WHERE_COLUMN_EQ;
  126008. assert( saved_nEq==pNew->u.btree.nEq );
  126009. if( iCol==XN_ROWID
  126010. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  126011. ){
  126012. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  126013. pNew->wsFlags |= WHERE_UNQ_WANTED;
  126014. }else{
  126015. pNew->wsFlags |= WHERE_ONEROW;
  126016. }
  126017. }
  126018. }else if( eOp & WO_ISNULL ){
  126019. pNew->wsFlags |= WHERE_COLUMN_NULL;
  126020. }else if( eOp & (WO_GT|WO_GE) ){
  126021. testcase( eOp & WO_GT );
  126022. testcase( eOp & WO_GE );
  126023. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  126024. pNew->u.btree.nBtm = whereRangeVectorLen(
  126025. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  126026. );
  126027. pBtm = pTerm;
  126028. pTop = 0;
  126029. if( pTerm->wtFlags & TERM_LIKEOPT ){
  126030. /* Range contraints that come from the LIKE optimization are
  126031. ** always used in pairs. */
  126032. pTop = &pTerm[1];
  126033. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  126034. assert( pTop->wtFlags & TERM_LIKEOPT );
  126035. assert( pTop->eOperator==WO_LT );
  126036. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  126037. pNew->aLTerm[pNew->nLTerm++] = pTop;
  126038. pNew->wsFlags |= WHERE_TOP_LIMIT;
  126039. pNew->u.btree.nTop = 1;
  126040. }
  126041. }else{
  126042. assert( eOp & (WO_LT|WO_LE) );
  126043. testcase( eOp & WO_LT );
  126044. testcase( eOp & WO_LE );
  126045. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  126046. pNew->u.btree.nTop = whereRangeVectorLen(
  126047. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  126048. );
  126049. pTop = pTerm;
  126050. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  126051. pNew->aLTerm[pNew->nLTerm-2] : 0;
  126052. }
  126053. /* At this point pNew->nOut is set to the number of rows expected to
  126054. ** be visited by the index scan before considering term pTerm, or the
  126055. ** values of nIn and nInMul. In other words, assuming that all
  126056. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  126057. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  126058. assert( pNew->nOut==saved_nOut );
  126059. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  126060. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  126061. ** data, using some other estimate. */
  126062. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  126063. }else{
  126064. int nEq = ++pNew->u.btree.nEq;
  126065. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  126066. assert( pNew->nOut==saved_nOut );
  126067. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  126068. assert( (eOp & WO_IN) || nIn==0 );
  126069. testcase( eOp & WO_IN );
  126070. pNew->nOut += pTerm->truthProb;
  126071. pNew->nOut -= nIn;
  126072. }else{
  126073. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126074. tRowcnt nOut = 0;
  126075. if( nInMul==0
  126076. && pProbe->nSample
  126077. && pNew->u.btree.nEq<=pProbe->nSampleCol
  126078. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  126079. ){
  126080. Expr *pExpr = pTerm->pExpr;
  126081. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  126082. testcase( eOp & WO_EQ );
  126083. testcase( eOp & WO_IS );
  126084. testcase( eOp & WO_ISNULL );
  126085. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  126086. }else{
  126087. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  126088. }
  126089. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  126090. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  126091. if( nOut ){
  126092. pNew->nOut = sqlite3LogEst(nOut);
  126093. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  126094. pNew->nOut -= nIn;
  126095. }
  126096. }
  126097. if( nOut==0 )
  126098. #endif
  126099. {
  126100. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  126101. if( eOp & WO_ISNULL ){
  126102. /* TUNING: If there is no likelihood() value, assume that a
  126103. ** "col IS NULL" expression matches twice as many rows
  126104. ** as (col=?). */
  126105. pNew->nOut += 10;
  126106. }
  126107. }
  126108. }
  126109. }
  126110. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  126111. ** it to pNew->rRun, which is currently set to the cost of the index
  126112. ** seek only. Then, if this is a non-covering index, add the cost of
  126113. ** visiting the rows in the main table. */
  126114. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  126115. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  126116. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  126117. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  126118. }
  126119. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  126120. nOutUnadjusted = pNew->nOut;
  126121. pNew->rRun += nInMul + nIn;
  126122. pNew->nOut += nInMul + nIn;
  126123. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  126124. rc = whereLoopInsert(pBuilder, pNew);
  126125. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  126126. pNew->nOut = saved_nOut;
  126127. }else{
  126128. pNew->nOut = nOutUnadjusted;
  126129. }
  126130. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  126131. && pNew->u.btree.nEq<pProbe->nColumn
  126132. ){
  126133. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  126134. }
  126135. pNew->nOut = saved_nOut;
  126136. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126137. pBuilder->nRecValid = nRecValid;
  126138. #endif
  126139. }
  126140. pNew->prereq = saved_prereq;
  126141. pNew->u.btree.nEq = saved_nEq;
  126142. pNew->u.btree.nBtm = saved_nBtm;
  126143. pNew->u.btree.nTop = saved_nTop;
  126144. pNew->nSkip = saved_nSkip;
  126145. pNew->wsFlags = saved_wsFlags;
  126146. pNew->nOut = saved_nOut;
  126147. pNew->nLTerm = saved_nLTerm;
  126148. /* Consider using a skip-scan if there are no WHERE clause constraints
  126149. ** available for the left-most terms of the index, and if the average
  126150. ** number of repeats in the left-most terms is at least 18.
  126151. **
  126152. ** The magic number 18 is selected on the basis that scanning 17 rows
  126153. ** is almost always quicker than an index seek (even though if the index
  126154. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  126155. ** the code). And, even if it is not, it should not be too much slower.
  126156. ** On the other hand, the extra seeks could end up being significantly
  126157. ** more expensive. */
  126158. assert( 42==sqlite3LogEst(18) );
  126159. if( saved_nEq==saved_nSkip
  126160. && saved_nEq+1<pProbe->nKeyCol
  126161. && pProbe->noSkipScan==0
  126162. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  126163. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  126164. ){
  126165. LogEst nIter;
  126166. pNew->u.btree.nEq++;
  126167. pNew->nSkip++;
  126168. pNew->aLTerm[pNew->nLTerm++] = 0;
  126169. pNew->wsFlags |= WHERE_SKIPSCAN;
  126170. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  126171. pNew->nOut -= nIter;
  126172. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  126173. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  126174. nIter += 5;
  126175. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  126176. pNew->nOut = saved_nOut;
  126177. pNew->u.btree.nEq = saved_nEq;
  126178. pNew->nSkip = saved_nSkip;
  126179. pNew->wsFlags = saved_wsFlags;
  126180. }
  126181. WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
  126182. pProbe->zName, saved_nEq, rc));
  126183. return rc;
  126184. }
  126185. /*
  126186. ** Return True if it is possible that pIndex might be useful in
  126187. ** implementing the ORDER BY clause in pBuilder.
  126188. **
  126189. ** Return False if pBuilder does not contain an ORDER BY clause or
  126190. ** if there is no way for pIndex to be useful in implementing that
  126191. ** ORDER BY clause.
  126192. */
  126193. static int indexMightHelpWithOrderBy(
  126194. WhereLoopBuilder *pBuilder,
  126195. Index *pIndex,
  126196. int iCursor
  126197. ){
  126198. ExprList *pOB;
  126199. ExprList *aColExpr;
  126200. int ii, jj;
  126201. if( pIndex->bUnordered ) return 0;
  126202. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  126203. for(ii=0; ii<pOB->nExpr; ii++){
  126204. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  126205. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  126206. if( pExpr->iColumn<0 ) return 1;
  126207. for(jj=0; jj<pIndex->nKeyCol; jj++){
  126208. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  126209. }
  126210. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  126211. for(jj=0; jj<pIndex->nKeyCol; jj++){
  126212. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  126213. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  126214. return 1;
  126215. }
  126216. }
  126217. }
  126218. }
  126219. return 0;
  126220. }
  126221. /*
  126222. ** Return a bitmask where 1s indicate that the corresponding column of
  126223. ** the table is used by an index. Only the first 63 columns are considered.
  126224. */
  126225. static Bitmask columnsInIndex(Index *pIdx){
  126226. Bitmask m = 0;
  126227. int j;
  126228. for(j=pIdx->nColumn-1; j>=0; j--){
  126229. int x = pIdx->aiColumn[j];
  126230. if( x>=0 ){
  126231. testcase( x==BMS-1 );
  126232. testcase( x==BMS-2 );
  126233. if( x<BMS-1 ) m |= MASKBIT(x);
  126234. }
  126235. }
  126236. return m;
  126237. }
  126238. /* Check to see if a partial index with pPartIndexWhere can be used
  126239. ** in the current query. Return true if it can be and false if not.
  126240. */
  126241. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  126242. int i;
  126243. WhereTerm *pTerm;
  126244. Parse *pParse = pWC->pWInfo->pParse;
  126245. while( pWhere->op==TK_AND ){
  126246. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  126247. pWhere = pWhere->pRight;
  126248. }
  126249. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  126250. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  126251. Expr *pExpr = pTerm->pExpr;
  126252. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  126253. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  126254. ){
  126255. return 1;
  126256. }
  126257. }
  126258. return 0;
  126259. }
  126260. /*
  126261. ** Add all WhereLoop objects for a single table of the join where the table
  126262. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  126263. ** a b-tree table, not a virtual table.
  126264. **
  126265. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  126266. ** are calculated as follows:
  126267. **
  126268. ** For a full scan, assuming the table (or index) contains nRow rows:
  126269. **
  126270. ** cost = nRow * 3.0 // full-table scan
  126271. ** cost = nRow * K // scan of covering index
  126272. ** cost = nRow * (K+3.0) // scan of non-covering index
  126273. **
  126274. ** where K is a value between 1.1 and 3.0 set based on the relative
  126275. ** estimated average size of the index and table records.
  126276. **
  126277. ** For an index scan, where nVisit is the number of index rows visited
  126278. ** by the scan, and nSeek is the number of seek operations required on
  126279. ** the index b-tree:
  126280. **
  126281. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  126282. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  126283. **
  126284. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  126285. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  126286. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  126287. **
  126288. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  126289. ** of uncertainty. For this reason, scoring is designed to pick plans that
  126290. ** "do the least harm" if the estimates are inaccurate. For example, a
  126291. ** log(nRow) factor is omitted from a non-covering index scan in order to
  126292. ** bias the scoring in favor of using an index, since the worst-case
  126293. ** performance of using an index is far better than the worst-case performance
  126294. ** of a full table scan.
  126295. */
  126296. static int whereLoopAddBtree(
  126297. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  126298. Bitmask mPrereq /* Extra prerequesites for using this table */
  126299. ){
  126300. WhereInfo *pWInfo; /* WHERE analysis context */
  126301. Index *pProbe; /* An index we are evaluating */
  126302. Index sPk; /* A fake index object for the primary key */
  126303. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  126304. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  126305. SrcList *pTabList; /* The FROM clause */
  126306. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  126307. WhereLoop *pNew; /* Template WhereLoop object */
  126308. int rc = SQLITE_OK; /* Return code */
  126309. int iSortIdx = 1; /* Index number */
  126310. int b; /* A boolean value */
  126311. LogEst rSize; /* number of rows in the table */
  126312. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  126313. WhereClause *pWC; /* The parsed WHERE clause */
  126314. Table *pTab; /* Table being queried */
  126315. pNew = pBuilder->pNew;
  126316. pWInfo = pBuilder->pWInfo;
  126317. pTabList = pWInfo->pTabList;
  126318. pSrc = pTabList->a + pNew->iTab;
  126319. pTab = pSrc->pTab;
  126320. pWC = pBuilder->pWC;
  126321. assert( !IsVirtual(pSrc->pTab) );
  126322. if( pSrc->pIBIndex ){
  126323. /* An INDEXED BY clause specifies a particular index to use */
  126324. pProbe = pSrc->pIBIndex;
  126325. }else if( !HasRowid(pTab) ){
  126326. pProbe = pTab->pIndex;
  126327. }else{
  126328. /* There is no INDEXED BY clause. Create a fake Index object in local
  126329. ** variable sPk to represent the rowid primary key index. Make this
  126330. ** fake index the first in a chain of Index objects with all of the real
  126331. ** indices to follow */
  126332. Index *pFirst; /* First of real indices on the table */
  126333. memset(&sPk, 0, sizeof(Index));
  126334. sPk.nKeyCol = 1;
  126335. sPk.nColumn = 1;
  126336. sPk.aiColumn = &aiColumnPk;
  126337. sPk.aiRowLogEst = aiRowEstPk;
  126338. sPk.onError = OE_Replace;
  126339. sPk.pTable = pTab;
  126340. sPk.szIdxRow = pTab->szTabRow;
  126341. aiRowEstPk[0] = pTab->nRowLogEst;
  126342. aiRowEstPk[1] = 0;
  126343. pFirst = pSrc->pTab->pIndex;
  126344. if( pSrc->fg.notIndexed==0 ){
  126345. /* The real indices of the table are only considered if the
  126346. ** NOT INDEXED qualifier is omitted from the FROM clause */
  126347. sPk.pNext = pFirst;
  126348. }
  126349. pProbe = &sPk;
  126350. }
  126351. rSize = pTab->nRowLogEst;
  126352. rLogSize = estLog(rSize);
  126353. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  126354. /* Automatic indexes */
  126355. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  126356. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  126357. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  126358. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  126359. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  126360. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  126361. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  126362. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  126363. ){
  126364. /* Generate auto-index WhereLoops */
  126365. WhereTerm *pTerm;
  126366. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  126367. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  126368. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  126369. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  126370. pNew->u.btree.nEq = 1;
  126371. pNew->nSkip = 0;
  126372. pNew->u.btree.pIndex = 0;
  126373. pNew->nLTerm = 1;
  126374. pNew->aLTerm[0] = pTerm;
  126375. /* TUNING: One-time cost for computing the automatic index is
  126376. ** estimated to be X*N*log2(N) where N is the number of rows in
  126377. ** the table being indexed and where X is 7 (LogEst=28) for normal
  126378. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  126379. ** of X is smaller for views and subqueries so that the query planner
  126380. ** will be more aggressive about generating automatic indexes for
  126381. ** those objects, since there is no opportunity to add schema
  126382. ** indexes on subqueries and views. */
  126383. pNew->rSetup = rLogSize + rSize + 4;
  126384. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  126385. pNew->rSetup += 24;
  126386. }
  126387. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  126388. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  126389. /* TUNING: Each index lookup yields 20 rows in the table. This
  126390. ** is more than the usual guess of 10 rows, since we have no way
  126391. ** of knowing how selective the index will ultimately be. It would
  126392. ** not be unreasonable to make this value much larger. */
  126393. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  126394. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  126395. pNew->wsFlags = WHERE_AUTO_INDEX;
  126396. pNew->prereq = mPrereq | pTerm->prereqRight;
  126397. rc = whereLoopInsert(pBuilder, pNew);
  126398. }
  126399. }
  126400. }
  126401. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  126402. /* Loop over all indices
  126403. */
  126404. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  126405. if( pProbe->pPartIdxWhere!=0
  126406. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  126407. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  126408. continue; /* Partial index inappropriate for this query */
  126409. }
  126410. rSize = pProbe->aiRowLogEst[0];
  126411. pNew->u.btree.nEq = 0;
  126412. pNew->u.btree.nBtm = 0;
  126413. pNew->u.btree.nTop = 0;
  126414. pNew->nSkip = 0;
  126415. pNew->nLTerm = 0;
  126416. pNew->iSortIdx = 0;
  126417. pNew->rSetup = 0;
  126418. pNew->prereq = mPrereq;
  126419. pNew->nOut = rSize;
  126420. pNew->u.btree.pIndex = pProbe;
  126421. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  126422. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  126423. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  126424. if( pProbe->tnum<=0 ){
  126425. /* Integer primary key index */
  126426. pNew->wsFlags = WHERE_IPK;
  126427. /* Full table scan */
  126428. pNew->iSortIdx = b ? iSortIdx : 0;
  126429. /* TUNING: Cost of full table scan is (N*3.0). */
  126430. pNew->rRun = rSize + 16;
  126431. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  126432. whereLoopOutputAdjust(pWC, pNew, rSize);
  126433. rc = whereLoopInsert(pBuilder, pNew);
  126434. pNew->nOut = rSize;
  126435. if( rc ) break;
  126436. }else{
  126437. Bitmask m;
  126438. if( pProbe->isCovering ){
  126439. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  126440. m = 0;
  126441. }else{
  126442. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  126443. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  126444. }
  126445. /* Full scan via index */
  126446. if( b
  126447. || !HasRowid(pTab)
  126448. || pProbe->pPartIdxWhere!=0
  126449. || ( m==0
  126450. && pProbe->bUnordered==0
  126451. && (pProbe->szIdxRow<pTab->szTabRow)
  126452. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  126453. && sqlite3GlobalConfig.bUseCis
  126454. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  126455. )
  126456. ){
  126457. pNew->iSortIdx = b ? iSortIdx : 0;
  126458. /* The cost of visiting the index rows is N*K, where K is
  126459. ** between 1.1 and 3.0, depending on the relative sizes of the
  126460. ** index and table rows. */
  126461. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  126462. if( m!=0 ){
  126463. /* If this is a non-covering index scan, add in the cost of
  126464. ** doing table lookups. The cost will be 3x the number of
  126465. ** lookups. Take into account WHERE clause terms that can be
  126466. ** satisfied using just the index, and that do not require a
  126467. ** table lookup. */
  126468. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  126469. int ii;
  126470. int iCur = pSrc->iCursor;
  126471. WhereClause *pWC2 = &pWInfo->sWC;
  126472. for(ii=0; ii<pWC2->nTerm; ii++){
  126473. WhereTerm *pTerm = &pWC2->a[ii];
  126474. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  126475. break;
  126476. }
  126477. /* pTerm can be evaluated using just the index. So reduce
  126478. ** the expected number of table lookups accordingly */
  126479. if( pTerm->truthProb<=0 ){
  126480. nLookup += pTerm->truthProb;
  126481. }else{
  126482. nLookup--;
  126483. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  126484. }
  126485. }
  126486. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  126487. }
  126488. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  126489. whereLoopOutputAdjust(pWC, pNew, rSize);
  126490. rc = whereLoopInsert(pBuilder, pNew);
  126491. pNew->nOut = rSize;
  126492. if( rc ) break;
  126493. }
  126494. }
  126495. pBuilder->bldFlags = 0;
  126496. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  126497. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  126498. /* If a non-unique index is used, or if a prefix of the key for
  126499. ** unique index is used (making the index functionally non-unique)
  126500. ** then the sqlite_stat1 data becomes important for scoring the
  126501. ** plan */
  126502. pTab->tabFlags |= TF_StatsUsed;
  126503. }
  126504. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126505. sqlite3Stat4ProbeFree(pBuilder->pRec);
  126506. pBuilder->nRecValid = 0;
  126507. pBuilder->pRec = 0;
  126508. #endif
  126509. /* If there was an INDEXED BY clause, then only that one index is
  126510. ** considered. */
  126511. if( pSrc->pIBIndex ) break;
  126512. }
  126513. return rc;
  126514. }
  126515. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126516. /*
  126517. ** Argument pIdxInfo is already populated with all constraints that may
  126518. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  126519. ** function marks a subset of those constraints usable, invokes the
  126520. ** xBestIndex method and adds the returned plan to pBuilder.
  126521. **
  126522. ** A constraint is marked usable if:
  126523. **
  126524. ** * Argument mUsable indicates that its prerequisites are available, and
  126525. **
  126526. ** * It is not one of the operators specified in the mExclude mask passed
  126527. ** as the fourth argument (which in practice is either WO_IN or 0).
  126528. **
  126529. ** Argument mPrereq is a mask of tables that must be scanned before the
  126530. ** virtual table in question. These are added to the plans prerequisites
  126531. ** before it is added to pBuilder.
  126532. **
  126533. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  126534. ** uses one or more WO_IN terms, or false otherwise.
  126535. */
  126536. static int whereLoopAddVirtualOne(
  126537. WhereLoopBuilder *pBuilder,
  126538. Bitmask mPrereq, /* Mask of tables that must be used. */
  126539. Bitmask mUsable, /* Mask of usable tables */
  126540. u16 mExclude, /* Exclude terms using these operators */
  126541. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  126542. u16 mNoOmit, /* Do not omit these constraints */
  126543. int *pbIn /* OUT: True if plan uses an IN(...) op */
  126544. ){
  126545. WhereClause *pWC = pBuilder->pWC;
  126546. struct sqlite3_index_constraint *pIdxCons;
  126547. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  126548. int i;
  126549. int mxTerm;
  126550. int rc = SQLITE_OK;
  126551. WhereLoop *pNew = pBuilder->pNew;
  126552. Parse *pParse = pBuilder->pWInfo->pParse;
  126553. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  126554. int nConstraint = pIdxInfo->nConstraint;
  126555. assert( (mUsable & mPrereq)==mPrereq );
  126556. *pbIn = 0;
  126557. pNew->prereq = mPrereq;
  126558. /* Set the usable flag on the subset of constraints identified by
  126559. ** arguments mUsable and mExclude. */
  126560. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  126561. for(i=0; i<nConstraint; i++, pIdxCons++){
  126562. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  126563. pIdxCons->usable = 0;
  126564. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  126565. && (pTerm->eOperator & mExclude)==0
  126566. ){
  126567. pIdxCons->usable = 1;
  126568. }
  126569. }
  126570. /* Initialize the output fields of the sqlite3_index_info structure */
  126571. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  126572. assert( pIdxInfo->needToFreeIdxStr==0 );
  126573. pIdxInfo->idxStr = 0;
  126574. pIdxInfo->idxNum = 0;
  126575. pIdxInfo->orderByConsumed = 0;
  126576. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  126577. pIdxInfo->estimatedRows = 25;
  126578. pIdxInfo->idxFlags = 0;
  126579. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  126580. /* Invoke the virtual table xBestIndex() method */
  126581. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  126582. if( rc ) return rc;
  126583. mxTerm = -1;
  126584. assert( pNew->nLSlot>=nConstraint );
  126585. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  126586. pNew->u.vtab.omitMask = 0;
  126587. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  126588. for(i=0; i<nConstraint; i++, pIdxCons++){
  126589. int iTerm;
  126590. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  126591. WhereTerm *pTerm;
  126592. int j = pIdxCons->iTermOffset;
  126593. if( iTerm>=nConstraint
  126594. || j<0
  126595. || j>=pWC->nTerm
  126596. || pNew->aLTerm[iTerm]!=0
  126597. || pIdxCons->usable==0
  126598. ){
  126599. rc = SQLITE_ERROR;
  126600. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  126601. return rc;
  126602. }
  126603. testcase( iTerm==nConstraint-1 );
  126604. testcase( j==0 );
  126605. testcase( j==pWC->nTerm-1 );
  126606. pTerm = &pWC->a[j];
  126607. pNew->prereq |= pTerm->prereqRight;
  126608. assert( iTerm<pNew->nLSlot );
  126609. pNew->aLTerm[iTerm] = pTerm;
  126610. if( iTerm>mxTerm ) mxTerm = iTerm;
  126611. testcase( iTerm==15 );
  126612. testcase( iTerm==16 );
  126613. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  126614. if( (pTerm->eOperator & WO_IN)!=0 ){
  126615. /* A virtual table that is constrained by an IN clause may not
  126616. ** consume the ORDER BY clause because (1) the order of IN terms
  126617. ** is not necessarily related to the order of output terms and
  126618. ** (2) Multiple outputs from a single IN value will not merge
  126619. ** together. */
  126620. pIdxInfo->orderByConsumed = 0;
  126621. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  126622. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  126623. }
  126624. }
  126625. }
  126626. pNew->u.vtab.omitMask &= ~mNoOmit;
  126627. pNew->nLTerm = mxTerm+1;
  126628. assert( pNew->nLTerm<=pNew->nLSlot );
  126629. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  126630. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  126631. pIdxInfo->needToFreeIdxStr = 0;
  126632. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  126633. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  126634. pIdxInfo->nOrderBy : 0);
  126635. pNew->rSetup = 0;
  126636. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  126637. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  126638. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  126639. ** that the scan will visit at most one row. Clear it otherwise. */
  126640. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  126641. pNew->wsFlags |= WHERE_ONEROW;
  126642. }else{
  126643. pNew->wsFlags &= ~WHERE_ONEROW;
  126644. }
  126645. rc = whereLoopInsert(pBuilder, pNew);
  126646. if( pNew->u.vtab.needFree ){
  126647. sqlite3_free(pNew->u.vtab.idxStr);
  126648. pNew->u.vtab.needFree = 0;
  126649. }
  126650. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  126651. *pbIn, (sqlite3_uint64)mPrereq,
  126652. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  126653. return rc;
  126654. }
  126655. /*
  126656. ** Add all WhereLoop objects for a table of the join identified by
  126657. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  126658. **
  126659. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  126660. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  126661. ** entries that occur before the virtual table in the FROM clause and are
  126662. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  126663. ** mUnusable mask contains all FROM clause entries that occur after the
  126664. ** virtual table and are separated from it by at least one LEFT or
  126665. ** CROSS JOIN.
  126666. **
  126667. ** For example, if the query were:
  126668. **
  126669. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  126670. **
  126671. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  126672. **
  126673. ** All the tables in mPrereq must be scanned before the current virtual
  126674. ** table. So any terms for which all prerequisites are satisfied by
  126675. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  126676. ** Conversely, all tables in mUnusable must be scanned after the current
  126677. ** virtual table, so any terms for which the prerequisites overlap with
  126678. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  126679. */
  126680. static int whereLoopAddVirtual(
  126681. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  126682. Bitmask mPrereq, /* Tables that must be scanned before this one */
  126683. Bitmask mUnusable /* Tables that must be scanned after this one */
  126684. ){
  126685. int rc = SQLITE_OK; /* Return code */
  126686. WhereInfo *pWInfo; /* WHERE analysis context */
  126687. Parse *pParse; /* The parsing context */
  126688. WhereClause *pWC; /* The WHERE clause */
  126689. struct SrcList_item *pSrc; /* The FROM clause term to search */
  126690. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  126691. int nConstraint; /* Number of constraints in p */
  126692. int bIn; /* True if plan uses IN(...) operator */
  126693. WhereLoop *pNew;
  126694. Bitmask mBest; /* Tables used by best possible plan */
  126695. u16 mNoOmit;
  126696. assert( (mPrereq & mUnusable)==0 );
  126697. pWInfo = pBuilder->pWInfo;
  126698. pParse = pWInfo->pParse;
  126699. pWC = pBuilder->pWC;
  126700. pNew = pBuilder->pNew;
  126701. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  126702. assert( IsVirtual(pSrc->pTab) );
  126703. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  126704. &mNoOmit);
  126705. if( p==0 ) return SQLITE_NOMEM_BKPT;
  126706. pNew->rSetup = 0;
  126707. pNew->wsFlags = WHERE_VIRTUALTABLE;
  126708. pNew->nLTerm = 0;
  126709. pNew->u.vtab.needFree = 0;
  126710. nConstraint = p->nConstraint;
  126711. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  126712. sqlite3DbFree(pParse->db, p);
  126713. return SQLITE_NOMEM_BKPT;
  126714. }
  126715. /* First call xBestIndex() with all constraints usable. */
  126716. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  126717. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  126718. /* If the call to xBestIndex() with all terms enabled produced a plan
  126719. ** that does not require any source tables (IOW: a plan with mBest==0),
  126720. ** then there is no point in making any further calls to xBestIndex()
  126721. ** since they will all return the same result (if the xBestIndex()
  126722. ** implementation is sane). */
  126723. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  126724. int seenZero = 0; /* True if a plan with no prereqs seen */
  126725. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  126726. Bitmask mPrev = 0;
  126727. Bitmask mBestNoIn = 0;
  126728. /* If the plan produced by the earlier call uses an IN(...) term, call
  126729. ** xBestIndex again, this time with IN(...) terms disabled. */
  126730. if( bIn ){
  126731. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  126732. rc = whereLoopAddVirtualOne(
  126733. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  126734. assert( bIn==0 );
  126735. mBestNoIn = pNew->prereq & ~mPrereq;
  126736. if( mBestNoIn==0 ){
  126737. seenZero = 1;
  126738. seenZeroNoIN = 1;
  126739. }
  126740. }
  126741. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  126742. ** in the set of terms that apply to the current virtual table. */
  126743. while( rc==SQLITE_OK ){
  126744. int i;
  126745. Bitmask mNext = ALLBITS;
  126746. assert( mNext>0 );
  126747. for(i=0; i<nConstraint; i++){
  126748. Bitmask mThis = (
  126749. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  126750. );
  126751. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  126752. }
  126753. mPrev = mNext;
  126754. if( mNext==ALLBITS ) break;
  126755. if( mNext==mBest || mNext==mBestNoIn ) continue;
  126756. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  126757. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  126758. rc = whereLoopAddVirtualOne(
  126759. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  126760. if( pNew->prereq==mPrereq ){
  126761. seenZero = 1;
  126762. if( bIn==0 ) seenZeroNoIN = 1;
  126763. }
  126764. }
  126765. /* If the calls to xBestIndex() in the above loop did not find a plan
  126766. ** that requires no source tables at all (i.e. one guaranteed to be
  126767. ** usable), make a call here with all source tables disabled */
  126768. if( rc==SQLITE_OK && seenZero==0 ){
  126769. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  126770. rc = whereLoopAddVirtualOne(
  126771. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  126772. if( bIn==0 ) seenZeroNoIN = 1;
  126773. }
  126774. /* If the calls to xBestIndex() have so far failed to find a plan
  126775. ** that requires no source tables at all and does not use an IN(...)
  126776. ** operator, make a final call to obtain one here. */
  126777. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  126778. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  126779. rc = whereLoopAddVirtualOne(
  126780. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  126781. }
  126782. }
  126783. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  126784. sqlite3DbFreeNN(pParse->db, p);
  126785. return rc;
  126786. }
  126787. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126788. /*
  126789. ** Add WhereLoop entries to handle OR terms. This works for either
  126790. ** btrees or virtual tables.
  126791. */
  126792. static int whereLoopAddOr(
  126793. WhereLoopBuilder *pBuilder,
  126794. Bitmask mPrereq,
  126795. Bitmask mUnusable
  126796. ){
  126797. WhereInfo *pWInfo = pBuilder->pWInfo;
  126798. WhereClause *pWC;
  126799. WhereLoop *pNew;
  126800. WhereTerm *pTerm, *pWCEnd;
  126801. int rc = SQLITE_OK;
  126802. int iCur;
  126803. WhereClause tempWC;
  126804. WhereLoopBuilder sSubBuild;
  126805. WhereOrSet sSum, sCur;
  126806. struct SrcList_item *pItem;
  126807. pWC = pBuilder->pWC;
  126808. pWCEnd = pWC->a + pWC->nTerm;
  126809. pNew = pBuilder->pNew;
  126810. memset(&sSum, 0, sizeof(sSum));
  126811. pItem = pWInfo->pTabList->a + pNew->iTab;
  126812. iCur = pItem->iCursor;
  126813. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  126814. if( (pTerm->eOperator & WO_OR)!=0
  126815. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  126816. ){
  126817. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  126818. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  126819. WhereTerm *pOrTerm;
  126820. int once = 1;
  126821. int i, j;
  126822. sSubBuild = *pBuilder;
  126823. sSubBuild.pOrderBy = 0;
  126824. sSubBuild.pOrSet = &sCur;
  126825. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  126826. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  126827. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  126828. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  126829. }else if( pOrTerm->leftCursor==iCur ){
  126830. tempWC.pWInfo = pWC->pWInfo;
  126831. tempWC.pOuter = pWC;
  126832. tempWC.op = TK_AND;
  126833. tempWC.nTerm = 1;
  126834. tempWC.a = pOrTerm;
  126835. sSubBuild.pWC = &tempWC;
  126836. }else{
  126837. continue;
  126838. }
  126839. sCur.n = 0;
  126840. #ifdef WHERETRACE_ENABLED
  126841. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  126842. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  126843. if( sqlite3WhereTrace & 0x400 ){
  126844. sqlite3WhereClausePrint(sSubBuild.pWC);
  126845. }
  126846. #endif
  126847. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126848. if( IsVirtual(pItem->pTab) ){
  126849. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  126850. }else
  126851. #endif
  126852. {
  126853. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  126854. }
  126855. if( rc==SQLITE_OK ){
  126856. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  126857. }
  126858. assert( rc==SQLITE_OK || sCur.n==0 );
  126859. if( sCur.n==0 ){
  126860. sSum.n = 0;
  126861. break;
  126862. }else if( once ){
  126863. whereOrMove(&sSum, &sCur);
  126864. once = 0;
  126865. }else{
  126866. WhereOrSet sPrev;
  126867. whereOrMove(&sPrev, &sSum);
  126868. sSum.n = 0;
  126869. for(i=0; i<sPrev.n; i++){
  126870. for(j=0; j<sCur.n; j++){
  126871. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  126872. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  126873. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  126874. }
  126875. }
  126876. }
  126877. }
  126878. pNew->nLTerm = 1;
  126879. pNew->aLTerm[0] = pTerm;
  126880. pNew->wsFlags = WHERE_MULTI_OR;
  126881. pNew->rSetup = 0;
  126882. pNew->iSortIdx = 0;
  126883. memset(&pNew->u, 0, sizeof(pNew->u));
  126884. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  126885. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  126886. ** of all sub-scans required by the OR-scan. However, due to rounding
  126887. ** errors, it may be that the cost of the OR-scan is equal to its
  126888. ** most expensive sub-scan. Add the smallest possible penalty
  126889. ** (equivalent to multiplying the cost by 1.07) to ensure that
  126890. ** this does not happen. Otherwise, for WHERE clauses such as the
  126891. ** following where there is an index on "y":
  126892. **
  126893. ** WHERE likelihood(x=?, 0.99) OR y=?
  126894. **
  126895. ** the planner may elect to "OR" together a full-table scan and an
  126896. ** index lookup. And other similarly odd results. */
  126897. pNew->rRun = sSum.a[i].rRun + 1;
  126898. pNew->nOut = sSum.a[i].nOut;
  126899. pNew->prereq = sSum.a[i].prereq;
  126900. rc = whereLoopInsert(pBuilder, pNew);
  126901. }
  126902. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  126903. }
  126904. }
  126905. return rc;
  126906. }
  126907. /*
  126908. ** Add all WhereLoop objects for all tables
  126909. */
  126910. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  126911. WhereInfo *pWInfo = pBuilder->pWInfo;
  126912. Bitmask mPrereq = 0;
  126913. Bitmask mPrior = 0;
  126914. int iTab;
  126915. SrcList *pTabList = pWInfo->pTabList;
  126916. struct SrcList_item *pItem;
  126917. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  126918. sqlite3 *db = pWInfo->pParse->db;
  126919. int rc = SQLITE_OK;
  126920. WhereLoop *pNew;
  126921. u8 priorJointype = 0;
  126922. /* Loop over the tables in the join, from left to right */
  126923. pNew = pBuilder->pNew;
  126924. whereLoopInit(pNew);
  126925. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  126926. Bitmask mUnusable = 0;
  126927. pNew->iTab = iTab;
  126928. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  126929. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  126930. /* This condition is true when pItem is the FROM clause term on the
  126931. ** right-hand-side of a LEFT or CROSS JOIN. */
  126932. mPrereq = mPrior;
  126933. }
  126934. priorJointype = pItem->fg.jointype;
  126935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126936. if( IsVirtual(pItem->pTab) ){
  126937. struct SrcList_item *p;
  126938. for(p=&pItem[1]; p<pEnd; p++){
  126939. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  126940. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  126941. }
  126942. }
  126943. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  126944. }else
  126945. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126946. {
  126947. rc = whereLoopAddBtree(pBuilder, mPrereq);
  126948. }
  126949. if( rc==SQLITE_OK ){
  126950. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  126951. }
  126952. mPrior |= pNew->maskSelf;
  126953. if( rc || db->mallocFailed ) break;
  126954. }
  126955. whereLoopClear(db, pNew);
  126956. return rc;
  126957. }
  126958. /*
  126959. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  126960. ** parameters) to see if it outputs rows in the requested ORDER BY
  126961. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  126962. **
  126963. ** N>0: N terms of the ORDER BY clause are satisfied
  126964. ** N==0: No terms of the ORDER BY clause are satisfied
  126965. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  126966. **
  126967. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  126968. ** strict. With GROUP BY and DISTINCT the only requirement is that
  126969. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  126970. ** and DISTINCT do not require rows to appear in any particular order as long
  126971. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  126972. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  126973. ** pOrderBy terms must be matched in strict left-to-right order.
  126974. */
  126975. static i8 wherePathSatisfiesOrderBy(
  126976. WhereInfo *pWInfo, /* The WHERE clause */
  126977. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  126978. WherePath *pPath, /* The WherePath to check */
  126979. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  126980. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  126981. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  126982. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  126983. ){
  126984. u8 revSet; /* True if rev is known */
  126985. u8 rev; /* Composite sort order */
  126986. u8 revIdx; /* Index sort order */
  126987. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  126988. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  126989. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  126990. u16 eqOpMask; /* Allowed equality operators */
  126991. u16 nKeyCol; /* Number of key columns in pIndex */
  126992. u16 nColumn; /* Total number of ordered columns in the index */
  126993. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  126994. int iLoop; /* Index of WhereLoop in pPath being processed */
  126995. int i, j; /* Loop counters */
  126996. int iCur; /* Cursor number for current WhereLoop */
  126997. int iColumn; /* A column number within table iCur */
  126998. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  126999. WhereTerm *pTerm; /* A single term of the WHERE clause */
  127000. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  127001. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  127002. Index *pIndex; /* The index associated with pLoop */
  127003. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  127004. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  127005. Bitmask obDone; /* Mask of all ORDER BY terms */
  127006. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  127007. Bitmask ready; /* Mask of inner loops */
  127008. /*
  127009. ** We say the WhereLoop is "one-row" if it generates no more than one
  127010. ** row of output. A WhereLoop is one-row if all of the following are true:
  127011. ** (a) All index columns match with WHERE_COLUMN_EQ.
  127012. ** (b) The index is unique
  127013. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  127014. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  127015. **
  127016. ** We say the WhereLoop is "order-distinct" if the set of columns from
  127017. ** that WhereLoop that are in the ORDER BY clause are different for every
  127018. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  127019. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  127020. ** is not order-distinct. To be order-distinct is not quite the same as being
  127021. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  127022. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  127023. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  127024. **
  127025. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  127026. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  127027. ** automatically order-distinct.
  127028. */
  127029. assert( pOrderBy!=0 );
  127030. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  127031. nOrderBy = pOrderBy->nExpr;
  127032. testcase( nOrderBy==BMS-1 );
  127033. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  127034. isOrderDistinct = 1;
  127035. obDone = MASKBIT(nOrderBy)-1;
  127036. orderDistinctMask = 0;
  127037. ready = 0;
  127038. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  127039. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  127040. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  127041. if( iLoop>0 ) ready |= pLoop->maskSelf;
  127042. if( iLoop<nLoop ){
  127043. pLoop = pPath->aLoop[iLoop];
  127044. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  127045. }else{
  127046. pLoop = pLast;
  127047. }
  127048. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  127049. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  127050. break;
  127051. }else{
  127052. pLoop->u.btree.nIdxCol = 0;
  127053. }
  127054. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  127055. /* Mark off any ORDER BY term X that is a column in the table of
  127056. ** the current loop for which there is term in the WHERE
  127057. ** clause of the form X IS NULL or X=? that reference only outer
  127058. ** loops.
  127059. */
  127060. for(i=0; i<nOrderBy; i++){
  127061. if( MASKBIT(i) & obSat ) continue;
  127062. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  127063. if( pOBExpr->op!=TK_COLUMN ) continue;
  127064. if( pOBExpr->iTable!=iCur ) continue;
  127065. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  127066. ~ready, eqOpMask, 0);
  127067. if( pTerm==0 ) continue;
  127068. if( pTerm->eOperator==WO_IN ){
  127069. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  127070. ** optimization, and then only if they are actually used
  127071. ** by the query plan */
  127072. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  127073. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  127074. if( j>=pLoop->nLTerm ) continue;
  127075. }
  127076. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  127077. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  127078. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  127079. continue;
  127080. }
  127081. testcase( pTerm->pExpr->op==TK_IS );
  127082. }
  127083. obSat |= MASKBIT(i);
  127084. }
  127085. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  127086. if( pLoop->wsFlags & WHERE_IPK ){
  127087. pIndex = 0;
  127088. nKeyCol = 0;
  127089. nColumn = 1;
  127090. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  127091. return 0;
  127092. }else{
  127093. nKeyCol = pIndex->nKeyCol;
  127094. nColumn = pIndex->nColumn;
  127095. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  127096. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  127097. || !HasRowid(pIndex->pTable));
  127098. isOrderDistinct = IsUniqueIndex(pIndex);
  127099. }
  127100. /* Loop through all columns of the index and deal with the ones
  127101. ** that are not constrained by == or IN.
  127102. */
  127103. rev = revSet = 0;
  127104. distinctColumns = 0;
  127105. for(j=0; j<nColumn; j++){
  127106. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  127107. assert( j>=pLoop->u.btree.nEq
  127108. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  127109. );
  127110. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  127111. u16 eOp = pLoop->aLTerm[j]->eOperator;
  127112. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  127113. ** doing WHERE_ORDERBY_LIMIT processing).
  127114. **
  127115. ** If the current term is a column of an ((?,?) IN (SELECT...))
  127116. ** expression for which the SELECT returns more than one column,
  127117. ** check that it is the only column used by this loop. Otherwise,
  127118. ** if it is one of two or more, none of the columns can be
  127119. ** considered to match an ORDER BY term. */
  127120. if( (eOp & eqOpMask)!=0 ){
  127121. if( eOp & WO_ISNULL ){
  127122. testcase( isOrderDistinct );
  127123. isOrderDistinct = 0;
  127124. }
  127125. continue;
  127126. }else if( ALWAYS(eOp & WO_IN) ){
  127127. /* ALWAYS() justification: eOp is an equality operator due to the
  127128. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  127129. ** than WO_IN is captured by the previous "if". So this one
  127130. ** always has to be WO_IN. */
  127131. Expr *pX = pLoop->aLTerm[j]->pExpr;
  127132. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  127133. if( pLoop->aLTerm[i]->pExpr==pX ){
  127134. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  127135. bOnce = 0;
  127136. break;
  127137. }
  127138. }
  127139. }
  127140. }
  127141. /* Get the column number in the table (iColumn) and sort order
  127142. ** (revIdx) for the j-th column of the index.
  127143. */
  127144. if( pIndex ){
  127145. iColumn = pIndex->aiColumn[j];
  127146. revIdx = pIndex->aSortOrder[j];
  127147. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  127148. }else{
  127149. iColumn = XN_ROWID;
  127150. revIdx = 0;
  127151. }
  127152. /* An unconstrained column that might be NULL means that this
  127153. ** WhereLoop is not well-ordered
  127154. */
  127155. if( isOrderDistinct
  127156. && iColumn>=0
  127157. && j>=pLoop->u.btree.nEq
  127158. && pIndex->pTable->aCol[iColumn].notNull==0
  127159. ){
  127160. isOrderDistinct = 0;
  127161. }
  127162. /* Find the ORDER BY term that corresponds to the j-th column
  127163. ** of the index and mark that ORDER BY term off
  127164. */
  127165. isMatch = 0;
  127166. for(i=0; bOnce && i<nOrderBy; i++){
  127167. if( MASKBIT(i) & obSat ) continue;
  127168. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  127169. testcase( wctrlFlags & WHERE_GROUPBY );
  127170. testcase( wctrlFlags & WHERE_DISTINCTBY );
  127171. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  127172. if( iColumn>=XN_ROWID ){
  127173. if( pOBExpr->op!=TK_COLUMN ) continue;
  127174. if( pOBExpr->iTable!=iCur ) continue;
  127175. if( pOBExpr->iColumn!=iColumn ) continue;
  127176. }else{
  127177. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  127178. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  127179. continue;
  127180. }
  127181. }
  127182. if( iColumn!=XN_ROWID ){
  127183. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  127184. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  127185. }
  127186. pLoop->u.btree.nIdxCol = j+1;
  127187. isMatch = 1;
  127188. break;
  127189. }
  127190. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  127191. /* Make sure the sort order is compatible in an ORDER BY clause.
  127192. ** Sort order is irrelevant for a GROUP BY clause. */
  127193. if( revSet ){
  127194. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  127195. }else{
  127196. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  127197. if( rev ) *pRevMask |= MASKBIT(iLoop);
  127198. revSet = 1;
  127199. }
  127200. }
  127201. if( isMatch ){
  127202. if( iColumn==XN_ROWID ){
  127203. testcase( distinctColumns==0 );
  127204. distinctColumns = 1;
  127205. }
  127206. obSat |= MASKBIT(i);
  127207. }else{
  127208. /* No match found */
  127209. if( j==0 || j<nKeyCol ){
  127210. testcase( isOrderDistinct!=0 );
  127211. isOrderDistinct = 0;
  127212. }
  127213. break;
  127214. }
  127215. } /* end Loop over all index columns */
  127216. if( distinctColumns ){
  127217. testcase( isOrderDistinct==0 );
  127218. isOrderDistinct = 1;
  127219. }
  127220. } /* end-if not one-row */
  127221. /* Mark off any other ORDER BY terms that reference pLoop */
  127222. if( isOrderDistinct ){
  127223. orderDistinctMask |= pLoop->maskSelf;
  127224. for(i=0; i<nOrderBy; i++){
  127225. Expr *p;
  127226. Bitmask mTerm;
  127227. if( MASKBIT(i) & obSat ) continue;
  127228. p = pOrderBy->a[i].pExpr;
  127229. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  127230. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  127231. if( (mTerm&~orderDistinctMask)==0 ){
  127232. obSat |= MASKBIT(i);
  127233. }
  127234. }
  127235. }
  127236. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  127237. if( obSat==obDone ) return (i8)nOrderBy;
  127238. if( !isOrderDistinct ){
  127239. for(i=nOrderBy-1; i>0; i--){
  127240. Bitmask m = MASKBIT(i) - 1;
  127241. if( (obSat&m)==m ) return i;
  127242. }
  127243. return 0;
  127244. }
  127245. return -1;
  127246. }
  127247. /*
  127248. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  127249. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  127250. ** BY clause - and so any order that groups rows as required satisfies the
  127251. ** request.
  127252. **
  127253. ** Normally, in this case it is not possible for the caller to determine
  127254. ** whether or not the rows are really being delivered in sorted order, or
  127255. ** just in some other order that provides the required grouping. However,
  127256. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  127257. ** this function may be called on the returned WhereInfo object. It returns
  127258. ** true if the rows really will be sorted in the specified order, or false
  127259. ** otherwise.
  127260. **
  127261. ** For example, assuming:
  127262. **
  127263. ** CREATE INDEX i1 ON t1(x, Y);
  127264. **
  127265. ** then
  127266. **
  127267. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  127268. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  127269. */
  127270. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  127271. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  127272. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  127273. return pWInfo->sorted;
  127274. }
  127275. #ifdef WHERETRACE_ENABLED
  127276. /* For debugging use only: */
  127277. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  127278. static char zName[65];
  127279. int i;
  127280. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  127281. if( pLast ) zName[i++] = pLast->cId;
  127282. zName[i] = 0;
  127283. return zName;
  127284. }
  127285. #endif
  127286. /*
  127287. ** Return the cost of sorting nRow rows, assuming that the keys have
  127288. ** nOrderby columns and that the first nSorted columns are already in
  127289. ** order.
  127290. */
  127291. static LogEst whereSortingCost(
  127292. WhereInfo *pWInfo,
  127293. LogEst nRow,
  127294. int nOrderBy,
  127295. int nSorted
  127296. ){
  127297. /* TUNING: Estimated cost of a full external sort, where N is
  127298. ** the number of rows to sort is:
  127299. **
  127300. ** cost = (3.0 * N * log(N)).
  127301. **
  127302. ** Or, if the order-by clause has X terms but only the last Y
  127303. ** terms are out of order, then block-sorting will reduce the
  127304. ** sorting cost to:
  127305. **
  127306. ** cost = (3.0 * N * log(N)) * (Y/X)
  127307. **
  127308. ** The (Y/X) term is implemented using stack variable rScale
  127309. ** below. */
  127310. LogEst rScale, rSortCost;
  127311. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  127312. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  127313. rSortCost = nRow + rScale + 16;
  127314. /* Multiple by log(M) where M is the number of output rows.
  127315. ** Use the LIMIT for M if it is smaller */
  127316. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  127317. nRow = pWInfo->iLimit;
  127318. }
  127319. rSortCost += estLog(nRow);
  127320. return rSortCost;
  127321. }
  127322. /*
  127323. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  127324. ** attempts to find the lowest cost path that visits each WhereLoop
  127325. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  127326. **
  127327. ** Assume that the total number of output rows that will need to be sorted
  127328. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  127329. ** costs if nRowEst==0.
  127330. **
  127331. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  127332. ** error occurs.
  127333. */
  127334. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  127335. int mxChoice; /* Maximum number of simultaneous paths tracked */
  127336. int nLoop; /* Number of terms in the join */
  127337. Parse *pParse; /* Parsing context */
  127338. sqlite3 *db; /* The database connection */
  127339. int iLoop; /* Loop counter over the terms of the join */
  127340. int ii, jj; /* Loop counters */
  127341. int mxI = 0; /* Index of next entry to replace */
  127342. int nOrderBy; /* Number of ORDER BY clause terms */
  127343. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  127344. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  127345. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  127346. WherePath *aFrom; /* All nFrom paths at the previous level */
  127347. WherePath *aTo; /* The nTo best paths at the current level */
  127348. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  127349. WherePath *pTo; /* An element of aTo[] that we are working on */
  127350. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  127351. WhereLoop **pX; /* Used to divy up the pSpace memory */
  127352. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  127353. char *pSpace; /* Temporary memory used by this routine */
  127354. int nSpace; /* Bytes of space allocated at pSpace */
  127355. pParse = pWInfo->pParse;
  127356. db = pParse->db;
  127357. nLoop = pWInfo->nLevel;
  127358. /* TUNING: For simple queries, only the best path is tracked.
  127359. ** For 2-way joins, the 5 best paths are followed.
  127360. ** For joins of 3 or more tables, track the 10 best paths */
  127361. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  127362. assert( nLoop<=pWInfo->pTabList->nSrc );
  127363. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  127364. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  127365. ** case the purpose of this call is to estimate the number of rows returned
  127366. ** by the overall query. Once this estimate has been obtained, the caller
  127367. ** will invoke this function a second time, passing the estimate as the
  127368. ** nRowEst parameter. */
  127369. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  127370. nOrderBy = 0;
  127371. }else{
  127372. nOrderBy = pWInfo->pOrderBy->nExpr;
  127373. }
  127374. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  127375. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  127376. nSpace += sizeof(LogEst) * nOrderBy;
  127377. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  127378. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  127379. aTo = (WherePath*)pSpace;
  127380. aFrom = aTo+mxChoice;
  127381. memset(aFrom, 0, sizeof(aFrom[0]));
  127382. pX = (WhereLoop**)(aFrom+mxChoice);
  127383. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  127384. pFrom->aLoop = pX;
  127385. }
  127386. if( nOrderBy ){
  127387. /* If there is an ORDER BY clause and it is not being ignored, set up
  127388. ** space for the aSortCost[] array. Each element of the aSortCost array
  127389. ** is either zero - meaning it has not yet been initialized - or the
  127390. ** cost of sorting nRowEst rows of data where the first X terms of
  127391. ** the ORDER BY clause are already in order, where X is the array
  127392. ** index. */
  127393. aSortCost = (LogEst*)pX;
  127394. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  127395. }
  127396. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  127397. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  127398. /* Seed the search with a single WherePath containing zero WhereLoops.
  127399. **
  127400. ** TUNING: Do not let the number of iterations go above 28. If the cost
  127401. ** of computing an automatic index is not paid back within the first 28
  127402. ** rows, then do not use the automatic index. */
  127403. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  127404. nFrom = 1;
  127405. assert( aFrom[0].isOrdered==0 );
  127406. if( nOrderBy ){
  127407. /* If nLoop is zero, then there are no FROM terms in the query. Since
  127408. ** in this case the query may return a maximum of one row, the results
  127409. ** are already in the requested order. Set isOrdered to nOrderBy to
  127410. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  127411. ** -1, indicating that the result set may or may not be ordered,
  127412. ** depending on the loops added to the current plan. */
  127413. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  127414. }
  127415. /* Compute successively longer WherePaths using the previous generation
  127416. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  127417. ** best paths at each generation */
  127418. for(iLoop=0; iLoop<nLoop; iLoop++){
  127419. nTo = 0;
  127420. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  127421. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  127422. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  127423. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  127424. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  127425. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  127426. Bitmask maskNew; /* Mask of src visited by (..) */
  127427. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  127428. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  127429. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  127430. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
  127431. /* Do not use an automatic index if the this loop is expected
  127432. ** to run less than 2 times. */
  127433. assert( 10==sqlite3LogEst(2) );
  127434. continue;
  127435. }
  127436. /* At this point, pWLoop is a candidate to be the next loop.
  127437. ** Compute its cost */
  127438. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  127439. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  127440. nOut = pFrom->nRow + pWLoop->nOut;
  127441. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  127442. if( isOrdered<0 ){
  127443. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  127444. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  127445. iLoop, pWLoop, &revMask);
  127446. }else{
  127447. revMask = pFrom->revLoop;
  127448. }
  127449. if( isOrdered>=0 && isOrdered<nOrderBy ){
  127450. if( aSortCost[isOrdered]==0 ){
  127451. aSortCost[isOrdered] = whereSortingCost(
  127452. pWInfo, nRowEst, nOrderBy, isOrdered
  127453. );
  127454. }
  127455. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  127456. WHERETRACE(0x002,
  127457. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  127458. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  127459. rUnsorted, rCost));
  127460. }else{
  127461. rCost = rUnsorted;
  127462. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  127463. }
  127464. /* Check to see if pWLoop should be added to the set of
  127465. ** mxChoice best-so-far paths.
  127466. **
  127467. ** First look for an existing path among best-so-far paths
  127468. ** that covers the same set of loops and has the same isOrdered
  127469. ** setting as the current path candidate.
  127470. **
  127471. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  127472. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  127473. ** of legal values for isOrdered, -1..64.
  127474. */
  127475. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  127476. if( pTo->maskLoop==maskNew
  127477. && ((pTo->isOrdered^isOrdered)&0x80)==0
  127478. ){
  127479. testcase( jj==nTo-1 );
  127480. break;
  127481. }
  127482. }
  127483. if( jj>=nTo ){
  127484. /* None of the existing best-so-far paths match the candidate. */
  127485. if( nTo>=mxChoice
  127486. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  127487. ){
  127488. /* The current candidate is no better than any of the mxChoice
  127489. ** paths currently in the best-so-far buffer. So discard
  127490. ** this candidate as not viable. */
  127491. #ifdef WHERETRACE_ENABLED /* 0x4 */
  127492. if( sqlite3WhereTrace&0x4 ){
  127493. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  127494. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  127495. isOrdered>=0 ? isOrdered+'0' : '?');
  127496. }
  127497. #endif
  127498. continue;
  127499. }
  127500. /* If we reach this points it means that the new candidate path
  127501. ** needs to be added to the set of best-so-far paths. */
  127502. if( nTo<mxChoice ){
  127503. /* Increase the size of the aTo set by one */
  127504. jj = nTo++;
  127505. }else{
  127506. /* New path replaces the prior worst to keep count below mxChoice */
  127507. jj = mxI;
  127508. }
  127509. pTo = &aTo[jj];
  127510. #ifdef WHERETRACE_ENABLED /* 0x4 */
  127511. if( sqlite3WhereTrace&0x4 ){
  127512. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  127513. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  127514. isOrdered>=0 ? isOrdered+'0' : '?');
  127515. }
  127516. #endif
  127517. }else{
  127518. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  127519. ** same set of loops and has the same isOrdered setting as the
  127520. ** candidate path. Check to see if the candidate should replace
  127521. ** pTo or if the candidate should be skipped.
  127522. **
  127523. ** The conditional is an expanded vector comparison equivalent to:
  127524. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  127525. */
  127526. if( pTo->rCost<rCost
  127527. || (pTo->rCost==rCost
  127528. && (pTo->nRow<nOut
  127529. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  127530. )
  127531. )
  127532. ){
  127533. #ifdef WHERETRACE_ENABLED /* 0x4 */
  127534. if( sqlite3WhereTrace&0x4 ){
  127535. sqlite3DebugPrintf(
  127536. "Skip %s cost=%-3d,%3d,%3d order=%c",
  127537. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  127538. isOrdered>=0 ? isOrdered+'0' : '?');
  127539. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  127540. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  127541. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  127542. }
  127543. #endif
  127544. /* Discard the candidate path from further consideration */
  127545. testcase( pTo->rCost==rCost );
  127546. continue;
  127547. }
  127548. testcase( pTo->rCost==rCost+1 );
  127549. /* Control reaches here if the candidate path is better than the
  127550. ** pTo path. Replace pTo with the candidate. */
  127551. #ifdef WHERETRACE_ENABLED /* 0x4 */
  127552. if( sqlite3WhereTrace&0x4 ){
  127553. sqlite3DebugPrintf(
  127554. "Update %s cost=%-3d,%3d,%3d order=%c",
  127555. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  127556. isOrdered>=0 ? isOrdered+'0' : '?');
  127557. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  127558. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  127559. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  127560. }
  127561. #endif
  127562. }
  127563. /* pWLoop is a winner. Add it to the set of best so far */
  127564. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  127565. pTo->revLoop = revMask;
  127566. pTo->nRow = nOut;
  127567. pTo->rCost = rCost;
  127568. pTo->rUnsorted = rUnsorted;
  127569. pTo->isOrdered = isOrdered;
  127570. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  127571. pTo->aLoop[iLoop] = pWLoop;
  127572. if( nTo>=mxChoice ){
  127573. mxI = 0;
  127574. mxCost = aTo[0].rCost;
  127575. mxUnsorted = aTo[0].nRow;
  127576. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  127577. if( pTo->rCost>mxCost
  127578. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  127579. ){
  127580. mxCost = pTo->rCost;
  127581. mxUnsorted = pTo->rUnsorted;
  127582. mxI = jj;
  127583. }
  127584. }
  127585. }
  127586. }
  127587. }
  127588. #ifdef WHERETRACE_ENABLED /* >=2 */
  127589. if( sqlite3WhereTrace & 0x02 ){
  127590. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  127591. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  127592. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  127593. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  127594. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  127595. if( pTo->isOrdered>0 ){
  127596. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  127597. }else{
  127598. sqlite3DebugPrintf("\n");
  127599. }
  127600. }
  127601. }
  127602. #endif
  127603. /* Swap the roles of aFrom and aTo for the next generation */
  127604. pFrom = aTo;
  127605. aTo = aFrom;
  127606. aFrom = pFrom;
  127607. nFrom = nTo;
  127608. }
  127609. if( nFrom==0 ){
  127610. sqlite3ErrorMsg(pParse, "no query solution");
  127611. sqlite3DbFreeNN(db, pSpace);
  127612. return SQLITE_ERROR;
  127613. }
  127614. /* Find the lowest cost path. pFrom will be left pointing to that path */
  127615. pFrom = aFrom;
  127616. for(ii=1; ii<nFrom; ii++){
  127617. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  127618. }
  127619. assert( pWInfo->nLevel==nLoop );
  127620. /* Load the lowest cost path into pWInfo */
  127621. for(iLoop=0; iLoop<nLoop; iLoop++){
  127622. WhereLevel *pLevel = pWInfo->a + iLoop;
  127623. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  127624. pLevel->iFrom = pWLoop->iTab;
  127625. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  127626. }
  127627. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  127628. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  127629. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  127630. && nRowEst
  127631. ){
  127632. Bitmask notUsed;
  127633. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  127634. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  127635. if( rc==pWInfo->pResultSet->nExpr ){
  127636. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  127637. }
  127638. }
  127639. if( pWInfo->pOrderBy ){
  127640. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  127641. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  127642. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  127643. }
  127644. }else{
  127645. pWInfo->nOBSat = pFrom->isOrdered;
  127646. pWInfo->revMask = pFrom->revLoop;
  127647. if( pWInfo->nOBSat<=0 ){
  127648. pWInfo->nOBSat = 0;
  127649. if( nLoop>0 ){
  127650. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  127651. if( (wsFlags & WHERE_ONEROW)==0
  127652. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  127653. ){
  127654. Bitmask m = 0;
  127655. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  127656. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  127657. testcase( wsFlags & WHERE_IPK );
  127658. testcase( wsFlags & WHERE_COLUMN_IN );
  127659. if( rc==pWInfo->pOrderBy->nExpr ){
  127660. pWInfo->bOrderedInnerLoop = 1;
  127661. pWInfo->revMask = m;
  127662. }
  127663. }
  127664. }
  127665. }
  127666. }
  127667. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  127668. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  127669. ){
  127670. Bitmask revMask = 0;
  127671. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  127672. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  127673. );
  127674. assert( pWInfo->sorted==0 );
  127675. if( nOrder==pWInfo->pOrderBy->nExpr ){
  127676. pWInfo->sorted = 1;
  127677. pWInfo->revMask = revMask;
  127678. }
  127679. }
  127680. }
  127681. pWInfo->nRowOut = pFrom->nRow;
  127682. /* Free temporary memory and return success */
  127683. sqlite3DbFreeNN(db, pSpace);
  127684. return SQLITE_OK;
  127685. }
  127686. /*
  127687. ** Most queries use only a single table (they are not joins) and have
  127688. ** simple == constraints against indexed fields. This routine attempts
  127689. ** to plan those simple cases using much less ceremony than the
  127690. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  127691. ** times for the common case.
  127692. **
  127693. ** Return non-zero on success, if this query can be handled by this
  127694. ** no-frills query planner. Return zero if this query needs the
  127695. ** general-purpose query planner.
  127696. */
  127697. static int whereShortCut(WhereLoopBuilder *pBuilder){
  127698. WhereInfo *pWInfo;
  127699. struct SrcList_item *pItem;
  127700. WhereClause *pWC;
  127701. WhereTerm *pTerm;
  127702. WhereLoop *pLoop;
  127703. int iCur;
  127704. int j;
  127705. Table *pTab;
  127706. Index *pIdx;
  127707. pWInfo = pBuilder->pWInfo;
  127708. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  127709. assert( pWInfo->pTabList->nSrc>=1 );
  127710. pItem = pWInfo->pTabList->a;
  127711. pTab = pItem->pTab;
  127712. if( IsVirtual(pTab) ) return 0;
  127713. if( pItem->fg.isIndexedBy ) return 0;
  127714. iCur = pItem->iCursor;
  127715. pWC = &pWInfo->sWC;
  127716. pLoop = pBuilder->pNew;
  127717. pLoop->wsFlags = 0;
  127718. pLoop->nSkip = 0;
  127719. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  127720. if( pTerm ){
  127721. testcase( pTerm->eOperator & WO_IS );
  127722. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  127723. pLoop->aLTerm[0] = pTerm;
  127724. pLoop->nLTerm = 1;
  127725. pLoop->u.btree.nEq = 1;
  127726. /* TUNING: Cost of a rowid lookup is 10 */
  127727. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  127728. }else{
  127729. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  127730. int opMask;
  127731. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  127732. if( !IsUniqueIndex(pIdx)
  127733. || pIdx->pPartIdxWhere!=0
  127734. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  127735. ) continue;
  127736. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  127737. for(j=0; j<pIdx->nKeyCol; j++){
  127738. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  127739. if( pTerm==0 ) break;
  127740. testcase( pTerm->eOperator & WO_IS );
  127741. pLoop->aLTerm[j] = pTerm;
  127742. }
  127743. if( j!=pIdx->nKeyCol ) continue;
  127744. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  127745. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  127746. pLoop->wsFlags |= WHERE_IDX_ONLY;
  127747. }
  127748. pLoop->nLTerm = j;
  127749. pLoop->u.btree.nEq = j;
  127750. pLoop->u.btree.pIndex = pIdx;
  127751. /* TUNING: Cost of a unique index lookup is 15 */
  127752. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  127753. break;
  127754. }
  127755. }
  127756. if( pLoop->wsFlags ){
  127757. pLoop->nOut = (LogEst)1;
  127758. pWInfo->a[0].pWLoop = pLoop;
  127759. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  127760. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  127761. pWInfo->a[0].iTabCur = iCur;
  127762. pWInfo->nRowOut = 1;
  127763. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  127764. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  127765. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  127766. }
  127767. #ifdef SQLITE_DEBUG
  127768. pLoop->cId = '0';
  127769. #endif
  127770. return 1;
  127771. }
  127772. return 0;
  127773. }
  127774. /*
  127775. ** Helper function for exprIsDeterministic().
  127776. */
  127777. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  127778. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  127779. pWalker->eCode = 0;
  127780. return WRC_Abort;
  127781. }
  127782. return WRC_Continue;
  127783. }
  127784. /*
  127785. ** Return true if the expression contains no non-deterministic SQL
  127786. ** functions. Do not consider non-deterministic SQL functions that are
  127787. ** part of sub-select statements.
  127788. */
  127789. static int exprIsDeterministic(Expr *p){
  127790. Walker w;
  127791. memset(&w, 0, sizeof(w));
  127792. w.eCode = 1;
  127793. w.xExprCallback = exprNodeIsDeterministic;
  127794. w.xSelectCallback = sqlite3SelectWalkFail;
  127795. sqlite3WalkExpr(&w, p);
  127796. return w.eCode;
  127797. }
  127798. /*
  127799. ** Generate the beginning of the loop used for WHERE clause processing.
  127800. ** The return value is a pointer to an opaque structure that contains
  127801. ** information needed to terminate the loop. Later, the calling routine
  127802. ** should invoke sqlite3WhereEnd() with the return value of this function
  127803. ** in order to complete the WHERE clause processing.
  127804. **
  127805. ** If an error occurs, this routine returns NULL.
  127806. **
  127807. ** The basic idea is to do a nested loop, one loop for each table in
  127808. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  127809. ** same as a SELECT with only a single table in the FROM clause.) For
  127810. ** example, if the SQL is this:
  127811. **
  127812. ** SELECT * FROM t1, t2, t3 WHERE ...;
  127813. **
  127814. ** Then the code generated is conceptually like the following:
  127815. **
  127816. ** foreach row1 in t1 do \ Code generated
  127817. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  127818. ** foreach row3 in t3 do /
  127819. ** ...
  127820. ** end \ Code generated
  127821. ** end |-- by sqlite3WhereEnd()
  127822. ** end /
  127823. **
  127824. ** Note that the loops might not be nested in the order in which they
  127825. ** appear in the FROM clause if a different order is better able to make
  127826. ** use of indices. Note also that when the IN operator appears in
  127827. ** the WHERE clause, it might result in additional nested loops for
  127828. ** scanning through all values on the right-hand side of the IN.
  127829. **
  127830. ** There are Btree cursors associated with each table. t1 uses cursor
  127831. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  127832. ** And so forth. This routine generates code to open those VDBE cursors
  127833. ** and sqlite3WhereEnd() generates the code to close them.
  127834. **
  127835. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  127836. ** in pTabList pointing at their appropriate entries. The [...] code
  127837. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  127838. ** data from the various tables of the loop.
  127839. **
  127840. ** If the WHERE clause is empty, the foreach loops must each scan their
  127841. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  127842. ** the tables have indices and there are terms in the WHERE clause that
  127843. ** refer to those indices, a complete table scan can be avoided and the
  127844. ** code will run much faster. Most of the work of this routine is checking
  127845. ** to see if there are indices that can be used to speed up the loop.
  127846. **
  127847. ** Terms of the WHERE clause are also used to limit which rows actually
  127848. ** make it to the "..." in the middle of the loop. After each "foreach",
  127849. ** terms of the WHERE clause that use only terms in that loop and outer
  127850. ** loops are evaluated and if false a jump is made around all subsequent
  127851. ** inner loops (or around the "..." if the test occurs within the inner-
  127852. ** most loop)
  127853. **
  127854. ** OUTER JOINS
  127855. **
  127856. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  127857. **
  127858. ** foreach row1 in t1 do
  127859. ** flag = 0
  127860. ** foreach row2 in t2 do
  127861. ** start:
  127862. ** ...
  127863. ** flag = 1
  127864. ** end
  127865. ** if flag==0 then
  127866. ** move the row2 cursor to a null row
  127867. ** goto start
  127868. ** fi
  127869. ** end
  127870. **
  127871. ** ORDER BY CLAUSE PROCESSING
  127872. **
  127873. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  127874. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  127875. ** if there is one. If there is no ORDER BY clause or if this routine
  127876. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  127877. **
  127878. ** The iIdxCur parameter is the cursor number of an index. If
  127879. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  127880. ** to use for OR clause processing. The WHERE clause should use this
  127881. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  127882. ** the first cursor in an array of cursors for all indices. iIdxCur should
  127883. ** be used to compute the appropriate cursor depending on which index is
  127884. ** used.
  127885. */
  127886. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  127887. Parse *pParse, /* The parser context */
  127888. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  127889. Expr *pWhere, /* The WHERE clause */
  127890. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  127891. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  127892. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  127893. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  127894. ** If WHERE_USE_LIMIT, then the limit amount */
  127895. ){
  127896. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  127897. int nTabList; /* Number of elements in pTabList */
  127898. WhereInfo *pWInfo; /* Will become the return value of this function */
  127899. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  127900. Bitmask notReady; /* Cursors that are not yet positioned */
  127901. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  127902. WhereMaskSet *pMaskSet; /* The expression mask set */
  127903. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  127904. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  127905. int ii; /* Loop counter */
  127906. sqlite3 *db; /* Database connection */
  127907. int rc; /* Return code */
  127908. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  127909. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  127910. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  127911. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  127912. ));
  127913. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  127914. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  127915. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  127916. /* Variable initialization */
  127917. db = pParse->db;
  127918. memset(&sWLB, 0, sizeof(sWLB));
  127919. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  127920. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  127921. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  127922. sWLB.pOrderBy = pOrderBy;
  127923. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  127924. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  127925. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  127926. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  127927. }
  127928. /* The number of tables in the FROM clause is limited by the number of
  127929. ** bits in a Bitmask
  127930. */
  127931. testcase( pTabList->nSrc==BMS );
  127932. if( pTabList->nSrc>BMS ){
  127933. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  127934. return 0;
  127935. }
  127936. /* This function normally generates a nested loop for all tables in
  127937. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  127938. ** only generate code for the first table in pTabList and assume that
  127939. ** any cursors associated with subsequent tables are uninitialized.
  127940. */
  127941. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  127942. /* Allocate and initialize the WhereInfo structure that will become the
  127943. ** return value. A single allocation is used to store the WhereInfo
  127944. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  127945. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  127946. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  127947. ** some architectures. Hence the ROUND8() below.
  127948. */
  127949. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  127950. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  127951. if( db->mallocFailed ){
  127952. sqlite3DbFree(db, pWInfo);
  127953. pWInfo = 0;
  127954. goto whereBeginError;
  127955. }
  127956. pWInfo->pParse = pParse;
  127957. pWInfo->pTabList = pTabList;
  127958. pWInfo->pOrderBy = pOrderBy;
  127959. pWInfo->pWhere = pWhere;
  127960. pWInfo->pResultSet = pResultSet;
  127961. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  127962. pWInfo->nLevel = nTabList;
  127963. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  127964. pWInfo->wctrlFlags = wctrlFlags;
  127965. pWInfo->iLimit = iAuxArg;
  127966. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  127967. memset(&pWInfo->nOBSat, 0,
  127968. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  127969. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  127970. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  127971. pMaskSet = &pWInfo->sMaskSet;
  127972. sWLB.pWInfo = pWInfo;
  127973. sWLB.pWC = &pWInfo->sWC;
  127974. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  127975. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  127976. whereLoopInit(sWLB.pNew);
  127977. #ifdef SQLITE_DEBUG
  127978. sWLB.pNew->cId = '*';
  127979. #endif
  127980. /* Split the WHERE clause into separate subexpressions where each
  127981. ** subexpression is separated by an AND operator.
  127982. */
  127983. initMaskSet(pMaskSet);
  127984. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  127985. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  127986. /* Special case: No FROM clause
  127987. */
  127988. if( nTabList==0 ){
  127989. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  127990. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  127991. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  127992. }
  127993. }else{
  127994. /* Assign a bit from the bitmask to every term in the FROM clause.
  127995. **
  127996. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  127997. **
  127998. ** The rule of the previous sentence ensures thta if X is the bitmask for
  127999. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  128000. ** Knowing the bitmask for all tables to the left of a left join is
  128001. ** important. Ticket #3015.
  128002. **
  128003. ** Note that bitmasks are created for all pTabList->nSrc tables in
  128004. ** pTabList, not just the first nTabList tables. nTabList is normally
  128005. ** equal to pTabList->nSrc but might be shortened to 1 if the
  128006. ** WHERE_OR_SUBCLAUSE flag is set.
  128007. */
  128008. ii = 0;
  128009. do{
  128010. createMask(pMaskSet, pTabList->a[ii].iCursor);
  128011. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  128012. }while( (++ii)<pTabList->nSrc );
  128013. #ifdef SQLITE_DEBUG
  128014. {
  128015. Bitmask mx = 0;
  128016. for(ii=0; ii<pTabList->nSrc; ii++){
  128017. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  128018. assert( m>=mx );
  128019. mx = m;
  128020. }
  128021. }
  128022. #endif
  128023. }
  128024. /* Analyze all of the subexpressions. */
  128025. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  128026. if( db->mallocFailed ) goto whereBeginError;
  128027. /* Special case: WHERE terms that do not refer to any tables in the join
  128028. ** (constant expressions). Evaluate each such term, and jump over all the
  128029. ** generated code if the result is not true.
  128030. **
  128031. ** Do not do this if the expression contains non-deterministic functions
  128032. ** that are not within a sub-select. This is not strictly required, but
  128033. ** preserves SQLite's legacy behaviour in the following two cases:
  128034. **
  128035. ** FROM ... WHERE random()>0; -- eval random() once per row
  128036. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  128037. */
  128038. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  128039. WhereTerm *pT = &sWLB.pWC->a[ii];
  128040. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  128041. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  128042. pT->wtFlags |= TERM_CODED;
  128043. }
  128044. }
  128045. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  128046. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  128047. /* The DISTINCT marking is pointless. Ignore it. */
  128048. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  128049. }else if( pOrderBy==0 ){
  128050. /* Try to ORDER BY the result set to make distinct processing easier */
  128051. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  128052. pWInfo->pOrderBy = pResultSet;
  128053. }
  128054. }
  128055. /* Construct the WhereLoop objects */
  128056. #if defined(WHERETRACE_ENABLED)
  128057. if( sqlite3WhereTrace & 0xffff ){
  128058. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  128059. if( wctrlFlags & WHERE_USE_LIMIT ){
  128060. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  128061. }
  128062. sqlite3DebugPrintf(")\n");
  128063. }
  128064. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  128065. sqlite3WhereClausePrint(sWLB.pWC);
  128066. }
  128067. #endif
  128068. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  128069. rc = whereLoopAddAll(&sWLB);
  128070. if( rc ) goto whereBeginError;
  128071. #ifdef WHERETRACE_ENABLED
  128072. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  128073. WhereLoop *p;
  128074. int i;
  128075. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  128076. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  128077. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  128078. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  128079. whereLoopPrint(p, sWLB.pWC);
  128080. }
  128081. }
  128082. #endif
  128083. wherePathSolver(pWInfo, 0);
  128084. if( db->mallocFailed ) goto whereBeginError;
  128085. if( pWInfo->pOrderBy ){
  128086. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  128087. if( db->mallocFailed ) goto whereBeginError;
  128088. }
  128089. }
  128090. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  128091. pWInfo->revMask = ALLBITS;
  128092. }
  128093. if( pParse->nErr || NEVER(db->mallocFailed) ){
  128094. goto whereBeginError;
  128095. }
  128096. #ifdef WHERETRACE_ENABLED
  128097. if( sqlite3WhereTrace ){
  128098. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  128099. if( pWInfo->nOBSat>0 ){
  128100. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  128101. }
  128102. switch( pWInfo->eDistinct ){
  128103. case WHERE_DISTINCT_UNIQUE: {
  128104. sqlite3DebugPrintf(" DISTINCT=unique");
  128105. break;
  128106. }
  128107. case WHERE_DISTINCT_ORDERED: {
  128108. sqlite3DebugPrintf(" DISTINCT=ordered");
  128109. break;
  128110. }
  128111. case WHERE_DISTINCT_UNORDERED: {
  128112. sqlite3DebugPrintf(" DISTINCT=unordered");
  128113. break;
  128114. }
  128115. }
  128116. sqlite3DebugPrintf("\n");
  128117. for(ii=0; ii<pWInfo->nLevel; ii++){
  128118. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  128119. }
  128120. }
  128121. #endif
  128122. /* Attempt to omit tables from the join that do not effect the result */
  128123. if( pWInfo->nLevel>=2
  128124. && pResultSet!=0
  128125. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  128126. ){
  128127. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  128128. if( sWLB.pOrderBy ){
  128129. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  128130. }
  128131. while( pWInfo->nLevel>=2 ){
  128132. WhereTerm *pTerm, *pEnd;
  128133. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  128134. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  128135. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  128136. && (pLoop->wsFlags & WHERE_ONEROW)==0
  128137. ){
  128138. break;
  128139. }
  128140. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  128141. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  128142. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  128143. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  128144. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  128145. ){
  128146. break;
  128147. }
  128148. }
  128149. if( pTerm<pEnd ) break;
  128150. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  128151. pWInfo->nLevel--;
  128152. nTabList--;
  128153. }
  128154. }
  128155. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  128156. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  128157. /* If the caller is an UPDATE or DELETE statement that is requesting
  128158. ** to use a one-pass algorithm, determine if this is appropriate.
  128159. */
  128160. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  128161. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  128162. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  128163. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  128164. if( bOnerow
  128165. || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
  128166. && 0==(wsFlags & WHERE_VIRTUALTABLE))
  128167. ){
  128168. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  128169. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  128170. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  128171. bFordelete = OPFLAG_FORDELETE;
  128172. }
  128173. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  128174. }
  128175. }
  128176. }
  128177. /* Open all tables in the pTabList and any indices selected for
  128178. ** searching those tables.
  128179. */
  128180. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  128181. Table *pTab; /* Table to open */
  128182. int iDb; /* Index of database containing table/index */
  128183. struct SrcList_item *pTabItem;
  128184. pTabItem = &pTabList->a[pLevel->iFrom];
  128185. pTab = pTabItem->pTab;
  128186. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  128187. pLoop = pLevel->pWLoop;
  128188. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  128189. /* Do nothing */
  128190. }else
  128191. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128192. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  128193. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  128194. int iCur = pTabItem->iCursor;
  128195. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  128196. }else if( IsVirtual(pTab) ){
  128197. /* noop */
  128198. }else
  128199. #endif
  128200. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  128201. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  128202. int op = OP_OpenRead;
  128203. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  128204. op = OP_OpenWrite;
  128205. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  128206. };
  128207. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  128208. assert( pTabItem->iCursor==pLevel->iTabCur );
  128209. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  128210. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  128211. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  128212. Bitmask b = pTabItem->colUsed;
  128213. int n = 0;
  128214. for(; b; b=b>>1, n++){}
  128215. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  128216. assert( n<=pTab->nCol );
  128217. }
  128218. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  128219. if( pLoop->u.btree.pIndex!=0 ){
  128220. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  128221. }else
  128222. #endif
  128223. {
  128224. sqlite3VdbeChangeP5(v, bFordelete);
  128225. }
  128226. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  128227. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  128228. (const u8*)&pTabItem->colUsed, P4_INT64);
  128229. #endif
  128230. }else{
  128231. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  128232. }
  128233. if( pLoop->wsFlags & WHERE_INDEXED ){
  128234. Index *pIx = pLoop->u.btree.pIndex;
  128235. int iIndexCur;
  128236. int op = OP_OpenRead;
  128237. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  128238. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  128239. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  128240. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  128241. ){
  128242. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  128243. ** WITHOUT ROWID table. No need for a separate index */
  128244. iIndexCur = pLevel->iTabCur;
  128245. op = 0;
  128246. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  128247. Index *pJ = pTabItem->pTab->pIndex;
  128248. iIndexCur = iAuxArg;
  128249. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  128250. while( ALWAYS(pJ) && pJ!=pIx ){
  128251. iIndexCur++;
  128252. pJ = pJ->pNext;
  128253. }
  128254. op = OP_OpenWrite;
  128255. pWInfo->aiCurOnePass[1] = iIndexCur;
  128256. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  128257. iIndexCur = iAuxArg;
  128258. op = OP_ReopenIdx;
  128259. }else{
  128260. iIndexCur = pParse->nTab++;
  128261. }
  128262. pLevel->iIdxCur = iIndexCur;
  128263. assert( pIx->pSchema==pTab->pSchema );
  128264. assert( iIndexCur>=0 );
  128265. if( op ){
  128266. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  128267. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  128268. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  128269. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  128270. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  128271. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  128272. ){
  128273. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  128274. }
  128275. VdbeComment((v, "%s", pIx->zName));
  128276. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  128277. {
  128278. u64 colUsed = 0;
  128279. int ii, jj;
  128280. for(ii=0; ii<pIx->nColumn; ii++){
  128281. jj = pIx->aiColumn[ii];
  128282. if( jj<0 ) continue;
  128283. if( jj>63 ) jj = 63;
  128284. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  128285. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  128286. }
  128287. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  128288. (u8*)&colUsed, P4_INT64);
  128289. }
  128290. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  128291. }
  128292. }
  128293. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  128294. }
  128295. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  128296. if( db->mallocFailed ) goto whereBeginError;
  128297. /* Generate the code to do the search. Each iteration of the for
  128298. ** loop below generates code for a single nested loop of the VM
  128299. ** program.
  128300. */
  128301. notReady = ~(Bitmask)0;
  128302. for(ii=0; ii<nTabList; ii++){
  128303. int addrExplain;
  128304. int wsFlags;
  128305. pLevel = &pWInfo->a[ii];
  128306. wsFlags = pLevel->pWLoop->wsFlags;
  128307. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  128308. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  128309. constructAutomaticIndex(pParse, &pWInfo->sWC,
  128310. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  128311. if( db->mallocFailed ) goto whereBeginError;
  128312. }
  128313. #endif
  128314. addrExplain = sqlite3WhereExplainOneScan(
  128315. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  128316. );
  128317. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  128318. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  128319. pWInfo->iContinue = pLevel->addrCont;
  128320. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  128321. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  128322. }
  128323. }
  128324. /* Done. */
  128325. VdbeModuleComment((v, "Begin WHERE-core"));
  128326. return pWInfo;
  128327. /* Jump here if malloc fails */
  128328. whereBeginError:
  128329. if( pWInfo ){
  128330. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  128331. whereInfoFree(db, pWInfo);
  128332. }
  128333. return 0;
  128334. }
  128335. /*
  128336. ** Generate the end of the WHERE loop. See comments on
  128337. ** sqlite3WhereBegin() for additional information.
  128338. */
  128339. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  128340. Parse *pParse = pWInfo->pParse;
  128341. Vdbe *v = pParse->pVdbe;
  128342. int i;
  128343. WhereLevel *pLevel;
  128344. WhereLoop *pLoop;
  128345. SrcList *pTabList = pWInfo->pTabList;
  128346. sqlite3 *db = pParse->db;
  128347. /* Generate loop termination code.
  128348. */
  128349. VdbeModuleComment((v, "End WHERE-core"));
  128350. sqlite3ExprCacheClear(pParse);
  128351. for(i=pWInfo->nLevel-1; i>=0; i--){
  128352. int addr;
  128353. pLevel = &pWInfo->a[i];
  128354. pLoop = pLevel->pWLoop;
  128355. if( pLevel->op!=OP_Noop ){
  128356. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  128357. int addrSeek = 0;
  128358. Index *pIdx;
  128359. int n;
  128360. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  128361. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  128362. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  128363. && (n = pLoop->u.btree.nIdxCol)>0
  128364. && pIdx->aiRowLogEst[n]>=36
  128365. ){
  128366. int r1 = pParse->nMem+1;
  128367. int j, op;
  128368. for(j=0; j<n; j++){
  128369. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  128370. }
  128371. pParse->nMem += n+1;
  128372. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  128373. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  128374. VdbeCoverageIf(v, op==OP_SeekLT);
  128375. VdbeCoverageIf(v, op==OP_SeekGT);
  128376. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  128377. }
  128378. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  128379. /* The common case: Advance to the next row */
  128380. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  128381. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  128382. sqlite3VdbeChangeP5(v, pLevel->p5);
  128383. VdbeCoverage(v);
  128384. VdbeCoverageIf(v, pLevel->op==OP_Next);
  128385. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  128386. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  128387. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  128388. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  128389. #endif
  128390. }else{
  128391. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  128392. }
  128393. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  128394. struct InLoop *pIn;
  128395. int j;
  128396. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  128397. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  128398. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  128399. if( pIn->eEndLoopOp!=OP_Noop ){
  128400. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  128401. VdbeCoverage(v);
  128402. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  128403. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  128404. }
  128405. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  128406. }
  128407. }
  128408. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  128409. if( pLevel->addrSkip ){
  128410. sqlite3VdbeGoto(v, pLevel->addrSkip);
  128411. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  128412. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  128413. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  128414. }
  128415. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  128416. if( pLevel->addrLikeRep ){
  128417. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  128418. pLevel->addrLikeRep);
  128419. VdbeCoverage(v);
  128420. }
  128421. #endif
  128422. if( pLevel->iLeftJoin ){
  128423. int ws = pLoop->wsFlags;
  128424. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  128425. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  128426. if( (ws & WHERE_IDX_ONLY)==0 ){
  128427. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  128428. }
  128429. if( (ws & WHERE_INDEXED)
  128430. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  128431. ){
  128432. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  128433. }
  128434. if( pLevel->op==OP_Return ){
  128435. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  128436. }else{
  128437. sqlite3VdbeGoto(v, pLevel->addrFirst);
  128438. }
  128439. sqlite3VdbeJumpHere(v, addr);
  128440. }
  128441. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  128442. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  128443. }
  128444. /* The "break" point is here, just past the end of the outer loop.
  128445. ** Set it.
  128446. */
  128447. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  128448. assert( pWInfo->nLevel<=pTabList->nSrc );
  128449. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  128450. int k, last;
  128451. VdbeOp *pOp;
  128452. Index *pIdx = 0;
  128453. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  128454. Table *pTab = pTabItem->pTab;
  128455. assert( pTab!=0 );
  128456. pLoop = pLevel->pWLoop;
  128457. /* For a co-routine, change all OP_Column references to the table of
  128458. ** the co-routine into OP_Copy of result contained in a register.
  128459. ** OP_Rowid becomes OP_Null.
  128460. */
  128461. if( pTabItem->fg.viaCoroutine ){
  128462. testcase( pParse->db->mallocFailed );
  128463. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  128464. pTabItem->regResult, 0);
  128465. continue;
  128466. }
  128467. /* If this scan uses an index, make VDBE code substitutions to read data
  128468. ** from the index instead of from the table where possible. In some cases
  128469. ** this optimization prevents the table from ever being read, which can
  128470. ** yield a significant performance boost.
  128471. **
  128472. ** Calls to the code generator in between sqlite3WhereBegin and
  128473. ** sqlite3WhereEnd will have created code that references the table
  128474. ** directly. This loop scans all that code looking for opcodes
  128475. ** that reference the table and converts them into opcodes that
  128476. ** reference the index.
  128477. */
  128478. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  128479. pIdx = pLoop->u.btree.pIndex;
  128480. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  128481. pIdx = pLevel->u.pCovidx;
  128482. }
  128483. if( pIdx
  128484. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  128485. && !db->mallocFailed
  128486. ){
  128487. last = sqlite3VdbeCurrentAddr(v);
  128488. k = pLevel->addrBody;
  128489. pOp = sqlite3VdbeGetOp(v, k);
  128490. for(; k<last; k++, pOp++){
  128491. if( pOp->p1!=pLevel->iTabCur ) continue;
  128492. if( pOp->opcode==OP_Column ){
  128493. int x = pOp->p2;
  128494. assert( pIdx->pTable==pTab );
  128495. if( !HasRowid(pTab) ){
  128496. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  128497. x = pPk->aiColumn[x];
  128498. assert( x>=0 );
  128499. }
  128500. x = sqlite3ColumnOfIndex(pIdx, x);
  128501. if( x>=0 ){
  128502. pOp->p2 = x;
  128503. pOp->p1 = pLevel->iIdxCur;
  128504. }
  128505. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  128506. || pWInfo->eOnePass );
  128507. }else if( pOp->opcode==OP_Rowid ){
  128508. pOp->p1 = pLevel->iIdxCur;
  128509. pOp->opcode = OP_IdxRowid;
  128510. }else if( pOp->opcode==OP_IfNullRow ){
  128511. pOp->p1 = pLevel->iIdxCur;
  128512. }
  128513. }
  128514. }
  128515. }
  128516. /* Final cleanup
  128517. */
  128518. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  128519. whereInfoFree(db, pWInfo);
  128520. return;
  128521. }
  128522. /************** End of where.c ***********************************************/
  128523. /************** Begin file parse.c *******************************************/
  128524. /*
  128525. ** 2000-05-29
  128526. **
  128527. ** The author disclaims copyright to this source code. In place of
  128528. ** a legal notice, here is a blessing:
  128529. **
  128530. ** May you do good and not evil.
  128531. ** May you find forgiveness for yourself and forgive others.
  128532. ** May you share freely, never taking more than you give.
  128533. **
  128534. *************************************************************************
  128535. ** Driver template for the LEMON parser generator.
  128536. **
  128537. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  128538. ** this template to construct a parser. The "lemon" program inserts text
  128539. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  128540. ** interstitial "-" characters) contained in this template is changed into
  128541. ** the value of the %name directive from the grammar. Otherwise, the content
  128542. ** of this template is copied straight through into the generate parser
  128543. ** source file.
  128544. **
  128545. ** The following is the concatenation of all %include directives from the
  128546. ** input grammar file:
  128547. */
  128548. /* #include <stdio.h> */
  128549. /************ Begin %include sections from the grammar ************************/
  128550. /* #include "sqliteInt.h" */
  128551. /*
  128552. ** Disable all error recovery processing in the parser push-down
  128553. ** automaton.
  128554. */
  128555. #define YYNOERRORRECOVERY 1
  128556. /*
  128557. ** Make yytestcase() the same as testcase()
  128558. */
  128559. #define yytestcase(X) testcase(X)
  128560. /*
  128561. ** Indicate that sqlite3ParserFree() will never be called with a null
  128562. ** pointer.
  128563. */
  128564. #define YYPARSEFREENEVERNULL 1
  128565. /*
  128566. ** In the amalgamation, the parse.c file generated by lemon and the
  128567. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  128568. ** has access to the the size of the yyParser object and so the parser
  128569. ** engine can be allocated from stack. In that case, only the
  128570. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  128571. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  128572. ** omitted.
  128573. */
  128574. #ifdef SQLITE_AMALGAMATION
  128575. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  128576. #endif
  128577. /*
  128578. ** Alternative datatype for the argument to the malloc() routine passed
  128579. ** into sqlite3ParserAlloc(). The default is size_t.
  128580. */
  128581. #define YYMALLOCARGTYPE u64
  128582. /*
  128583. ** An instance of this structure holds information about the
  128584. ** LIMIT clause of a SELECT statement.
  128585. */
  128586. struct LimitVal {
  128587. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  128588. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  128589. };
  128590. /*
  128591. ** An instance of the following structure describes the event of a
  128592. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  128593. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  128594. **
  128595. ** UPDATE ON (a,b,c)
  128596. **
  128597. ** Then the "b" IdList records the list "a,b,c".
  128598. */
  128599. struct TrigEvent { int a; IdList * b; };
  128600. /*
  128601. ** Disable lookaside memory allocation for objects that might be
  128602. ** shared across database connections.
  128603. */
  128604. static void disableLookaside(Parse *pParse){
  128605. pParse->disableLookaside++;
  128606. pParse->db->lookaside.bDisable++;
  128607. }
  128608. /*
  128609. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  128610. ** all elements in the list. And make sure list length does not exceed
  128611. ** SQLITE_LIMIT_COMPOUND_SELECT.
  128612. */
  128613. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  128614. if( p->pPrior ){
  128615. Select *pNext = 0, *pLoop;
  128616. int mxSelect, cnt = 0;
  128617. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  128618. pLoop->pNext = pNext;
  128619. pLoop->selFlags |= SF_Compound;
  128620. }
  128621. if( (p->selFlags & SF_MultiValue)==0 &&
  128622. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  128623. cnt>mxSelect
  128624. ){
  128625. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  128626. }
  128627. }
  128628. }
  128629. /* This is a utility routine used to set the ExprSpan.zStart and
  128630. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  128631. ** range of text beginning with pStart and going to the end of pEnd.
  128632. */
  128633. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  128634. pOut->zStart = pStart->z;
  128635. pOut->zEnd = &pEnd->z[pEnd->n];
  128636. }
  128637. /* Construct a new Expr object from a single identifier. Use the
  128638. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  128639. ** that created the expression.
  128640. */
  128641. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
  128642. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  128643. if( p ){
  128644. memset(p, 0, sizeof(Expr));
  128645. p->op = (u8)op;
  128646. p->flags = EP_Leaf;
  128647. p->iAgg = -1;
  128648. p->u.zToken = (char*)&p[1];
  128649. memcpy(p->u.zToken, t.z, t.n);
  128650. p->u.zToken[t.n] = 0;
  128651. if( sqlite3Isquote(p->u.zToken[0]) ){
  128652. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  128653. sqlite3Dequote(p->u.zToken);
  128654. }
  128655. #if SQLITE_MAX_EXPR_DEPTH>0
  128656. p->nHeight = 1;
  128657. #endif
  128658. }
  128659. pOut->pExpr = p;
  128660. pOut->zStart = t.z;
  128661. pOut->zEnd = &t.z[t.n];
  128662. }
  128663. /* This routine constructs a binary expression node out of two ExprSpan
  128664. ** objects and uses the result to populate a new ExprSpan object.
  128665. */
  128666. static void spanBinaryExpr(
  128667. Parse *pParse, /* The parsing context. Errors accumulate here */
  128668. int op, /* The binary operation */
  128669. ExprSpan *pLeft, /* The left operand, and output */
  128670. ExprSpan *pRight /* The right operand */
  128671. ){
  128672. pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
  128673. pLeft->zEnd = pRight->zEnd;
  128674. }
  128675. /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
  128676. ** outside of *ppExpr.
  128677. */
  128678. static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
  128679. if( doNot ){
  128680. pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
  128681. }
  128682. }
  128683. /* Construct an expression node for a unary postfix operator
  128684. */
  128685. static void spanUnaryPostfix(
  128686. Parse *pParse, /* Parsing context to record errors */
  128687. int op, /* The operator */
  128688. ExprSpan *pOperand, /* The operand, and output */
  128689. Token *pPostOp /* The operand token for setting the span */
  128690. ){
  128691. pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  128692. pOperand->zEnd = &pPostOp->z[pPostOp->n];
  128693. }
  128694. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  128695. ** unary TK_ISNULL or TK_NOTNULL expression. */
  128696. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  128697. sqlite3 *db = pParse->db;
  128698. if( pA && pY && pY->op==TK_NULL ){
  128699. pA->op = (u8)op;
  128700. sqlite3ExprDelete(db, pA->pRight);
  128701. pA->pRight = 0;
  128702. }
  128703. }
  128704. /* Construct an expression node for a unary prefix operator
  128705. */
  128706. static void spanUnaryPrefix(
  128707. ExprSpan *pOut, /* Write the new expression node here */
  128708. Parse *pParse, /* Parsing context to record errors */
  128709. int op, /* The operator */
  128710. ExprSpan *pOperand, /* The operand */
  128711. Token *pPreOp /* The operand token for setting the span */
  128712. ){
  128713. pOut->zStart = pPreOp->z;
  128714. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  128715. pOut->zEnd = pOperand->zEnd;
  128716. }
  128717. /* Add a single new term to an ExprList that is used to store a
  128718. ** list of identifiers. Report an error if the ID list contains
  128719. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  128720. ** error while parsing a legacy schema.
  128721. */
  128722. static ExprList *parserAddExprIdListTerm(
  128723. Parse *pParse,
  128724. ExprList *pPrior,
  128725. Token *pIdToken,
  128726. int hasCollate,
  128727. int sortOrder
  128728. ){
  128729. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  128730. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  128731. && pParse->db->init.busy==0
  128732. ){
  128733. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  128734. pIdToken->n, pIdToken->z);
  128735. }
  128736. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  128737. return p;
  128738. }
  128739. /**************** End of %include directives **********************************/
  128740. /* These constants specify the various numeric values for terminal symbols
  128741. ** in a format understandable to "makeheaders". This section is blank unless
  128742. ** "lemon" is run with the "-m" command-line option.
  128743. ***************** Begin makeheaders token definitions *************************/
  128744. /**************** End makeheaders token definitions ***************************/
  128745. /* The next sections is a series of control #defines.
  128746. ** various aspects of the generated parser.
  128747. ** YYCODETYPE is the data type used to store the integer codes
  128748. ** that represent terminal and non-terminal symbols.
  128749. ** "unsigned char" is used if there are fewer than
  128750. ** 256 symbols. Larger types otherwise.
  128751. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  128752. ** any terminal or nonterminal symbol.
  128753. ** YYFALLBACK If defined, this indicates that one or more tokens
  128754. ** (also known as: "terminal symbols") have fall-back
  128755. ** values which should be used if the original symbol
  128756. ** would not parse. This permits keywords to sometimes
  128757. ** be used as identifiers, for example.
  128758. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  128759. ** that indicate what to do in response to the next
  128760. ** token.
  128761. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  128762. ** symbols. Background: A "minor type" is a semantic
  128763. ** value associated with a terminal or non-terminal
  128764. ** symbols. For example, for an "ID" terminal symbol,
  128765. ** the minor type might be the name of the identifier.
  128766. ** Each non-terminal can have a different minor type.
  128767. ** Terminal symbols all have the same minor type, though.
  128768. ** This macros defines the minor type for terminal
  128769. ** symbols.
  128770. ** YYMINORTYPE is the data type used for all minor types.
  128771. ** This is typically a union of many types, one of
  128772. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  128773. ** for terminal symbols is called "yy0".
  128774. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  128775. ** zero the stack is dynamically sized using realloc()
  128776. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  128777. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  128778. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  128779. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  128780. ** YYERRORSYMBOL is the code number of the error symbol. If not
  128781. ** defined, then do no error processing.
  128782. ** YYNSTATE the combined number of states.
  128783. ** YYNRULE the number of rules in the grammar
  128784. ** YY_MAX_SHIFT Maximum value for shift actions
  128785. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  128786. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  128787. ** YY_MIN_REDUCE Minimum value for reduce actions
  128788. ** YY_MAX_REDUCE Maximum value for reduce actions
  128789. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  128790. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  128791. ** YY_NO_ACTION The yy_action[] code for no-op
  128792. */
  128793. #ifndef INTERFACE
  128794. # define INTERFACE 1
  128795. #endif
  128796. /************* Begin control #defines *****************************************/
  128797. #define YYCODETYPE unsigned char
  128798. #define YYNOCODE 252
  128799. #define YYACTIONTYPE unsigned short int
  128800. #define YYWILDCARD 83
  128801. #define sqlite3ParserTOKENTYPE Token
  128802. typedef union {
  128803. int yyinit;
  128804. sqlite3ParserTOKENTYPE yy0;
  128805. Expr* yy72;
  128806. TriggerStep* yy145;
  128807. ExprList* yy148;
  128808. SrcList* yy185;
  128809. ExprSpan yy190;
  128810. int yy194;
  128811. Select* yy243;
  128812. IdList* yy254;
  128813. With* yy285;
  128814. struct TrigEvent yy332;
  128815. struct LimitVal yy354;
  128816. struct {int value; int mask;} yy497;
  128817. } YYMINORTYPE;
  128818. #ifndef YYSTACKDEPTH
  128819. #define YYSTACKDEPTH 100
  128820. #endif
  128821. #define sqlite3ParserARG_SDECL Parse *pParse;
  128822. #define sqlite3ParserARG_PDECL ,Parse *pParse
  128823. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  128824. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  128825. #define YYFALLBACK 1
  128826. #define YYNSTATE 455
  128827. #define YYNRULE 329
  128828. #define YY_MAX_SHIFT 454
  128829. #define YY_MIN_SHIFTREDUCE 664
  128830. #define YY_MAX_SHIFTREDUCE 992
  128831. #define YY_MIN_REDUCE 993
  128832. #define YY_MAX_REDUCE 1321
  128833. #define YY_ERROR_ACTION 1322
  128834. #define YY_ACCEPT_ACTION 1323
  128835. #define YY_NO_ACTION 1324
  128836. /************* End control #defines *******************************************/
  128837. /* Define the yytestcase() macro to be a no-op if is not already defined
  128838. ** otherwise.
  128839. **
  128840. ** Applications can choose to define yytestcase() in the %include section
  128841. ** to a macro that can assist in verifying code coverage. For production
  128842. ** code the yytestcase() macro should be turned off. But it is useful
  128843. ** for testing.
  128844. */
  128845. #ifndef yytestcase
  128846. # define yytestcase(X)
  128847. #endif
  128848. /* Next are the tables used to determine what action to take based on the
  128849. ** current state and lookahead token. These tables are used to implement
  128850. ** functions that take a state number and lookahead value and return an
  128851. ** action integer.
  128852. **
  128853. ** Suppose the action integer is N. Then the action is determined as
  128854. ** follows
  128855. **
  128856. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  128857. ** token onto the stack and goto state N.
  128858. **
  128859. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  128860. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  128861. **
  128862. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  128863. ** and YY_MAX_REDUCE
  128864. **
  128865. ** N == YY_ERROR_ACTION A syntax error has occurred.
  128866. **
  128867. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  128868. **
  128869. ** N == YY_NO_ACTION No such action. Denotes unused
  128870. ** slots in the yy_action[] table.
  128871. **
  128872. ** The action table is constructed as a single large table named yy_action[].
  128873. ** Given state S and lookahead X, the action is computed as either:
  128874. **
  128875. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  128876. ** (B) N = yy_default[S]
  128877. **
  128878. ** The (A) formula is preferred. The B formula is used instead if:
  128879. ** (1) The yy_shift_ofst[S]+X value is out of range, or
  128880. ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
  128881. ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
  128882. ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
  128883. ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  128884. ** Hence only tests (1) and (2) need to be evaluated.)
  128885. **
  128886. ** The formulas above are for computing the action when the lookahead is
  128887. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  128888. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  128889. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  128890. ** YY_SHIFT_USE_DFLT.
  128891. **
  128892. ** The following are the tables generated in this section:
  128893. **
  128894. ** yy_action[] A single table containing all actions.
  128895. ** yy_lookahead[] A table containing the lookahead for each entry in
  128896. ** yy_action. Used to detect hash collisions.
  128897. ** yy_shift_ofst[] For each state, the offset into yy_action for
  128898. ** shifting terminals.
  128899. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  128900. ** shifting non-terminals after a reduce.
  128901. ** yy_default[] Default action for each state.
  128902. **
  128903. *********** Begin parsing tables **********************************************/
  128904. #define YY_ACTTAB_COUNT (1566)
  128905. static const YYACTIONTYPE yy_action[] = {
  128906. /* 0 */ 324, 1323, 155, 155, 2, 203, 94, 94, 94, 93,
  128907. /* 10 */ 350, 98, 98, 98, 98, 91, 95, 95, 94, 94,
  128908. /* 20 */ 94, 93, 350, 268, 99, 100, 90, 971, 971, 847,
  128909. /* 30 */ 850, 839, 839, 97, 97, 98, 98, 98, 98, 350,
  128910. /* 40 */ 969, 96, 96, 96, 96, 95, 95, 94, 94, 94,
  128911. /* 50 */ 93, 350, 950, 96, 96, 96, 96, 95, 95, 94,
  128912. /* 60 */ 94, 94, 93, 350, 250, 96, 96, 96, 96, 95,
  128913. /* 70 */ 95, 94, 94, 94, 93, 350, 224, 224, 969, 132,
  128914. /* 80 */ 888, 348, 347, 415, 172, 324, 1286, 449, 414, 950,
  128915. /* 90 */ 951, 952, 808, 977, 1032, 950, 300, 786, 428, 132,
  128916. /* 100 */ 975, 362, 976, 9, 9, 787, 132, 52, 52, 99,
  128917. /* 110 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
  128918. /* 120 */ 98, 98, 98, 98, 372, 978, 241, 978, 262, 369,
  128919. /* 130 */ 261, 120, 950, 951, 952, 194, 58, 324, 401, 398,
  128920. /* 140 */ 397, 808, 427, 429, 75, 808, 1260, 1260, 132, 396,
  128921. /* 150 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
  128922. /* 160 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839,
  128923. /* 170 */ 97, 97, 98, 98, 98, 98, 786, 262, 369, 261,
  128924. /* 180 */ 826, 262, 364, 251, 787, 1084, 101, 1114, 72, 324,
  128925. /* 190 */ 227, 1113, 242, 411, 442, 819, 92, 89, 178, 818,
  128926. /* 200 */ 1022, 268, 96, 96, 96, 96, 95, 95, 94, 94,
  128927. /* 210 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850,
  128928. /* 220 */ 839, 839, 97, 97, 98, 98, 98, 98, 449, 372,
  128929. /* 230 */ 818, 818, 820, 92, 89, 178, 60, 92, 89, 178,
  128930. /* 240 */ 1025, 324, 357, 930, 1316, 300, 61, 1316, 52, 52,
  128931. /* 250 */ 836, 836, 848, 851, 96, 96, 96, 96, 95, 95,
  128932. /* 260 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971,
  128933. /* 270 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98,
  128934. /* 280 */ 92, 89, 178, 427, 412, 198, 930, 1317, 454, 995,
  128935. /* 290 */ 1317, 355, 1024, 324, 243, 231, 114, 277, 348, 347,
  128936. /* 300 */ 1242, 950, 416, 1071, 928, 840, 96, 96, 96, 96,
  128937. /* 310 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90,
  128938. /* 320 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
  128939. /* 330 */ 98, 98, 449, 328, 449, 120, 23, 256, 950, 951,
  128940. /* 340 */ 952, 968, 978, 438, 978, 324, 329, 928, 954, 701,
  128941. /* 350 */ 200, 175, 52, 52, 52, 52, 939, 353, 96, 96,
  128942. /* 360 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99,
  128943. /* 370 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
  128944. /* 380 */ 98, 98, 98, 98, 354, 449, 954, 427, 417, 427,
  128945. /* 390 */ 426, 1290, 92, 89, 178, 268, 253, 324, 255, 1058,
  128946. /* 400 */ 1037, 694, 93, 350, 383, 52, 52, 380, 1058, 374,
  128947. /* 410 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
  128948. /* 420 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839,
  128949. /* 430 */ 97, 97, 98, 98, 98, 98, 228, 449, 167, 449,
  128950. /* 440 */ 427, 407, 157, 446, 446, 446, 349, 349, 349, 324,
  128951. /* 450 */ 310, 316, 991, 827, 320, 242, 411, 51, 51, 36,
  128952. /* 460 */ 36, 254, 96, 96, 96, 96, 95, 95, 94, 94,
  128953. /* 470 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850,
  128954. /* 480 */ 839, 839, 97, 97, 98, 98, 98, 98, 194, 316,
  128955. /* 490 */ 929, 401, 398, 397, 224, 224, 1265, 939, 353, 1318,
  128956. /* 500 */ 317, 324, 396, 1063, 1063, 813, 414, 1061, 1061, 950,
  128957. /* 510 */ 299, 448, 992, 268, 96, 96, 96, 96, 95, 95,
  128958. /* 520 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971,
  128959. /* 530 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98,
  128960. /* 540 */ 757, 1041, 449, 893, 893, 386, 950, 951, 952, 410,
  128961. /* 550 */ 992, 747, 747, 324, 229, 268, 221, 296, 268, 771,
  128962. /* 560 */ 890, 378, 52, 52, 890, 421, 96, 96, 96, 96,
  128963. /* 570 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90,
  128964. /* 580 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
  128965. /* 590 */ 98, 98, 103, 449, 275, 384, 1241, 343, 157, 1207,
  128966. /* 600 */ 909, 669, 670, 671, 176, 197, 196, 195, 324, 298,
  128967. /* 610 */ 319, 1266, 2, 37, 37, 910, 1134, 1040, 96, 96,
  128968. /* 620 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 697,
  128969. /* 630 */ 911, 177, 99, 100, 90, 971, 971, 847, 850, 839,
  128970. /* 640 */ 839, 97, 97, 98, 98, 98, 98, 230, 146, 120,
  128971. /* 650 */ 735, 1235, 826, 270, 1141, 273, 1141, 771, 171, 170,
  128972. /* 660 */ 736, 1141, 82, 324, 80, 268, 697, 819, 158, 268,
  128973. /* 670 */ 378, 818, 78, 96, 96, 96, 96, 95, 95, 94,
  128974. /* 680 */ 94, 94, 93, 350, 120, 950, 393, 99, 100, 90,
  128975. /* 690 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
  128976. /* 700 */ 98, 98, 818, 818, 820, 1141, 1070, 370, 331, 133,
  128977. /* 710 */ 1066, 1141, 1250, 198, 268, 324, 1016, 330, 245, 333,
  128978. /* 720 */ 24, 334, 950, 951, 952, 368, 335, 81, 96, 96,
  128979. /* 730 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99,
  128980. /* 740 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
  128981. /* 750 */ 98, 98, 98, 98, 132, 267, 260, 445, 330, 223,
  128982. /* 760 */ 175, 1289, 925, 752, 724, 318, 1073, 324, 751, 246,
  128983. /* 770 */ 385, 301, 301, 378, 329, 361, 344, 414, 1233, 280,
  128984. /* 780 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
  128985. /* 790 */ 350, 99, 88, 90, 971, 971, 847, 850, 839, 839,
  128986. /* 800 */ 97, 97, 98, 98, 98, 98, 337, 346, 721, 722,
  128987. /* 810 */ 449, 120, 118, 887, 162, 887, 810, 371, 324, 202,
  128988. /* 820 */ 202, 373, 249, 263, 202, 394, 74, 704, 208, 1069,
  128989. /* 830 */ 12, 12, 96, 96, 96, 96, 95, 95, 94, 94,
  128990. /* 840 */ 94, 93, 350, 100, 90, 971, 971, 847, 850, 839,
  128991. /* 850 */ 839, 97, 97, 98, 98, 98, 98, 449, 771, 232,
  128992. /* 860 */ 449, 278, 120, 286, 74, 704, 714, 713, 324, 342,
  128993. /* 870 */ 749, 877, 1209, 77, 285, 1255, 780, 52, 52, 202,
  128994. /* 880 */ 27, 27, 418, 96, 96, 96, 96, 95, 95, 94,
  128995. /* 890 */ 94, 94, 93, 350, 90, 971, 971, 847, 850, 839,
  128996. /* 900 */ 839, 97, 97, 98, 98, 98, 98, 86, 444, 877,
  128997. /* 910 */ 3, 1193, 422, 1013, 873, 435, 886, 208, 886, 689,
  128998. /* 920 */ 1091, 257, 116, 822, 447, 1230, 117, 1229, 86, 444,
  128999. /* 930 */ 177, 3, 381, 96, 96, 96, 96, 95, 95, 94,
  129000. /* 940 */ 94, 94, 93, 350, 339, 447, 120, 351, 120, 212,
  129001. /* 950 */ 169, 287, 404, 282, 403, 199, 771, 950, 433, 419,
  129002. /* 960 */ 439, 822, 280, 691, 1039, 264, 269, 132, 351, 153,
  129003. /* 970 */ 826, 376, 74, 272, 274, 276, 83, 84, 1054, 433,
  129004. /* 980 */ 147, 1038, 443, 85, 351, 451, 450, 281, 132, 818,
  129005. /* 990 */ 25, 826, 449, 120, 950, 951, 952, 83, 84, 86,
  129006. /* 1000 */ 444, 691, 3, 408, 85, 351, 451, 450, 449, 5,
  129007. /* 1010 */ 818, 203, 32, 32, 1107, 120, 447, 950, 225, 1140,
  129008. /* 1020 */ 818, 818, 820, 821, 19, 203, 226, 950, 38, 38,
  129009. /* 1030 */ 1087, 314, 314, 313, 215, 311, 120, 449, 678, 351,
  129010. /* 1040 */ 237, 818, 818, 820, 821, 19, 969, 409, 377, 1,
  129011. /* 1050 */ 433, 180, 706, 248, 950, 951, 952, 10, 10, 449,
  129012. /* 1060 */ 969, 247, 826, 1098, 950, 951, 952, 430, 83, 84,
  129013. /* 1070 */ 756, 336, 950, 20, 431, 85, 351, 451, 450, 10,
  129014. /* 1080 */ 10, 818, 86, 444, 969, 3, 950, 449, 302, 303,
  129015. /* 1090 */ 182, 950, 1146, 338, 1021, 1015, 1004, 183, 969, 447,
  129016. /* 1100 */ 132, 181, 76, 444, 21, 3, 449, 10, 10, 950,
  129017. /* 1110 */ 951, 952, 818, 818, 820, 821, 19, 715, 1279, 447,
  129018. /* 1120 */ 389, 233, 351, 950, 951, 952, 10, 10, 950, 951,
  129019. /* 1130 */ 952, 1003, 218, 433, 1005, 325, 1273, 773, 289, 291,
  129020. /* 1140 */ 424, 293, 351, 7, 159, 826, 363, 402, 315, 360,
  129021. /* 1150 */ 1129, 83, 84, 433, 1232, 716, 772, 259, 85, 351,
  129022. /* 1160 */ 451, 450, 358, 375, 818, 826, 360, 359, 399, 1211,
  129023. /* 1170 */ 157, 83, 84, 681, 98, 98, 98, 98, 85, 351,
  129024. /* 1180 */ 451, 450, 323, 252, 818, 295, 1211, 1213, 1235, 173,
  129025. /* 1190 */ 1037, 284, 434, 340, 1204, 818, 818, 820, 821, 19,
  129026. /* 1200 */ 308, 234, 449, 234, 96, 96, 96, 96, 95, 95,
  129027. /* 1210 */ 94, 94, 94, 93, 350, 818, 818, 820, 821, 19,
  129028. /* 1220 */ 909, 120, 39, 39, 1203, 449, 168, 360, 449, 1276,
  129029. /* 1230 */ 367, 449, 135, 449, 986, 910, 449, 1249, 449, 1247,
  129030. /* 1240 */ 449, 205, 983, 449, 370, 40, 40, 1211, 41, 41,
  129031. /* 1250 */ 911, 42, 42, 28, 28, 870, 29, 29, 31, 31,
  129032. /* 1260 */ 43, 43, 379, 44, 44, 449, 59, 449, 332, 449,
  129033. /* 1270 */ 432, 62, 144, 156, 449, 130, 449, 72, 449, 137,
  129034. /* 1280 */ 449, 365, 449, 392, 139, 45, 45, 11, 11, 46,
  129035. /* 1290 */ 46, 140, 1200, 449, 105, 105, 47, 47, 48, 48,
  129036. /* 1300 */ 33, 33, 49, 49, 1126, 449, 141, 366, 449, 185,
  129037. /* 1310 */ 142, 449, 1234, 50, 50, 449, 160, 449, 148, 449,
  129038. /* 1320 */ 1136, 382, 449, 67, 449, 34, 34, 449, 122, 122,
  129039. /* 1330 */ 449, 123, 123, 449, 1198, 124, 124, 56, 56, 35,
  129040. /* 1340 */ 35, 449, 106, 106, 53, 53, 449, 107, 107, 449,
  129041. /* 1350 */ 108, 108, 449, 104, 104, 449, 406, 449, 388, 449,
  129042. /* 1360 */ 189, 121, 121, 449, 190, 449, 119, 119, 449, 112,
  129043. /* 1370 */ 112, 449, 111, 111, 1218, 109, 109, 110, 110, 55,
  129044. /* 1380 */ 55, 266, 752, 57, 57, 54, 54, 751, 26, 26,
  129045. /* 1390 */ 1099, 30, 30, 219, 154, 390, 271, 191, 321, 1006,
  129046. /* 1400 */ 192, 405, 1057, 1056, 1055, 341, 1048, 706, 1047, 1029,
  129047. /* 1410 */ 322, 420, 1028, 71, 1095, 283, 288, 1027, 1288, 204,
  129048. /* 1420 */ 6, 297, 79, 1184, 437, 1096, 1094, 290, 345, 292,
  129049. /* 1430 */ 441, 1093, 294, 102, 425, 73, 423, 213, 1012, 22,
  129050. /* 1440 */ 452, 945, 214, 1077, 216, 217, 238, 453, 306, 304,
  129051. /* 1450 */ 307, 239, 240, 1001, 305, 125, 996, 126, 115, 235,
  129052. /* 1460 */ 127, 665, 352, 166, 244, 179, 356, 113, 885, 883,
  129053. /* 1470 */ 806, 136, 128, 738, 326, 138, 327, 258, 184, 899,
  129054. /* 1480 */ 143, 129, 145, 63, 64, 65, 66, 902, 186, 187,
  129055. /* 1490 */ 898, 8, 13, 188, 134, 265, 891, 202, 980, 387,
  129056. /* 1500 */ 150, 149, 680, 161, 391, 193, 285, 279, 395, 151,
  129057. /* 1510 */ 68, 717, 14, 15, 400, 69, 16, 131, 236, 825,
  129058. /* 1520 */ 824, 853, 746, 750, 4, 70, 174, 413, 220, 222,
  129059. /* 1530 */ 152, 779, 774, 77, 868, 74, 854, 201, 17, 852,
  129060. /* 1540 */ 908, 206, 907, 207, 18, 857, 934, 163, 436, 210,
  129061. /* 1550 */ 935, 164, 209, 165, 440, 856, 823, 312, 690, 87,
  129062. /* 1560 */ 211, 309, 1281, 940, 995, 1280,
  129063. };
  129064. static const YYCODETYPE yy_lookahead[] = {
  129065. /* 0 */ 19, 144, 145, 146, 147, 24, 90, 91, 92, 93,
  129066. /* 10 */ 94, 54, 55, 56, 57, 58, 88, 89, 90, 91,
  129067. /* 20 */ 92, 93, 94, 152, 43, 44, 45, 46, 47, 48,
  129068. /* 30 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 94,
  129069. /* 40 */ 59, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  129070. /* 50 */ 93, 94, 59, 84, 85, 86, 87, 88, 89, 90,
  129071. /* 60 */ 91, 92, 93, 94, 193, 84, 85, 86, 87, 88,
  129072. /* 70 */ 89, 90, 91, 92, 93, 94, 194, 195, 97, 79,
  129073. /* 80 */ 11, 88, 89, 152, 26, 19, 171, 152, 206, 96,
  129074. /* 90 */ 97, 98, 72, 100, 179, 59, 152, 31, 163, 79,
  129075. /* 100 */ 107, 219, 109, 172, 173, 39, 79, 172, 173, 43,
  129076. /* 110 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  129077. /* 120 */ 54, 55, 56, 57, 152, 132, 199, 134, 108, 109,
  129078. /* 130 */ 110, 196, 96, 97, 98, 99, 209, 19, 102, 103,
  129079. /* 140 */ 104, 72, 207, 208, 26, 72, 119, 120, 79, 113,
  129080. /* 150 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  129081. /* 160 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  129082. /* 170 */ 52, 53, 54, 55, 56, 57, 31, 108, 109, 110,
  129083. /* 180 */ 82, 108, 109, 110, 39, 210, 68, 175, 130, 19,
  129084. /* 190 */ 218, 175, 119, 120, 250, 97, 221, 222, 223, 101,
  129085. /* 200 */ 172, 152, 84, 85, 86, 87, 88, 89, 90, 91,
  129086. /* 210 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
  129087. /* 220 */ 50, 51, 52, 53, 54, 55, 56, 57, 152, 152,
  129088. /* 230 */ 132, 133, 134, 221, 222, 223, 66, 221, 222, 223,
  129089. /* 240 */ 172, 19, 193, 22, 23, 152, 24, 26, 172, 173,
  129090. /* 250 */ 46, 47, 48, 49, 84, 85, 86, 87, 88, 89,
  129091. /* 260 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
  129092. /* 270 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  129093. /* 280 */ 221, 222, 223, 207, 208, 46, 22, 23, 148, 149,
  129094. /* 290 */ 26, 242, 172, 19, 154, 218, 156, 23, 88, 89,
  129095. /* 300 */ 241, 59, 163, 163, 83, 101, 84, 85, 86, 87,
  129096. /* 310 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
  129097. /* 320 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  129098. /* 330 */ 56, 57, 152, 157, 152, 196, 196, 16, 96, 97,
  129099. /* 340 */ 98, 26, 132, 250, 134, 19, 107, 83, 59, 23,
  129100. /* 350 */ 211, 212, 172, 173, 172, 173, 1, 2, 84, 85,
  129101. /* 360 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
  129102. /* 370 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  129103. /* 380 */ 54, 55, 56, 57, 244, 152, 97, 207, 208, 207,
  129104. /* 390 */ 208, 185, 221, 222, 223, 152, 75, 19, 77, 179,
  129105. /* 400 */ 180, 23, 93, 94, 228, 172, 173, 231, 188, 152,
  129106. /* 410 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  129107. /* 420 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  129108. /* 430 */ 52, 53, 54, 55, 56, 57, 193, 152, 123, 152,
  129109. /* 440 */ 207, 208, 152, 168, 169, 170, 168, 169, 170, 19,
  129110. /* 450 */ 160, 22, 23, 23, 164, 119, 120, 172, 173, 172,
  129111. /* 460 */ 173, 140, 84, 85, 86, 87, 88, 89, 90, 91,
  129112. /* 470 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
  129113. /* 480 */ 50, 51, 52, 53, 54, 55, 56, 57, 99, 22,
  129114. /* 490 */ 23, 102, 103, 104, 194, 195, 0, 1, 2, 247,
  129115. /* 500 */ 248, 19, 113, 190, 191, 23, 206, 190, 191, 59,
  129116. /* 510 */ 225, 152, 83, 152, 84, 85, 86, 87, 88, 89,
  129117. /* 520 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
  129118. /* 530 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  129119. /* 540 */ 90, 181, 152, 108, 109, 110, 96, 97, 98, 115,
  129120. /* 550 */ 83, 117, 118, 19, 193, 152, 23, 152, 152, 26,
  129121. /* 560 */ 29, 152, 172, 173, 33, 152, 84, 85, 86, 87,
  129122. /* 570 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
  129123. /* 580 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  129124. /* 590 */ 56, 57, 22, 152, 16, 64, 193, 207, 152, 193,
  129125. /* 600 */ 12, 7, 8, 9, 152, 108, 109, 110, 19, 152,
  129126. /* 610 */ 164, 146, 147, 172, 173, 27, 163, 181, 84, 85,
  129127. /* 620 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 59,
  129128. /* 630 */ 42, 98, 43, 44, 45, 46, 47, 48, 49, 50,
  129129. /* 640 */ 51, 52, 53, 54, 55, 56, 57, 238, 22, 196,
  129130. /* 650 */ 62, 163, 82, 75, 152, 77, 152, 124, 88, 89,
  129131. /* 660 */ 72, 152, 137, 19, 139, 152, 96, 97, 24, 152,
  129132. /* 670 */ 152, 101, 138, 84, 85, 86, 87, 88, 89, 90,
  129133. /* 680 */ 91, 92, 93, 94, 196, 59, 19, 43, 44, 45,
  129134. /* 690 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  129135. /* 700 */ 56, 57, 132, 133, 134, 152, 193, 219, 245, 246,
  129136. /* 710 */ 193, 152, 152, 46, 152, 19, 166, 167, 152, 217,
  129137. /* 720 */ 232, 217, 96, 97, 98, 237, 217, 138, 84, 85,
  129138. /* 730 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
  129139. /* 740 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  129140. /* 750 */ 54, 55, 56, 57, 79, 193, 238, 166, 167, 211,
  129141. /* 760 */ 212, 23, 23, 116, 26, 26, 195, 19, 121, 152,
  129142. /* 770 */ 217, 152, 152, 152, 107, 100, 217, 206, 163, 112,
  129143. /* 780 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  129144. /* 790 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  129145. /* 800 */ 52, 53, 54, 55, 56, 57, 187, 187, 7, 8,
  129146. /* 810 */ 152, 196, 22, 132, 24, 134, 23, 23, 19, 26,
  129147. /* 820 */ 26, 23, 152, 23, 26, 23, 26, 59, 26, 163,
  129148. /* 830 */ 172, 173, 84, 85, 86, 87, 88, 89, 90, 91,
  129149. /* 840 */ 92, 93, 94, 44, 45, 46, 47, 48, 49, 50,
  129150. /* 850 */ 51, 52, 53, 54, 55, 56, 57, 152, 26, 238,
  129151. /* 860 */ 152, 23, 196, 101, 26, 97, 100, 101, 19, 19,
  129152. /* 870 */ 23, 59, 152, 26, 112, 152, 23, 172, 173, 26,
  129153. /* 880 */ 172, 173, 19, 84, 85, 86, 87, 88, 89, 90,
  129154. /* 890 */ 91, 92, 93, 94, 45, 46, 47, 48, 49, 50,
  129155. /* 900 */ 51, 52, 53, 54, 55, 56, 57, 19, 20, 97,
  129156. /* 910 */ 22, 23, 207, 163, 23, 163, 132, 26, 134, 23,
  129157. /* 920 */ 213, 152, 26, 59, 36, 152, 22, 152, 19, 20,
  129158. /* 930 */ 98, 22, 152, 84, 85, 86, 87, 88, 89, 90,
  129159. /* 940 */ 91, 92, 93, 94, 94, 36, 196, 59, 196, 99,
  129160. /* 950 */ 100, 101, 102, 103, 104, 105, 124, 59, 70, 96,
  129161. /* 960 */ 163, 97, 112, 59, 181, 152, 152, 79, 59, 71,
  129162. /* 970 */ 82, 19, 26, 152, 152, 152, 88, 89, 152, 70,
  129163. /* 980 */ 22, 152, 163, 95, 96, 97, 98, 152, 79, 101,
  129164. /* 990 */ 22, 82, 152, 196, 96, 97, 98, 88, 89, 19,
  129165. /* 1000 */ 20, 97, 22, 163, 95, 96, 97, 98, 152, 22,
  129166. /* 1010 */ 101, 24, 172, 173, 152, 196, 36, 59, 22, 152,
  129167. /* 1020 */ 132, 133, 134, 135, 136, 24, 5, 59, 172, 173,
  129168. /* 1030 */ 152, 10, 11, 12, 13, 14, 196, 152, 17, 59,
  129169. /* 1040 */ 210, 132, 133, 134, 135, 136, 59, 207, 96, 22,
  129170. /* 1050 */ 70, 30, 106, 32, 96, 97, 98, 172, 173, 152,
  129171. /* 1060 */ 59, 40, 82, 152, 96, 97, 98, 152, 88, 89,
  129172. /* 1070 */ 90, 186, 59, 22, 191, 95, 96, 97, 98, 172,
  129173. /* 1080 */ 173, 101, 19, 20, 97, 22, 59, 152, 152, 152,
  129174. /* 1090 */ 69, 59, 152, 186, 152, 152, 152, 76, 97, 36,
  129175. /* 1100 */ 79, 80, 19, 20, 53, 22, 152, 172, 173, 96,
  129176. /* 1110 */ 97, 98, 132, 133, 134, 135, 136, 35, 122, 36,
  129177. /* 1120 */ 234, 186, 59, 96, 97, 98, 172, 173, 96, 97,
  129178. /* 1130 */ 98, 152, 233, 70, 152, 114, 152, 124, 210, 210,
  129179. /* 1140 */ 186, 210, 59, 198, 197, 82, 214, 65, 150, 152,
  129180. /* 1150 */ 201, 88, 89, 70, 201, 73, 124, 239, 95, 96,
  129181. /* 1160 */ 97, 98, 141, 239, 101, 82, 169, 170, 176, 152,
  129182. /* 1170 */ 152, 88, 89, 21, 54, 55, 56, 57, 95, 96,
  129183. /* 1180 */ 97, 98, 164, 214, 101, 214, 169, 170, 163, 184,
  129184. /* 1190 */ 180, 175, 227, 111, 175, 132, 133, 134, 135, 136,
  129185. /* 1200 */ 200, 183, 152, 185, 84, 85, 86, 87, 88, 89,
  129186. /* 1210 */ 90, 91, 92, 93, 94, 132, 133, 134, 135, 136,
  129187. /* 1220 */ 12, 196, 172, 173, 175, 152, 198, 230, 152, 155,
  129188. /* 1230 */ 78, 152, 243, 152, 60, 27, 152, 159, 152, 159,
  129189. /* 1240 */ 152, 122, 38, 152, 219, 172, 173, 230, 172, 173,
  129190. /* 1250 */ 42, 172, 173, 172, 173, 103, 172, 173, 172, 173,
  129191. /* 1260 */ 172, 173, 237, 172, 173, 152, 240, 152, 159, 152,
  129192. /* 1270 */ 62, 240, 22, 220, 152, 43, 152, 130, 152, 189,
  129193. /* 1280 */ 152, 18, 152, 18, 192, 172, 173, 172, 173, 172,
  129194. /* 1290 */ 173, 192, 140, 152, 172, 173, 172, 173, 172, 173,
  129195. /* 1300 */ 172, 173, 172, 173, 201, 152, 192, 159, 152, 158,
  129196. /* 1310 */ 192, 152, 201, 172, 173, 152, 220, 152, 189, 152,
  129197. /* 1320 */ 189, 159, 152, 137, 152, 172, 173, 152, 172, 173,
  129198. /* 1330 */ 152, 172, 173, 152, 201, 172, 173, 172, 173, 172,
  129199. /* 1340 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152,
  129200. /* 1350 */ 172, 173, 152, 172, 173, 152, 90, 152, 61, 152,
  129201. /* 1360 */ 158, 172, 173, 152, 158, 152, 172, 173, 152, 172,
  129202. /* 1370 */ 173, 152, 172, 173, 236, 172, 173, 172, 173, 172,
  129203. /* 1380 */ 173, 235, 116, 172, 173, 172, 173, 121, 172, 173,
  129204. /* 1390 */ 159, 172, 173, 159, 22, 177, 159, 158, 177, 159,
  129205. /* 1400 */ 158, 107, 174, 174, 174, 63, 182, 106, 182, 174,
  129206. /* 1410 */ 177, 125, 176, 107, 216, 174, 215, 174, 174, 159,
  129207. /* 1420 */ 22, 159, 137, 224, 177, 216, 216, 215, 94, 215,
  129208. /* 1430 */ 177, 216, 215, 129, 126, 128, 127, 25, 162, 26,
  129209. /* 1440 */ 161, 13, 153, 205, 153, 6, 226, 151, 202, 204,
  129210. /* 1450 */ 201, 229, 229, 151, 203, 165, 151, 165, 178, 178,
  129211. /* 1460 */ 165, 4, 3, 22, 142, 15, 81, 16, 23, 23,
  129212. /* 1470 */ 120, 131, 111, 20, 249, 123, 249, 16, 125, 1,
  129213. /* 1480 */ 123, 111, 131, 53, 53, 53, 53, 96, 34, 122,
  129214. /* 1490 */ 1, 5, 22, 107, 246, 140, 67, 26, 74, 41,
  129215. /* 1500 */ 107, 67, 20, 24, 19, 105, 112, 23, 66, 22,
  129216. /* 1510 */ 22, 28, 22, 22, 66, 22, 22, 37, 66, 23,
  129217. /* 1520 */ 23, 23, 116, 23, 22, 26, 122, 26, 23, 23,
  129218. /* 1530 */ 22, 96, 124, 26, 23, 26, 23, 34, 34, 23,
  129219. /* 1540 */ 23, 26, 23, 22, 34, 11, 23, 22, 24, 122,
  129220. /* 1550 */ 23, 22, 26, 22, 24, 23, 23, 15, 23, 22,
  129221. /* 1560 */ 122, 23, 122, 1, 251, 122,
  129222. };
  129223. #define YY_SHIFT_USE_DFLT (1566)
  129224. #define YY_SHIFT_COUNT (454)
  129225. #define YY_SHIFT_MIN (-84)
  129226. #define YY_SHIFT_MAX (1562)
  129227. static const short yy_shift_ofst[] = {
  129228. /* 0 */ 355, 888, 1021, 909, 1063, 1063, 1063, 1063, 20, -19,
  129229. /* 10 */ 66, 66, 170, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
  129230. /* 20 */ -7, -7, 36, 73, 69, 27, 118, 222, 274, 326,
  129231. /* 30 */ 378, 430, 482, 534, 589, 644, 696, 696, 696, 696,
  129232. /* 40 */ 696, 696, 696, 696, 696, 696, 696, 696, 696, 696,
  129233. /* 50 */ 696, 696, 696, 748, 696, 799, 849, 849, 980, 1063,
  129234. /* 60 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
  129235. /* 70 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
  129236. /* 80 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
  129237. /* 90 */ 1083, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
  129238. /* 100 */ 1063, 1063, 1063, 1063, -43, 1120, 1120, 1120, 1120, 1120,
  129239. /* 110 */ -31, -72, -84, 242, 1152, 667, 210, 210, 242, 309,
  129240. /* 120 */ 336, -55, 1566, 1566, 1566, 850, 850, 850, 626, 626,
  129241. /* 130 */ 588, 588, 898, 221, 264, 242, 242, 242, 242, 242,
  129242. /* 140 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
  129243. /* 150 */ 242, 242, 242, 242, 242, 496, 675, 289, 289, 336,
  129244. /* 160 */ 0, 0, 0, 0, 0, 0, 1566, 1566, 1566, 570,
  129245. /* 170 */ 98, 98, 958, 389, 450, 968, 1013, 1032, 1027, 242,
  129246. /* 180 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
  129247. /* 190 */ 242, 242, 242, 242, 242, 1082, 1082, 1082, 242, 242,
  129248. /* 200 */ 533, 242, 242, 242, 987, 242, 242, 1208, 242, 242,
  129249. /* 210 */ 242, 242, 242, 242, 242, 242, 242, 242, 435, 531,
  129250. /* 220 */ 1001, 1001, 1001, 832, 434, 1266, 594, 58, 863, 863,
  129251. /* 230 */ 952, 58, 952, 946, 738, 239, 145, 863, 525, 145,
  129252. /* 240 */ 145, 315, 647, 790, 1174, 1119, 1119, 1204, 1204, 1119,
  129253. /* 250 */ 1250, 1232, 1147, 1263, 1263, 1263, 1263, 1119, 1265, 1147,
  129254. /* 260 */ 1250, 1232, 1232, 1147, 1119, 1265, 1186, 1297, 1119, 1119,
  129255. /* 270 */ 1265, 1372, 1119, 1265, 1119, 1265, 1372, 1294, 1294, 1294,
  129256. /* 280 */ 1342, 1372, 1294, 1301, 1294, 1342, 1294, 1294, 1286, 1306,
  129257. /* 290 */ 1286, 1306, 1286, 1306, 1286, 1306, 1119, 1398, 1119, 1285,
  129258. /* 300 */ 1372, 1334, 1334, 1372, 1304, 1308, 1307, 1309, 1147, 1412,
  129259. /* 310 */ 1413, 1428, 1428, 1439, 1439, 1439, 1566, 1566, 1566, 1566,
  129260. /* 320 */ 1566, 1566, 1566, 1566, 204, 321, 429, 467, 578, 497,
  129261. /* 330 */ 904, 739, 1051, 793, 794, 798, 800, 802, 838, 768,
  129262. /* 340 */ 766, 801, 762, 847, 853, 812, 891, 681, 784, 896,
  129263. /* 350 */ 864, 996, 1457, 1459, 1441, 1322, 1450, 1385, 1451, 1445,
  129264. /* 360 */ 1446, 1350, 1340, 1361, 1352, 1453, 1353, 1461, 1478, 1357,
  129265. /* 370 */ 1351, 1430, 1431, 1432, 1433, 1370, 1391, 1454, 1367, 1489,
  129266. /* 380 */ 1486, 1470, 1386, 1355, 1429, 1471, 1434, 1424, 1458, 1393,
  129267. /* 390 */ 1479, 1482, 1485, 1394, 1400, 1487, 1442, 1488, 1490, 1484,
  129268. /* 400 */ 1491, 1448, 1483, 1493, 1452, 1480, 1496, 1497, 1498, 1499,
  129269. /* 410 */ 1406, 1494, 1500, 1502, 1501, 1404, 1505, 1506, 1435, 1503,
  129270. /* 420 */ 1508, 1408, 1507, 1504, 1509, 1510, 1511, 1507, 1513, 1516,
  129271. /* 430 */ 1517, 1515, 1519, 1521, 1534, 1523, 1525, 1524, 1526, 1527,
  129272. /* 440 */ 1529, 1530, 1526, 1532, 1531, 1533, 1535, 1537, 1427, 1438,
  129273. /* 450 */ 1440, 1443, 1538, 1542, 1562,
  129274. };
  129275. #define YY_REDUCE_USE_DFLT (-144)
  129276. #define YY_REDUCE_COUNT (323)
  129277. #define YY_REDUCE_MIN (-143)
  129278. #define YY_REDUCE_MAX (1305)
  129279. static const short yy_reduce_ofst[] = {
  129280. /* 0 */ -143, -65, 140, 840, 76, 180, 182, 233, 488, -25,
  129281. /* 10 */ 12, 16, 59, 885, 907, 935, 390, 705, 954, 285,
  129282. /* 20 */ 997, 1017, 1018, -118, 1025, 139, 171, 171, 171, 171,
  129283. /* 30 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
  129284. /* 40 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
  129285. /* 50 */ 171, 171, 171, 171, 171, 171, 171, 171, -69, 287,
  129286. /* 60 */ 441, 658, 708, 856, 1050, 1073, 1076, 1079, 1081, 1084,
  129287. /* 70 */ 1086, 1088, 1091, 1113, 1115, 1117, 1122, 1124, 1126, 1128,
  129288. /* 80 */ 1130, 1141, 1153, 1156, 1159, 1163, 1165, 1167, 1170, 1172,
  129289. /* 90 */ 1175, 1178, 1181, 1189, 1194, 1197, 1200, 1203, 1205, 1207,
  129290. /* 100 */ 1211, 1213, 1216, 1219, 171, 171, 171, 171, 171, 171,
  129291. /* 110 */ 171, 171, 171, 49, 176, 220, 275, 278, 290, 171,
  129292. /* 120 */ 300, 171, 171, 171, 171, -85, -85, -85, -28, 77,
  129293. /* 130 */ 313, 317, -56, 252, 252, 446, -129, 243, 361, 403,
  129294. /* 140 */ 406, 513, 517, 409, 502, 518, 504, 509, 621, 553,
  129295. /* 150 */ 562, 619, 559, 93, 620, 465, 453, 550, 591, 571,
  129296. /* 160 */ 615, 666, 750, 752, 797, 819, 463, 548, -73, 28,
  129297. /* 170 */ 68, 120, 257, 206, 359, 405, 413, 452, 457, 560,
  129298. /* 180 */ 566, 617, 670, 720, 723, 769, 773, 775, 780, 813,
  129299. /* 190 */ 814, 821, 822, 823, 826, 360, 436, 783, 829, 835,
  129300. /* 200 */ 707, 862, 867, 878, 830, 911, 915, 883, 936, 937,
  129301. /* 210 */ 940, 359, 942, 943, 944, 979, 982, 984, 886, 899,
  129302. /* 220 */ 928, 929, 931, 707, 947, 945, 998, 949, 932, 969,
  129303. /* 230 */ 918, 953, 924, 992, 1005, 1010, 1016, 971, 965, 1019,
  129304. /* 240 */ 1049, 1000, 1028, 1074, 989, 1078, 1080, 1026, 1031, 1109,
  129305. /* 250 */ 1053, 1090, 1103, 1092, 1099, 1114, 1118, 1148, 1151, 1111,
  129306. /* 260 */ 1096, 1129, 1131, 1133, 1162, 1202, 1138, 1146, 1231, 1234,
  129307. /* 270 */ 1206, 1218, 1237, 1239, 1240, 1242, 1221, 1228, 1229, 1230,
  129308. /* 280 */ 1224, 1233, 1235, 1236, 1241, 1226, 1243, 1244, 1198, 1201,
  129309. /* 290 */ 1209, 1212, 1210, 1214, 1215, 1217, 1260, 1199, 1262, 1220,
  129310. /* 300 */ 1247, 1222, 1223, 1253, 1238, 1245, 1251, 1246, 1249, 1276,
  129311. /* 310 */ 1279, 1289, 1291, 1296, 1302, 1305, 1225, 1227, 1248, 1290,
  129312. /* 320 */ 1292, 1280, 1281, 1295,
  129313. };
  129314. static const YYACTIONTYPE yy_default[] = {
  129315. /* 0 */ 1270, 1260, 1260, 1260, 1193, 1193, 1193, 1193, 1260, 1088,
  129316. /* 10 */ 1117, 1117, 1244, 1322, 1322, 1322, 1322, 1322, 1322, 1192,
  129317. /* 20 */ 1322, 1322, 1322, 1322, 1260, 1092, 1123, 1322, 1322, 1322,
  129318. /* 30 */ 1322, 1194, 1195, 1322, 1322, 1322, 1243, 1245, 1133, 1132,
  129319. /* 40 */ 1131, 1130, 1226, 1104, 1128, 1121, 1125, 1194, 1188, 1189,
  129320. /* 50 */ 1187, 1191, 1195, 1322, 1124, 1158, 1172, 1157, 1322, 1322,
  129321. /* 60 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129322. /* 70 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129323. /* 80 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129324. /* 90 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129325. /* 100 */ 1322, 1322, 1322, 1322, 1166, 1171, 1178, 1170, 1167, 1160,
  129326. /* 110 */ 1159, 1161, 1162, 1322, 1011, 1059, 1322, 1322, 1322, 1163,
  129327. /* 120 */ 1322, 1164, 1175, 1174, 1173, 1251, 1278, 1277, 1322, 1322,
  129328. /* 130 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129329. /* 140 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129330. /* 150 */ 1322, 1322, 1322, 1322, 1322, 1270, 1260, 1017, 1017, 1322,
  129331. /* 160 */ 1260, 1260, 1260, 1260, 1260, 1260, 1256, 1092, 1083, 1322,
  129332. /* 170 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129333. /* 180 */ 1248, 1246, 1322, 1208, 1322, 1322, 1322, 1322, 1322, 1322,
  129334. /* 190 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129335. /* 200 */ 1322, 1322, 1322, 1322, 1088, 1322, 1322, 1322, 1322, 1322,
  129336. /* 210 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1272, 1322, 1221,
  129337. /* 220 */ 1088, 1088, 1088, 1090, 1072, 1082, 997, 1127, 1106, 1106,
  129338. /* 230 */ 1311, 1127, 1311, 1034, 1292, 1031, 1117, 1106, 1190, 1117,
  129339. /* 240 */ 1117, 1089, 1082, 1322, 1314, 1097, 1097, 1313, 1313, 1097,
  129340. /* 250 */ 1138, 1062, 1127, 1068, 1068, 1068, 1068, 1097, 1008, 1127,
  129341. /* 260 */ 1138, 1062, 1062, 1127, 1097, 1008, 1225, 1308, 1097, 1097,
  129342. /* 270 */ 1008, 1201, 1097, 1008, 1097, 1008, 1201, 1060, 1060, 1060,
  129343. /* 280 */ 1049, 1201, 1060, 1034, 1060, 1049, 1060, 1060, 1110, 1105,
  129344. /* 290 */ 1110, 1105, 1110, 1105, 1110, 1105, 1097, 1196, 1097, 1322,
  129345. /* 300 */ 1201, 1205, 1205, 1201, 1122, 1111, 1120, 1118, 1127, 1014,
  129346. /* 310 */ 1052, 1275, 1275, 1271, 1271, 1271, 1319, 1319, 1256, 1287,
  129347. /* 320 */ 1287, 1036, 1036, 1287, 1322, 1322, 1322, 1322, 1322, 1322,
  129348. /* 330 */ 1282, 1322, 1210, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129349. /* 340 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129350. /* 350 */ 1322, 1143, 1322, 993, 1253, 1322, 1322, 1252, 1322, 1322,
  129351. /* 360 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129352. /* 370 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1310, 1322,
  129353. /* 380 */ 1322, 1322, 1322, 1322, 1322, 1224, 1223, 1322, 1322, 1322,
  129354. /* 390 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129355. /* 400 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
  129356. /* 410 */ 1074, 1322, 1322, 1322, 1296, 1322, 1322, 1322, 1322, 1322,
  129357. /* 420 */ 1322, 1322, 1119, 1322, 1112, 1322, 1322, 1301, 1322, 1322,
  129358. /* 430 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1262, 1322,
  129359. /* 440 */ 1322, 1322, 1261, 1322, 1322, 1322, 1322, 1322, 1145, 1322,
  129360. /* 450 */ 1144, 1148, 1322, 1002, 1322,
  129361. };
  129362. /********** End of lemon-generated parsing tables *****************************/
  129363. /* The next table maps tokens (terminal symbols) into fallback tokens.
  129364. ** If a construct like the following:
  129365. **
  129366. ** %fallback ID X Y Z.
  129367. **
  129368. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  129369. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  129370. ** but it does not parse, the type of the token is changed to ID and
  129371. ** the parse is retried before an error is thrown.
  129372. **
  129373. ** This feature can be used, for example, to cause some keywords in a language
  129374. ** to revert to identifiers if they keyword does not apply in the context where
  129375. ** it appears.
  129376. */
  129377. #ifdef YYFALLBACK
  129378. static const YYCODETYPE yyFallback[] = {
  129379. 0, /* $ => nothing */
  129380. 0, /* SEMI => nothing */
  129381. 59, /* EXPLAIN => ID */
  129382. 59, /* QUERY => ID */
  129383. 59, /* PLAN => ID */
  129384. 59, /* BEGIN => ID */
  129385. 0, /* TRANSACTION => nothing */
  129386. 59, /* DEFERRED => ID */
  129387. 59, /* IMMEDIATE => ID */
  129388. 59, /* EXCLUSIVE => ID */
  129389. 0, /* COMMIT => nothing */
  129390. 59, /* END => ID */
  129391. 59, /* ROLLBACK => ID */
  129392. 59, /* SAVEPOINT => ID */
  129393. 59, /* RELEASE => ID */
  129394. 0, /* TO => nothing */
  129395. 0, /* TABLE => nothing */
  129396. 0, /* CREATE => nothing */
  129397. 59, /* IF => ID */
  129398. 0, /* NOT => nothing */
  129399. 0, /* EXISTS => nothing */
  129400. 59, /* TEMP => ID */
  129401. 0, /* LP => nothing */
  129402. 0, /* RP => nothing */
  129403. 0, /* AS => nothing */
  129404. 59, /* WITHOUT => ID */
  129405. 0, /* COMMA => nothing */
  129406. 59, /* ABORT => ID */
  129407. 59, /* ACTION => ID */
  129408. 59, /* AFTER => ID */
  129409. 59, /* ANALYZE => ID */
  129410. 59, /* ASC => ID */
  129411. 59, /* ATTACH => ID */
  129412. 59, /* BEFORE => ID */
  129413. 59, /* BY => ID */
  129414. 59, /* CASCADE => ID */
  129415. 59, /* CAST => ID */
  129416. 59, /* CONFLICT => ID */
  129417. 59, /* DATABASE => ID */
  129418. 59, /* DESC => ID */
  129419. 59, /* DETACH => ID */
  129420. 59, /* EACH => ID */
  129421. 59, /* FAIL => ID */
  129422. 0, /* OR => nothing */
  129423. 0, /* AND => nothing */
  129424. 0, /* IS => nothing */
  129425. 59, /* MATCH => ID */
  129426. 59, /* LIKE_KW => ID */
  129427. 0, /* BETWEEN => nothing */
  129428. 0, /* IN => nothing */
  129429. 0, /* ISNULL => nothing */
  129430. 0, /* NOTNULL => nothing */
  129431. 0, /* NE => nothing */
  129432. 0, /* EQ => nothing */
  129433. 0, /* GT => nothing */
  129434. 0, /* LE => nothing */
  129435. 0, /* LT => nothing */
  129436. 0, /* GE => nothing */
  129437. 0, /* ESCAPE => nothing */
  129438. 0, /* ID => nothing */
  129439. 59, /* COLUMNKW => ID */
  129440. 59, /* FOR => ID */
  129441. 59, /* IGNORE => ID */
  129442. 59, /* INITIALLY => ID */
  129443. 59, /* INSTEAD => ID */
  129444. 59, /* NO => ID */
  129445. 59, /* KEY => ID */
  129446. 59, /* OF => ID */
  129447. 59, /* OFFSET => ID */
  129448. 59, /* PRAGMA => ID */
  129449. 59, /* RAISE => ID */
  129450. 59, /* RECURSIVE => ID */
  129451. 59, /* REPLACE => ID */
  129452. 59, /* RESTRICT => ID */
  129453. 59, /* ROW => ID */
  129454. 59, /* TRIGGER => ID */
  129455. 59, /* VACUUM => ID */
  129456. 59, /* VIEW => ID */
  129457. 59, /* VIRTUAL => ID */
  129458. 59, /* WITH => ID */
  129459. 59, /* REINDEX => ID */
  129460. 59, /* RENAME => ID */
  129461. 59, /* CTIME_KW => ID */
  129462. };
  129463. #endif /* YYFALLBACK */
  129464. /* The following structure represents a single element of the
  129465. ** parser's stack. Information stored includes:
  129466. **
  129467. ** + The state number for the parser at this level of the stack.
  129468. **
  129469. ** + The value of the token stored at this level of the stack.
  129470. ** (In other words, the "major" token.)
  129471. **
  129472. ** + The semantic value stored at this level of the stack. This is
  129473. ** the information used by the action routines in the grammar.
  129474. ** It is sometimes called the "minor" token.
  129475. **
  129476. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  129477. ** actually contains the reduce action for the second half of the
  129478. ** SHIFTREDUCE.
  129479. */
  129480. struct yyStackEntry {
  129481. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  129482. YYCODETYPE major; /* The major token value. This is the code
  129483. ** number for the token at this stack level */
  129484. YYMINORTYPE minor; /* The user-supplied minor token value. This
  129485. ** is the value of the token */
  129486. };
  129487. typedef struct yyStackEntry yyStackEntry;
  129488. /* The state of the parser is completely contained in an instance of
  129489. ** the following structure */
  129490. struct yyParser {
  129491. yyStackEntry *yytos; /* Pointer to top element of the stack */
  129492. #ifdef YYTRACKMAXSTACKDEPTH
  129493. int yyhwm; /* High-water mark of the stack */
  129494. #endif
  129495. #ifndef YYNOERRORRECOVERY
  129496. int yyerrcnt; /* Shifts left before out of the error */
  129497. #endif
  129498. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  129499. #if YYSTACKDEPTH<=0
  129500. int yystksz; /* Current side of the stack */
  129501. yyStackEntry *yystack; /* The parser's stack */
  129502. yyStackEntry yystk0; /* First stack entry */
  129503. #else
  129504. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  129505. yyStackEntry *yystackEnd; /* Last entry in the stack */
  129506. #endif
  129507. };
  129508. typedef struct yyParser yyParser;
  129509. #ifndef NDEBUG
  129510. /* #include <stdio.h> */
  129511. static FILE *yyTraceFILE = 0;
  129512. static char *yyTracePrompt = 0;
  129513. #endif /* NDEBUG */
  129514. #ifndef NDEBUG
  129515. /*
  129516. ** Turn parser tracing on by giving a stream to which to write the trace
  129517. ** and a prompt to preface each trace message. Tracing is turned off
  129518. ** by making either argument NULL
  129519. **
  129520. ** Inputs:
  129521. ** <ul>
  129522. ** <li> A FILE* to which trace output should be written.
  129523. ** If NULL, then tracing is turned off.
  129524. ** <li> A prefix string written at the beginning of every
  129525. ** line of trace output. If NULL, then tracing is
  129526. ** turned off.
  129527. ** </ul>
  129528. **
  129529. ** Outputs:
  129530. ** None.
  129531. */
  129532. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  129533. yyTraceFILE = TraceFILE;
  129534. yyTracePrompt = zTracePrompt;
  129535. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  129536. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  129537. }
  129538. #endif /* NDEBUG */
  129539. #ifndef NDEBUG
  129540. /* For tracing shifts, the names of all terminals and nonterminals
  129541. ** are required. The following table supplies these names */
  129542. static const char *const yyTokenName[] = {
  129543. "$", "SEMI", "EXPLAIN", "QUERY",
  129544. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  129545. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  129546. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  129547. "TABLE", "CREATE", "IF", "NOT",
  129548. "EXISTS", "TEMP", "LP", "RP",
  129549. "AS", "WITHOUT", "COMMA", "ABORT",
  129550. "ACTION", "AFTER", "ANALYZE", "ASC",
  129551. "ATTACH", "BEFORE", "BY", "CASCADE",
  129552. "CAST", "CONFLICT", "DATABASE", "DESC",
  129553. "DETACH", "EACH", "FAIL", "OR",
  129554. "AND", "IS", "MATCH", "LIKE_KW",
  129555. "BETWEEN", "IN", "ISNULL", "NOTNULL",
  129556. "NE", "EQ", "GT", "LE",
  129557. "LT", "GE", "ESCAPE", "ID",
  129558. "COLUMNKW", "FOR", "IGNORE", "INITIALLY",
  129559. "INSTEAD", "NO", "KEY", "OF",
  129560. "OFFSET", "PRAGMA", "RAISE", "RECURSIVE",
  129561. "REPLACE", "RESTRICT", "ROW", "TRIGGER",
  129562. "VACUUM", "VIEW", "VIRTUAL", "WITH",
  129563. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  129564. "BITAND", "BITOR", "LSHIFT", "RSHIFT",
  129565. "PLUS", "MINUS", "STAR", "SLASH",
  129566. "REM", "CONCAT", "COLLATE", "BITNOT",
  129567. "INDEXED", "STRING", "JOIN_KW", "CONSTRAINT",
  129568. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  129569. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  129570. "INSERT", "DELETE", "UPDATE", "SET",
  129571. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  129572. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  129573. "VALUES", "DISTINCT", "DOT", "FROM",
  129574. "JOIN", "USING", "ORDER", "GROUP",
  129575. "HAVING", "LIMIT", "WHERE", "INTO",
  129576. "FLOAT", "BLOB", "INTEGER", "VARIABLE",
  129577. "CASE", "WHEN", "THEN", "ELSE",
  129578. "INDEX", "ALTER", "ADD", "error",
  129579. "input", "cmdlist", "ecmd", "explain",
  129580. "cmdx", "cmd", "transtype", "trans_opt",
  129581. "nm", "savepoint_opt", "create_table", "create_table_args",
  129582. "createkw", "temp", "ifnotexists", "dbnm",
  129583. "columnlist", "conslist_opt", "table_options", "select",
  129584. "columnname", "carglist", "typetoken", "typename",
  129585. "signed", "plus_num", "minus_num", "ccons",
  129586. "term", "expr", "onconf", "sortorder",
  129587. "autoinc", "eidlist_opt", "refargs", "defer_subclause",
  129588. "refarg", "refact", "init_deferred_pred_opt", "conslist",
  129589. "tconscomma", "tcons", "sortlist", "eidlist",
  129590. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  129591. "ifexists", "fullname", "selectnowith", "oneselect",
  129592. "with", "multiselect_op", "distinct", "selcollist",
  129593. "from", "where_opt", "groupby_opt", "having_opt",
  129594. "orderby_opt", "limit_opt", "values", "nexprlist",
  129595. "exprlist", "sclp", "as", "seltablist",
  129596. "stl_prefix", "joinop", "indexed_opt", "on_opt",
  129597. "using_opt", "idlist", "setlist", "insert_cmd",
  129598. "idlist_opt", "likeop", "between_op", "in_op",
  129599. "paren_exprlist", "case_operand", "case_exprlist", "case_else",
  129600. "uniqueflag", "collate", "nmnum", "trigger_decl",
  129601. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  129602. "when_clause", "trigger_cmd", "trnm", "tridxby",
  129603. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  129604. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  129605. "lp", "anylist", "wqlist",
  129606. };
  129607. #endif /* NDEBUG */
  129608. #ifndef NDEBUG
  129609. /* For tracing reduce actions, the names of all rules are required.
  129610. */
  129611. static const char *const yyRuleName[] = {
  129612. /* 0 */ "explain ::= EXPLAIN",
  129613. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  129614. /* 2 */ "cmdx ::= cmd",
  129615. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  129616. /* 4 */ "transtype ::=",
  129617. /* 5 */ "transtype ::= DEFERRED",
  129618. /* 6 */ "transtype ::= IMMEDIATE",
  129619. /* 7 */ "transtype ::= EXCLUSIVE",
  129620. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  129621. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  129622. /* 10 */ "cmd ::= SAVEPOINT nm",
  129623. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  129624. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  129625. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  129626. /* 14 */ "createkw ::= CREATE",
  129627. /* 15 */ "ifnotexists ::=",
  129628. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  129629. /* 17 */ "temp ::= TEMP",
  129630. /* 18 */ "temp ::=",
  129631. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  129632. /* 20 */ "create_table_args ::= AS select",
  129633. /* 21 */ "table_options ::=",
  129634. /* 22 */ "table_options ::= WITHOUT nm",
  129635. /* 23 */ "columnname ::= nm typetoken",
  129636. /* 24 */ "typetoken ::=",
  129637. /* 25 */ "typetoken ::= typename LP signed RP",
  129638. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  129639. /* 27 */ "typename ::= typename ID|STRING",
  129640. /* 28 */ "ccons ::= CONSTRAINT nm",
  129641. /* 29 */ "ccons ::= DEFAULT term",
  129642. /* 30 */ "ccons ::= DEFAULT LP expr RP",
  129643. /* 31 */ "ccons ::= DEFAULT PLUS term",
  129644. /* 32 */ "ccons ::= DEFAULT MINUS term",
  129645. /* 33 */ "ccons ::= DEFAULT ID|INDEXED",
  129646. /* 34 */ "ccons ::= NOT NULL onconf",
  129647. /* 35 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  129648. /* 36 */ "ccons ::= UNIQUE onconf",
  129649. /* 37 */ "ccons ::= CHECK LP expr RP",
  129650. /* 38 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  129651. /* 39 */ "ccons ::= defer_subclause",
  129652. /* 40 */ "ccons ::= COLLATE ID|STRING",
  129653. /* 41 */ "autoinc ::=",
  129654. /* 42 */ "autoinc ::= AUTOINCR",
  129655. /* 43 */ "refargs ::=",
  129656. /* 44 */ "refargs ::= refargs refarg",
  129657. /* 45 */ "refarg ::= MATCH nm",
  129658. /* 46 */ "refarg ::= ON INSERT refact",
  129659. /* 47 */ "refarg ::= ON DELETE refact",
  129660. /* 48 */ "refarg ::= ON UPDATE refact",
  129661. /* 49 */ "refact ::= SET NULL",
  129662. /* 50 */ "refact ::= SET DEFAULT",
  129663. /* 51 */ "refact ::= CASCADE",
  129664. /* 52 */ "refact ::= RESTRICT",
  129665. /* 53 */ "refact ::= NO ACTION",
  129666. /* 54 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  129667. /* 55 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  129668. /* 56 */ "init_deferred_pred_opt ::=",
  129669. /* 57 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  129670. /* 58 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  129671. /* 59 */ "conslist_opt ::=",
  129672. /* 60 */ "tconscomma ::= COMMA",
  129673. /* 61 */ "tcons ::= CONSTRAINT nm",
  129674. /* 62 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  129675. /* 63 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  129676. /* 64 */ "tcons ::= CHECK LP expr RP onconf",
  129677. /* 65 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  129678. /* 66 */ "defer_subclause_opt ::=",
  129679. /* 67 */ "onconf ::=",
  129680. /* 68 */ "onconf ::= ON CONFLICT resolvetype",
  129681. /* 69 */ "orconf ::=",
  129682. /* 70 */ "orconf ::= OR resolvetype",
  129683. /* 71 */ "resolvetype ::= IGNORE",
  129684. /* 72 */ "resolvetype ::= REPLACE",
  129685. /* 73 */ "cmd ::= DROP TABLE ifexists fullname",
  129686. /* 74 */ "ifexists ::= IF EXISTS",
  129687. /* 75 */ "ifexists ::=",
  129688. /* 76 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  129689. /* 77 */ "cmd ::= DROP VIEW ifexists fullname",
  129690. /* 78 */ "cmd ::= select",
  129691. /* 79 */ "select ::= with selectnowith",
  129692. /* 80 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  129693. /* 81 */ "multiselect_op ::= UNION",
  129694. /* 82 */ "multiselect_op ::= UNION ALL",
  129695. /* 83 */ "multiselect_op ::= EXCEPT|INTERSECT",
  129696. /* 84 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  129697. /* 85 */ "values ::= VALUES LP nexprlist RP",
  129698. /* 86 */ "values ::= values COMMA LP exprlist RP",
  129699. /* 87 */ "distinct ::= DISTINCT",
  129700. /* 88 */ "distinct ::= ALL",
  129701. /* 89 */ "distinct ::=",
  129702. /* 90 */ "sclp ::=",
  129703. /* 91 */ "selcollist ::= sclp expr as",
  129704. /* 92 */ "selcollist ::= sclp STAR",
  129705. /* 93 */ "selcollist ::= sclp nm DOT STAR",
  129706. /* 94 */ "as ::= AS nm",
  129707. /* 95 */ "as ::=",
  129708. /* 96 */ "from ::=",
  129709. /* 97 */ "from ::= FROM seltablist",
  129710. /* 98 */ "stl_prefix ::= seltablist joinop",
  129711. /* 99 */ "stl_prefix ::=",
  129712. /* 100 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  129713. /* 101 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  129714. /* 102 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  129715. /* 103 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  129716. /* 104 */ "dbnm ::=",
  129717. /* 105 */ "dbnm ::= DOT nm",
  129718. /* 106 */ "fullname ::= nm dbnm",
  129719. /* 107 */ "joinop ::= COMMA|JOIN",
  129720. /* 108 */ "joinop ::= JOIN_KW JOIN",
  129721. /* 109 */ "joinop ::= JOIN_KW nm JOIN",
  129722. /* 110 */ "joinop ::= JOIN_KW nm nm JOIN",
  129723. /* 111 */ "on_opt ::= ON expr",
  129724. /* 112 */ "on_opt ::=",
  129725. /* 113 */ "indexed_opt ::=",
  129726. /* 114 */ "indexed_opt ::= INDEXED BY nm",
  129727. /* 115 */ "indexed_opt ::= NOT INDEXED",
  129728. /* 116 */ "using_opt ::= USING LP idlist RP",
  129729. /* 117 */ "using_opt ::=",
  129730. /* 118 */ "orderby_opt ::=",
  129731. /* 119 */ "orderby_opt ::= ORDER BY sortlist",
  129732. /* 120 */ "sortlist ::= sortlist COMMA expr sortorder",
  129733. /* 121 */ "sortlist ::= expr sortorder",
  129734. /* 122 */ "sortorder ::= ASC",
  129735. /* 123 */ "sortorder ::= DESC",
  129736. /* 124 */ "sortorder ::=",
  129737. /* 125 */ "groupby_opt ::=",
  129738. /* 126 */ "groupby_opt ::= GROUP BY nexprlist",
  129739. /* 127 */ "having_opt ::=",
  129740. /* 128 */ "having_opt ::= HAVING expr",
  129741. /* 129 */ "limit_opt ::=",
  129742. /* 130 */ "limit_opt ::= LIMIT expr",
  129743. /* 131 */ "limit_opt ::= LIMIT expr OFFSET expr",
  129744. /* 132 */ "limit_opt ::= LIMIT expr COMMA expr",
  129745. /* 133 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  129746. /* 134 */ "where_opt ::=",
  129747. /* 135 */ "where_opt ::= WHERE expr",
  129748. /* 136 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  129749. /* 137 */ "setlist ::= setlist COMMA nm EQ expr",
  129750. /* 138 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  129751. /* 139 */ "setlist ::= nm EQ expr",
  129752. /* 140 */ "setlist ::= LP idlist RP EQ expr",
  129753. /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  129754. /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  129755. /* 143 */ "insert_cmd ::= INSERT orconf",
  129756. /* 144 */ "insert_cmd ::= REPLACE",
  129757. /* 145 */ "idlist_opt ::=",
  129758. /* 146 */ "idlist_opt ::= LP idlist RP",
  129759. /* 147 */ "idlist ::= idlist COMMA nm",
  129760. /* 148 */ "idlist ::= nm",
  129761. /* 149 */ "expr ::= LP expr RP",
  129762. /* 150 */ "expr ::= ID|INDEXED",
  129763. /* 151 */ "expr ::= JOIN_KW",
  129764. /* 152 */ "expr ::= nm DOT nm",
  129765. /* 153 */ "expr ::= nm DOT nm DOT nm",
  129766. /* 154 */ "term ::= NULL|FLOAT|BLOB",
  129767. /* 155 */ "term ::= STRING",
  129768. /* 156 */ "term ::= INTEGER",
  129769. /* 157 */ "expr ::= VARIABLE",
  129770. /* 158 */ "expr ::= expr COLLATE ID|STRING",
  129771. /* 159 */ "expr ::= CAST LP expr AS typetoken RP",
  129772. /* 160 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  129773. /* 161 */ "expr ::= ID|INDEXED LP STAR RP",
  129774. /* 162 */ "term ::= CTIME_KW",
  129775. /* 163 */ "expr ::= LP nexprlist COMMA expr RP",
  129776. /* 164 */ "expr ::= expr AND expr",
  129777. /* 165 */ "expr ::= expr OR expr",
  129778. /* 166 */ "expr ::= expr LT|GT|GE|LE expr",
  129779. /* 167 */ "expr ::= expr EQ|NE expr",
  129780. /* 168 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  129781. /* 169 */ "expr ::= expr PLUS|MINUS expr",
  129782. /* 170 */ "expr ::= expr STAR|SLASH|REM expr",
  129783. /* 171 */ "expr ::= expr CONCAT expr",
  129784. /* 172 */ "likeop ::= NOT LIKE_KW|MATCH",
  129785. /* 173 */ "expr ::= expr likeop expr",
  129786. /* 174 */ "expr ::= expr likeop expr ESCAPE expr",
  129787. /* 175 */ "expr ::= expr ISNULL|NOTNULL",
  129788. /* 176 */ "expr ::= expr NOT NULL",
  129789. /* 177 */ "expr ::= expr IS expr",
  129790. /* 178 */ "expr ::= expr IS NOT expr",
  129791. /* 179 */ "expr ::= NOT expr",
  129792. /* 180 */ "expr ::= BITNOT expr",
  129793. /* 181 */ "expr ::= MINUS expr",
  129794. /* 182 */ "expr ::= PLUS expr",
  129795. /* 183 */ "between_op ::= BETWEEN",
  129796. /* 184 */ "between_op ::= NOT BETWEEN",
  129797. /* 185 */ "expr ::= expr between_op expr AND expr",
  129798. /* 186 */ "in_op ::= IN",
  129799. /* 187 */ "in_op ::= NOT IN",
  129800. /* 188 */ "expr ::= expr in_op LP exprlist RP",
  129801. /* 189 */ "expr ::= LP select RP",
  129802. /* 190 */ "expr ::= expr in_op LP select RP",
  129803. /* 191 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  129804. /* 192 */ "expr ::= EXISTS LP select RP",
  129805. /* 193 */ "expr ::= CASE case_operand case_exprlist case_else END",
  129806. /* 194 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  129807. /* 195 */ "case_exprlist ::= WHEN expr THEN expr",
  129808. /* 196 */ "case_else ::= ELSE expr",
  129809. /* 197 */ "case_else ::=",
  129810. /* 198 */ "case_operand ::= expr",
  129811. /* 199 */ "case_operand ::=",
  129812. /* 200 */ "exprlist ::=",
  129813. /* 201 */ "nexprlist ::= nexprlist COMMA expr",
  129814. /* 202 */ "nexprlist ::= expr",
  129815. /* 203 */ "paren_exprlist ::=",
  129816. /* 204 */ "paren_exprlist ::= LP exprlist RP",
  129817. /* 205 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  129818. /* 206 */ "uniqueflag ::= UNIQUE",
  129819. /* 207 */ "uniqueflag ::=",
  129820. /* 208 */ "eidlist_opt ::=",
  129821. /* 209 */ "eidlist_opt ::= LP eidlist RP",
  129822. /* 210 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  129823. /* 211 */ "eidlist ::= nm collate sortorder",
  129824. /* 212 */ "collate ::=",
  129825. /* 213 */ "collate ::= COLLATE ID|STRING",
  129826. /* 214 */ "cmd ::= DROP INDEX ifexists fullname",
  129827. /* 215 */ "cmd ::= VACUUM",
  129828. /* 216 */ "cmd ::= VACUUM nm",
  129829. /* 217 */ "cmd ::= PRAGMA nm dbnm",
  129830. /* 218 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  129831. /* 219 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  129832. /* 220 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  129833. /* 221 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  129834. /* 222 */ "plus_num ::= PLUS INTEGER|FLOAT",
  129835. /* 223 */ "minus_num ::= MINUS INTEGER|FLOAT",
  129836. /* 224 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  129837. /* 225 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  129838. /* 226 */ "trigger_time ::= BEFORE|AFTER",
  129839. /* 227 */ "trigger_time ::= INSTEAD OF",
  129840. /* 228 */ "trigger_time ::=",
  129841. /* 229 */ "trigger_event ::= DELETE|INSERT",
  129842. /* 230 */ "trigger_event ::= UPDATE",
  129843. /* 231 */ "trigger_event ::= UPDATE OF idlist",
  129844. /* 232 */ "when_clause ::=",
  129845. /* 233 */ "when_clause ::= WHEN expr",
  129846. /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  129847. /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  129848. /* 236 */ "trnm ::= nm DOT nm",
  129849. /* 237 */ "tridxby ::= INDEXED BY nm",
  129850. /* 238 */ "tridxby ::= NOT INDEXED",
  129851. /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  129852. /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  129853. /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  129854. /* 242 */ "trigger_cmd ::= select",
  129855. /* 243 */ "expr ::= RAISE LP IGNORE RP",
  129856. /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  129857. /* 245 */ "raisetype ::= ROLLBACK",
  129858. /* 246 */ "raisetype ::= ABORT",
  129859. /* 247 */ "raisetype ::= FAIL",
  129860. /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
  129861. /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  129862. /* 250 */ "cmd ::= DETACH database_kw_opt expr",
  129863. /* 251 */ "key_opt ::=",
  129864. /* 252 */ "key_opt ::= KEY expr",
  129865. /* 253 */ "cmd ::= REINDEX",
  129866. /* 254 */ "cmd ::= REINDEX nm dbnm",
  129867. /* 255 */ "cmd ::= ANALYZE",
  129868. /* 256 */ "cmd ::= ANALYZE nm dbnm",
  129869. /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  129870. /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  129871. /* 259 */ "add_column_fullname ::= fullname",
  129872. /* 260 */ "cmd ::= create_vtab",
  129873. /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
  129874. /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  129875. /* 263 */ "vtabarg ::=",
  129876. /* 264 */ "vtabargtoken ::= ANY",
  129877. /* 265 */ "vtabargtoken ::= lp anylist RP",
  129878. /* 266 */ "lp ::= LP",
  129879. /* 267 */ "with ::=",
  129880. /* 268 */ "with ::= WITH wqlist",
  129881. /* 269 */ "with ::= WITH RECURSIVE wqlist",
  129882. /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  129883. /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  129884. /* 272 */ "input ::= cmdlist",
  129885. /* 273 */ "cmdlist ::= cmdlist ecmd",
  129886. /* 274 */ "cmdlist ::= ecmd",
  129887. /* 275 */ "ecmd ::= SEMI",
  129888. /* 276 */ "ecmd ::= explain cmdx SEMI",
  129889. /* 277 */ "explain ::=",
  129890. /* 278 */ "trans_opt ::=",
  129891. /* 279 */ "trans_opt ::= TRANSACTION",
  129892. /* 280 */ "trans_opt ::= TRANSACTION nm",
  129893. /* 281 */ "savepoint_opt ::= SAVEPOINT",
  129894. /* 282 */ "savepoint_opt ::=",
  129895. /* 283 */ "cmd ::= create_table create_table_args",
  129896. /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
  129897. /* 285 */ "columnlist ::= columnname carglist",
  129898. /* 286 */ "nm ::= ID|INDEXED",
  129899. /* 287 */ "nm ::= STRING",
  129900. /* 288 */ "nm ::= JOIN_KW",
  129901. /* 289 */ "typetoken ::= typename",
  129902. /* 290 */ "typename ::= ID|STRING",
  129903. /* 291 */ "signed ::= plus_num",
  129904. /* 292 */ "signed ::= minus_num",
  129905. /* 293 */ "carglist ::= carglist ccons",
  129906. /* 294 */ "carglist ::=",
  129907. /* 295 */ "ccons ::= NULL onconf",
  129908. /* 296 */ "conslist_opt ::= COMMA conslist",
  129909. /* 297 */ "conslist ::= conslist tconscomma tcons",
  129910. /* 298 */ "conslist ::= tcons",
  129911. /* 299 */ "tconscomma ::=",
  129912. /* 300 */ "defer_subclause_opt ::= defer_subclause",
  129913. /* 301 */ "resolvetype ::= raisetype",
  129914. /* 302 */ "selectnowith ::= oneselect",
  129915. /* 303 */ "oneselect ::= values",
  129916. /* 304 */ "sclp ::= selcollist COMMA",
  129917. /* 305 */ "as ::= ID|STRING",
  129918. /* 306 */ "expr ::= term",
  129919. /* 307 */ "likeop ::= LIKE_KW|MATCH",
  129920. /* 308 */ "exprlist ::= nexprlist",
  129921. /* 309 */ "nmnum ::= plus_num",
  129922. /* 310 */ "nmnum ::= nm",
  129923. /* 311 */ "nmnum ::= ON",
  129924. /* 312 */ "nmnum ::= DELETE",
  129925. /* 313 */ "nmnum ::= DEFAULT",
  129926. /* 314 */ "plus_num ::= INTEGER|FLOAT",
  129927. /* 315 */ "foreach_clause ::=",
  129928. /* 316 */ "foreach_clause ::= FOR EACH ROW",
  129929. /* 317 */ "trnm ::= nm",
  129930. /* 318 */ "tridxby ::=",
  129931. /* 319 */ "database_kw_opt ::= DATABASE",
  129932. /* 320 */ "database_kw_opt ::=",
  129933. /* 321 */ "kwcolumn_opt ::=",
  129934. /* 322 */ "kwcolumn_opt ::= COLUMNKW",
  129935. /* 323 */ "vtabarglist ::= vtabarg",
  129936. /* 324 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  129937. /* 325 */ "vtabarg ::= vtabarg vtabargtoken",
  129938. /* 326 */ "anylist ::=",
  129939. /* 327 */ "anylist ::= anylist LP anylist RP",
  129940. /* 328 */ "anylist ::= anylist ANY",
  129941. };
  129942. #endif /* NDEBUG */
  129943. #if YYSTACKDEPTH<=0
  129944. /*
  129945. ** Try to increase the size of the parser stack. Return the number
  129946. ** of errors. Return 0 on success.
  129947. */
  129948. static int yyGrowStack(yyParser *p){
  129949. int newSize;
  129950. int idx;
  129951. yyStackEntry *pNew;
  129952. newSize = p->yystksz*2 + 100;
  129953. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  129954. if( p->yystack==&p->yystk0 ){
  129955. pNew = malloc(newSize*sizeof(pNew[0]));
  129956. if( pNew ) pNew[0] = p->yystk0;
  129957. }else{
  129958. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  129959. }
  129960. if( pNew ){
  129961. p->yystack = pNew;
  129962. p->yytos = &p->yystack[idx];
  129963. #ifndef NDEBUG
  129964. if( yyTraceFILE ){
  129965. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  129966. yyTracePrompt, p->yystksz, newSize);
  129967. }
  129968. #endif
  129969. p->yystksz = newSize;
  129970. }
  129971. return pNew==0;
  129972. }
  129973. #endif
  129974. /* Datatype of the argument to the memory allocated passed as the
  129975. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  129976. ** putting an appropriate #define in the %include section of the input
  129977. ** grammar.
  129978. */
  129979. #ifndef YYMALLOCARGTYPE
  129980. # define YYMALLOCARGTYPE size_t
  129981. #endif
  129982. /* Initialize a new parser that has already been allocated.
  129983. */
  129984. SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
  129985. yyParser *pParser = (yyParser*)yypParser;
  129986. #ifdef YYTRACKMAXSTACKDEPTH
  129987. pParser->yyhwm = 0;
  129988. #endif
  129989. #if YYSTACKDEPTH<=0
  129990. pParser->yytos = NULL;
  129991. pParser->yystack = NULL;
  129992. pParser->yystksz = 0;
  129993. if( yyGrowStack(pParser) ){
  129994. pParser->yystack = &pParser->yystk0;
  129995. pParser->yystksz = 1;
  129996. }
  129997. #endif
  129998. #ifndef YYNOERRORRECOVERY
  129999. pParser->yyerrcnt = -1;
  130000. #endif
  130001. pParser->yytos = pParser->yystack;
  130002. pParser->yystack[0].stateno = 0;
  130003. pParser->yystack[0].major = 0;
  130004. #if YYSTACKDEPTH>0
  130005. pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
  130006. #endif
  130007. }
  130008. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  130009. /*
  130010. ** This function allocates a new parser.
  130011. ** The only argument is a pointer to a function which works like
  130012. ** malloc.
  130013. **
  130014. ** Inputs:
  130015. ** A pointer to the function used to allocate memory.
  130016. **
  130017. ** Outputs:
  130018. ** A pointer to a parser. This pointer is used in subsequent calls
  130019. ** to sqlite3Parser and sqlite3ParserFree.
  130020. */
  130021. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  130022. yyParser *pParser;
  130023. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  130024. if( pParser ) sqlite3ParserInit(pParser);
  130025. return pParser;
  130026. }
  130027. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  130028. /* The following function deletes the "minor type" or semantic value
  130029. ** associated with a symbol. The symbol can be either a terminal
  130030. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  130031. ** a pointer to the value to be deleted. The code used to do the
  130032. ** deletions is derived from the %destructor and/or %token_destructor
  130033. ** directives of the input grammar.
  130034. */
  130035. static void yy_destructor(
  130036. yyParser *yypParser, /* The parser */
  130037. YYCODETYPE yymajor, /* Type code for object to destroy */
  130038. YYMINORTYPE *yypminor /* The object to be destroyed */
  130039. ){
  130040. sqlite3ParserARG_FETCH;
  130041. switch( yymajor ){
  130042. /* Here is inserted the actions which take place when a
  130043. ** terminal or non-terminal is destroyed. This can happen
  130044. ** when the symbol is popped from the stack during a
  130045. ** reduce or during error processing or when a parser is
  130046. ** being destroyed before it is finished parsing.
  130047. **
  130048. ** Note: during a reduce, the only symbols destroyed are those
  130049. ** which appear on the RHS of the rule, but which are *not* used
  130050. ** inside the C code.
  130051. */
  130052. /********* Begin destructor definitions ***************************************/
  130053. case 163: /* select */
  130054. case 194: /* selectnowith */
  130055. case 195: /* oneselect */
  130056. case 206: /* values */
  130057. {
  130058. sqlite3SelectDelete(pParse->db, (yypminor->yy243));
  130059. }
  130060. break;
  130061. case 172: /* term */
  130062. case 173: /* expr */
  130063. {
  130064. sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
  130065. }
  130066. break;
  130067. case 177: /* eidlist_opt */
  130068. case 186: /* sortlist */
  130069. case 187: /* eidlist */
  130070. case 199: /* selcollist */
  130071. case 202: /* groupby_opt */
  130072. case 204: /* orderby_opt */
  130073. case 207: /* nexprlist */
  130074. case 208: /* exprlist */
  130075. case 209: /* sclp */
  130076. case 218: /* setlist */
  130077. case 224: /* paren_exprlist */
  130078. case 226: /* case_exprlist */
  130079. {
  130080. sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
  130081. }
  130082. break;
  130083. case 193: /* fullname */
  130084. case 200: /* from */
  130085. case 211: /* seltablist */
  130086. case 212: /* stl_prefix */
  130087. {
  130088. sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
  130089. }
  130090. break;
  130091. case 196: /* with */
  130092. case 250: /* wqlist */
  130093. {
  130094. sqlite3WithDelete(pParse->db, (yypminor->yy285));
  130095. }
  130096. break;
  130097. case 201: /* where_opt */
  130098. case 203: /* having_opt */
  130099. case 215: /* on_opt */
  130100. case 225: /* case_operand */
  130101. case 227: /* case_else */
  130102. case 236: /* when_clause */
  130103. case 241: /* key_opt */
  130104. {
  130105. sqlite3ExprDelete(pParse->db, (yypminor->yy72));
  130106. }
  130107. break;
  130108. case 216: /* using_opt */
  130109. case 217: /* idlist */
  130110. case 220: /* idlist_opt */
  130111. {
  130112. sqlite3IdListDelete(pParse->db, (yypminor->yy254));
  130113. }
  130114. break;
  130115. case 232: /* trigger_cmd_list */
  130116. case 237: /* trigger_cmd */
  130117. {
  130118. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
  130119. }
  130120. break;
  130121. case 234: /* trigger_event */
  130122. {
  130123. sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
  130124. }
  130125. break;
  130126. /********* End destructor definitions *****************************************/
  130127. default: break; /* If no destructor action specified: do nothing */
  130128. }
  130129. }
  130130. /*
  130131. ** Pop the parser's stack once.
  130132. **
  130133. ** If there is a destructor routine associated with the token which
  130134. ** is popped from the stack, then call it.
  130135. */
  130136. static void yy_pop_parser_stack(yyParser *pParser){
  130137. yyStackEntry *yytos;
  130138. assert( pParser->yytos!=0 );
  130139. assert( pParser->yytos > pParser->yystack );
  130140. yytos = pParser->yytos--;
  130141. #ifndef NDEBUG
  130142. if( yyTraceFILE ){
  130143. fprintf(yyTraceFILE,"%sPopping %s\n",
  130144. yyTracePrompt,
  130145. yyTokenName[yytos->major]);
  130146. }
  130147. #endif
  130148. yy_destructor(pParser, yytos->major, &yytos->minor);
  130149. }
  130150. /*
  130151. ** Clear all secondary memory allocations from the parser
  130152. */
  130153. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  130154. yyParser *pParser = (yyParser*)p;
  130155. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  130156. #if YYSTACKDEPTH<=0
  130157. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  130158. #endif
  130159. }
  130160. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  130161. /*
  130162. ** Deallocate and destroy a parser. Destructors are called for
  130163. ** all stack elements before shutting the parser down.
  130164. **
  130165. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  130166. ** is defined in a %include section of the input grammar) then it is
  130167. ** assumed that the input pointer is never NULL.
  130168. */
  130169. SQLITE_PRIVATE void sqlite3ParserFree(
  130170. void *p, /* The parser to be deleted */
  130171. void (*freeProc)(void*) /* Function used to reclaim memory */
  130172. ){
  130173. #ifndef YYPARSEFREENEVERNULL
  130174. if( p==0 ) return;
  130175. #endif
  130176. sqlite3ParserFinalize(p);
  130177. (*freeProc)(p);
  130178. }
  130179. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  130180. /*
  130181. ** Return the peak depth of the stack for a parser.
  130182. */
  130183. #ifdef YYTRACKMAXSTACKDEPTH
  130184. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  130185. yyParser *pParser = (yyParser*)p;
  130186. return pParser->yyhwm;
  130187. }
  130188. #endif
  130189. /*
  130190. ** Find the appropriate action for a parser given the terminal
  130191. ** look-ahead token iLookAhead.
  130192. */
  130193. static unsigned int yy_find_shift_action(
  130194. yyParser *pParser, /* The parser */
  130195. YYCODETYPE iLookAhead /* The look-ahead token */
  130196. ){
  130197. int i;
  130198. int stateno = pParser->yytos->stateno;
  130199. if( stateno>=YY_MIN_REDUCE ) return stateno;
  130200. assert( stateno <= YY_SHIFT_COUNT );
  130201. do{
  130202. i = yy_shift_ofst[stateno];
  130203. assert( iLookAhead!=YYNOCODE );
  130204. i += iLookAhead;
  130205. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  130206. #ifdef YYFALLBACK
  130207. YYCODETYPE iFallback; /* Fallback token */
  130208. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  130209. && (iFallback = yyFallback[iLookAhead])!=0 ){
  130210. #ifndef NDEBUG
  130211. if( yyTraceFILE ){
  130212. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  130213. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  130214. }
  130215. #endif
  130216. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  130217. iLookAhead = iFallback;
  130218. continue;
  130219. }
  130220. #endif
  130221. #ifdef YYWILDCARD
  130222. {
  130223. int j = i - iLookAhead + YYWILDCARD;
  130224. if(
  130225. #if YY_SHIFT_MIN+YYWILDCARD<0
  130226. j>=0 &&
  130227. #endif
  130228. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  130229. j<YY_ACTTAB_COUNT &&
  130230. #endif
  130231. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  130232. ){
  130233. #ifndef NDEBUG
  130234. if( yyTraceFILE ){
  130235. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  130236. yyTracePrompt, yyTokenName[iLookAhead],
  130237. yyTokenName[YYWILDCARD]);
  130238. }
  130239. #endif /* NDEBUG */
  130240. return yy_action[j];
  130241. }
  130242. }
  130243. #endif /* YYWILDCARD */
  130244. return yy_default[stateno];
  130245. }else{
  130246. return yy_action[i];
  130247. }
  130248. }while(1);
  130249. }
  130250. /*
  130251. ** Find the appropriate action for a parser given the non-terminal
  130252. ** look-ahead token iLookAhead.
  130253. */
  130254. static int yy_find_reduce_action(
  130255. int stateno, /* Current state number */
  130256. YYCODETYPE iLookAhead /* The look-ahead token */
  130257. ){
  130258. int i;
  130259. #ifdef YYERRORSYMBOL
  130260. if( stateno>YY_REDUCE_COUNT ){
  130261. return yy_default[stateno];
  130262. }
  130263. #else
  130264. assert( stateno<=YY_REDUCE_COUNT );
  130265. #endif
  130266. i = yy_reduce_ofst[stateno];
  130267. assert( i!=YY_REDUCE_USE_DFLT );
  130268. assert( iLookAhead!=YYNOCODE );
  130269. i += iLookAhead;
  130270. #ifdef YYERRORSYMBOL
  130271. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  130272. return yy_default[stateno];
  130273. }
  130274. #else
  130275. assert( i>=0 && i<YY_ACTTAB_COUNT );
  130276. assert( yy_lookahead[i]==iLookAhead );
  130277. #endif
  130278. return yy_action[i];
  130279. }
  130280. /*
  130281. ** The following routine is called if the stack overflows.
  130282. */
  130283. static void yyStackOverflow(yyParser *yypParser){
  130284. sqlite3ParserARG_FETCH;
  130285. #ifndef NDEBUG
  130286. if( yyTraceFILE ){
  130287. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  130288. }
  130289. #endif
  130290. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  130291. /* Here code is inserted which will execute if the parser
  130292. ** stack every overflows */
  130293. /******** Begin %stack_overflow code ******************************************/
  130294. sqlite3ErrorMsg(pParse, "parser stack overflow");
  130295. /******** End %stack_overflow code ********************************************/
  130296. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  130297. }
  130298. /*
  130299. ** Print tracing information for a SHIFT action
  130300. */
  130301. #ifndef NDEBUG
  130302. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  130303. if( yyTraceFILE ){
  130304. if( yyNewState<YYNSTATE ){
  130305. fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
  130306. yyTracePrompt,yyTokenName[yypParser->yytos->major],
  130307. yyNewState);
  130308. }else{
  130309. fprintf(yyTraceFILE,"%sShift '%s'\n",
  130310. yyTracePrompt,yyTokenName[yypParser->yytos->major]);
  130311. }
  130312. }
  130313. }
  130314. #else
  130315. # define yyTraceShift(X,Y)
  130316. #endif
  130317. /*
  130318. ** Perform a shift action.
  130319. */
  130320. static void yy_shift(
  130321. yyParser *yypParser, /* The parser to be shifted */
  130322. int yyNewState, /* The new state to shift in */
  130323. int yyMajor, /* The major token to shift in */
  130324. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  130325. ){
  130326. yyStackEntry *yytos;
  130327. yypParser->yytos++;
  130328. #ifdef YYTRACKMAXSTACKDEPTH
  130329. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  130330. yypParser->yyhwm++;
  130331. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  130332. }
  130333. #endif
  130334. #if YYSTACKDEPTH>0
  130335. if( yypParser->yytos>yypParser->yystackEnd ){
  130336. yypParser->yytos--;
  130337. yyStackOverflow(yypParser);
  130338. return;
  130339. }
  130340. #else
  130341. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  130342. if( yyGrowStack(yypParser) ){
  130343. yypParser->yytos--;
  130344. yyStackOverflow(yypParser);
  130345. return;
  130346. }
  130347. }
  130348. #endif
  130349. if( yyNewState > YY_MAX_SHIFT ){
  130350. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  130351. }
  130352. yytos = yypParser->yytos;
  130353. yytos->stateno = (YYACTIONTYPE)yyNewState;
  130354. yytos->major = (YYCODETYPE)yyMajor;
  130355. yytos->minor.yy0 = yyMinor;
  130356. yyTraceShift(yypParser, yyNewState);
  130357. }
  130358. /* The following table contains information about every rule that
  130359. ** is used during the reduce.
  130360. */
  130361. static const struct {
  130362. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  130363. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  130364. } yyRuleInfo[] = {
  130365. { 147, -1 },
  130366. { 147, -3 },
  130367. { 148, -1 },
  130368. { 149, -3 },
  130369. { 150, 0 },
  130370. { 150, -1 },
  130371. { 150, -1 },
  130372. { 150, -1 },
  130373. { 149, -2 },
  130374. { 149, -2 },
  130375. { 149, -2 },
  130376. { 149, -3 },
  130377. { 149, -5 },
  130378. { 154, -6 },
  130379. { 156, -1 },
  130380. { 158, 0 },
  130381. { 158, -3 },
  130382. { 157, -1 },
  130383. { 157, 0 },
  130384. { 155, -5 },
  130385. { 155, -2 },
  130386. { 162, 0 },
  130387. { 162, -2 },
  130388. { 164, -2 },
  130389. { 166, 0 },
  130390. { 166, -4 },
  130391. { 166, -6 },
  130392. { 167, -2 },
  130393. { 171, -2 },
  130394. { 171, -2 },
  130395. { 171, -4 },
  130396. { 171, -3 },
  130397. { 171, -3 },
  130398. { 171, -2 },
  130399. { 171, -3 },
  130400. { 171, -5 },
  130401. { 171, -2 },
  130402. { 171, -4 },
  130403. { 171, -4 },
  130404. { 171, -1 },
  130405. { 171, -2 },
  130406. { 176, 0 },
  130407. { 176, -1 },
  130408. { 178, 0 },
  130409. { 178, -2 },
  130410. { 180, -2 },
  130411. { 180, -3 },
  130412. { 180, -3 },
  130413. { 180, -3 },
  130414. { 181, -2 },
  130415. { 181, -2 },
  130416. { 181, -1 },
  130417. { 181, -1 },
  130418. { 181, -2 },
  130419. { 179, -3 },
  130420. { 179, -2 },
  130421. { 182, 0 },
  130422. { 182, -2 },
  130423. { 182, -2 },
  130424. { 161, 0 },
  130425. { 184, -1 },
  130426. { 185, -2 },
  130427. { 185, -7 },
  130428. { 185, -5 },
  130429. { 185, -5 },
  130430. { 185, -10 },
  130431. { 188, 0 },
  130432. { 174, 0 },
  130433. { 174, -3 },
  130434. { 189, 0 },
  130435. { 189, -2 },
  130436. { 190, -1 },
  130437. { 190, -1 },
  130438. { 149, -4 },
  130439. { 192, -2 },
  130440. { 192, 0 },
  130441. { 149, -9 },
  130442. { 149, -4 },
  130443. { 149, -1 },
  130444. { 163, -2 },
  130445. { 194, -3 },
  130446. { 197, -1 },
  130447. { 197, -2 },
  130448. { 197, -1 },
  130449. { 195, -9 },
  130450. { 206, -4 },
  130451. { 206, -5 },
  130452. { 198, -1 },
  130453. { 198, -1 },
  130454. { 198, 0 },
  130455. { 209, 0 },
  130456. { 199, -3 },
  130457. { 199, -2 },
  130458. { 199, -4 },
  130459. { 210, -2 },
  130460. { 210, 0 },
  130461. { 200, 0 },
  130462. { 200, -2 },
  130463. { 212, -2 },
  130464. { 212, 0 },
  130465. { 211, -7 },
  130466. { 211, -9 },
  130467. { 211, -7 },
  130468. { 211, -7 },
  130469. { 159, 0 },
  130470. { 159, -2 },
  130471. { 193, -2 },
  130472. { 213, -1 },
  130473. { 213, -2 },
  130474. { 213, -3 },
  130475. { 213, -4 },
  130476. { 215, -2 },
  130477. { 215, 0 },
  130478. { 214, 0 },
  130479. { 214, -3 },
  130480. { 214, -2 },
  130481. { 216, -4 },
  130482. { 216, 0 },
  130483. { 204, 0 },
  130484. { 204, -3 },
  130485. { 186, -4 },
  130486. { 186, -2 },
  130487. { 175, -1 },
  130488. { 175, -1 },
  130489. { 175, 0 },
  130490. { 202, 0 },
  130491. { 202, -3 },
  130492. { 203, 0 },
  130493. { 203, -2 },
  130494. { 205, 0 },
  130495. { 205, -2 },
  130496. { 205, -4 },
  130497. { 205, -4 },
  130498. { 149, -6 },
  130499. { 201, 0 },
  130500. { 201, -2 },
  130501. { 149, -8 },
  130502. { 218, -5 },
  130503. { 218, -7 },
  130504. { 218, -3 },
  130505. { 218, -5 },
  130506. { 149, -6 },
  130507. { 149, -7 },
  130508. { 219, -2 },
  130509. { 219, -1 },
  130510. { 220, 0 },
  130511. { 220, -3 },
  130512. { 217, -3 },
  130513. { 217, -1 },
  130514. { 173, -3 },
  130515. { 173, -1 },
  130516. { 173, -1 },
  130517. { 173, -3 },
  130518. { 173, -5 },
  130519. { 172, -1 },
  130520. { 172, -1 },
  130521. { 172, -1 },
  130522. { 173, -1 },
  130523. { 173, -3 },
  130524. { 173, -6 },
  130525. { 173, -5 },
  130526. { 173, -4 },
  130527. { 172, -1 },
  130528. { 173, -5 },
  130529. { 173, -3 },
  130530. { 173, -3 },
  130531. { 173, -3 },
  130532. { 173, -3 },
  130533. { 173, -3 },
  130534. { 173, -3 },
  130535. { 173, -3 },
  130536. { 173, -3 },
  130537. { 221, -2 },
  130538. { 173, -3 },
  130539. { 173, -5 },
  130540. { 173, -2 },
  130541. { 173, -3 },
  130542. { 173, -3 },
  130543. { 173, -4 },
  130544. { 173, -2 },
  130545. { 173, -2 },
  130546. { 173, -2 },
  130547. { 173, -2 },
  130548. { 222, -1 },
  130549. { 222, -2 },
  130550. { 173, -5 },
  130551. { 223, -1 },
  130552. { 223, -2 },
  130553. { 173, -5 },
  130554. { 173, -3 },
  130555. { 173, -5 },
  130556. { 173, -5 },
  130557. { 173, -4 },
  130558. { 173, -5 },
  130559. { 226, -5 },
  130560. { 226, -4 },
  130561. { 227, -2 },
  130562. { 227, 0 },
  130563. { 225, -1 },
  130564. { 225, 0 },
  130565. { 208, 0 },
  130566. { 207, -3 },
  130567. { 207, -1 },
  130568. { 224, 0 },
  130569. { 224, -3 },
  130570. { 149, -12 },
  130571. { 228, -1 },
  130572. { 228, 0 },
  130573. { 177, 0 },
  130574. { 177, -3 },
  130575. { 187, -5 },
  130576. { 187, -3 },
  130577. { 229, 0 },
  130578. { 229, -2 },
  130579. { 149, -4 },
  130580. { 149, -1 },
  130581. { 149, -2 },
  130582. { 149, -3 },
  130583. { 149, -5 },
  130584. { 149, -6 },
  130585. { 149, -5 },
  130586. { 149, -6 },
  130587. { 169, -2 },
  130588. { 170, -2 },
  130589. { 149, -5 },
  130590. { 231, -11 },
  130591. { 233, -1 },
  130592. { 233, -2 },
  130593. { 233, 0 },
  130594. { 234, -1 },
  130595. { 234, -1 },
  130596. { 234, -3 },
  130597. { 236, 0 },
  130598. { 236, -2 },
  130599. { 232, -3 },
  130600. { 232, -2 },
  130601. { 238, -3 },
  130602. { 239, -3 },
  130603. { 239, -2 },
  130604. { 237, -7 },
  130605. { 237, -5 },
  130606. { 237, -5 },
  130607. { 237, -1 },
  130608. { 173, -4 },
  130609. { 173, -6 },
  130610. { 191, -1 },
  130611. { 191, -1 },
  130612. { 191, -1 },
  130613. { 149, -4 },
  130614. { 149, -6 },
  130615. { 149, -3 },
  130616. { 241, 0 },
  130617. { 241, -2 },
  130618. { 149, -1 },
  130619. { 149, -3 },
  130620. { 149, -1 },
  130621. { 149, -3 },
  130622. { 149, -6 },
  130623. { 149, -7 },
  130624. { 242, -1 },
  130625. { 149, -1 },
  130626. { 149, -4 },
  130627. { 244, -8 },
  130628. { 246, 0 },
  130629. { 247, -1 },
  130630. { 247, -3 },
  130631. { 248, -1 },
  130632. { 196, 0 },
  130633. { 196, -2 },
  130634. { 196, -3 },
  130635. { 250, -6 },
  130636. { 250, -8 },
  130637. { 144, -1 },
  130638. { 145, -2 },
  130639. { 145, -1 },
  130640. { 146, -1 },
  130641. { 146, -3 },
  130642. { 147, 0 },
  130643. { 151, 0 },
  130644. { 151, -1 },
  130645. { 151, -2 },
  130646. { 153, -1 },
  130647. { 153, 0 },
  130648. { 149, -2 },
  130649. { 160, -4 },
  130650. { 160, -2 },
  130651. { 152, -1 },
  130652. { 152, -1 },
  130653. { 152, -1 },
  130654. { 166, -1 },
  130655. { 167, -1 },
  130656. { 168, -1 },
  130657. { 168, -1 },
  130658. { 165, -2 },
  130659. { 165, 0 },
  130660. { 171, -2 },
  130661. { 161, -2 },
  130662. { 183, -3 },
  130663. { 183, -1 },
  130664. { 184, 0 },
  130665. { 188, -1 },
  130666. { 190, -1 },
  130667. { 194, -1 },
  130668. { 195, -1 },
  130669. { 209, -2 },
  130670. { 210, -1 },
  130671. { 173, -1 },
  130672. { 221, -1 },
  130673. { 208, -1 },
  130674. { 230, -1 },
  130675. { 230, -1 },
  130676. { 230, -1 },
  130677. { 230, -1 },
  130678. { 230, -1 },
  130679. { 169, -1 },
  130680. { 235, 0 },
  130681. { 235, -3 },
  130682. { 238, -1 },
  130683. { 239, 0 },
  130684. { 240, -1 },
  130685. { 240, 0 },
  130686. { 243, 0 },
  130687. { 243, -1 },
  130688. { 245, -1 },
  130689. { 245, -3 },
  130690. { 246, -2 },
  130691. { 249, 0 },
  130692. { 249, -4 },
  130693. { 249, -2 },
  130694. };
  130695. static void yy_accept(yyParser*); /* Forward Declaration */
  130696. /*
  130697. ** Perform a reduce action and the shift that must immediately
  130698. ** follow the reduce.
  130699. */
  130700. static void yy_reduce(
  130701. yyParser *yypParser, /* The parser */
  130702. unsigned int yyruleno /* Number of the rule by which to reduce */
  130703. ){
  130704. int yygoto; /* The next state */
  130705. int yyact; /* The next action */
  130706. yyStackEntry *yymsp; /* The top of the parser's stack */
  130707. int yysize; /* Amount to pop the stack */
  130708. sqlite3ParserARG_FETCH;
  130709. yymsp = yypParser->yytos;
  130710. #ifndef NDEBUG
  130711. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  130712. yysize = yyRuleInfo[yyruleno].nrhs;
  130713. fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
  130714. yyRuleName[yyruleno], yymsp[yysize].stateno);
  130715. }
  130716. #endif /* NDEBUG */
  130717. /* Check that the stack is large enough to grow by a single entry
  130718. ** if the RHS of the rule is empty. This ensures that there is room
  130719. ** enough on the stack to push the LHS value */
  130720. if( yyRuleInfo[yyruleno].nrhs==0 ){
  130721. #ifdef YYTRACKMAXSTACKDEPTH
  130722. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  130723. yypParser->yyhwm++;
  130724. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  130725. }
  130726. #endif
  130727. #if YYSTACKDEPTH>0
  130728. if( yypParser->yytos>=yypParser->yystackEnd ){
  130729. yyStackOverflow(yypParser);
  130730. return;
  130731. }
  130732. #else
  130733. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  130734. if( yyGrowStack(yypParser) ){
  130735. yyStackOverflow(yypParser);
  130736. return;
  130737. }
  130738. yymsp = yypParser->yytos;
  130739. }
  130740. #endif
  130741. }
  130742. switch( yyruleno ){
  130743. /* Beginning here are the reduction cases. A typical example
  130744. ** follows:
  130745. ** case 0:
  130746. ** #line <lineno> <grammarfile>
  130747. ** { ... } // User supplied code
  130748. ** #line <lineno> <thisfile>
  130749. ** break;
  130750. */
  130751. /********** Begin reduce actions **********************************************/
  130752. YYMINORTYPE yylhsminor;
  130753. case 0: /* explain ::= EXPLAIN */
  130754. { pParse->explain = 1; }
  130755. break;
  130756. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  130757. { pParse->explain = 2; }
  130758. break;
  130759. case 2: /* cmdx ::= cmd */
  130760. { sqlite3FinishCoding(pParse); }
  130761. break;
  130762. case 3: /* cmd ::= BEGIN transtype trans_opt */
  130763. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
  130764. break;
  130765. case 4: /* transtype ::= */
  130766. {yymsp[1].minor.yy194 = TK_DEFERRED;}
  130767. break;
  130768. case 5: /* transtype ::= DEFERRED */
  130769. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  130770. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  130771. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
  130772. break;
  130773. case 8: /* cmd ::= COMMIT|END trans_opt */
  130774. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  130775. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  130776. break;
  130777. case 10: /* cmd ::= SAVEPOINT nm */
  130778. {
  130779. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  130780. }
  130781. break;
  130782. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  130783. {
  130784. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  130785. }
  130786. break;
  130787. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  130788. {
  130789. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  130790. }
  130791. break;
  130792. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  130793. {
  130794. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
  130795. }
  130796. break;
  130797. case 14: /* createkw ::= CREATE */
  130798. {disableLookaside(pParse);}
  130799. break;
  130800. case 15: /* ifnotexists ::= */
  130801. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  130802. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  130803. case 41: /* autoinc ::= */ yytestcase(yyruleno==41);
  130804. case 56: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==56);
  130805. case 66: /* defer_subclause_opt ::= */ yytestcase(yyruleno==66);
  130806. case 75: /* ifexists ::= */ yytestcase(yyruleno==75);
  130807. case 89: /* distinct ::= */ yytestcase(yyruleno==89);
  130808. case 212: /* collate ::= */ yytestcase(yyruleno==212);
  130809. {yymsp[1].minor.yy194 = 0;}
  130810. break;
  130811. case 16: /* ifnotexists ::= IF NOT EXISTS */
  130812. {yymsp[-2].minor.yy194 = 1;}
  130813. break;
  130814. case 17: /* temp ::= TEMP */
  130815. case 42: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==42);
  130816. {yymsp[0].minor.yy194 = 1;}
  130817. break;
  130818. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  130819. {
  130820. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
  130821. }
  130822. break;
  130823. case 20: /* create_table_args ::= AS select */
  130824. {
  130825. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
  130826. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  130827. }
  130828. break;
  130829. case 22: /* table_options ::= WITHOUT nm */
  130830. {
  130831. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  130832. yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
  130833. }else{
  130834. yymsp[-1].minor.yy194 = 0;
  130835. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  130836. }
  130837. }
  130838. break;
  130839. case 23: /* columnname ::= nm typetoken */
  130840. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  130841. break;
  130842. case 24: /* typetoken ::= */
  130843. case 59: /* conslist_opt ::= */ yytestcase(yyruleno==59);
  130844. case 95: /* as ::= */ yytestcase(yyruleno==95);
  130845. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  130846. break;
  130847. case 25: /* typetoken ::= typename LP signed RP */
  130848. {
  130849. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  130850. }
  130851. break;
  130852. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  130853. {
  130854. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  130855. }
  130856. break;
  130857. case 27: /* typename ::= typename ID|STRING */
  130858. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  130859. break;
  130860. case 28: /* ccons ::= CONSTRAINT nm */
  130861. case 61: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==61);
  130862. {pParse->constraintName = yymsp[0].minor.yy0;}
  130863. break;
  130864. case 29: /* ccons ::= DEFAULT term */
  130865. case 31: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==31);
  130866. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
  130867. break;
  130868. case 30: /* ccons ::= DEFAULT LP expr RP */
  130869. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
  130870. break;
  130871. case 32: /* ccons ::= DEFAULT MINUS term */
  130872. {
  130873. ExprSpan v;
  130874. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
  130875. v.zStart = yymsp[-1].minor.yy0.z;
  130876. v.zEnd = yymsp[0].minor.yy190.zEnd;
  130877. sqlite3AddDefaultValue(pParse,&v);
  130878. }
  130879. break;
  130880. case 33: /* ccons ::= DEFAULT ID|INDEXED */
  130881. {
  130882. ExprSpan v;
  130883. spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
  130884. sqlite3AddDefaultValue(pParse,&v);
  130885. }
  130886. break;
  130887. case 34: /* ccons ::= NOT NULL onconf */
  130888. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
  130889. break;
  130890. case 35: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  130891. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
  130892. break;
  130893. case 36: /* ccons ::= UNIQUE onconf */
  130894. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
  130895. SQLITE_IDXTYPE_UNIQUE);}
  130896. break;
  130897. case 37: /* ccons ::= CHECK LP expr RP */
  130898. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
  130899. break;
  130900. case 38: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  130901. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
  130902. break;
  130903. case 39: /* ccons ::= defer_subclause */
  130904. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
  130905. break;
  130906. case 40: /* ccons ::= COLLATE ID|STRING */
  130907. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  130908. break;
  130909. case 43: /* refargs ::= */
  130910. { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
  130911. break;
  130912. case 44: /* refargs ::= refargs refarg */
  130913. { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
  130914. break;
  130915. case 45: /* refarg ::= MATCH nm */
  130916. { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
  130917. break;
  130918. case 46: /* refarg ::= ON INSERT refact */
  130919. { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
  130920. break;
  130921. case 47: /* refarg ::= ON DELETE refact */
  130922. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
  130923. break;
  130924. case 48: /* refarg ::= ON UPDATE refact */
  130925. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
  130926. break;
  130927. case 49: /* refact ::= SET NULL */
  130928. { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
  130929. break;
  130930. case 50: /* refact ::= SET DEFAULT */
  130931. { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
  130932. break;
  130933. case 51: /* refact ::= CASCADE */
  130934. { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
  130935. break;
  130936. case 52: /* refact ::= RESTRICT */
  130937. { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
  130938. break;
  130939. case 53: /* refact ::= NO ACTION */
  130940. { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
  130941. break;
  130942. case 54: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  130943. {yymsp[-2].minor.yy194 = 0;}
  130944. break;
  130945. case 55: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  130946. case 70: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==70);
  130947. case 143: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==143);
  130948. {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
  130949. break;
  130950. case 57: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  130951. case 74: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==74);
  130952. case 184: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==184);
  130953. case 187: /* in_op ::= NOT IN */ yytestcase(yyruleno==187);
  130954. case 213: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==213);
  130955. {yymsp[-1].minor.yy194 = 1;}
  130956. break;
  130957. case 58: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  130958. {yymsp[-1].minor.yy194 = 0;}
  130959. break;
  130960. case 60: /* tconscomma ::= COMMA */
  130961. {pParse->constraintName.n = 0;}
  130962. break;
  130963. case 62: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  130964. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
  130965. break;
  130966. case 63: /* tcons ::= UNIQUE LP sortlist RP onconf */
  130967. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
  130968. SQLITE_IDXTYPE_UNIQUE);}
  130969. break;
  130970. case 64: /* tcons ::= CHECK LP expr RP onconf */
  130971. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
  130972. break;
  130973. case 65: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  130974. {
  130975. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
  130976. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
  130977. }
  130978. break;
  130979. case 67: /* onconf ::= */
  130980. case 69: /* orconf ::= */ yytestcase(yyruleno==69);
  130981. {yymsp[1].minor.yy194 = OE_Default;}
  130982. break;
  130983. case 68: /* onconf ::= ON CONFLICT resolvetype */
  130984. {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
  130985. break;
  130986. case 71: /* resolvetype ::= IGNORE */
  130987. {yymsp[0].minor.yy194 = OE_Ignore;}
  130988. break;
  130989. case 72: /* resolvetype ::= REPLACE */
  130990. case 144: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==144);
  130991. {yymsp[0].minor.yy194 = OE_Replace;}
  130992. break;
  130993. case 73: /* cmd ::= DROP TABLE ifexists fullname */
  130994. {
  130995. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
  130996. }
  130997. break;
  130998. case 76: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  130999. {
  131000. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
  131001. }
  131002. break;
  131003. case 77: /* cmd ::= DROP VIEW ifexists fullname */
  131004. {
  131005. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
  131006. }
  131007. break;
  131008. case 78: /* cmd ::= select */
  131009. {
  131010. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  131011. sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
  131012. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  131013. }
  131014. break;
  131015. case 79: /* select ::= with selectnowith */
  131016. {
  131017. Select *p = yymsp[0].minor.yy243;
  131018. if( p ){
  131019. p->pWith = yymsp[-1].minor.yy285;
  131020. parserDoubleLinkSelect(pParse, p);
  131021. }else{
  131022. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
  131023. }
  131024. yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
  131025. }
  131026. break;
  131027. case 80: /* selectnowith ::= selectnowith multiselect_op oneselect */
  131028. {
  131029. Select *pRhs = yymsp[0].minor.yy243;
  131030. Select *pLhs = yymsp[-2].minor.yy243;
  131031. if( pRhs && pRhs->pPrior ){
  131032. SrcList *pFrom;
  131033. Token x;
  131034. x.n = 0;
  131035. parserDoubleLinkSelect(pParse, pRhs);
  131036. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  131037. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  131038. }
  131039. if( pRhs ){
  131040. pRhs->op = (u8)yymsp[-1].minor.yy194;
  131041. pRhs->pPrior = pLhs;
  131042. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  131043. pRhs->selFlags &= ~SF_MultiValue;
  131044. if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
  131045. }else{
  131046. sqlite3SelectDelete(pParse->db, pLhs);
  131047. }
  131048. yymsp[-2].minor.yy243 = pRhs;
  131049. }
  131050. break;
  131051. case 81: /* multiselect_op ::= UNION */
  131052. case 83: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==83);
  131053. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
  131054. break;
  131055. case 82: /* multiselect_op ::= UNION ALL */
  131056. {yymsp[-1].minor.yy194 = TK_ALL;}
  131057. break;
  131058. case 84: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  131059. {
  131060. #if SELECTTRACE_ENABLED
  131061. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  131062. #endif
  131063. yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
  131064. #if SELECTTRACE_ENABLED
  131065. /* Populate the Select.zSelName[] string that is used to help with
  131066. ** query planner debugging, to differentiate between multiple Select
  131067. ** objects in a complex query.
  131068. **
  131069. ** If the SELECT keyword is immediately followed by a C-style comment
  131070. ** then extract the first few alphanumeric characters from within that
  131071. ** comment to be the zSelName value. Otherwise, the label is #N where
  131072. ** is an integer that is incremented with each SELECT statement seen.
  131073. */
  131074. if( yymsp[-8].minor.yy243!=0 ){
  131075. const char *z = s.z+6;
  131076. int i;
  131077. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
  131078. ++pParse->nSelect);
  131079. while( z[0]==' ' ) z++;
  131080. if( z[0]=='/' && z[1]=='*' ){
  131081. z += 2;
  131082. while( z[0]==' ' ) z++;
  131083. for(i=0; sqlite3Isalnum(z[i]); i++){}
  131084. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
  131085. }
  131086. }
  131087. #endif /* SELECTRACE_ENABLED */
  131088. }
  131089. break;
  131090. case 85: /* values ::= VALUES LP nexprlist RP */
  131091. {
  131092. yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
  131093. }
  131094. break;
  131095. case 86: /* values ::= values COMMA LP exprlist RP */
  131096. {
  131097. Select *pRight, *pLeft = yymsp[-4].minor.yy243;
  131098. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  131099. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  131100. if( pRight ){
  131101. pRight->op = TK_ALL;
  131102. pRight->pPrior = pLeft;
  131103. yymsp[-4].minor.yy243 = pRight;
  131104. }else{
  131105. yymsp[-4].minor.yy243 = pLeft;
  131106. }
  131107. }
  131108. break;
  131109. case 87: /* distinct ::= DISTINCT */
  131110. {yymsp[0].minor.yy194 = SF_Distinct;}
  131111. break;
  131112. case 88: /* distinct ::= ALL */
  131113. {yymsp[0].minor.yy194 = SF_All;}
  131114. break;
  131115. case 90: /* sclp ::= */
  131116. case 118: /* orderby_opt ::= */ yytestcase(yyruleno==118);
  131117. case 125: /* groupby_opt ::= */ yytestcase(yyruleno==125);
  131118. case 200: /* exprlist ::= */ yytestcase(yyruleno==200);
  131119. case 203: /* paren_exprlist ::= */ yytestcase(yyruleno==203);
  131120. case 208: /* eidlist_opt ::= */ yytestcase(yyruleno==208);
  131121. {yymsp[1].minor.yy148 = 0;}
  131122. break;
  131123. case 91: /* selcollist ::= sclp expr as */
  131124. {
  131125. yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  131126. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
  131127. sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
  131128. }
  131129. break;
  131130. case 92: /* selcollist ::= sclp STAR */
  131131. {
  131132. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  131133. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
  131134. }
  131135. break;
  131136. case 93: /* selcollist ::= sclp nm DOT STAR */
  131137. {
  131138. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  131139. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  131140. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  131141. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
  131142. }
  131143. break;
  131144. case 94: /* as ::= AS nm */
  131145. case 105: /* dbnm ::= DOT nm */ yytestcase(yyruleno==105);
  131146. case 222: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
  131147. case 223: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==223);
  131148. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  131149. break;
  131150. case 96: /* from ::= */
  131151. {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
  131152. break;
  131153. case 97: /* from ::= FROM seltablist */
  131154. {
  131155. yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
  131156. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
  131157. }
  131158. break;
  131159. case 98: /* stl_prefix ::= seltablist joinop */
  131160. {
  131161. if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
  131162. }
  131163. break;
  131164. case 99: /* stl_prefix ::= */
  131165. {yymsp[1].minor.yy185 = 0;}
  131166. break;
  131167. case 100: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  131168. {
  131169. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  131170. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
  131171. }
  131172. break;
  131173. case 101: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  131174. {
  131175. yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  131176. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
  131177. }
  131178. break;
  131179. case 102: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  131180. {
  131181. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  131182. }
  131183. break;
  131184. case 103: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  131185. {
  131186. if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
  131187. yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
  131188. }else if( yymsp[-4].minor.yy185->nSrc==1 ){
  131189. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  131190. if( yymsp[-6].minor.yy185 ){
  131191. struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
  131192. struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
  131193. pNew->zName = pOld->zName;
  131194. pNew->zDatabase = pOld->zDatabase;
  131195. pNew->pSelect = pOld->pSelect;
  131196. pOld->zName = pOld->zDatabase = 0;
  131197. pOld->pSelect = 0;
  131198. }
  131199. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
  131200. }else{
  131201. Select *pSubquery;
  131202. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
  131203. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
  131204. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  131205. }
  131206. }
  131207. break;
  131208. case 104: /* dbnm ::= */
  131209. case 113: /* indexed_opt ::= */ yytestcase(yyruleno==113);
  131210. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  131211. break;
  131212. case 106: /* fullname ::= nm dbnm */
  131213. {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  131214. break;
  131215. case 107: /* joinop ::= COMMA|JOIN */
  131216. { yymsp[0].minor.yy194 = JT_INNER; }
  131217. break;
  131218. case 108: /* joinop ::= JOIN_KW JOIN */
  131219. {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  131220. break;
  131221. case 109: /* joinop ::= JOIN_KW nm JOIN */
  131222. {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  131223. break;
  131224. case 110: /* joinop ::= JOIN_KW nm nm JOIN */
  131225. {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  131226. break;
  131227. case 111: /* on_opt ::= ON expr */
  131228. case 128: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==128);
  131229. case 135: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==135);
  131230. case 196: /* case_else ::= ELSE expr */ yytestcase(yyruleno==196);
  131231. {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
  131232. break;
  131233. case 112: /* on_opt ::= */
  131234. case 127: /* having_opt ::= */ yytestcase(yyruleno==127);
  131235. case 134: /* where_opt ::= */ yytestcase(yyruleno==134);
  131236. case 197: /* case_else ::= */ yytestcase(yyruleno==197);
  131237. case 199: /* case_operand ::= */ yytestcase(yyruleno==199);
  131238. {yymsp[1].minor.yy72 = 0;}
  131239. break;
  131240. case 114: /* indexed_opt ::= INDEXED BY nm */
  131241. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  131242. break;
  131243. case 115: /* indexed_opt ::= NOT INDEXED */
  131244. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  131245. break;
  131246. case 116: /* using_opt ::= USING LP idlist RP */
  131247. {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
  131248. break;
  131249. case 117: /* using_opt ::= */
  131250. case 145: /* idlist_opt ::= */ yytestcase(yyruleno==145);
  131251. {yymsp[1].minor.yy254 = 0;}
  131252. break;
  131253. case 119: /* orderby_opt ::= ORDER BY sortlist */
  131254. case 126: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==126);
  131255. {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
  131256. break;
  131257. case 120: /* sortlist ::= sortlist COMMA expr sortorder */
  131258. {
  131259. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
  131260. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
  131261. }
  131262. break;
  131263. case 121: /* sortlist ::= expr sortorder */
  131264. {
  131265. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
  131266. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
  131267. }
  131268. break;
  131269. case 122: /* sortorder ::= ASC */
  131270. {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
  131271. break;
  131272. case 123: /* sortorder ::= DESC */
  131273. {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
  131274. break;
  131275. case 124: /* sortorder ::= */
  131276. {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
  131277. break;
  131278. case 129: /* limit_opt ::= */
  131279. {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
  131280. break;
  131281. case 130: /* limit_opt ::= LIMIT expr */
  131282. {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
  131283. break;
  131284. case 131: /* limit_opt ::= LIMIT expr OFFSET expr */
  131285. {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
  131286. break;
  131287. case 132: /* limit_opt ::= LIMIT expr COMMA expr */
  131288. {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
  131289. break;
  131290. case 133: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  131291. {
  131292. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  131293. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
  131294. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
  131295. }
  131296. break;
  131297. case 136: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  131298. {
  131299. sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
  131300. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
  131301. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
  131302. sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
  131303. }
  131304. break;
  131305. case 137: /* setlist ::= setlist COMMA nm EQ expr */
  131306. {
  131307. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  131308. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
  131309. }
  131310. break;
  131311. case 138: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  131312. {
  131313. yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  131314. }
  131315. break;
  131316. case 139: /* setlist ::= nm EQ expr */
  131317. {
  131318. yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
  131319. sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
  131320. }
  131321. yymsp[-2].minor.yy148 = yylhsminor.yy148;
  131322. break;
  131323. case 140: /* setlist ::= LP idlist RP EQ expr */
  131324. {
  131325. yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  131326. }
  131327. break;
  131328. case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  131329. {
  131330. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  131331. sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
  131332. }
  131333. break;
  131334. case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  131335. {
  131336. sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
  131337. sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
  131338. }
  131339. break;
  131340. case 146: /* idlist_opt ::= LP idlist RP */
  131341. {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
  131342. break;
  131343. case 147: /* idlist ::= idlist COMMA nm */
  131344. {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
  131345. break;
  131346. case 148: /* idlist ::= nm */
  131347. {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  131348. break;
  131349. case 149: /* expr ::= LP expr RP */
  131350. {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
  131351. break;
  131352. case 150: /* expr ::= ID|INDEXED */
  131353. case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
  131354. {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  131355. break;
  131356. case 152: /* expr ::= nm DOT nm */
  131357. {
  131358. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  131359. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  131360. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  131361. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  131362. }
  131363. break;
  131364. case 153: /* expr ::= nm DOT nm DOT nm */
  131365. {
  131366. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  131367. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  131368. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  131369. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  131370. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  131371. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  131372. }
  131373. break;
  131374. case 154: /* term ::= NULL|FLOAT|BLOB */
  131375. case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
  131376. {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  131377. break;
  131378. case 156: /* term ::= INTEGER */
  131379. {
  131380. yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  131381. yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
  131382. yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
  131383. }
  131384. yymsp[0].minor.yy190 = yylhsminor.yy190;
  131385. break;
  131386. case 157: /* expr ::= VARIABLE */
  131387. {
  131388. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  131389. u32 n = yymsp[0].minor.yy0.n;
  131390. spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  131391. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
  131392. }else{
  131393. /* When doing a nested parse, one can include terms in an expression
  131394. ** that look like this: #1 #2 ... These terms refer to registers
  131395. ** in the virtual machine. #N is the N-th register. */
  131396. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  131397. assert( t.n>=2 );
  131398. spanSet(&yymsp[0].minor.yy190, &t, &t);
  131399. if( pParse->nested==0 ){
  131400. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  131401. yymsp[0].minor.yy190.pExpr = 0;
  131402. }else{
  131403. yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  131404. if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
  131405. }
  131406. }
  131407. }
  131408. break;
  131409. case 158: /* expr ::= expr COLLATE ID|STRING */
  131410. {
  131411. yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
  131412. yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  131413. }
  131414. break;
  131415. case 159: /* expr ::= CAST LP expr AS typetoken RP */
  131416. {
  131417. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  131418. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  131419. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
  131420. }
  131421. break;
  131422. case 160: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  131423. {
  131424. if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  131425. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  131426. }
  131427. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
  131428. spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  131429. if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
  131430. yylhsminor.yy190.pExpr->flags |= EP_Distinct;
  131431. }
  131432. }
  131433. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  131434. break;
  131435. case 161: /* expr ::= ID|INDEXED LP STAR RP */
  131436. {
  131437. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  131438. spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  131439. }
  131440. yymsp[-3].minor.yy190 = yylhsminor.yy190;
  131441. break;
  131442. case 162: /* term ::= CTIME_KW */
  131443. {
  131444. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  131445. spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  131446. }
  131447. yymsp[0].minor.yy190 = yylhsminor.yy190;
  131448. break;
  131449. case 163: /* expr ::= LP nexprlist COMMA expr RP */
  131450. {
  131451. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  131452. yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  131453. if( yylhsminor.yy190.pExpr ){
  131454. yylhsminor.yy190.pExpr->x.pList = pList;
  131455. spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  131456. }else{
  131457. sqlite3ExprListDelete(pParse->db, pList);
  131458. }
  131459. }
  131460. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  131461. break;
  131462. case 164: /* expr ::= expr AND expr */
  131463. case 165: /* expr ::= expr OR expr */ yytestcase(yyruleno==165);
  131464. case 166: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==166);
  131465. case 167: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==167);
  131466. case 168: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==168);
  131467. case 169: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==169);
  131468. case 170: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==170);
  131469. case 171: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==171);
  131470. {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
  131471. break;
  131472. case 172: /* likeop ::= NOT LIKE_KW|MATCH */
  131473. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  131474. break;
  131475. case 173: /* expr ::= expr likeop expr */
  131476. {
  131477. ExprList *pList;
  131478. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  131479. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  131480. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
  131481. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
  131482. yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
  131483. exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
  131484. yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  131485. if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
  131486. }
  131487. break;
  131488. case 174: /* expr ::= expr likeop expr ESCAPE expr */
  131489. {
  131490. ExprList *pList;
  131491. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  131492. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  131493. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  131494. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
  131495. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  131496. yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
  131497. exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
  131498. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  131499. if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
  131500. }
  131501. break;
  131502. case 175: /* expr ::= expr ISNULL|NOTNULL */
  131503. {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
  131504. break;
  131505. case 176: /* expr ::= expr NOT NULL */
  131506. {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
  131507. break;
  131508. case 177: /* expr ::= expr IS expr */
  131509. {
  131510. spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
  131511. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
  131512. }
  131513. break;
  131514. case 178: /* expr ::= expr IS NOT expr */
  131515. {
  131516. spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
  131517. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
  131518. }
  131519. break;
  131520. case 179: /* expr ::= NOT expr */
  131521. case 180: /* expr ::= BITNOT expr */ yytestcase(yyruleno==180);
  131522. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  131523. break;
  131524. case 181: /* expr ::= MINUS expr */
  131525. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  131526. break;
  131527. case 182: /* expr ::= PLUS expr */
  131528. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  131529. break;
  131530. case 183: /* between_op ::= BETWEEN */
  131531. case 186: /* in_op ::= IN */ yytestcase(yyruleno==186);
  131532. {yymsp[0].minor.yy194 = 0;}
  131533. break;
  131534. case 185: /* expr ::= expr between_op expr AND expr */
  131535. {
  131536. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  131537. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  131538. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
  131539. if( yymsp[-4].minor.yy190.pExpr ){
  131540. yymsp[-4].minor.yy190.pExpr->x.pList = pList;
  131541. }else{
  131542. sqlite3ExprListDelete(pParse->db, pList);
  131543. }
  131544. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  131545. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  131546. }
  131547. break;
  131548. case 188: /* expr ::= expr in_op LP exprlist RP */
  131549. {
  131550. if( yymsp[-1].minor.yy148==0 ){
  131551. /* Expressions of the form
  131552. **
  131553. ** expr1 IN ()
  131554. ** expr1 NOT IN ()
  131555. **
  131556. ** simplify to constants 0 (false) and 1 (true), respectively,
  131557. ** regardless of the value of expr1.
  131558. */
  131559. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
  131560. yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
  131561. }else if( yymsp[-1].minor.yy148->nExpr==1 ){
  131562. /* Expressions of the form:
  131563. **
  131564. ** expr1 IN (?1)
  131565. ** expr1 NOT IN (?2)
  131566. **
  131567. ** with exactly one value on the RHS can be simplified to something
  131568. ** like this:
  131569. **
  131570. ** expr1 == ?1
  131571. ** expr1 <> ?2
  131572. **
  131573. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  131574. ** so that it may not contribute to the computation of comparison
  131575. ** affinity or the collating sequence to use for comparison. Otherwise,
  131576. ** the semantics would be subtly different from IN or NOT IN.
  131577. */
  131578. Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
  131579. yymsp[-1].minor.yy148->a[0].pExpr = 0;
  131580. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  131581. /* pRHS cannot be NULL because a malloc error would have been detected
  131582. ** before now and control would have never reached this point */
  131583. if( ALWAYS(pRHS) ){
  131584. pRHS->flags &= ~EP_Collate;
  131585. pRHS->flags |= EP_Generic;
  131586. }
  131587. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
  131588. }else{
  131589. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  131590. if( yymsp[-4].minor.yy190.pExpr ){
  131591. yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
  131592. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  131593. }else{
  131594. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  131595. }
  131596. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  131597. }
  131598. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  131599. }
  131600. break;
  131601. case 189: /* expr ::= LP select RP */
  131602. {
  131603. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  131604. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  131605. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  131606. }
  131607. break;
  131608. case 190: /* expr ::= expr in_op LP select RP */
  131609. {
  131610. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  131611. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  131612. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  131613. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  131614. }
  131615. break;
  131616. case 191: /* expr ::= expr in_op nm dbnm paren_exprlist */
  131617. {
  131618. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  131619. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  131620. if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
  131621. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  131622. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
  131623. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  131624. yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
  131625. }
  131626. break;
  131627. case 192: /* expr ::= EXISTS LP select RP */
  131628. {
  131629. Expr *p;
  131630. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  131631. p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  131632. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
  131633. }
  131634. break;
  131635. case 193: /* expr ::= CASE case_operand case_exprlist case_else END */
  131636. {
  131637. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
  131638. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
  131639. if( yymsp[-4].minor.yy190.pExpr ){
  131640. yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
  131641. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  131642. }else{
  131643. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
  131644. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
  131645. }
  131646. }
  131647. break;
  131648. case 194: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  131649. {
  131650. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
  131651. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  131652. }
  131653. break;
  131654. case 195: /* case_exprlist ::= WHEN expr THEN expr */
  131655. {
  131656. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  131657. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
  131658. }
  131659. break;
  131660. case 198: /* case_operand ::= expr */
  131661. {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
  131662. break;
  131663. case 201: /* nexprlist ::= nexprlist COMMA expr */
  131664. {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
  131665. break;
  131666. case 202: /* nexprlist ::= expr */
  131667. {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
  131668. break;
  131669. case 204: /* paren_exprlist ::= LP exprlist RP */
  131670. case 209: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==209);
  131671. {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
  131672. break;
  131673. case 205: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  131674. {
  131675. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  131676. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
  131677. &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
  131678. }
  131679. break;
  131680. case 206: /* uniqueflag ::= UNIQUE */
  131681. case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
  131682. {yymsp[0].minor.yy194 = OE_Abort;}
  131683. break;
  131684. case 207: /* uniqueflag ::= */
  131685. {yymsp[1].minor.yy194 = OE_None;}
  131686. break;
  131687. case 210: /* eidlist ::= eidlist COMMA nm collate sortorder */
  131688. {
  131689. yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
  131690. }
  131691. break;
  131692. case 211: /* eidlist ::= nm collate sortorder */
  131693. {
  131694. yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
  131695. }
  131696. break;
  131697. case 214: /* cmd ::= DROP INDEX ifexists fullname */
  131698. {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
  131699. break;
  131700. case 215: /* cmd ::= VACUUM */
  131701. {sqlite3Vacuum(pParse,0);}
  131702. break;
  131703. case 216: /* cmd ::= VACUUM nm */
  131704. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  131705. break;
  131706. case 217: /* cmd ::= PRAGMA nm dbnm */
  131707. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  131708. break;
  131709. case 218: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  131710. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  131711. break;
  131712. case 219: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  131713. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  131714. break;
  131715. case 220: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  131716. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  131717. break;
  131718. case 221: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  131719. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  131720. break;
  131721. case 224: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  131722. {
  131723. Token all;
  131724. all.z = yymsp[-3].minor.yy0.z;
  131725. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  131726. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
  131727. }
  131728. break;
  131729. case 225: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  131730. {
  131731. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
  131732. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  131733. }
  131734. break;
  131735. case 226: /* trigger_time ::= BEFORE|AFTER */
  131736. { yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/ }
  131737. break;
  131738. case 227: /* trigger_time ::= INSTEAD OF */
  131739. { yymsp[-1].minor.yy194 = TK_INSTEAD;}
  131740. break;
  131741. case 228: /* trigger_time ::= */
  131742. { yymsp[1].minor.yy194 = TK_BEFORE; }
  131743. break;
  131744. case 229: /* trigger_event ::= DELETE|INSERT */
  131745. case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
  131746. {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
  131747. break;
  131748. case 231: /* trigger_event ::= UPDATE OF idlist */
  131749. {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
  131750. break;
  131751. case 232: /* when_clause ::= */
  131752. case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
  131753. { yymsp[1].minor.yy72 = 0; }
  131754. break;
  131755. case 233: /* when_clause ::= WHEN expr */
  131756. case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
  131757. { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
  131758. break;
  131759. case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  131760. {
  131761. assert( yymsp[-2].minor.yy145!=0 );
  131762. yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
  131763. yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
  131764. }
  131765. break;
  131766. case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
  131767. {
  131768. assert( yymsp[-1].minor.yy145!=0 );
  131769. yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
  131770. }
  131771. break;
  131772. case 236: /* trnm ::= nm DOT nm */
  131773. {
  131774. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  131775. sqlite3ErrorMsg(pParse,
  131776. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  131777. "statements within triggers");
  131778. }
  131779. break;
  131780. case 237: /* tridxby ::= INDEXED BY nm */
  131781. {
  131782. sqlite3ErrorMsg(pParse,
  131783. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  131784. "within triggers");
  131785. }
  131786. break;
  131787. case 238: /* tridxby ::= NOT INDEXED */
  131788. {
  131789. sqlite3ErrorMsg(pParse,
  131790. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  131791. "within triggers");
  131792. }
  131793. break;
  131794. case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  131795. {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
  131796. break;
  131797. case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  131798. {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
  131799. break;
  131800. case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  131801. {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
  131802. break;
  131803. case 242: /* trigger_cmd ::= select */
  131804. {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
  131805. break;
  131806. case 243: /* expr ::= RAISE LP IGNORE RP */
  131807. {
  131808. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  131809. yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  131810. if( yymsp[-3].minor.yy190.pExpr ){
  131811. yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
  131812. }
  131813. }
  131814. break;
  131815. case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
  131816. {
  131817. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  131818. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  131819. if( yymsp[-5].minor.yy190.pExpr ) {
  131820. yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
  131821. }
  131822. }
  131823. break;
  131824. case 245: /* raisetype ::= ROLLBACK */
  131825. {yymsp[0].minor.yy194 = OE_Rollback;}
  131826. break;
  131827. case 247: /* raisetype ::= FAIL */
  131828. {yymsp[0].minor.yy194 = OE_Fail;}
  131829. break;
  131830. case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
  131831. {
  131832. sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
  131833. }
  131834. break;
  131835. case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  131836. {
  131837. sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
  131838. }
  131839. break;
  131840. case 250: /* cmd ::= DETACH database_kw_opt expr */
  131841. {
  131842. sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
  131843. }
  131844. break;
  131845. case 253: /* cmd ::= REINDEX */
  131846. {sqlite3Reindex(pParse, 0, 0);}
  131847. break;
  131848. case 254: /* cmd ::= REINDEX nm dbnm */
  131849. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  131850. break;
  131851. case 255: /* cmd ::= ANALYZE */
  131852. {sqlite3Analyze(pParse, 0, 0);}
  131853. break;
  131854. case 256: /* cmd ::= ANALYZE nm dbnm */
  131855. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  131856. break;
  131857. case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  131858. {
  131859. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
  131860. }
  131861. break;
  131862. case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  131863. {
  131864. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  131865. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  131866. }
  131867. break;
  131868. case 259: /* add_column_fullname ::= fullname */
  131869. {
  131870. disableLookaside(pParse);
  131871. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
  131872. }
  131873. break;
  131874. case 260: /* cmd ::= create_vtab */
  131875. {sqlite3VtabFinishParse(pParse,0);}
  131876. break;
  131877. case 261: /* cmd ::= create_vtab LP vtabarglist RP */
  131878. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  131879. break;
  131880. case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  131881. {
  131882. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
  131883. }
  131884. break;
  131885. case 263: /* vtabarg ::= */
  131886. {sqlite3VtabArgInit(pParse);}
  131887. break;
  131888. case 264: /* vtabargtoken ::= ANY */
  131889. case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
  131890. case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
  131891. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  131892. break;
  131893. case 267: /* with ::= */
  131894. {yymsp[1].minor.yy285 = 0;}
  131895. break;
  131896. case 268: /* with ::= WITH wqlist */
  131897. { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
  131898. break;
  131899. case 269: /* with ::= WITH RECURSIVE wqlist */
  131900. { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
  131901. break;
  131902. case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
  131903. {
  131904. yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
  131905. }
  131906. break;
  131907. case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  131908. {
  131909. yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
  131910. }
  131911. break;
  131912. default:
  131913. /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
  131914. /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
  131915. /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
  131916. /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
  131917. /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
  131918. /* (277) explain ::= */ yytestcase(yyruleno==277);
  131919. /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
  131920. /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
  131921. /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
  131922. /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
  131923. /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
  131924. /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
  131925. /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
  131926. /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
  131927. /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
  131928. /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
  131929. /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
  131930. /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
  131931. /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
  131932. /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
  131933. /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
  131934. /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
  131935. /* (294) carglist ::= */ yytestcase(yyruleno==294);
  131936. /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
  131937. /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
  131938. /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
  131939. /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
  131940. /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
  131941. /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
  131942. /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
  131943. /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
  131944. /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
  131945. /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
  131946. /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
  131947. /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
  131948. /* (307) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==307);
  131949. /* (308) exprlist ::= nexprlist */ yytestcase(yyruleno==308);
  131950. /* (309) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=309);
  131951. /* (310) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=310);
  131952. /* (311) nmnum ::= ON */ yytestcase(yyruleno==311);
  131953. /* (312) nmnum ::= DELETE */ yytestcase(yyruleno==312);
  131954. /* (313) nmnum ::= DEFAULT */ yytestcase(yyruleno==313);
  131955. /* (314) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==314);
  131956. /* (315) foreach_clause ::= */ yytestcase(yyruleno==315);
  131957. /* (316) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==316);
  131958. /* (317) trnm ::= nm */ yytestcase(yyruleno==317);
  131959. /* (318) tridxby ::= */ yytestcase(yyruleno==318);
  131960. /* (319) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==319);
  131961. /* (320) database_kw_opt ::= */ yytestcase(yyruleno==320);
  131962. /* (321) kwcolumn_opt ::= */ yytestcase(yyruleno==321);
  131963. /* (322) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==322);
  131964. /* (323) vtabarglist ::= vtabarg */ yytestcase(yyruleno==323);
  131965. /* (324) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==324);
  131966. /* (325) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==325);
  131967. /* (326) anylist ::= */ yytestcase(yyruleno==326);
  131968. /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
  131969. /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
  131970. break;
  131971. /********** End reduce actions ************************************************/
  131972. };
  131973. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  131974. yygoto = yyRuleInfo[yyruleno].lhs;
  131975. yysize = yyRuleInfo[yyruleno].nrhs;
  131976. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  131977. /* There are no SHIFTREDUCE actions on nonterminals because the table
  131978. ** generator has simplified them to pure REDUCE actions. */
  131979. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  131980. /* It is not possible for a REDUCE to be followed by an error */
  131981. assert( yyact!=YY_ERROR_ACTION );
  131982. if( yyact==YY_ACCEPT_ACTION ){
  131983. yypParser->yytos += yysize;
  131984. yy_accept(yypParser);
  131985. }else{
  131986. yymsp += yysize+1;
  131987. yypParser->yytos = yymsp;
  131988. yymsp->stateno = (YYACTIONTYPE)yyact;
  131989. yymsp->major = (YYCODETYPE)yygoto;
  131990. yyTraceShift(yypParser, yyact);
  131991. }
  131992. }
  131993. /*
  131994. ** The following code executes when the parse fails
  131995. */
  131996. #ifndef YYNOERRORRECOVERY
  131997. static void yy_parse_failed(
  131998. yyParser *yypParser /* The parser */
  131999. ){
  132000. sqlite3ParserARG_FETCH;
  132001. #ifndef NDEBUG
  132002. if( yyTraceFILE ){
  132003. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  132004. }
  132005. #endif
  132006. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  132007. /* Here code is inserted which will be executed whenever the
  132008. ** parser fails */
  132009. /************ Begin %parse_failure code ***************************************/
  132010. /************ End %parse_failure code *****************************************/
  132011. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  132012. }
  132013. #endif /* YYNOERRORRECOVERY */
  132014. /*
  132015. ** The following code executes when a syntax error first occurs.
  132016. */
  132017. static void yy_syntax_error(
  132018. yyParser *yypParser, /* The parser */
  132019. int yymajor, /* The major type of the error token */
  132020. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  132021. ){
  132022. sqlite3ParserARG_FETCH;
  132023. #define TOKEN yyminor
  132024. /************ Begin %syntax_error code ****************************************/
  132025. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  132026. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  132027. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  132028. /************ End %syntax_error code ******************************************/
  132029. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  132030. }
  132031. /*
  132032. ** The following is executed when the parser accepts
  132033. */
  132034. static void yy_accept(
  132035. yyParser *yypParser /* The parser */
  132036. ){
  132037. sqlite3ParserARG_FETCH;
  132038. #ifndef NDEBUG
  132039. if( yyTraceFILE ){
  132040. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  132041. }
  132042. #endif
  132043. #ifndef YYNOERRORRECOVERY
  132044. yypParser->yyerrcnt = -1;
  132045. #endif
  132046. assert( yypParser->yytos==yypParser->yystack );
  132047. /* Here code is inserted which will be executed whenever the
  132048. ** parser accepts */
  132049. /*********** Begin %parse_accept code *****************************************/
  132050. /*********** End %parse_accept code *******************************************/
  132051. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  132052. }
  132053. /* The main parser program.
  132054. ** The first argument is a pointer to a structure obtained from
  132055. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  132056. ** The second argument is the major token number. The third is
  132057. ** the minor token. The fourth optional argument is whatever the
  132058. ** user wants (and specified in the grammar) and is available for
  132059. ** use by the action routines.
  132060. **
  132061. ** Inputs:
  132062. ** <ul>
  132063. ** <li> A pointer to the parser (an opaque structure.)
  132064. ** <li> The major token number.
  132065. ** <li> The minor token number.
  132066. ** <li> An option argument of a grammar-specified type.
  132067. ** </ul>
  132068. **
  132069. ** Outputs:
  132070. ** None.
  132071. */
  132072. SQLITE_PRIVATE void sqlite3Parser(
  132073. void *yyp, /* The parser */
  132074. int yymajor, /* The major token code number */
  132075. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  132076. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  132077. ){
  132078. YYMINORTYPE yyminorunion;
  132079. unsigned int yyact; /* The parser action. */
  132080. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  132081. int yyendofinput; /* True if we are at the end of input */
  132082. #endif
  132083. #ifdef YYERRORSYMBOL
  132084. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  132085. #endif
  132086. yyParser *yypParser; /* The parser */
  132087. yypParser = (yyParser*)yyp;
  132088. assert( yypParser->yytos!=0 );
  132089. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  132090. yyendofinput = (yymajor==0);
  132091. #endif
  132092. sqlite3ParserARG_STORE;
  132093. #ifndef NDEBUG
  132094. if( yyTraceFILE ){
  132095. fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
  132096. }
  132097. #endif
  132098. do{
  132099. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  132100. if( yyact <= YY_MAX_SHIFTREDUCE ){
  132101. yy_shift(yypParser,yyact,yymajor,yyminor);
  132102. #ifndef YYNOERRORRECOVERY
  132103. yypParser->yyerrcnt--;
  132104. #endif
  132105. yymajor = YYNOCODE;
  132106. }else if( yyact <= YY_MAX_REDUCE ){
  132107. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  132108. }else{
  132109. assert( yyact == YY_ERROR_ACTION );
  132110. yyminorunion.yy0 = yyminor;
  132111. #ifdef YYERRORSYMBOL
  132112. int yymx;
  132113. #endif
  132114. #ifndef NDEBUG
  132115. if( yyTraceFILE ){
  132116. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  132117. }
  132118. #endif
  132119. #ifdef YYERRORSYMBOL
  132120. /* A syntax error has occurred.
  132121. ** The response to an error depends upon whether or not the
  132122. ** grammar defines an error token "ERROR".
  132123. **
  132124. ** This is what we do if the grammar does define ERROR:
  132125. **
  132126. ** * Call the %syntax_error function.
  132127. **
  132128. ** * Begin popping the stack until we enter a state where
  132129. ** it is legal to shift the error symbol, then shift
  132130. ** the error symbol.
  132131. **
  132132. ** * Set the error count to three.
  132133. **
  132134. ** * Begin accepting and shifting new tokens. No new error
  132135. ** processing will occur until three tokens have been
  132136. ** shifted successfully.
  132137. **
  132138. */
  132139. if( yypParser->yyerrcnt<0 ){
  132140. yy_syntax_error(yypParser,yymajor,yyminor);
  132141. }
  132142. yymx = yypParser->yytos->major;
  132143. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  132144. #ifndef NDEBUG
  132145. if( yyTraceFILE ){
  132146. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  132147. yyTracePrompt,yyTokenName[yymajor]);
  132148. }
  132149. #endif
  132150. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  132151. yymajor = YYNOCODE;
  132152. }else{
  132153. while( yypParser->yytos >= yypParser->yystack
  132154. && yymx != YYERRORSYMBOL
  132155. && (yyact = yy_find_reduce_action(
  132156. yypParser->yytos->stateno,
  132157. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  132158. ){
  132159. yy_pop_parser_stack(yypParser);
  132160. }
  132161. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  132162. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  132163. yy_parse_failed(yypParser);
  132164. #ifndef YYNOERRORRECOVERY
  132165. yypParser->yyerrcnt = -1;
  132166. #endif
  132167. yymajor = YYNOCODE;
  132168. }else if( yymx!=YYERRORSYMBOL ){
  132169. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  132170. }
  132171. }
  132172. yypParser->yyerrcnt = 3;
  132173. yyerrorhit = 1;
  132174. #elif defined(YYNOERRORRECOVERY)
  132175. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  132176. ** do any kind of error recovery. Instead, simply invoke the syntax
  132177. ** error routine and continue going as if nothing had happened.
  132178. **
  132179. ** Applications can set this macro (for example inside %include) if
  132180. ** they intend to abandon the parse upon the first syntax error seen.
  132181. */
  132182. yy_syntax_error(yypParser,yymajor, yyminor);
  132183. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  132184. yymajor = YYNOCODE;
  132185. #else /* YYERRORSYMBOL is not defined */
  132186. /* This is what we do if the grammar does not define ERROR:
  132187. **
  132188. ** * Report an error message, and throw away the input token.
  132189. **
  132190. ** * If the input token is $, then fail the parse.
  132191. **
  132192. ** As before, subsequent error messages are suppressed until
  132193. ** three input tokens have been successfully shifted.
  132194. */
  132195. if( yypParser->yyerrcnt<=0 ){
  132196. yy_syntax_error(yypParser,yymajor, yyminor);
  132197. }
  132198. yypParser->yyerrcnt = 3;
  132199. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  132200. if( yyendofinput ){
  132201. yy_parse_failed(yypParser);
  132202. #ifndef YYNOERRORRECOVERY
  132203. yypParser->yyerrcnt = -1;
  132204. #endif
  132205. }
  132206. yymajor = YYNOCODE;
  132207. #endif
  132208. }
  132209. }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
  132210. #ifndef NDEBUG
  132211. if( yyTraceFILE ){
  132212. yyStackEntry *i;
  132213. char cDiv = '[';
  132214. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  132215. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  132216. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  132217. cDiv = ' ';
  132218. }
  132219. fprintf(yyTraceFILE,"]\n");
  132220. }
  132221. #endif
  132222. return;
  132223. }
  132224. /************** End of parse.c ***********************************************/
  132225. /************** Begin file tokenize.c ****************************************/
  132226. /*
  132227. ** 2001 September 15
  132228. **
  132229. ** The author disclaims copyright to this source code. In place of
  132230. ** a legal notice, here is a blessing:
  132231. **
  132232. ** May you do good and not evil.
  132233. ** May you find forgiveness for yourself and forgive others.
  132234. ** May you share freely, never taking more than you give.
  132235. **
  132236. *************************************************************************
  132237. ** An tokenizer for SQL
  132238. **
  132239. ** This file contains C code that splits an SQL input string up into
  132240. ** individual tokens and sends those tokens one-by-one over to the
  132241. ** parser for analysis.
  132242. */
  132243. /* #include "sqliteInt.h" */
  132244. /* #include <stdlib.h> */
  132245. /* Character classes for tokenizing
  132246. **
  132247. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  132248. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  132249. ** The lookup table is much faster. To maximize speed, and to ensure that
  132250. ** a lookup table is used, all of the classes need to be small integers and
  132251. ** all of them need to be used within the switch.
  132252. */
  132253. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  132254. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  132255. #define CC_ID 2 /* unicode characters usable in IDs */
  132256. #define CC_DIGIT 3 /* Digits */
  132257. #define CC_DOLLAR 4 /* '$' */
  132258. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  132259. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  132260. #define CC_SPACE 7 /* Space characters */
  132261. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  132262. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  132263. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  132264. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  132265. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  132266. #define CC_GT 13 /* '>'. Part of > or >= */
  132267. #define CC_EQ 14 /* '='. Part of = or == */
  132268. #define CC_BANG 15 /* '!'. Part of != */
  132269. #define CC_SLASH 16 /* '/'. / or c-style comment */
  132270. #define CC_LP 17 /* '(' */
  132271. #define CC_RP 18 /* ')' */
  132272. #define CC_SEMI 19 /* ';' */
  132273. #define CC_PLUS 20 /* '+' */
  132274. #define CC_STAR 21 /* '*' */
  132275. #define CC_PERCENT 22 /* '%' */
  132276. #define CC_COMMA 23 /* ',' */
  132277. #define CC_AND 24 /* '&' */
  132278. #define CC_TILDA 25 /* '~' */
  132279. #define CC_DOT 26 /* '.' */
  132280. #define CC_ILLEGAL 27 /* Illegal character */
  132281. static const unsigned char aiClass[] = {
  132282. #ifdef SQLITE_ASCII
  132283. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  132284. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  132285. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  132286. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  132287. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  132288. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  132289. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  132290. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  132291. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  132292. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132293. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132294. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132295. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132296. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132297. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132298. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  132299. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  132300. #endif
  132301. #ifdef SQLITE_EBCDIC
  132302. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  132303. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  132304. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  132305. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  132306. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  132307. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  132308. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  132309. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  132310. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  132311. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  132312. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  132313. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  132314. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  132315. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  132316. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  132317. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  132318. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  132319. #endif
  132320. };
  132321. /*
  132322. ** The charMap() macro maps alphabetic characters (only) into their
  132323. ** lower-case ASCII equivalent. On ASCII machines, this is just
  132324. ** an upper-to-lower case map. On EBCDIC machines we also need
  132325. ** to adjust the encoding. The mapping is only valid for alphabetics
  132326. ** which are the only characters for which this feature is used.
  132327. **
  132328. ** Used by keywordhash.h
  132329. */
  132330. #ifdef SQLITE_ASCII
  132331. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  132332. #endif
  132333. #ifdef SQLITE_EBCDIC
  132334. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  132335. const unsigned char ebcdicToAscii[] = {
  132336. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  132345. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  132346. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  132347. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  132349. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  132350. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  132351. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  132352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  132353. };
  132354. #endif
  132355. /*
  132356. ** The sqlite3KeywordCode function looks up an identifier to determine if
  132357. ** it is a keyword. If it is a keyword, the token code of that keyword is
  132358. ** returned. If the input is not a keyword, TK_ID is returned.
  132359. **
  132360. ** The implementation of this routine was generated by a program,
  132361. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  132362. ** The output of the mkkeywordhash.c program is written into a file
  132363. ** named keywordhash.h and then included into this source file by
  132364. ** the #include below.
  132365. */
  132366. /************** Include keywordhash.h in the middle of tokenize.c ************/
  132367. /************** Begin file keywordhash.h *************************************/
  132368. /***** This file contains automatically generated code ******
  132369. **
  132370. ** The code in this file has been automatically generated by
  132371. **
  132372. ** sqlite/tool/mkkeywordhash.c
  132373. **
  132374. ** The code in this file implements a function that determines whether
  132375. ** or not a given identifier is really an SQL keyword. The same thing
  132376. ** might be implemented more directly using a hand-written hash table.
  132377. ** But by using this automatically generated code, the size of the code
  132378. ** is substantially reduced. This is important for embedded applications
  132379. ** on platforms with limited memory.
  132380. */
  132381. /* Hash score: 182 */
  132382. /* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
  132383. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  132384. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  132385. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  132386. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  132387. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  132388. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  132389. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  132390. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  132391. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  132392. /* VACUUMVIEWINITIALLY */
  132393. static const char zKWText[553] = {
  132394. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  132395. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  132396. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  132397. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  132398. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  132399. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  132400. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  132401. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  132402. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  132403. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  132404. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  132405. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  132406. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  132407. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  132408. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  132409. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  132410. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  132411. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  132412. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  132413. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  132414. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  132415. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  132416. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  132417. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  132418. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  132419. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  132420. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  132421. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  132422. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  132423. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  132424. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  132425. };
  132426. /* aKWHash[i] is the hash value for the i-th keyword */
  132427. static const unsigned char aKWHash[127] = {
  132428. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  132429. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  132430. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  132431. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  132432. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  132433. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  132434. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  132435. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  132436. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  132437. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  132438. };
  132439. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  132440. ** then the i-th keyword has no more hash collisions. Otherwise,
  132441. ** the next keyword with the same hash is aKWHash[i]-1. */
  132442. static const unsigned char aKWNext[124] = {
  132443. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  132445. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  132447. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  132448. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  132449. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  132450. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  132451. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  132452. 73, 83, 0, 35, 68, 0, 0,
  132453. };
  132454. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  132455. static const unsigned char aKWLen[124] = {
  132456. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  132457. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  132458. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  132459. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  132460. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  132461. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  132462. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  132463. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  132464. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  132465. 3, 5, 5, 6, 4, 9, 3,
  132466. };
  132467. /* aKWOffset[i] is the index into zKWText[] of the start of
  132468. ** the text for the i-th keyword. */
  132469. static const unsigned short int aKWOffset[124] = {
  132470. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  132471. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  132472. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  132473. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  132474. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  132475. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  132476. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  132477. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  132478. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  132479. 521, 524, 529, 534, 540, 544, 549,
  132480. };
  132481. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  132482. static const unsigned char aKWCode[124] = {
  132483. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  132484. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  132485. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  132486. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  132487. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  132488. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  132489. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  132490. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  132491. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  132492. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  132493. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  132494. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  132495. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  132496. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  132497. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  132498. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  132499. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  132500. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  132501. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  132502. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  132503. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  132504. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  132505. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  132506. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  132507. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  132508. };
  132509. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  132510. ** parser symbol code for that keyword into *pType. Always
  132511. ** return the integer n (the length of the token). */
  132512. static int keywordCode(const char *z, int n, int *pType){
  132513. int i, j;
  132514. const char *zKW;
  132515. if( n>=2 ){
  132516. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  132517. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  132518. if( aKWLen[i]!=n ) continue;
  132519. j = 0;
  132520. zKW = &zKWText[aKWOffset[i]];
  132521. #ifdef SQLITE_ASCII
  132522. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  132523. #endif
  132524. #ifdef SQLITE_EBCDIC
  132525. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  132526. #endif
  132527. if( j<n ) continue;
  132528. testcase( i==0 ); /* REINDEX */
  132529. testcase( i==1 ); /* INDEXED */
  132530. testcase( i==2 ); /* INDEX */
  132531. testcase( i==3 ); /* DESC */
  132532. testcase( i==4 ); /* ESCAPE */
  132533. testcase( i==5 ); /* EACH */
  132534. testcase( i==6 ); /* CHECK */
  132535. testcase( i==7 ); /* KEY */
  132536. testcase( i==8 ); /* BEFORE */
  132537. testcase( i==9 ); /* FOREIGN */
  132538. testcase( i==10 ); /* FOR */
  132539. testcase( i==11 ); /* IGNORE */
  132540. testcase( i==12 ); /* REGEXP */
  132541. testcase( i==13 ); /* EXPLAIN */
  132542. testcase( i==14 ); /* INSTEAD */
  132543. testcase( i==15 ); /* ADD */
  132544. testcase( i==16 ); /* DATABASE */
  132545. testcase( i==17 ); /* AS */
  132546. testcase( i==18 ); /* SELECT */
  132547. testcase( i==19 ); /* TABLE */
  132548. testcase( i==20 ); /* LEFT */
  132549. testcase( i==21 ); /* THEN */
  132550. testcase( i==22 ); /* END */
  132551. testcase( i==23 ); /* DEFERRABLE */
  132552. testcase( i==24 ); /* ELSE */
  132553. testcase( i==25 ); /* EXCEPT */
  132554. testcase( i==26 ); /* TRANSACTION */
  132555. testcase( i==27 ); /* ACTION */
  132556. testcase( i==28 ); /* ON */
  132557. testcase( i==29 ); /* NATURAL */
  132558. testcase( i==30 ); /* ALTER */
  132559. testcase( i==31 ); /* RAISE */
  132560. testcase( i==32 ); /* EXCLUSIVE */
  132561. testcase( i==33 ); /* EXISTS */
  132562. testcase( i==34 ); /* SAVEPOINT */
  132563. testcase( i==35 ); /* INTERSECT */
  132564. testcase( i==36 ); /* TRIGGER */
  132565. testcase( i==37 ); /* REFERENCES */
  132566. testcase( i==38 ); /* CONSTRAINT */
  132567. testcase( i==39 ); /* INTO */
  132568. testcase( i==40 ); /* OFFSET */
  132569. testcase( i==41 ); /* OF */
  132570. testcase( i==42 ); /* SET */
  132571. testcase( i==43 ); /* TEMPORARY */
  132572. testcase( i==44 ); /* TEMP */
  132573. testcase( i==45 ); /* OR */
  132574. testcase( i==46 ); /* UNIQUE */
  132575. testcase( i==47 ); /* QUERY */
  132576. testcase( i==48 ); /* WITHOUT */
  132577. testcase( i==49 ); /* WITH */
  132578. testcase( i==50 ); /* OUTER */
  132579. testcase( i==51 ); /* RELEASE */
  132580. testcase( i==52 ); /* ATTACH */
  132581. testcase( i==53 ); /* HAVING */
  132582. testcase( i==54 ); /* GROUP */
  132583. testcase( i==55 ); /* UPDATE */
  132584. testcase( i==56 ); /* BEGIN */
  132585. testcase( i==57 ); /* INNER */
  132586. testcase( i==58 ); /* RECURSIVE */
  132587. testcase( i==59 ); /* BETWEEN */
  132588. testcase( i==60 ); /* NOTNULL */
  132589. testcase( i==61 ); /* NOT */
  132590. testcase( i==62 ); /* NO */
  132591. testcase( i==63 ); /* NULL */
  132592. testcase( i==64 ); /* LIKE */
  132593. testcase( i==65 ); /* CASCADE */
  132594. testcase( i==66 ); /* ASC */
  132595. testcase( i==67 ); /* DELETE */
  132596. testcase( i==68 ); /* CASE */
  132597. testcase( i==69 ); /* COLLATE */
  132598. testcase( i==70 ); /* CREATE */
  132599. testcase( i==71 ); /* CURRENT_DATE */
  132600. testcase( i==72 ); /* DETACH */
  132601. testcase( i==73 ); /* IMMEDIATE */
  132602. testcase( i==74 ); /* JOIN */
  132603. testcase( i==75 ); /* INSERT */
  132604. testcase( i==76 ); /* MATCH */
  132605. testcase( i==77 ); /* PLAN */
  132606. testcase( i==78 ); /* ANALYZE */
  132607. testcase( i==79 ); /* PRAGMA */
  132608. testcase( i==80 ); /* ABORT */
  132609. testcase( i==81 ); /* VALUES */
  132610. testcase( i==82 ); /* VIRTUAL */
  132611. testcase( i==83 ); /* LIMIT */
  132612. testcase( i==84 ); /* WHEN */
  132613. testcase( i==85 ); /* WHERE */
  132614. testcase( i==86 ); /* RENAME */
  132615. testcase( i==87 ); /* AFTER */
  132616. testcase( i==88 ); /* REPLACE */
  132617. testcase( i==89 ); /* AND */
  132618. testcase( i==90 ); /* DEFAULT */
  132619. testcase( i==91 ); /* AUTOINCREMENT */
  132620. testcase( i==92 ); /* TO */
  132621. testcase( i==93 ); /* IN */
  132622. testcase( i==94 ); /* CAST */
  132623. testcase( i==95 ); /* COLUMN */
  132624. testcase( i==96 ); /* COMMIT */
  132625. testcase( i==97 ); /* CONFLICT */
  132626. testcase( i==98 ); /* CROSS */
  132627. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  132628. testcase( i==100 ); /* CURRENT_TIME */
  132629. testcase( i==101 ); /* PRIMARY */
  132630. testcase( i==102 ); /* DEFERRED */
  132631. testcase( i==103 ); /* DISTINCT */
  132632. testcase( i==104 ); /* IS */
  132633. testcase( i==105 ); /* DROP */
  132634. testcase( i==106 ); /* FAIL */
  132635. testcase( i==107 ); /* FROM */
  132636. testcase( i==108 ); /* FULL */
  132637. testcase( i==109 ); /* GLOB */
  132638. testcase( i==110 ); /* BY */
  132639. testcase( i==111 ); /* IF */
  132640. testcase( i==112 ); /* ISNULL */
  132641. testcase( i==113 ); /* ORDER */
  132642. testcase( i==114 ); /* RESTRICT */
  132643. testcase( i==115 ); /* RIGHT */
  132644. testcase( i==116 ); /* ROLLBACK */
  132645. testcase( i==117 ); /* ROW */
  132646. testcase( i==118 ); /* UNION */
  132647. testcase( i==119 ); /* USING */
  132648. testcase( i==120 ); /* VACUUM */
  132649. testcase( i==121 ); /* VIEW */
  132650. testcase( i==122 ); /* INITIALLY */
  132651. testcase( i==123 ); /* ALL */
  132652. *pType = aKWCode[i];
  132653. break;
  132654. }
  132655. }
  132656. return n;
  132657. }
  132658. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  132659. int id = TK_ID;
  132660. keywordCode((char*)z, n, &id);
  132661. return id;
  132662. }
  132663. #define SQLITE_N_KEYWORD 124
  132664. /************** End of keywordhash.h *****************************************/
  132665. /************** Continuing where we left off in tokenize.c *******************/
  132666. /*
  132667. ** If X is a character that can be used in an identifier then
  132668. ** IdChar(X) will be true. Otherwise it is false.
  132669. **
  132670. ** For ASCII, any character with the high-order bit set is
  132671. ** allowed in an identifier. For 7-bit characters,
  132672. ** sqlite3IsIdChar[X] must be 1.
  132673. **
  132674. ** For EBCDIC, the rules are more complex but have the same
  132675. ** end result.
  132676. **
  132677. ** Ticket #1066. the SQL standard does not allow '$' in the
  132678. ** middle of identifiers. But many SQL implementations do.
  132679. ** SQLite will allow '$' in identifiers for compatibility.
  132680. ** But the feature is undocumented.
  132681. */
  132682. #ifdef SQLITE_ASCII
  132683. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  132684. #endif
  132685. #ifdef SQLITE_EBCDIC
  132686. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  132687. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  132688. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  132689. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  132690. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  132691. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  132692. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  132693. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  132694. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  132696. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  132697. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  132698. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  132699. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  132700. };
  132701. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  132702. #endif
  132703. /* Make the IdChar function accessible from ctime.c */
  132704. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  132705. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  132706. #endif
  132707. /*
  132708. ** Return the length (in bytes) of the token that begins at z[0].
  132709. ** Store the token type in *tokenType before returning.
  132710. */
  132711. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  132712. int i, c;
  132713. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  132714. ** of the token. See the comment on the CC_ defines
  132715. ** above. */
  132716. case CC_SPACE: {
  132717. testcase( z[0]==' ' );
  132718. testcase( z[0]=='\t' );
  132719. testcase( z[0]=='\n' );
  132720. testcase( z[0]=='\f' );
  132721. testcase( z[0]=='\r' );
  132722. for(i=1; sqlite3Isspace(z[i]); i++){}
  132723. *tokenType = TK_SPACE;
  132724. return i;
  132725. }
  132726. case CC_MINUS: {
  132727. if( z[1]=='-' ){
  132728. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  132729. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  132730. return i;
  132731. }
  132732. *tokenType = TK_MINUS;
  132733. return 1;
  132734. }
  132735. case CC_LP: {
  132736. *tokenType = TK_LP;
  132737. return 1;
  132738. }
  132739. case CC_RP: {
  132740. *tokenType = TK_RP;
  132741. return 1;
  132742. }
  132743. case CC_SEMI: {
  132744. *tokenType = TK_SEMI;
  132745. return 1;
  132746. }
  132747. case CC_PLUS: {
  132748. *tokenType = TK_PLUS;
  132749. return 1;
  132750. }
  132751. case CC_STAR: {
  132752. *tokenType = TK_STAR;
  132753. return 1;
  132754. }
  132755. case CC_SLASH: {
  132756. if( z[1]!='*' || z[2]==0 ){
  132757. *tokenType = TK_SLASH;
  132758. return 1;
  132759. }
  132760. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  132761. if( c ) i++;
  132762. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  132763. return i;
  132764. }
  132765. case CC_PERCENT: {
  132766. *tokenType = TK_REM;
  132767. return 1;
  132768. }
  132769. case CC_EQ: {
  132770. *tokenType = TK_EQ;
  132771. return 1 + (z[1]=='=');
  132772. }
  132773. case CC_LT: {
  132774. if( (c=z[1])=='=' ){
  132775. *tokenType = TK_LE;
  132776. return 2;
  132777. }else if( c=='>' ){
  132778. *tokenType = TK_NE;
  132779. return 2;
  132780. }else if( c=='<' ){
  132781. *tokenType = TK_LSHIFT;
  132782. return 2;
  132783. }else{
  132784. *tokenType = TK_LT;
  132785. return 1;
  132786. }
  132787. }
  132788. case CC_GT: {
  132789. if( (c=z[1])=='=' ){
  132790. *tokenType = TK_GE;
  132791. return 2;
  132792. }else if( c=='>' ){
  132793. *tokenType = TK_RSHIFT;
  132794. return 2;
  132795. }else{
  132796. *tokenType = TK_GT;
  132797. return 1;
  132798. }
  132799. }
  132800. case CC_BANG: {
  132801. if( z[1]!='=' ){
  132802. *tokenType = TK_ILLEGAL;
  132803. return 1;
  132804. }else{
  132805. *tokenType = TK_NE;
  132806. return 2;
  132807. }
  132808. }
  132809. case CC_PIPE: {
  132810. if( z[1]!='|' ){
  132811. *tokenType = TK_BITOR;
  132812. return 1;
  132813. }else{
  132814. *tokenType = TK_CONCAT;
  132815. return 2;
  132816. }
  132817. }
  132818. case CC_COMMA: {
  132819. *tokenType = TK_COMMA;
  132820. return 1;
  132821. }
  132822. case CC_AND: {
  132823. *tokenType = TK_BITAND;
  132824. return 1;
  132825. }
  132826. case CC_TILDA: {
  132827. *tokenType = TK_BITNOT;
  132828. return 1;
  132829. }
  132830. case CC_QUOTE: {
  132831. int delim = z[0];
  132832. testcase( delim=='`' );
  132833. testcase( delim=='\'' );
  132834. testcase( delim=='"' );
  132835. for(i=1; (c=z[i])!=0; i++){
  132836. if( c==delim ){
  132837. if( z[i+1]==delim ){
  132838. i++;
  132839. }else{
  132840. break;
  132841. }
  132842. }
  132843. }
  132844. if( c=='\'' ){
  132845. *tokenType = TK_STRING;
  132846. return i+1;
  132847. }else if( c!=0 ){
  132848. *tokenType = TK_ID;
  132849. return i+1;
  132850. }else{
  132851. *tokenType = TK_ILLEGAL;
  132852. return i;
  132853. }
  132854. }
  132855. case CC_DOT: {
  132856. #ifndef SQLITE_OMIT_FLOATING_POINT
  132857. if( !sqlite3Isdigit(z[1]) )
  132858. #endif
  132859. {
  132860. *tokenType = TK_DOT;
  132861. return 1;
  132862. }
  132863. /* If the next character is a digit, this is a floating point
  132864. ** number that begins with ".". Fall thru into the next case */
  132865. }
  132866. case CC_DIGIT: {
  132867. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  132868. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  132869. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  132870. testcase( z[0]=='9' );
  132871. *tokenType = TK_INTEGER;
  132872. #ifndef SQLITE_OMIT_HEX_INTEGER
  132873. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  132874. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  132875. return i;
  132876. }
  132877. #endif
  132878. for(i=0; sqlite3Isdigit(z[i]); i++){}
  132879. #ifndef SQLITE_OMIT_FLOATING_POINT
  132880. if( z[i]=='.' ){
  132881. i++;
  132882. while( sqlite3Isdigit(z[i]) ){ i++; }
  132883. *tokenType = TK_FLOAT;
  132884. }
  132885. if( (z[i]=='e' || z[i]=='E') &&
  132886. ( sqlite3Isdigit(z[i+1])
  132887. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  132888. )
  132889. ){
  132890. i += 2;
  132891. while( sqlite3Isdigit(z[i]) ){ i++; }
  132892. *tokenType = TK_FLOAT;
  132893. }
  132894. #endif
  132895. while( IdChar(z[i]) ){
  132896. *tokenType = TK_ILLEGAL;
  132897. i++;
  132898. }
  132899. return i;
  132900. }
  132901. case CC_QUOTE2: {
  132902. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  132903. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  132904. return i;
  132905. }
  132906. case CC_VARNUM: {
  132907. *tokenType = TK_VARIABLE;
  132908. for(i=1; sqlite3Isdigit(z[i]); i++){}
  132909. return i;
  132910. }
  132911. case CC_DOLLAR:
  132912. case CC_VARALPHA: {
  132913. int n = 0;
  132914. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  132915. testcase( z[0]==':' ); testcase( z[0]=='#' );
  132916. *tokenType = TK_VARIABLE;
  132917. for(i=1; (c=z[i])!=0; i++){
  132918. if( IdChar(c) ){
  132919. n++;
  132920. #ifndef SQLITE_OMIT_TCL_VARIABLE
  132921. }else if( c=='(' && n>0 ){
  132922. do{
  132923. i++;
  132924. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  132925. if( c==')' ){
  132926. i++;
  132927. }else{
  132928. *tokenType = TK_ILLEGAL;
  132929. }
  132930. break;
  132931. }else if( c==':' && z[i+1]==':' ){
  132932. i++;
  132933. #endif
  132934. }else{
  132935. break;
  132936. }
  132937. }
  132938. if( n==0 ) *tokenType = TK_ILLEGAL;
  132939. return i;
  132940. }
  132941. case CC_KYWD: {
  132942. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  132943. if( IdChar(z[i]) ){
  132944. /* This token started out using characters that can appear in keywords,
  132945. ** but z[i] is a character not allowed within keywords, so this must
  132946. ** be an identifier instead */
  132947. i++;
  132948. break;
  132949. }
  132950. *tokenType = TK_ID;
  132951. return keywordCode((char*)z, i, tokenType);
  132952. }
  132953. case CC_X: {
  132954. #ifndef SQLITE_OMIT_BLOB_LITERAL
  132955. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  132956. if( z[1]=='\'' ){
  132957. *tokenType = TK_BLOB;
  132958. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  132959. if( z[i]!='\'' || i%2 ){
  132960. *tokenType = TK_ILLEGAL;
  132961. while( z[i] && z[i]!='\'' ){ i++; }
  132962. }
  132963. if( z[i] ) i++;
  132964. return i;
  132965. }
  132966. #endif
  132967. /* If it is not a BLOB literal, then it must be an ID, since no
  132968. ** SQL keywords start with the letter 'x'. Fall through */
  132969. }
  132970. case CC_ID: {
  132971. i = 1;
  132972. break;
  132973. }
  132974. default: {
  132975. *tokenType = TK_ILLEGAL;
  132976. return 1;
  132977. }
  132978. }
  132979. while( IdChar(z[i]) ){ i++; }
  132980. *tokenType = TK_ID;
  132981. return i;
  132982. }
  132983. /*
  132984. ** Run the parser on the given SQL string. The parser structure is
  132985. ** passed in. An SQLITE_ status code is returned. If an error occurs
  132986. ** then an and attempt is made to write an error message into
  132987. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  132988. ** error message.
  132989. */
  132990. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  132991. int nErr = 0; /* Number of errors encountered */
  132992. void *pEngine; /* The LEMON-generated LALR(1) parser */
  132993. int n = 0; /* Length of the next token token */
  132994. int tokenType; /* type of the next token */
  132995. int lastTokenParsed = -1; /* type of the previous token */
  132996. sqlite3 *db = pParse->db; /* The database connection */
  132997. int mxSqlLen; /* Max length of an SQL string */
  132998. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  132999. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  133000. #endif
  133001. assert( zSql!=0 );
  133002. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  133003. if( db->nVdbeActive==0 ){
  133004. db->u1.isInterrupted = 0;
  133005. }
  133006. pParse->rc = SQLITE_OK;
  133007. pParse->zTail = zSql;
  133008. assert( pzErrMsg!=0 );
  133009. /* sqlite3ParserTrace(stdout, "parser: "); */
  133010. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  133011. pEngine = &sEngine;
  133012. sqlite3ParserInit(pEngine);
  133013. #else
  133014. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  133015. if( pEngine==0 ){
  133016. sqlite3OomFault(db);
  133017. return SQLITE_NOMEM_BKPT;
  133018. }
  133019. #endif
  133020. assert( pParse->pNewTable==0 );
  133021. assert( pParse->pNewTrigger==0 );
  133022. assert( pParse->nVar==0 );
  133023. assert( pParse->pVList==0 );
  133024. while( 1 ){
  133025. if( zSql[0]!=0 ){
  133026. n = sqlite3GetToken((u8*)zSql, &tokenType);
  133027. mxSqlLen -= n;
  133028. if( mxSqlLen<0 ){
  133029. pParse->rc = SQLITE_TOOBIG;
  133030. break;
  133031. }
  133032. }else{
  133033. /* Upon reaching the end of input, call the parser two more times
  133034. ** with tokens TK_SEMI and 0, in that order. */
  133035. if( lastTokenParsed==TK_SEMI ){
  133036. tokenType = 0;
  133037. }else if( lastTokenParsed==0 ){
  133038. break;
  133039. }else{
  133040. tokenType = TK_SEMI;
  133041. }
  133042. zSql -= n;
  133043. }
  133044. if( tokenType>=TK_SPACE ){
  133045. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  133046. if( db->u1.isInterrupted ){
  133047. pParse->rc = SQLITE_INTERRUPT;
  133048. break;
  133049. }
  133050. if( tokenType==TK_ILLEGAL ){
  133051. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  133052. break;
  133053. }
  133054. zSql += n;
  133055. }else{
  133056. pParse->sLastToken.z = zSql;
  133057. pParse->sLastToken.n = n;
  133058. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  133059. lastTokenParsed = tokenType;
  133060. zSql += n;
  133061. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  133062. }
  133063. }
  133064. assert( nErr==0 );
  133065. pParse->zTail = zSql;
  133066. #ifdef YYTRACKMAXSTACKDEPTH
  133067. sqlite3_mutex_enter(sqlite3MallocMutex());
  133068. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  133069. sqlite3ParserStackPeak(pEngine)
  133070. );
  133071. sqlite3_mutex_leave(sqlite3MallocMutex());
  133072. #endif /* YYDEBUG */
  133073. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  133074. sqlite3ParserFinalize(pEngine);
  133075. #else
  133076. sqlite3ParserFree(pEngine, sqlite3_free);
  133077. #endif
  133078. if( db->mallocFailed ){
  133079. pParse->rc = SQLITE_NOMEM_BKPT;
  133080. }
  133081. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  133082. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  133083. }
  133084. assert( pzErrMsg!=0 );
  133085. if( pParse->zErrMsg ){
  133086. *pzErrMsg = pParse->zErrMsg;
  133087. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  133088. pParse->zErrMsg = 0;
  133089. nErr++;
  133090. }
  133091. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  133092. sqlite3VdbeDelete(pParse->pVdbe);
  133093. pParse->pVdbe = 0;
  133094. }
  133095. #ifndef SQLITE_OMIT_SHARED_CACHE
  133096. if( pParse->nested==0 ){
  133097. sqlite3DbFree(db, pParse->aTableLock);
  133098. pParse->aTableLock = 0;
  133099. pParse->nTableLock = 0;
  133100. }
  133101. #endif
  133102. #ifndef SQLITE_OMIT_VIRTUALTABLE
  133103. sqlite3_free(pParse->apVtabLock);
  133104. #endif
  133105. if( !IN_DECLARE_VTAB ){
  133106. /* If the pParse->declareVtab flag is set, do not delete any table
  133107. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  133108. ** will take responsibility for freeing the Table structure.
  133109. */
  133110. sqlite3DeleteTable(db, pParse->pNewTable);
  133111. }
  133112. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  133113. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  133114. sqlite3DbFree(db, pParse->pVList);
  133115. while( pParse->pAinc ){
  133116. AutoincInfo *p = pParse->pAinc;
  133117. pParse->pAinc = p->pNext;
  133118. sqlite3DbFreeNN(db, p);
  133119. }
  133120. while( pParse->pZombieTab ){
  133121. Table *p = pParse->pZombieTab;
  133122. pParse->pZombieTab = p->pNextZombie;
  133123. sqlite3DeleteTable(db, p);
  133124. }
  133125. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  133126. return nErr;
  133127. }
  133128. /************** End of tokenize.c ********************************************/
  133129. /************** Begin file complete.c ****************************************/
  133130. /*
  133131. ** 2001 September 15
  133132. **
  133133. ** The author disclaims copyright to this source code. In place of
  133134. ** a legal notice, here is a blessing:
  133135. **
  133136. ** May you do good and not evil.
  133137. ** May you find forgiveness for yourself and forgive others.
  133138. ** May you share freely, never taking more than you give.
  133139. **
  133140. *************************************************************************
  133141. ** An tokenizer for SQL
  133142. **
  133143. ** This file contains C code that implements the sqlite3_complete() API.
  133144. ** This code used to be part of the tokenizer.c source file. But by
  133145. ** separating it out, the code will be automatically omitted from
  133146. ** static links that do not use it.
  133147. */
  133148. /* #include "sqliteInt.h" */
  133149. #ifndef SQLITE_OMIT_COMPLETE
  133150. /*
  133151. ** This is defined in tokenize.c. We just have to import the definition.
  133152. */
  133153. #ifndef SQLITE_AMALGAMATION
  133154. #ifdef SQLITE_ASCII
  133155. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  133156. #endif
  133157. #ifdef SQLITE_EBCDIC
  133158. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  133159. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  133160. #endif
  133161. #endif /* SQLITE_AMALGAMATION */
  133162. /*
  133163. ** Token types used by the sqlite3_complete() routine. See the header
  133164. ** comments on that procedure for additional information.
  133165. */
  133166. #define tkSEMI 0
  133167. #define tkWS 1
  133168. #define tkOTHER 2
  133169. #ifndef SQLITE_OMIT_TRIGGER
  133170. #define tkEXPLAIN 3
  133171. #define tkCREATE 4
  133172. #define tkTEMP 5
  133173. #define tkTRIGGER 6
  133174. #define tkEND 7
  133175. #endif
  133176. /*
  133177. ** Return TRUE if the given SQL string ends in a semicolon.
  133178. **
  133179. ** Special handling is require for CREATE TRIGGER statements.
  133180. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  133181. ** must end with ";END;".
  133182. **
  133183. ** This implementation uses a state machine with 8 states:
  133184. **
  133185. ** (0) INVALID We have not yet seen a non-whitespace character.
  133186. **
  133187. ** (1) START At the beginning or end of an SQL statement. This routine
  133188. ** returns 1 if it ends in the START state and 0 if it ends
  133189. ** in any other state.
  133190. **
  133191. ** (2) NORMAL We are in the middle of statement which ends with a single
  133192. ** semicolon.
  133193. **
  133194. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  133195. ** a statement.
  133196. **
  133197. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  133198. ** statement, possibly preceded by EXPLAIN and/or followed by
  133199. ** TEMP or TEMPORARY
  133200. **
  133201. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  133202. ** ended by a semicolon, the keyword END, and another semicolon.
  133203. **
  133204. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  133205. ** the end of a trigger definition.
  133206. **
  133207. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  133208. ** of a trigger definition.
  133209. **
  133210. ** Transitions between states above are determined by tokens extracted
  133211. ** from the input. The following tokens are significant:
  133212. **
  133213. ** (0) tkSEMI A semicolon.
  133214. ** (1) tkWS Whitespace.
  133215. ** (2) tkOTHER Any other SQL token.
  133216. ** (3) tkEXPLAIN The "explain" keyword.
  133217. ** (4) tkCREATE The "create" keyword.
  133218. ** (5) tkTEMP The "temp" or "temporary" keyword.
  133219. ** (6) tkTRIGGER The "trigger" keyword.
  133220. ** (7) tkEND The "end" keyword.
  133221. **
  133222. ** Whitespace never causes a state transition and is always ignored.
  133223. ** This means that a SQL string of all whitespace is invalid.
  133224. **
  133225. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  133226. ** to recognize the end of a trigger can be omitted. All we have to do
  133227. ** is look for a semicolon that is not part of an string or comment.
  133228. */
  133229. SQLITE_API int sqlite3_complete(const char *zSql){
  133230. u8 state = 0; /* Current state, using numbers defined in header comment */
  133231. u8 token; /* Value of the next token */
  133232. #ifndef SQLITE_OMIT_TRIGGER
  133233. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  133234. ** statement. This is the normal case.
  133235. */
  133236. static const u8 trans[8][8] = {
  133237. /* Token: */
  133238. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  133239. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  133240. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  133241. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  133242. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  133243. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  133244. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  133245. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  133246. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  133247. };
  133248. #else
  133249. /* If triggers are not supported by this compile then the statement machine
  133250. ** used to detect the end of a statement is much simpler
  133251. */
  133252. static const u8 trans[3][3] = {
  133253. /* Token: */
  133254. /* State: ** SEMI WS OTHER */
  133255. /* 0 INVALID: */ { 1, 0, 2, },
  133256. /* 1 START: */ { 1, 1, 2, },
  133257. /* 2 NORMAL: */ { 1, 2, 2, },
  133258. };
  133259. #endif /* SQLITE_OMIT_TRIGGER */
  133260. #ifdef SQLITE_ENABLE_API_ARMOR
  133261. if( zSql==0 ){
  133262. (void)SQLITE_MISUSE_BKPT;
  133263. return 0;
  133264. }
  133265. #endif
  133266. while( *zSql ){
  133267. switch( *zSql ){
  133268. case ';': { /* A semicolon */
  133269. token = tkSEMI;
  133270. break;
  133271. }
  133272. case ' ':
  133273. case '\r':
  133274. case '\t':
  133275. case '\n':
  133276. case '\f': { /* White space is ignored */
  133277. token = tkWS;
  133278. break;
  133279. }
  133280. case '/': { /* C-style comments */
  133281. if( zSql[1]!='*' ){
  133282. token = tkOTHER;
  133283. break;
  133284. }
  133285. zSql += 2;
  133286. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  133287. if( zSql[0]==0 ) return 0;
  133288. zSql++;
  133289. token = tkWS;
  133290. break;
  133291. }
  133292. case '-': { /* SQL-style comments from "--" to end of line */
  133293. if( zSql[1]!='-' ){
  133294. token = tkOTHER;
  133295. break;
  133296. }
  133297. while( *zSql && *zSql!='\n' ){ zSql++; }
  133298. if( *zSql==0 ) return state==1;
  133299. token = tkWS;
  133300. break;
  133301. }
  133302. case '[': { /* Microsoft-style identifiers in [...] */
  133303. zSql++;
  133304. while( *zSql && *zSql!=']' ){ zSql++; }
  133305. if( *zSql==0 ) return 0;
  133306. token = tkOTHER;
  133307. break;
  133308. }
  133309. case '`': /* Grave-accent quoted symbols used by MySQL */
  133310. case '"': /* single- and double-quoted strings */
  133311. case '\'': {
  133312. int c = *zSql;
  133313. zSql++;
  133314. while( *zSql && *zSql!=c ){ zSql++; }
  133315. if( *zSql==0 ) return 0;
  133316. token = tkOTHER;
  133317. break;
  133318. }
  133319. default: {
  133320. #ifdef SQLITE_EBCDIC
  133321. unsigned char c;
  133322. #endif
  133323. if( IdChar((u8)*zSql) ){
  133324. /* Keywords and unquoted identifiers */
  133325. int nId;
  133326. for(nId=1; IdChar(zSql[nId]); nId++){}
  133327. #ifdef SQLITE_OMIT_TRIGGER
  133328. token = tkOTHER;
  133329. #else
  133330. switch( *zSql ){
  133331. case 'c': case 'C': {
  133332. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  133333. token = tkCREATE;
  133334. }else{
  133335. token = tkOTHER;
  133336. }
  133337. break;
  133338. }
  133339. case 't': case 'T': {
  133340. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  133341. token = tkTRIGGER;
  133342. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  133343. token = tkTEMP;
  133344. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  133345. token = tkTEMP;
  133346. }else{
  133347. token = tkOTHER;
  133348. }
  133349. break;
  133350. }
  133351. case 'e': case 'E': {
  133352. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  133353. token = tkEND;
  133354. }else
  133355. #ifndef SQLITE_OMIT_EXPLAIN
  133356. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  133357. token = tkEXPLAIN;
  133358. }else
  133359. #endif
  133360. {
  133361. token = tkOTHER;
  133362. }
  133363. break;
  133364. }
  133365. default: {
  133366. token = tkOTHER;
  133367. break;
  133368. }
  133369. }
  133370. #endif /* SQLITE_OMIT_TRIGGER */
  133371. zSql += nId-1;
  133372. }else{
  133373. /* Operators and special symbols */
  133374. token = tkOTHER;
  133375. }
  133376. break;
  133377. }
  133378. }
  133379. state = trans[state][token];
  133380. zSql++;
  133381. }
  133382. return state==1;
  133383. }
  133384. #ifndef SQLITE_OMIT_UTF16
  133385. /*
  133386. ** This routine is the same as the sqlite3_complete() routine described
  133387. ** above, except that the parameter is required to be UTF-16 encoded, not
  133388. ** UTF-8.
  133389. */
  133390. SQLITE_API int sqlite3_complete16(const void *zSql){
  133391. sqlite3_value *pVal;
  133392. char const *zSql8;
  133393. int rc;
  133394. #ifndef SQLITE_OMIT_AUTOINIT
  133395. rc = sqlite3_initialize();
  133396. if( rc ) return rc;
  133397. #endif
  133398. pVal = sqlite3ValueNew(0);
  133399. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  133400. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  133401. if( zSql8 ){
  133402. rc = sqlite3_complete(zSql8);
  133403. }else{
  133404. rc = SQLITE_NOMEM_BKPT;
  133405. }
  133406. sqlite3ValueFree(pVal);
  133407. return rc & 0xff;
  133408. }
  133409. #endif /* SQLITE_OMIT_UTF16 */
  133410. #endif /* SQLITE_OMIT_COMPLETE */
  133411. /************** End of complete.c ********************************************/
  133412. /************** Begin file main.c ********************************************/
  133413. /*
  133414. ** 2001 September 15
  133415. **
  133416. ** The author disclaims copyright to this source code. In place of
  133417. ** a legal notice, here is a blessing:
  133418. **
  133419. ** May you do good and not evil.
  133420. ** May you find forgiveness for yourself and forgive others.
  133421. ** May you share freely, never taking more than you give.
  133422. **
  133423. *************************************************************************
  133424. ** Main file for the SQLite library. The routines in this file
  133425. ** implement the programmer interface to the library. Routines in
  133426. ** other files are for internal use by SQLite and should not be
  133427. ** accessed by users of the library.
  133428. */
  133429. /* #include "sqliteInt.h" */
  133430. #ifdef SQLITE_ENABLE_FTS3
  133431. /************** Include fts3.h in the middle of main.c ***********************/
  133432. /************** Begin file fts3.h ********************************************/
  133433. /*
  133434. ** 2006 Oct 10
  133435. **
  133436. ** The author disclaims copyright to this source code. In place of
  133437. ** a legal notice, here is a blessing:
  133438. **
  133439. ** May you do good and not evil.
  133440. ** May you find forgiveness for yourself and forgive others.
  133441. ** May you share freely, never taking more than you give.
  133442. **
  133443. ******************************************************************************
  133444. **
  133445. ** This header file is used by programs that want to link against the
  133446. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  133447. */
  133448. /* #include "sqlite3.h" */
  133449. #if 0
  133450. extern "C" {
  133451. #endif /* __cplusplus */
  133452. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  133453. #if 0
  133454. } /* extern "C" */
  133455. #endif /* __cplusplus */
  133456. /************** End of fts3.h ************************************************/
  133457. /************** Continuing where we left off in main.c ***********************/
  133458. #endif
  133459. #ifdef SQLITE_ENABLE_RTREE
  133460. /************** Include rtree.h in the middle of main.c **********************/
  133461. /************** Begin file rtree.h *******************************************/
  133462. /*
  133463. ** 2008 May 26
  133464. **
  133465. ** The author disclaims copyright to this source code. In place of
  133466. ** a legal notice, here is a blessing:
  133467. **
  133468. ** May you do good and not evil.
  133469. ** May you find forgiveness for yourself and forgive others.
  133470. ** May you share freely, never taking more than you give.
  133471. **
  133472. ******************************************************************************
  133473. **
  133474. ** This header file is used by programs that want to link against the
  133475. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  133476. */
  133477. /* #include "sqlite3.h" */
  133478. #if 0
  133479. extern "C" {
  133480. #endif /* __cplusplus */
  133481. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  133482. #if 0
  133483. } /* extern "C" */
  133484. #endif /* __cplusplus */
  133485. /************** End of rtree.h ***********************************************/
  133486. /************** Continuing where we left off in main.c ***********************/
  133487. #endif
  133488. #ifdef SQLITE_ENABLE_ICU
  133489. /************** Include sqliteicu.h in the middle of main.c ******************/
  133490. /************** Begin file sqliteicu.h ***************************************/
  133491. /*
  133492. ** 2008 May 26
  133493. **
  133494. ** The author disclaims copyright to this source code. In place of
  133495. ** a legal notice, here is a blessing:
  133496. **
  133497. ** May you do good and not evil.
  133498. ** May you find forgiveness for yourself and forgive others.
  133499. ** May you share freely, never taking more than you give.
  133500. **
  133501. ******************************************************************************
  133502. **
  133503. ** This header file is used by programs that want to link against the
  133504. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  133505. */
  133506. /* #include "sqlite3.h" */
  133507. #if 0
  133508. extern "C" {
  133509. #endif /* __cplusplus */
  133510. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  133511. #if 0
  133512. } /* extern "C" */
  133513. #endif /* __cplusplus */
  133514. /************** End of sqliteicu.h *******************************************/
  133515. /************** Continuing where we left off in main.c ***********************/
  133516. #endif
  133517. #ifdef SQLITE_ENABLE_JSON1
  133518. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  133519. #endif
  133520. #ifdef SQLITE_ENABLE_STMTVTAB
  133521. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  133522. #endif
  133523. #ifdef SQLITE_ENABLE_FTS5
  133524. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  133525. #endif
  133526. #ifndef SQLITE_AMALGAMATION
  133527. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  133528. ** contains the text of SQLITE_VERSION macro.
  133529. */
  133530. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  133531. #endif
  133532. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  133533. ** a pointer to the to the sqlite3_version[] string constant.
  133534. */
  133535. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  133536. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  133537. ** pointer to a string constant whose value is the same as the
  133538. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  133539. ** an edited copy of the amalgamation, then the last four characters of
  133540. ** the hash might be different from SQLITE_SOURCE_ID.
  133541. */
  133542. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  133543. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  133544. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  133545. */
  133546. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  133547. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  133548. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  133549. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  133550. */
  133551. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  133552. /*
  133553. ** When compiling the test fixture or with debugging enabled (on Win32),
  133554. ** this variable being set to non-zero will cause OSTRACE macros to emit
  133555. ** extra diagnostic information.
  133556. */
  133557. #ifdef SQLITE_HAVE_OS_TRACE
  133558. # ifndef SQLITE_DEBUG_OS_TRACE
  133559. # define SQLITE_DEBUG_OS_TRACE 0
  133560. # endif
  133561. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  133562. #endif
  133563. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  133564. /*
  133565. ** If the following function pointer is not NULL and if
  133566. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  133567. ** I/O active are written using this function. These messages
  133568. ** are intended for debugging activity only.
  133569. */
  133570. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  133571. #endif
  133572. /*
  133573. ** If the following global variable points to a string which is the
  133574. ** name of a directory, then that directory will be used to store
  133575. ** temporary files.
  133576. **
  133577. ** See also the "PRAGMA temp_store_directory" SQL command.
  133578. */
  133579. SQLITE_API char *sqlite3_temp_directory = 0;
  133580. /*
  133581. ** If the following global variable points to a string which is the
  133582. ** name of a directory, then that directory will be used to store
  133583. ** all database files specified with a relative pathname.
  133584. **
  133585. ** See also the "PRAGMA data_store_directory" SQL command.
  133586. */
  133587. SQLITE_API char *sqlite3_data_directory = 0;
  133588. /*
  133589. ** Initialize SQLite.
  133590. **
  133591. ** This routine must be called to initialize the memory allocation,
  133592. ** VFS, and mutex subsystems prior to doing any serious work with
  133593. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  133594. ** this routine will be called automatically by key routines such as
  133595. ** sqlite3_open().
  133596. **
  133597. ** This routine is a no-op except on its very first call for the process,
  133598. ** or for the first call after a call to sqlite3_shutdown.
  133599. **
  133600. ** The first thread to call this routine runs the initialization to
  133601. ** completion. If subsequent threads call this routine before the first
  133602. ** thread has finished the initialization process, then the subsequent
  133603. ** threads must block until the first thread finishes with the initialization.
  133604. **
  133605. ** The first thread might call this routine recursively. Recursive
  133606. ** calls to this routine should not block, of course. Otherwise the
  133607. ** initialization process would never complete.
  133608. **
  133609. ** Let X be the first thread to enter this routine. Let Y be some other
  133610. ** thread. Then while the initial invocation of this routine by X is
  133611. ** incomplete, it is required that:
  133612. **
  133613. ** * Calls to this routine from Y must block until the outer-most
  133614. ** call by X completes.
  133615. **
  133616. ** * Recursive calls to this routine from thread X return immediately
  133617. ** without blocking.
  133618. */
  133619. SQLITE_API int sqlite3_initialize(void){
  133620. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  133621. int rc; /* Result code */
  133622. #ifdef SQLITE_EXTRA_INIT
  133623. int bRunExtraInit = 0; /* Extra initialization needed */
  133624. #endif
  133625. #ifdef SQLITE_OMIT_WSD
  133626. rc = sqlite3_wsd_init(4096, 24);
  133627. if( rc!=SQLITE_OK ){
  133628. return rc;
  133629. }
  133630. #endif
  133631. /* If the following assert() fails on some obscure processor/compiler
  133632. ** combination, the work-around is to set the correct pointer
  133633. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  133634. assert( SQLITE_PTRSIZE==sizeof(char*) );
  133635. /* If SQLite is already completely initialized, then this call
  133636. ** to sqlite3_initialize() should be a no-op. But the initialization
  133637. ** must be complete. So isInit must not be set until the very end
  133638. ** of this routine.
  133639. */
  133640. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  133641. /* Make sure the mutex subsystem is initialized. If unable to
  133642. ** initialize the mutex subsystem, return early with the error.
  133643. ** If the system is so sick that we are unable to allocate a mutex,
  133644. ** there is not much SQLite is going to be able to do.
  133645. **
  133646. ** The mutex subsystem must take care of serializing its own
  133647. ** initialization.
  133648. */
  133649. rc = sqlite3MutexInit();
  133650. if( rc ) return rc;
  133651. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  133652. ** This operation is protected by the STATIC_MASTER mutex. Note that
  133653. ** MutexAlloc() is called for a static mutex prior to initializing the
  133654. ** malloc subsystem - this implies that the allocation of a static
  133655. ** mutex must not require support from the malloc subsystem.
  133656. */
  133657. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  133658. sqlite3_mutex_enter(pMaster);
  133659. sqlite3GlobalConfig.isMutexInit = 1;
  133660. if( !sqlite3GlobalConfig.isMallocInit ){
  133661. rc = sqlite3MallocInit();
  133662. }
  133663. if( rc==SQLITE_OK ){
  133664. sqlite3GlobalConfig.isMallocInit = 1;
  133665. if( !sqlite3GlobalConfig.pInitMutex ){
  133666. sqlite3GlobalConfig.pInitMutex =
  133667. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  133668. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  133669. rc = SQLITE_NOMEM_BKPT;
  133670. }
  133671. }
  133672. }
  133673. if( rc==SQLITE_OK ){
  133674. sqlite3GlobalConfig.nRefInitMutex++;
  133675. }
  133676. sqlite3_mutex_leave(pMaster);
  133677. /* If rc is not SQLITE_OK at this point, then either the malloc
  133678. ** subsystem could not be initialized or the system failed to allocate
  133679. ** the pInitMutex mutex. Return an error in either case. */
  133680. if( rc!=SQLITE_OK ){
  133681. return rc;
  133682. }
  133683. /* Do the rest of the initialization under the recursive mutex so
  133684. ** that we will be able to handle recursive calls into
  133685. ** sqlite3_initialize(). The recursive calls normally come through
  133686. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  133687. ** recursive calls might also be possible.
  133688. **
  133689. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  133690. ** to the xInit method, so the xInit method need not be threadsafe.
  133691. **
  133692. ** The following mutex is what serializes access to the appdef pcache xInit
  133693. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  133694. ** call to sqlite3PcacheInitialize().
  133695. */
  133696. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  133697. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  133698. sqlite3GlobalConfig.inProgress = 1;
  133699. #ifdef SQLITE_ENABLE_SQLLOG
  133700. {
  133701. extern void sqlite3_init_sqllog(void);
  133702. sqlite3_init_sqllog();
  133703. }
  133704. #endif
  133705. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  133706. sqlite3RegisterBuiltinFunctions();
  133707. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  133708. rc = sqlite3PcacheInitialize();
  133709. }
  133710. if( rc==SQLITE_OK ){
  133711. sqlite3GlobalConfig.isPCacheInit = 1;
  133712. rc = sqlite3OsInit();
  133713. }
  133714. if( rc==SQLITE_OK ){
  133715. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  133716. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  133717. sqlite3GlobalConfig.isInit = 1;
  133718. #ifdef SQLITE_EXTRA_INIT
  133719. bRunExtraInit = 1;
  133720. #endif
  133721. }
  133722. sqlite3GlobalConfig.inProgress = 0;
  133723. }
  133724. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  133725. /* Go back under the static mutex and clean up the recursive
  133726. ** mutex to prevent a resource leak.
  133727. */
  133728. sqlite3_mutex_enter(pMaster);
  133729. sqlite3GlobalConfig.nRefInitMutex--;
  133730. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  133731. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  133732. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  133733. sqlite3GlobalConfig.pInitMutex = 0;
  133734. }
  133735. sqlite3_mutex_leave(pMaster);
  133736. /* The following is just a sanity check to make sure SQLite has
  133737. ** been compiled correctly. It is important to run this code, but
  133738. ** we don't want to run it too often and soak up CPU cycles for no
  133739. ** reason. So we run it once during initialization.
  133740. */
  133741. #ifndef NDEBUG
  133742. #ifndef SQLITE_OMIT_FLOATING_POINT
  133743. /* This section of code's only "output" is via assert() statements. */
  133744. if ( rc==SQLITE_OK ){
  133745. u64 x = (((u64)1)<<63)-1;
  133746. double y;
  133747. assert(sizeof(x)==8);
  133748. assert(sizeof(x)==sizeof(y));
  133749. memcpy(&y, &x, 8);
  133750. assert( sqlite3IsNaN(y) );
  133751. }
  133752. #endif
  133753. #endif
  133754. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  133755. ** compile-time option.
  133756. */
  133757. #ifdef SQLITE_EXTRA_INIT
  133758. if( bRunExtraInit ){
  133759. int SQLITE_EXTRA_INIT(const char*);
  133760. rc = SQLITE_EXTRA_INIT(0);
  133761. }
  133762. #endif
  133763. return rc;
  133764. }
  133765. /*
  133766. ** Undo the effects of sqlite3_initialize(). Must not be called while
  133767. ** there are outstanding database connections or memory allocations or
  133768. ** while any part of SQLite is otherwise in use in any thread. This
  133769. ** routine is not threadsafe. But it is safe to invoke this routine
  133770. ** on when SQLite is already shut down. If SQLite is already shut down
  133771. ** when this routine is invoked, then this routine is a harmless no-op.
  133772. */
  133773. SQLITE_API int sqlite3_shutdown(void){
  133774. #ifdef SQLITE_OMIT_WSD
  133775. int rc = sqlite3_wsd_init(4096, 24);
  133776. if( rc!=SQLITE_OK ){
  133777. return rc;
  133778. }
  133779. #endif
  133780. if( sqlite3GlobalConfig.isInit ){
  133781. #ifdef SQLITE_EXTRA_SHUTDOWN
  133782. void SQLITE_EXTRA_SHUTDOWN(void);
  133783. SQLITE_EXTRA_SHUTDOWN();
  133784. #endif
  133785. sqlite3_os_end();
  133786. sqlite3_reset_auto_extension();
  133787. sqlite3GlobalConfig.isInit = 0;
  133788. }
  133789. if( sqlite3GlobalConfig.isPCacheInit ){
  133790. sqlite3PcacheShutdown();
  133791. sqlite3GlobalConfig.isPCacheInit = 0;
  133792. }
  133793. if( sqlite3GlobalConfig.isMallocInit ){
  133794. sqlite3MallocEnd();
  133795. sqlite3GlobalConfig.isMallocInit = 0;
  133796. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  133797. /* The heap subsystem has now been shutdown and these values are supposed
  133798. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  133799. ** which would rely on that heap subsystem; therefore, make sure these
  133800. ** values cannot refer to heap memory that was just invalidated when the
  133801. ** heap subsystem was shutdown. This is only done if the current call to
  133802. ** this function resulted in the heap subsystem actually being shutdown.
  133803. */
  133804. sqlite3_data_directory = 0;
  133805. sqlite3_temp_directory = 0;
  133806. #endif
  133807. }
  133808. if( sqlite3GlobalConfig.isMutexInit ){
  133809. sqlite3MutexEnd();
  133810. sqlite3GlobalConfig.isMutexInit = 0;
  133811. }
  133812. return SQLITE_OK;
  133813. }
  133814. /*
  133815. ** This API allows applications to modify the global configuration of
  133816. ** the SQLite library at run-time.
  133817. **
  133818. ** This routine should only be called when there are no outstanding
  133819. ** database connections or memory allocations. This routine is not
  133820. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  133821. ** behavior.
  133822. */
  133823. SQLITE_API int sqlite3_config(int op, ...){
  133824. va_list ap;
  133825. int rc = SQLITE_OK;
  133826. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  133827. ** the SQLite library is in use. */
  133828. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  133829. va_start(ap, op);
  133830. switch( op ){
  133831. /* Mutex configuration options are only available in a threadsafe
  133832. ** compile.
  133833. */
  133834. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  133835. case SQLITE_CONFIG_SINGLETHREAD: {
  133836. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  133837. ** Single-thread. */
  133838. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  133839. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  133840. break;
  133841. }
  133842. #endif
  133843. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  133844. case SQLITE_CONFIG_MULTITHREAD: {
  133845. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  133846. ** Multi-thread. */
  133847. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  133848. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  133849. break;
  133850. }
  133851. #endif
  133852. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  133853. case SQLITE_CONFIG_SERIALIZED: {
  133854. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  133855. ** Serialized. */
  133856. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  133857. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  133858. break;
  133859. }
  133860. #endif
  133861. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  133862. case SQLITE_CONFIG_MUTEX: {
  133863. /* Specify an alternative mutex implementation */
  133864. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  133865. break;
  133866. }
  133867. #endif
  133868. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  133869. case SQLITE_CONFIG_GETMUTEX: {
  133870. /* Retrieve the current mutex implementation */
  133871. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  133872. break;
  133873. }
  133874. #endif
  133875. case SQLITE_CONFIG_MALLOC: {
  133876. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  133877. ** single argument which is a pointer to an instance of the
  133878. ** sqlite3_mem_methods structure. The argument specifies alternative
  133879. ** low-level memory allocation routines to be used in place of the memory
  133880. ** allocation routines built into SQLite. */
  133881. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  133882. break;
  133883. }
  133884. case SQLITE_CONFIG_GETMALLOC: {
  133885. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  133886. ** single argument which is a pointer to an instance of the
  133887. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  133888. ** filled with the currently defined memory allocation routines. */
  133889. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  133890. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  133891. break;
  133892. }
  133893. case SQLITE_CONFIG_MEMSTATUS: {
  133894. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  133895. ** single argument of type int, interpreted as a boolean, which enables
  133896. ** or disables the collection of memory allocation statistics. */
  133897. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  133898. break;
  133899. }
  133900. case SQLITE_CONFIG_SMALL_MALLOC: {
  133901. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  133902. break;
  133903. }
  133904. case SQLITE_CONFIG_PAGECACHE: {
  133905. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  133906. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  133907. ** the size of each page cache line (sz), and the number of cache lines
  133908. ** (N). */
  133909. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  133910. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  133911. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  133912. break;
  133913. }
  133914. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  133915. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  133916. ** a single parameter which is a pointer to an integer and writes into
  133917. ** that integer the number of extra bytes per page required for each page
  133918. ** in SQLITE_CONFIG_PAGECACHE. */
  133919. *va_arg(ap, int*) =
  133920. sqlite3HeaderSizeBtree() +
  133921. sqlite3HeaderSizePcache() +
  133922. sqlite3HeaderSizePcache1();
  133923. break;
  133924. }
  133925. case SQLITE_CONFIG_PCACHE: {
  133926. /* no-op */
  133927. break;
  133928. }
  133929. case SQLITE_CONFIG_GETPCACHE: {
  133930. /* now an error */
  133931. rc = SQLITE_ERROR;
  133932. break;
  133933. }
  133934. case SQLITE_CONFIG_PCACHE2: {
  133935. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  133936. ** single argument which is a pointer to an sqlite3_pcache_methods2
  133937. ** object. This object specifies the interface to a custom page cache
  133938. ** implementation. */
  133939. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  133940. break;
  133941. }
  133942. case SQLITE_CONFIG_GETPCACHE2: {
  133943. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  133944. ** single argument which is a pointer to an sqlite3_pcache_methods2
  133945. ** object. SQLite copies of the current page cache implementation into
  133946. ** that object. */
  133947. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  133948. sqlite3PCacheSetDefault();
  133949. }
  133950. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  133951. break;
  133952. }
  133953. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  133954. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  133955. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  133956. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  133957. case SQLITE_CONFIG_HEAP: {
  133958. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  133959. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  133960. ** number of bytes in the memory buffer, and the minimum allocation size.
  133961. */
  133962. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  133963. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  133964. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  133965. if( sqlite3GlobalConfig.mnReq<1 ){
  133966. sqlite3GlobalConfig.mnReq = 1;
  133967. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  133968. /* cap min request size at 2^12 */
  133969. sqlite3GlobalConfig.mnReq = (1<<12);
  133970. }
  133971. if( sqlite3GlobalConfig.pHeap==0 ){
  133972. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  133973. ** is NULL, then SQLite reverts to using its default memory allocator
  133974. ** (the system malloc() implementation), undoing any prior invocation of
  133975. ** SQLITE_CONFIG_MALLOC.
  133976. **
  133977. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  133978. ** revert to its default implementation when sqlite3_initialize() is run
  133979. */
  133980. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  133981. }else{
  133982. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  133983. ** alternative memory allocator is engaged to handle all of SQLites
  133984. ** memory allocation needs. */
  133985. #ifdef SQLITE_ENABLE_MEMSYS3
  133986. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  133987. #endif
  133988. #ifdef SQLITE_ENABLE_MEMSYS5
  133989. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  133990. #endif
  133991. }
  133992. break;
  133993. }
  133994. #endif
  133995. case SQLITE_CONFIG_LOOKASIDE: {
  133996. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  133997. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  133998. break;
  133999. }
  134000. /* Record a pointer to the logger function and its first argument.
  134001. ** The default is NULL. Logging is disabled if the function pointer is
  134002. ** NULL.
  134003. */
  134004. case SQLITE_CONFIG_LOG: {
  134005. /* MSVC is picky about pulling func ptrs from va lists.
  134006. ** http://support.microsoft.com/kb/47961
  134007. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  134008. */
  134009. typedef void(*LOGFUNC_t)(void*,int,const char*);
  134010. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  134011. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  134012. break;
  134013. }
  134014. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  134015. ** can be changed at start-time using the
  134016. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  134017. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  134018. */
  134019. case SQLITE_CONFIG_URI: {
  134020. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  134021. ** argument of type int. If non-zero, then URI handling is globally
  134022. ** enabled. If the parameter is zero, then URI handling is globally
  134023. ** disabled. */
  134024. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  134025. break;
  134026. }
  134027. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  134028. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  134029. ** option takes a single integer argument which is interpreted as a
  134030. ** boolean in order to enable or disable the use of covering indices for
  134031. ** full table scans in the query optimizer. */
  134032. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  134033. break;
  134034. }
  134035. #ifdef SQLITE_ENABLE_SQLLOG
  134036. case SQLITE_CONFIG_SQLLOG: {
  134037. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  134038. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  134039. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  134040. break;
  134041. }
  134042. #endif
  134043. case SQLITE_CONFIG_MMAP_SIZE: {
  134044. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  134045. ** integer (sqlite3_int64) values that are the default mmap size limit
  134046. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  134047. ** mmap size limit. */
  134048. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  134049. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  134050. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  134051. ** negative, then that argument is changed to its compile-time default.
  134052. **
  134053. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  134054. ** silently truncated if necessary so that it does not exceed the
  134055. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  134056. ** compile-time option.
  134057. */
  134058. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  134059. mxMmap = SQLITE_MAX_MMAP_SIZE;
  134060. }
  134061. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  134062. if( szMmap>mxMmap) szMmap = mxMmap;
  134063. sqlite3GlobalConfig.mxMmap = mxMmap;
  134064. sqlite3GlobalConfig.szMmap = szMmap;
  134065. break;
  134066. }
  134067. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  134068. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  134069. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  134070. ** unsigned integer value that specifies the maximum size of the created
  134071. ** heap. */
  134072. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  134073. break;
  134074. }
  134075. #endif
  134076. case SQLITE_CONFIG_PMASZ: {
  134077. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  134078. break;
  134079. }
  134080. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  134081. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  134082. break;
  134083. }
  134084. default: {
  134085. rc = SQLITE_ERROR;
  134086. break;
  134087. }
  134088. }
  134089. va_end(ap);
  134090. return rc;
  134091. }
  134092. /*
  134093. ** Set up the lookaside buffers for a database connection.
  134094. ** Return SQLITE_OK on success.
  134095. ** If lookaside is already active, return SQLITE_BUSY.
  134096. **
  134097. ** The sz parameter is the number of bytes in each lookaside slot.
  134098. ** The cnt parameter is the number of slots. If pStart is NULL the
  134099. ** space for the lookaside memory is obtained from sqlite3_malloc().
  134100. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  134101. ** the lookaside memory.
  134102. */
  134103. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  134104. #ifndef SQLITE_OMIT_LOOKASIDE
  134105. void *pStart;
  134106. if( sqlite3LookasideUsed(db,0)>0 ){
  134107. return SQLITE_BUSY;
  134108. }
  134109. /* Free any existing lookaside buffer for this handle before
  134110. ** allocating a new one so we don't have to have space for
  134111. ** both at the same time.
  134112. */
  134113. if( db->lookaside.bMalloced ){
  134114. sqlite3_free(db->lookaside.pStart);
  134115. }
  134116. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  134117. ** than a pointer to be useful.
  134118. */
  134119. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  134120. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  134121. if( cnt<0 ) cnt = 0;
  134122. if( sz==0 || cnt==0 ){
  134123. sz = 0;
  134124. pStart = 0;
  134125. }else if( pBuf==0 ){
  134126. sqlite3BeginBenignMalloc();
  134127. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  134128. sqlite3EndBenignMalloc();
  134129. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  134130. }else{
  134131. pStart = pBuf;
  134132. }
  134133. db->lookaside.pStart = pStart;
  134134. db->lookaside.pInit = 0;
  134135. db->lookaside.pFree = 0;
  134136. db->lookaside.sz = (u16)sz;
  134137. if( pStart ){
  134138. int i;
  134139. LookasideSlot *p;
  134140. assert( sz > (int)sizeof(LookasideSlot*) );
  134141. db->lookaside.nSlot = cnt;
  134142. p = (LookasideSlot*)pStart;
  134143. for(i=cnt-1; i>=0; i--){
  134144. p->pNext = db->lookaside.pInit;
  134145. db->lookaside.pInit = p;
  134146. p = (LookasideSlot*)&((u8*)p)[sz];
  134147. }
  134148. db->lookaside.pEnd = p;
  134149. db->lookaside.bDisable = 0;
  134150. db->lookaside.bMalloced = pBuf==0 ?1:0;
  134151. }else{
  134152. db->lookaside.pStart = db;
  134153. db->lookaside.pEnd = db;
  134154. db->lookaside.bDisable = 1;
  134155. db->lookaside.bMalloced = 0;
  134156. db->lookaside.nSlot = 0;
  134157. }
  134158. #endif /* SQLITE_OMIT_LOOKASIDE */
  134159. return SQLITE_OK;
  134160. }
  134161. /*
  134162. ** Return the mutex associated with a database connection.
  134163. */
  134164. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  134165. #ifdef SQLITE_ENABLE_API_ARMOR
  134166. if( !sqlite3SafetyCheckOk(db) ){
  134167. (void)SQLITE_MISUSE_BKPT;
  134168. return 0;
  134169. }
  134170. #endif
  134171. return db->mutex;
  134172. }
  134173. /*
  134174. ** Free up as much memory as we can from the given database
  134175. ** connection.
  134176. */
  134177. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  134178. int i;
  134179. #ifdef SQLITE_ENABLE_API_ARMOR
  134180. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  134181. #endif
  134182. sqlite3_mutex_enter(db->mutex);
  134183. sqlite3BtreeEnterAll(db);
  134184. for(i=0; i<db->nDb; i++){
  134185. Btree *pBt = db->aDb[i].pBt;
  134186. if( pBt ){
  134187. Pager *pPager = sqlite3BtreePager(pBt);
  134188. sqlite3PagerShrink(pPager);
  134189. }
  134190. }
  134191. sqlite3BtreeLeaveAll(db);
  134192. sqlite3_mutex_leave(db->mutex);
  134193. return SQLITE_OK;
  134194. }
  134195. /*
  134196. ** Flush any dirty pages in the pager-cache for any attached database
  134197. ** to disk.
  134198. */
  134199. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  134200. int i;
  134201. int rc = SQLITE_OK;
  134202. int bSeenBusy = 0;
  134203. #ifdef SQLITE_ENABLE_API_ARMOR
  134204. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  134205. #endif
  134206. sqlite3_mutex_enter(db->mutex);
  134207. sqlite3BtreeEnterAll(db);
  134208. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  134209. Btree *pBt = db->aDb[i].pBt;
  134210. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  134211. Pager *pPager = sqlite3BtreePager(pBt);
  134212. rc = sqlite3PagerFlush(pPager);
  134213. if( rc==SQLITE_BUSY ){
  134214. bSeenBusy = 1;
  134215. rc = SQLITE_OK;
  134216. }
  134217. }
  134218. }
  134219. sqlite3BtreeLeaveAll(db);
  134220. sqlite3_mutex_leave(db->mutex);
  134221. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  134222. }
  134223. /*
  134224. ** Configuration settings for an individual database connection
  134225. */
  134226. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  134227. va_list ap;
  134228. int rc;
  134229. va_start(ap, op);
  134230. switch( op ){
  134231. case SQLITE_DBCONFIG_MAINDBNAME: {
  134232. /* IMP: R-06824-28531 */
  134233. /* IMP: R-36257-52125 */
  134234. db->aDb[0].zDbSName = va_arg(ap,char*);
  134235. rc = SQLITE_OK;
  134236. break;
  134237. }
  134238. case SQLITE_DBCONFIG_LOOKASIDE: {
  134239. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  134240. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  134241. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  134242. rc = setupLookaside(db, pBuf, sz, cnt);
  134243. break;
  134244. }
  134245. default: {
  134246. static const struct {
  134247. int op; /* The opcode */
  134248. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  134249. } aFlagOp[] = {
  134250. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  134251. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  134252. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  134253. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  134254. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  134255. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  134256. };
  134257. unsigned int i;
  134258. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  134259. for(i=0; i<ArraySize(aFlagOp); i++){
  134260. if( aFlagOp[i].op==op ){
  134261. int onoff = va_arg(ap, int);
  134262. int *pRes = va_arg(ap, int*);
  134263. u32 oldFlags = db->flags;
  134264. if( onoff>0 ){
  134265. db->flags |= aFlagOp[i].mask;
  134266. }else if( onoff==0 ){
  134267. db->flags &= ~aFlagOp[i].mask;
  134268. }
  134269. if( oldFlags!=db->flags ){
  134270. sqlite3ExpirePreparedStatements(db);
  134271. }
  134272. if( pRes ){
  134273. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  134274. }
  134275. rc = SQLITE_OK;
  134276. break;
  134277. }
  134278. }
  134279. break;
  134280. }
  134281. }
  134282. va_end(ap);
  134283. return rc;
  134284. }
  134285. /*
  134286. ** Return true if the buffer z[0..n-1] contains all spaces.
  134287. */
  134288. static int allSpaces(const char *z, int n){
  134289. while( n>0 && z[n-1]==' ' ){ n--; }
  134290. return n==0;
  134291. }
  134292. /*
  134293. ** This is the default collating function named "BINARY" which is always
  134294. ** available.
  134295. **
  134296. ** If the padFlag argument is not NULL then space padding at the end
  134297. ** of strings is ignored. This implements the RTRIM collation.
  134298. */
  134299. static int binCollFunc(
  134300. void *padFlag,
  134301. int nKey1, const void *pKey1,
  134302. int nKey2, const void *pKey2
  134303. ){
  134304. int rc, n;
  134305. n = nKey1<nKey2 ? nKey1 : nKey2;
  134306. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  134307. ** strings byte by byte using the memcmp() function from the standard C
  134308. ** library. */
  134309. assert( pKey1 && pKey2 );
  134310. rc = memcmp(pKey1, pKey2, n);
  134311. if( rc==0 ){
  134312. if( padFlag
  134313. && allSpaces(((char*)pKey1)+n, nKey1-n)
  134314. && allSpaces(((char*)pKey2)+n, nKey2-n)
  134315. ){
  134316. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  134317. ** spaces at the end of either string do not change the result. In other
  134318. ** words, strings will compare equal to one another as long as they
  134319. ** differ only in the number of spaces at the end.
  134320. */
  134321. }else{
  134322. rc = nKey1 - nKey2;
  134323. }
  134324. }
  134325. return rc;
  134326. }
  134327. /*
  134328. ** Another built-in collating sequence: NOCASE.
  134329. **
  134330. ** This collating sequence is intended to be used for "case independent
  134331. ** comparison". SQLite's knowledge of upper and lower case equivalents
  134332. ** extends only to the 26 characters used in the English language.
  134333. **
  134334. ** At the moment there is only a UTF-8 implementation.
  134335. */
  134336. static int nocaseCollatingFunc(
  134337. void *NotUsed,
  134338. int nKey1, const void *pKey1,
  134339. int nKey2, const void *pKey2
  134340. ){
  134341. int r = sqlite3StrNICmp(
  134342. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  134343. UNUSED_PARAMETER(NotUsed);
  134344. if( 0==r ){
  134345. r = nKey1-nKey2;
  134346. }
  134347. return r;
  134348. }
  134349. /*
  134350. ** Return the ROWID of the most recent insert
  134351. */
  134352. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  134353. #ifdef SQLITE_ENABLE_API_ARMOR
  134354. if( !sqlite3SafetyCheckOk(db) ){
  134355. (void)SQLITE_MISUSE_BKPT;
  134356. return 0;
  134357. }
  134358. #endif
  134359. return db->lastRowid;
  134360. }
  134361. /*
  134362. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  134363. */
  134364. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  134365. #ifdef SQLITE_ENABLE_API_ARMOR
  134366. if( !sqlite3SafetyCheckOk(db) ){
  134367. (void)SQLITE_MISUSE_BKPT;
  134368. return;
  134369. }
  134370. #endif
  134371. sqlite3_mutex_enter(db->mutex);
  134372. db->lastRowid = iRowid;
  134373. sqlite3_mutex_leave(db->mutex);
  134374. }
  134375. /*
  134376. ** Return the number of changes in the most recent call to sqlite3_exec().
  134377. */
  134378. SQLITE_API int sqlite3_changes(sqlite3 *db){
  134379. #ifdef SQLITE_ENABLE_API_ARMOR
  134380. if( !sqlite3SafetyCheckOk(db) ){
  134381. (void)SQLITE_MISUSE_BKPT;
  134382. return 0;
  134383. }
  134384. #endif
  134385. return db->nChange;
  134386. }
  134387. /*
  134388. ** Return the number of changes since the database handle was opened.
  134389. */
  134390. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  134391. #ifdef SQLITE_ENABLE_API_ARMOR
  134392. if( !sqlite3SafetyCheckOk(db) ){
  134393. (void)SQLITE_MISUSE_BKPT;
  134394. return 0;
  134395. }
  134396. #endif
  134397. return db->nTotalChange;
  134398. }
  134399. /*
  134400. ** Close all open savepoints. This function only manipulates fields of the
  134401. ** database handle object, it does not close any savepoints that may be open
  134402. ** at the b-tree/pager level.
  134403. */
  134404. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  134405. while( db->pSavepoint ){
  134406. Savepoint *pTmp = db->pSavepoint;
  134407. db->pSavepoint = pTmp->pNext;
  134408. sqlite3DbFree(db, pTmp);
  134409. }
  134410. db->nSavepoint = 0;
  134411. db->nStatement = 0;
  134412. db->isTransactionSavepoint = 0;
  134413. }
  134414. /*
  134415. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  134416. ** if this is not the last copy of the function, do not invoke it. Multiple
  134417. ** copies of a single function are created when create_function() is called
  134418. ** with SQLITE_ANY as the encoding.
  134419. */
  134420. static void functionDestroy(sqlite3 *db, FuncDef *p){
  134421. FuncDestructor *pDestructor = p->u.pDestructor;
  134422. if( pDestructor ){
  134423. pDestructor->nRef--;
  134424. if( pDestructor->nRef==0 ){
  134425. pDestructor->xDestroy(pDestructor->pUserData);
  134426. sqlite3DbFree(db, pDestructor);
  134427. }
  134428. }
  134429. }
  134430. /*
  134431. ** Disconnect all sqlite3_vtab objects that belong to database connection
  134432. ** db. This is called when db is being closed.
  134433. */
  134434. static void disconnectAllVtab(sqlite3 *db){
  134435. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134436. int i;
  134437. HashElem *p;
  134438. sqlite3BtreeEnterAll(db);
  134439. for(i=0; i<db->nDb; i++){
  134440. Schema *pSchema = db->aDb[i].pSchema;
  134441. if( db->aDb[i].pSchema ){
  134442. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  134443. Table *pTab = (Table *)sqliteHashData(p);
  134444. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  134445. }
  134446. }
  134447. }
  134448. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  134449. Module *pMod = (Module *)sqliteHashData(p);
  134450. if( pMod->pEpoTab ){
  134451. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  134452. }
  134453. }
  134454. sqlite3VtabUnlockList(db);
  134455. sqlite3BtreeLeaveAll(db);
  134456. #else
  134457. UNUSED_PARAMETER(db);
  134458. #endif
  134459. }
  134460. /*
  134461. ** Return TRUE if database connection db has unfinalized prepared
  134462. ** statements or unfinished sqlite3_backup objects.
  134463. */
  134464. static int connectionIsBusy(sqlite3 *db){
  134465. int j;
  134466. assert( sqlite3_mutex_held(db->mutex) );
  134467. if( db->pVdbe ) return 1;
  134468. for(j=0; j<db->nDb; j++){
  134469. Btree *pBt = db->aDb[j].pBt;
  134470. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  134471. }
  134472. return 0;
  134473. }
  134474. /*
  134475. ** Close an existing SQLite database
  134476. */
  134477. static int sqlite3Close(sqlite3 *db, int forceZombie){
  134478. if( !db ){
  134479. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  134480. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  134481. return SQLITE_OK;
  134482. }
  134483. if( !sqlite3SafetyCheckSickOrOk(db) ){
  134484. return SQLITE_MISUSE_BKPT;
  134485. }
  134486. sqlite3_mutex_enter(db->mutex);
  134487. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  134488. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  134489. }
  134490. /* Force xDisconnect calls on all virtual tables */
  134491. disconnectAllVtab(db);
  134492. /* If a transaction is open, the disconnectAllVtab() call above
  134493. ** will not have called the xDisconnect() method on any virtual
  134494. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  134495. ** call will do so. We need to do this before the check for active
  134496. ** SQL statements below, as the v-table implementation may be storing
  134497. ** some prepared statements internally.
  134498. */
  134499. sqlite3VtabRollback(db);
  134500. /* Legacy behavior (sqlite3_close() behavior) is to return
  134501. ** SQLITE_BUSY if the connection can not be closed immediately.
  134502. */
  134503. if( !forceZombie && connectionIsBusy(db) ){
  134504. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  134505. "statements or unfinished backups");
  134506. sqlite3_mutex_leave(db->mutex);
  134507. return SQLITE_BUSY;
  134508. }
  134509. #ifdef SQLITE_ENABLE_SQLLOG
  134510. if( sqlite3GlobalConfig.xSqllog ){
  134511. /* Closing the handle. Fourth parameter is passed the value 2. */
  134512. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  134513. }
  134514. #endif
  134515. /* Convert the connection into a zombie and then close it.
  134516. */
  134517. db->magic = SQLITE_MAGIC_ZOMBIE;
  134518. sqlite3LeaveMutexAndCloseZombie(db);
  134519. return SQLITE_OK;
  134520. }
  134521. /*
  134522. ** Two variations on the public interface for closing a database
  134523. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  134524. ** leaves the connection option if there are unfinalized prepared
  134525. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  134526. ** version forces the connection to become a zombie if there are
  134527. ** unclosed resources, and arranges for deallocation when the last
  134528. ** prepare statement or sqlite3_backup closes.
  134529. */
  134530. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  134531. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  134532. /*
  134533. ** Close the mutex on database connection db.
  134534. **
  134535. ** Furthermore, if database connection db is a zombie (meaning that there
  134536. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  134537. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  134538. ** finished, then free all resources.
  134539. */
  134540. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  134541. HashElem *i; /* Hash table iterator */
  134542. int j;
  134543. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  134544. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  134545. ** then just leave the mutex and return.
  134546. */
  134547. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  134548. sqlite3_mutex_leave(db->mutex);
  134549. return;
  134550. }
  134551. /* If we reach this point, it means that the database connection has
  134552. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  134553. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  134554. ** go ahead and free all resources.
  134555. */
  134556. /* If a transaction is open, roll it back. This also ensures that if
  134557. ** any database schemas have been modified by an uncommitted transaction
  134558. ** they are reset. And that the required b-tree mutex is held to make
  134559. ** the pager rollback and schema reset an atomic operation. */
  134560. sqlite3RollbackAll(db, SQLITE_OK);
  134561. /* Free any outstanding Savepoint structures. */
  134562. sqlite3CloseSavepoints(db);
  134563. /* Close all database connections */
  134564. for(j=0; j<db->nDb; j++){
  134565. struct Db *pDb = &db->aDb[j];
  134566. if( pDb->pBt ){
  134567. sqlite3BtreeClose(pDb->pBt);
  134568. pDb->pBt = 0;
  134569. if( j!=1 ){
  134570. pDb->pSchema = 0;
  134571. }
  134572. }
  134573. }
  134574. /* Clear the TEMP schema separately and last */
  134575. if( db->aDb[1].pSchema ){
  134576. sqlite3SchemaClear(db->aDb[1].pSchema);
  134577. }
  134578. sqlite3VtabUnlockList(db);
  134579. /* Free up the array of auxiliary databases */
  134580. sqlite3CollapseDatabaseArray(db);
  134581. assert( db->nDb<=2 );
  134582. assert( db->aDb==db->aDbStatic );
  134583. /* Tell the code in notify.c that the connection no longer holds any
  134584. ** locks and does not require any further unlock-notify callbacks.
  134585. */
  134586. sqlite3ConnectionClosed(db);
  134587. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  134588. FuncDef *pNext, *p;
  134589. p = sqliteHashData(i);
  134590. do{
  134591. functionDestroy(db, p);
  134592. pNext = p->pNext;
  134593. sqlite3DbFree(db, p);
  134594. p = pNext;
  134595. }while( p );
  134596. }
  134597. sqlite3HashClear(&db->aFunc);
  134598. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  134599. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  134600. /* Invoke any destructors registered for collation sequence user data. */
  134601. for(j=0; j<3; j++){
  134602. if( pColl[j].xDel ){
  134603. pColl[j].xDel(pColl[j].pUser);
  134604. }
  134605. }
  134606. sqlite3DbFree(db, pColl);
  134607. }
  134608. sqlite3HashClear(&db->aCollSeq);
  134609. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134610. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  134611. Module *pMod = (Module *)sqliteHashData(i);
  134612. if( pMod->xDestroy ){
  134613. pMod->xDestroy(pMod->pAux);
  134614. }
  134615. sqlite3VtabEponymousTableClear(db, pMod);
  134616. sqlite3DbFree(db, pMod);
  134617. }
  134618. sqlite3HashClear(&db->aModule);
  134619. #endif
  134620. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  134621. sqlite3ValueFree(db->pErr);
  134622. sqlite3CloseExtensions(db);
  134623. #if SQLITE_USER_AUTHENTICATION
  134624. sqlite3_free(db->auth.zAuthUser);
  134625. sqlite3_free(db->auth.zAuthPW);
  134626. #endif
  134627. db->magic = SQLITE_MAGIC_ERROR;
  134628. /* The temp-database schema is allocated differently from the other schema
  134629. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  134630. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  134631. ** the same sqliteMalloc() as the one that allocates the database
  134632. ** structure?
  134633. */
  134634. sqlite3DbFree(db, db->aDb[1].pSchema);
  134635. sqlite3_mutex_leave(db->mutex);
  134636. db->magic = SQLITE_MAGIC_CLOSED;
  134637. sqlite3_mutex_free(db->mutex);
  134638. assert( sqlite3LookasideUsed(db,0)==0 );
  134639. if( db->lookaside.bMalloced ){
  134640. sqlite3_free(db->lookaside.pStart);
  134641. }
  134642. sqlite3_free(db);
  134643. }
  134644. /*
  134645. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  134646. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  134647. ** breaker") and made to return tripCode if there are any further
  134648. ** attempts to use that cursor. Read cursors remain open and valid
  134649. ** but are "saved" in case the table pages are moved around.
  134650. */
  134651. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  134652. int i;
  134653. int inTrans = 0;
  134654. int schemaChange;
  134655. assert( sqlite3_mutex_held(db->mutex) );
  134656. sqlite3BeginBenignMalloc();
  134657. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  134658. ** This is important in case the transaction being rolled back has
  134659. ** modified the database schema. If the b-tree mutexes are not taken
  134660. ** here, then another shared-cache connection might sneak in between
  134661. ** the database rollback and schema reset, which can cause false
  134662. ** corruption reports in some cases. */
  134663. sqlite3BtreeEnterAll(db);
  134664. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  134665. for(i=0; i<db->nDb; i++){
  134666. Btree *p = db->aDb[i].pBt;
  134667. if( p ){
  134668. if( sqlite3BtreeIsInTrans(p) ){
  134669. inTrans = 1;
  134670. }
  134671. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  134672. }
  134673. }
  134674. sqlite3VtabRollback(db);
  134675. sqlite3EndBenignMalloc();
  134676. if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
  134677. sqlite3ExpirePreparedStatements(db);
  134678. sqlite3ResetAllSchemasOfConnection(db);
  134679. }
  134680. sqlite3BtreeLeaveAll(db);
  134681. /* Any deferred constraint violations have now been resolved. */
  134682. db->nDeferredCons = 0;
  134683. db->nDeferredImmCons = 0;
  134684. db->flags &= ~SQLITE_DeferFKs;
  134685. /* If one has been configured, invoke the rollback-hook callback */
  134686. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  134687. db->xRollbackCallback(db->pRollbackArg);
  134688. }
  134689. }
  134690. /*
  134691. ** Return a static string containing the name corresponding to the error code
  134692. ** specified in the argument.
  134693. */
  134694. #if defined(SQLITE_NEED_ERR_NAME)
  134695. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  134696. const char *zName = 0;
  134697. int i, origRc = rc;
  134698. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  134699. switch( rc ){
  134700. case SQLITE_OK: zName = "SQLITE_OK"; break;
  134701. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  134702. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  134703. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  134704. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  134705. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  134706. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  134707. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  134708. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  134709. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  134710. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  134711. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  134712. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  134713. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  134714. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  134715. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  134716. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  134717. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  134718. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  134719. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  134720. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  134721. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  134722. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  134723. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  134724. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  134725. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  134726. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  134727. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  134728. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  134729. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  134730. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  134731. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  134732. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  134733. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  134734. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  134735. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  134736. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  134737. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  134738. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  134739. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  134740. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  134741. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  134742. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  134743. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  134744. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  134745. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  134746. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  134747. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  134748. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  134749. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  134750. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  134751. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  134752. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  134753. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  134754. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  134755. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  134756. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  134757. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  134758. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  134759. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  134760. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  134761. case SQLITE_CONSTRAINT_FOREIGNKEY:
  134762. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  134763. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  134764. case SQLITE_CONSTRAINT_PRIMARYKEY:
  134765. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  134766. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  134767. case SQLITE_CONSTRAINT_COMMITHOOK:
  134768. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  134769. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  134770. case SQLITE_CONSTRAINT_FUNCTION:
  134771. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  134772. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  134773. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  134774. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  134775. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  134776. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  134777. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  134778. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  134779. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  134780. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  134781. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  134782. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  134783. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  134784. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  134785. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  134786. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  134787. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  134788. }
  134789. }
  134790. if( zName==0 ){
  134791. static char zBuf[50];
  134792. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  134793. zName = zBuf;
  134794. }
  134795. return zName;
  134796. }
  134797. #endif
  134798. /*
  134799. ** Return a static string that describes the kind of error specified in the
  134800. ** argument.
  134801. */
  134802. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  134803. static const char* const aMsg[] = {
  134804. /* SQLITE_OK */ "not an error",
  134805. /* SQLITE_ERROR */ "SQL logic error",
  134806. /* SQLITE_INTERNAL */ 0,
  134807. /* SQLITE_PERM */ "access permission denied",
  134808. /* SQLITE_ABORT */ "query aborted",
  134809. /* SQLITE_BUSY */ "database is locked",
  134810. /* SQLITE_LOCKED */ "database table is locked",
  134811. /* SQLITE_NOMEM */ "out of memory",
  134812. /* SQLITE_READONLY */ "attempt to write a readonly database",
  134813. /* SQLITE_INTERRUPT */ "interrupted",
  134814. /* SQLITE_IOERR */ "disk I/O error",
  134815. /* SQLITE_CORRUPT */ "database disk image is malformed",
  134816. /* SQLITE_NOTFOUND */ "unknown operation",
  134817. /* SQLITE_FULL */ "database or disk is full",
  134818. /* SQLITE_CANTOPEN */ "unable to open database file",
  134819. /* SQLITE_PROTOCOL */ "locking protocol",
  134820. /* SQLITE_EMPTY */ 0,
  134821. /* SQLITE_SCHEMA */ "database schema has changed",
  134822. /* SQLITE_TOOBIG */ "string or blob too big",
  134823. /* SQLITE_CONSTRAINT */ "constraint failed",
  134824. /* SQLITE_MISMATCH */ "datatype mismatch",
  134825. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  134826. #ifdef SQLITE_DISABLE_LFS
  134827. /* SQLITE_NOLFS */ "large file support is disabled",
  134828. #else
  134829. /* SQLITE_NOLFS */ 0,
  134830. #endif
  134831. /* SQLITE_AUTH */ "authorization denied",
  134832. /* SQLITE_FORMAT */ 0,
  134833. /* SQLITE_RANGE */ "column index out of range",
  134834. /* SQLITE_NOTADB */ "file is not a database",
  134835. };
  134836. const char *zErr = "unknown error";
  134837. switch( rc ){
  134838. case SQLITE_ABORT_ROLLBACK: {
  134839. zErr = "abort due to ROLLBACK";
  134840. break;
  134841. }
  134842. default: {
  134843. rc &= 0xff;
  134844. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  134845. zErr = aMsg[rc];
  134846. }
  134847. break;
  134848. }
  134849. }
  134850. return zErr;
  134851. }
  134852. /*
  134853. ** This routine implements a busy callback that sleeps and tries
  134854. ** again until a timeout value is reached. The timeout value is
  134855. ** an integer number of milliseconds passed in as the first
  134856. ** argument.
  134857. */
  134858. static int sqliteDefaultBusyCallback(
  134859. void *ptr, /* Database connection */
  134860. int count /* Number of times table has been busy */
  134861. ){
  134862. #if SQLITE_OS_WIN || HAVE_USLEEP
  134863. static const u8 delays[] =
  134864. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  134865. static const u8 totals[] =
  134866. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  134867. # define NDELAY ArraySize(delays)
  134868. sqlite3 *db = (sqlite3 *)ptr;
  134869. int timeout = db->busyTimeout;
  134870. int delay, prior;
  134871. assert( count>=0 );
  134872. if( count < NDELAY ){
  134873. delay = delays[count];
  134874. prior = totals[count];
  134875. }else{
  134876. delay = delays[NDELAY-1];
  134877. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  134878. }
  134879. if( prior + delay > timeout ){
  134880. delay = timeout - prior;
  134881. if( delay<=0 ) return 0;
  134882. }
  134883. sqlite3OsSleep(db->pVfs, delay*1000);
  134884. return 1;
  134885. #else
  134886. sqlite3 *db = (sqlite3 *)ptr;
  134887. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  134888. if( (count+1)*1000 > timeout ){
  134889. return 0;
  134890. }
  134891. sqlite3OsSleep(db->pVfs, 1000000);
  134892. return 1;
  134893. #endif
  134894. }
  134895. /*
  134896. ** Invoke the given busy handler.
  134897. **
  134898. ** This routine is called when an operation failed with a lock.
  134899. ** If this routine returns non-zero, the lock is retried. If it
  134900. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  134901. */
  134902. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  134903. int rc;
  134904. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  134905. rc = p->xFunc(p->pArg, p->nBusy);
  134906. if( rc==0 ){
  134907. p->nBusy = -1;
  134908. }else{
  134909. p->nBusy++;
  134910. }
  134911. return rc;
  134912. }
  134913. /*
  134914. ** This routine sets the busy callback for an Sqlite database to the
  134915. ** given callback function with the given argument.
  134916. */
  134917. SQLITE_API int sqlite3_busy_handler(
  134918. sqlite3 *db,
  134919. int (*xBusy)(void*,int),
  134920. void *pArg
  134921. ){
  134922. #ifdef SQLITE_ENABLE_API_ARMOR
  134923. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  134924. #endif
  134925. sqlite3_mutex_enter(db->mutex);
  134926. db->busyHandler.xFunc = xBusy;
  134927. db->busyHandler.pArg = pArg;
  134928. db->busyHandler.nBusy = 0;
  134929. db->busyTimeout = 0;
  134930. sqlite3_mutex_leave(db->mutex);
  134931. return SQLITE_OK;
  134932. }
  134933. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  134934. /*
  134935. ** This routine sets the progress callback for an Sqlite database to the
  134936. ** given callback function with the given argument. The progress callback will
  134937. ** be invoked every nOps opcodes.
  134938. */
  134939. SQLITE_API void sqlite3_progress_handler(
  134940. sqlite3 *db,
  134941. int nOps,
  134942. int (*xProgress)(void*),
  134943. void *pArg
  134944. ){
  134945. #ifdef SQLITE_ENABLE_API_ARMOR
  134946. if( !sqlite3SafetyCheckOk(db) ){
  134947. (void)SQLITE_MISUSE_BKPT;
  134948. return;
  134949. }
  134950. #endif
  134951. sqlite3_mutex_enter(db->mutex);
  134952. if( nOps>0 ){
  134953. db->xProgress = xProgress;
  134954. db->nProgressOps = (unsigned)nOps;
  134955. db->pProgressArg = pArg;
  134956. }else{
  134957. db->xProgress = 0;
  134958. db->nProgressOps = 0;
  134959. db->pProgressArg = 0;
  134960. }
  134961. sqlite3_mutex_leave(db->mutex);
  134962. }
  134963. #endif
  134964. /*
  134965. ** This routine installs a default busy handler that waits for the
  134966. ** specified number of milliseconds before returning 0.
  134967. */
  134968. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  134969. #ifdef SQLITE_ENABLE_API_ARMOR
  134970. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  134971. #endif
  134972. if( ms>0 ){
  134973. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  134974. db->busyTimeout = ms;
  134975. }else{
  134976. sqlite3_busy_handler(db, 0, 0);
  134977. }
  134978. return SQLITE_OK;
  134979. }
  134980. /*
  134981. ** Cause any pending operation to stop at its earliest opportunity.
  134982. */
  134983. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  134984. #ifdef SQLITE_ENABLE_API_ARMOR
  134985. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  134986. (void)SQLITE_MISUSE_BKPT;
  134987. return;
  134988. }
  134989. #endif
  134990. db->u1.isInterrupted = 1;
  134991. }
  134992. /*
  134993. ** This function is exactly the same as sqlite3_create_function(), except
  134994. ** that it is designed to be called by internal code. The difference is
  134995. ** that if a malloc() fails in sqlite3_create_function(), an error code
  134996. ** is returned and the mallocFailed flag cleared.
  134997. */
  134998. SQLITE_PRIVATE int sqlite3CreateFunc(
  134999. sqlite3 *db,
  135000. const char *zFunctionName,
  135001. int nArg,
  135002. int enc,
  135003. void *pUserData,
  135004. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  135005. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  135006. void (*xFinal)(sqlite3_context*),
  135007. FuncDestructor *pDestructor
  135008. ){
  135009. FuncDef *p;
  135010. int nName;
  135011. int extraFlags;
  135012. assert( sqlite3_mutex_held(db->mutex) );
  135013. if( zFunctionName==0 ||
  135014. (xSFunc && (xFinal || xStep)) ||
  135015. (!xSFunc && (xFinal && !xStep)) ||
  135016. (!xSFunc && (!xFinal && xStep)) ||
  135017. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  135018. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  135019. return SQLITE_MISUSE_BKPT;
  135020. }
  135021. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  135022. extraFlags = enc & SQLITE_DETERMINISTIC;
  135023. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  135024. #ifndef SQLITE_OMIT_UTF16
  135025. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  135026. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  135027. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  135028. **
  135029. ** If SQLITE_ANY is specified, add three versions of the function
  135030. ** to the hash table.
  135031. */
  135032. if( enc==SQLITE_UTF16 ){
  135033. enc = SQLITE_UTF16NATIVE;
  135034. }else if( enc==SQLITE_ANY ){
  135035. int rc;
  135036. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  135037. pUserData, xSFunc, xStep, xFinal, pDestructor);
  135038. if( rc==SQLITE_OK ){
  135039. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  135040. pUserData, xSFunc, xStep, xFinal, pDestructor);
  135041. }
  135042. if( rc!=SQLITE_OK ){
  135043. return rc;
  135044. }
  135045. enc = SQLITE_UTF16BE;
  135046. }
  135047. #else
  135048. enc = SQLITE_UTF8;
  135049. #endif
  135050. /* Check if an existing function is being overridden or deleted. If so,
  135051. ** and there are active VMs, then return SQLITE_BUSY. If a function
  135052. ** is being overridden/deleted but there are no active VMs, allow the
  135053. ** operation to continue but invalidate all precompiled statements.
  135054. */
  135055. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  135056. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  135057. if( db->nVdbeActive ){
  135058. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  135059. "unable to delete/modify user-function due to active statements");
  135060. assert( !db->mallocFailed );
  135061. return SQLITE_BUSY;
  135062. }else{
  135063. sqlite3ExpirePreparedStatements(db);
  135064. }
  135065. }
  135066. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  135067. assert(p || db->mallocFailed);
  135068. if( !p ){
  135069. return SQLITE_NOMEM_BKPT;
  135070. }
  135071. /* If an older version of the function with a configured destructor is
  135072. ** being replaced invoke the destructor function here. */
  135073. functionDestroy(db, p);
  135074. if( pDestructor ){
  135075. pDestructor->nRef++;
  135076. }
  135077. p->u.pDestructor = pDestructor;
  135078. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  135079. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  135080. p->xSFunc = xSFunc ? xSFunc : xStep;
  135081. p->xFinalize = xFinal;
  135082. p->pUserData = pUserData;
  135083. p->nArg = (u16)nArg;
  135084. return SQLITE_OK;
  135085. }
  135086. /*
  135087. ** Create new user functions.
  135088. */
  135089. SQLITE_API int sqlite3_create_function(
  135090. sqlite3 *db,
  135091. const char *zFunc,
  135092. int nArg,
  135093. int enc,
  135094. void *p,
  135095. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  135096. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  135097. void (*xFinal)(sqlite3_context*)
  135098. ){
  135099. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  135100. xFinal, 0);
  135101. }
  135102. SQLITE_API int sqlite3_create_function_v2(
  135103. sqlite3 *db,
  135104. const char *zFunc,
  135105. int nArg,
  135106. int enc,
  135107. void *p,
  135108. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  135109. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  135110. void (*xFinal)(sqlite3_context*),
  135111. void (*xDestroy)(void *)
  135112. ){
  135113. int rc = SQLITE_ERROR;
  135114. FuncDestructor *pArg = 0;
  135115. #ifdef SQLITE_ENABLE_API_ARMOR
  135116. if( !sqlite3SafetyCheckOk(db) ){
  135117. return SQLITE_MISUSE_BKPT;
  135118. }
  135119. #endif
  135120. sqlite3_mutex_enter(db->mutex);
  135121. if( xDestroy ){
  135122. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  135123. if( !pArg ){
  135124. xDestroy(p);
  135125. goto out;
  135126. }
  135127. pArg->xDestroy = xDestroy;
  135128. pArg->pUserData = p;
  135129. }
  135130. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  135131. if( pArg && pArg->nRef==0 ){
  135132. assert( rc!=SQLITE_OK );
  135133. xDestroy(p);
  135134. sqlite3DbFree(db, pArg);
  135135. }
  135136. out:
  135137. rc = sqlite3ApiExit(db, rc);
  135138. sqlite3_mutex_leave(db->mutex);
  135139. return rc;
  135140. }
  135141. #ifndef SQLITE_OMIT_UTF16
  135142. SQLITE_API int sqlite3_create_function16(
  135143. sqlite3 *db,
  135144. const void *zFunctionName,
  135145. int nArg,
  135146. int eTextRep,
  135147. void *p,
  135148. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  135149. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  135150. void (*xFinal)(sqlite3_context*)
  135151. ){
  135152. int rc;
  135153. char *zFunc8;
  135154. #ifdef SQLITE_ENABLE_API_ARMOR
  135155. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  135156. #endif
  135157. sqlite3_mutex_enter(db->mutex);
  135158. assert( !db->mallocFailed );
  135159. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  135160. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  135161. sqlite3DbFree(db, zFunc8);
  135162. rc = sqlite3ApiExit(db, rc);
  135163. sqlite3_mutex_leave(db->mutex);
  135164. return rc;
  135165. }
  135166. #endif
  135167. /*
  135168. ** Declare that a function has been overloaded by a virtual table.
  135169. **
  135170. ** If the function already exists as a regular global function, then
  135171. ** this routine is a no-op. If the function does not exist, then create
  135172. ** a new one that always throws a run-time error.
  135173. **
  135174. ** When virtual tables intend to provide an overloaded function, they
  135175. ** should call this routine to make sure the global function exists.
  135176. ** A global function must exist in order for name resolution to work
  135177. ** properly.
  135178. */
  135179. SQLITE_API int sqlite3_overload_function(
  135180. sqlite3 *db,
  135181. const char *zName,
  135182. int nArg
  135183. ){
  135184. int rc = SQLITE_OK;
  135185. #ifdef SQLITE_ENABLE_API_ARMOR
  135186. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  135187. return SQLITE_MISUSE_BKPT;
  135188. }
  135189. #endif
  135190. sqlite3_mutex_enter(db->mutex);
  135191. if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
  135192. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  135193. 0, sqlite3InvalidFunction, 0, 0, 0);
  135194. }
  135195. rc = sqlite3ApiExit(db, rc);
  135196. sqlite3_mutex_leave(db->mutex);
  135197. return rc;
  135198. }
  135199. #ifndef SQLITE_OMIT_TRACE
  135200. /*
  135201. ** Register a trace function. The pArg from the previously registered trace
  135202. ** is returned.
  135203. **
  135204. ** A NULL trace function means that no tracing is executes. A non-NULL
  135205. ** trace is a pointer to a function that is invoked at the start of each
  135206. ** SQL statement.
  135207. */
  135208. #ifndef SQLITE_OMIT_DEPRECATED
  135209. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  135210. void *pOld;
  135211. #ifdef SQLITE_ENABLE_API_ARMOR
  135212. if( !sqlite3SafetyCheckOk(db) ){
  135213. (void)SQLITE_MISUSE_BKPT;
  135214. return 0;
  135215. }
  135216. #endif
  135217. sqlite3_mutex_enter(db->mutex);
  135218. pOld = db->pTraceArg;
  135219. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  135220. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  135221. db->pTraceArg = pArg;
  135222. sqlite3_mutex_leave(db->mutex);
  135223. return pOld;
  135224. }
  135225. #endif /* SQLITE_OMIT_DEPRECATED */
  135226. /* Register a trace callback using the version-2 interface.
  135227. */
  135228. SQLITE_API int sqlite3_trace_v2(
  135229. sqlite3 *db, /* Trace this connection */
  135230. unsigned mTrace, /* Mask of events to be traced */
  135231. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  135232. void *pArg /* Context */
  135233. ){
  135234. #ifdef SQLITE_ENABLE_API_ARMOR
  135235. if( !sqlite3SafetyCheckOk(db) ){
  135236. return SQLITE_MISUSE_BKPT;
  135237. }
  135238. #endif
  135239. sqlite3_mutex_enter(db->mutex);
  135240. if( mTrace==0 ) xTrace = 0;
  135241. if( xTrace==0 ) mTrace = 0;
  135242. db->mTrace = mTrace;
  135243. db->xTrace = xTrace;
  135244. db->pTraceArg = pArg;
  135245. sqlite3_mutex_leave(db->mutex);
  135246. return SQLITE_OK;
  135247. }
  135248. #ifndef SQLITE_OMIT_DEPRECATED
  135249. /*
  135250. ** Register a profile function. The pArg from the previously registered
  135251. ** profile function is returned.
  135252. **
  135253. ** A NULL profile function means that no profiling is executes. A non-NULL
  135254. ** profile is a pointer to a function that is invoked at the conclusion of
  135255. ** each SQL statement that is run.
  135256. */
  135257. SQLITE_API void *sqlite3_profile(
  135258. sqlite3 *db,
  135259. void (*xProfile)(void*,const char*,sqlite_uint64),
  135260. void *pArg
  135261. ){
  135262. void *pOld;
  135263. #ifdef SQLITE_ENABLE_API_ARMOR
  135264. if( !sqlite3SafetyCheckOk(db) ){
  135265. (void)SQLITE_MISUSE_BKPT;
  135266. return 0;
  135267. }
  135268. #endif
  135269. sqlite3_mutex_enter(db->mutex);
  135270. pOld = db->pProfileArg;
  135271. db->xProfile = xProfile;
  135272. db->pProfileArg = pArg;
  135273. sqlite3_mutex_leave(db->mutex);
  135274. return pOld;
  135275. }
  135276. #endif /* SQLITE_OMIT_DEPRECATED */
  135277. #endif /* SQLITE_OMIT_TRACE */
  135278. /*
  135279. ** Register a function to be invoked when a transaction commits.
  135280. ** If the invoked function returns non-zero, then the commit becomes a
  135281. ** rollback.
  135282. */
  135283. SQLITE_API void *sqlite3_commit_hook(
  135284. sqlite3 *db, /* Attach the hook to this database */
  135285. int (*xCallback)(void*), /* Function to invoke on each commit */
  135286. void *pArg /* Argument to the function */
  135287. ){
  135288. void *pOld;
  135289. #ifdef SQLITE_ENABLE_API_ARMOR
  135290. if( !sqlite3SafetyCheckOk(db) ){
  135291. (void)SQLITE_MISUSE_BKPT;
  135292. return 0;
  135293. }
  135294. #endif
  135295. sqlite3_mutex_enter(db->mutex);
  135296. pOld = db->pCommitArg;
  135297. db->xCommitCallback = xCallback;
  135298. db->pCommitArg = pArg;
  135299. sqlite3_mutex_leave(db->mutex);
  135300. return pOld;
  135301. }
  135302. /*
  135303. ** Register a callback to be invoked each time a row is updated,
  135304. ** inserted or deleted using this database connection.
  135305. */
  135306. SQLITE_API void *sqlite3_update_hook(
  135307. sqlite3 *db, /* Attach the hook to this database */
  135308. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  135309. void *pArg /* Argument to the function */
  135310. ){
  135311. void *pRet;
  135312. #ifdef SQLITE_ENABLE_API_ARMOR
  135313. if( !sqlite3SafetyCheckOk(db) ){
  135314. (void)SQLITE_MISUSE_BKPT;
  135315. return 0;
  135316. }
  135317. #endif
  135318. sqlite3_mutex_enter(db->mutex);
  135319. pRet = db->pUpdateArg;
  135320. db->xUpdateCallback = xCallback;
  135321. db->pUpdateArg = pArg;
  135322. sqlite3_mutex_leave(db->mutex);
  135323. return pRet;
  135324. }
  135325. /*
  135326. ** Register a callback to be invoked each time a transaction is rolled
  135327. ** back by this database connection.
  135328. */
  135329. SQLITE_API void *sqlite3_rollback_hook(
  135330. sqlite3 *db, /* Attach the hook to this database */
  135331. void (*xCallback)(void*), /* Callback function */
  135332. void *pArg /* Argument to the function */
  135333. ){
  135334. void *pRet;
  135335. #ifdef SQLITE_ENABLE_API_ARMOR
  135336. if( !sqlite3SafetyCheckOk(db) ){
  135337. (void)SQLITE_MISUSE_BKPT;
  135338. return 0;
  135339. }
  135340. #endif
  135341. sqlite3_mutex_enter(db->mutex);
  135342. pRet = db->pRollbackArg;
  135343. db->xRollbackCallback = xCallback;
  135344. db->pRollbackArg = pArg;
  135345. sqlite3_mutex_leave(db->mutex);
  135346. return pRet;
  135347. }
  135348. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  135349. /*
  135350. ** Register a callback to be invoked each time a row is updated,
  135351. ** inserted or deleted using this database connection.
  135352. */
  135353. SQLITE_API void *sqlite3_preupdate_hook(
  135354. sqlite3 *db, /* Attach the hook to this database */
  135355. void(*xCallback)( /* Callback function */
  135356. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  135357. void *pArg /* First callback argument */
  135358. ){
  135359. void *pRet;
  135360. sqlite3_mutex_enter(db->mutex);
  135361. pRet = db->pPreUpdateArg;
  135362. db->xPreUpdateCallback = xCallback;
  135363. db->pPreUpdateArg = pArg;
  135364. sqlite3_mutex_leave(db->mutex);
  135365. return pRet;
  135366. }
  135367. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  135368. #ifndef SQLITE_OMIT_WAL
  135369. /*
  135370. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  135371. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  135372. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  135373. ** wal_autocheckpoint()).
  135374. */
  135375. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  135376. void *pClientData, /* Argument */
  135377. sqlite3 *db, /* Connection */
  135378. const char *zDb, /* Database */
  135379. int nFrame /* Size of WAL */
  135380. ){
  135381. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  135382. sqlite3BeginBenignMalloc();
  135383. sqlite3_wal_checkpoint(db, zDb);
  135384. sqlite3EndBenignMalloc();
  135385. }
  135386. return SQLITE_OK;
  135387. }
  135388. #endif /* SQLITE_OMIT_WAL */
  135389. /*
  135390. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  135391. ** a database after committing a transaction if there are nFrame or
  135392. ** more frames in the log file. Passing zero or a negative value as the
  135393. ** nFrame parameter disables automatic checkpoints entirely.
  135394. **
  135395. ** The callback registered by this function replaces any existing callback
  135396. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  135397. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  135398. ** configured by this function.
  135399. */
  135400. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  135401. #ifdef SQLITE_OMIT_WAL
  135402. UNUSED_PARAMETER(db);
  135403. UNUSED_PARAMETER(nFrame);
  135404. #else
  135405. #ifdef SQLITE_ENABLE_API_ARMOR
  135406. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135407. #endif
  135408. if( nFrame>0 ){
  135409. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  135410. }else{
  135411. sqlite3_wal_hook(db, 0, 0);
  135412. }
  135413. #endif
  135414. return SQLITE_OK;
  135415. }
  135416. /*
  135417. ** Register a callback to be invoked each time a transaction is written
  135418. ** into the write-ahead-log by this database connection.
  135419. */
  135420. SQLITE_API void *sqlite3_wal_hook(
  135421. sqlite3 *db, /* Attach the hook to this db handle */
  135422. int(*xCallback)(void *, sqlite3*, const char*, int),
  135423. void *pArg /* First argument passed to xCallback() */
  135424. ){
  135425. #ifndef SQLITE_OMIT_WAL
  135426. void *pRet;
  135427. #ifdef SQLITE_ENABLE_API_ARMOR
  135428. if( !sqlite3SafetyCheckOk(db) ){
  135429. (void)SQLITE_MISUSE_BKPT;
  135430. return 0;
  135431. }
  135432. #endif
  135433. sqlite3_mutex_enter(db->mutex);
  135434. pRet = db->pWalArg;
  135435. db->xWalCallback = xCallback;
  135436. db->pWalArg = pArg;
  135437. sqlite3_mutex_leave(db->mutex);
  135438. return pRet;
  135439. #else
  135440. return 0;
  135441. #endif
  135442. }
  135443. /*
  135444. ** Checkpoint database zDb.
  135445. */
  135446. SQLITE_API int sqlite3_wal_checkpoint_v2(
  135447. sqlite3 *db, /* Database handle */
  135448. const char *zDb, /* Name of attached database (or NULL) */
  135449. int eMode, /* SQLITE_CHECKPOINT_* value */
  135450. int *pnLog, /* OUT: Size of WAL log in frames */
  135451. int *pnCkpt /* OUT: Total number of frames checkpointed */
  135452. ){
  135453. #ifdef SQLITE_OMIT_WAL
  135454. return SQLITE_OK;
  135455. #else
  135456. int rc; /* Return code */
  135457. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  135458. #ifdef SQLITE_ENABLE_API_ARMOR
  135459. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135460. #endif
  135461. /* Initialize the output variables to -1 in case an error occurs. */
  135462. if( pnLog ) *pnLog = -1;
  135463. if( pnCkpt ) *pnCkpt = -1;
  135464. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  135465. assert( SQLITE_CHECKPOINT_FULL==1 );
  135466. assert( SQLITE_CHECKPOINT_RESTART==2 );
  135467. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  135468. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  135469. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  135470. ** mode: */
  135471. return SQLITE_MISUSE;
  135472. }
  135473. sqlite3_mutex_enter(db->mutex);
  135474. if( zDb && zDb[0] ){
  135475. iDb = sqlite3FindDbName(db, zDb);
  135476. }
  135477. if( iDb<0 ){
  135478. rc = SQLITE_ERROR;
  135479. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  135480. }else{
  135481. db->busyHandler.nBusy = 0;
  135482. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  135483. sqlite3Error(db, rc);
  135484. }
  135485. rc = sqlite3ApiExit(db, rc);
  135486. /* If there are no active statements, clear the interrupt flag at this
  135487. ** point. */
  135488. if( db->nVdbeActive==0 ){
  135489. db->u1.isInterrupted = 0;
  135490. }
  135491. sqlite3_mutex_leave(db->mutex);
  135492. return rc;
  135493. #endif
  135494. }
  135495. /*
  135496. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  135497. ** to contains a zero-length string, all attached databases are
  135498. ** checkpointed.
  135499. */
  135500. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  135501. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  135502. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  135503. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  135504. }
  135505. #ifndef SQLITE_OMIT_WAL
  135506. /*
  135507. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  135508. ** not currently open in WAL mode.
  135509. **
  135510. ** If a transaction is open on the database being checkpointed, this
  135511. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  135512. ** an error occurs while running the checkpoint, an SQLite error code is
  135513. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  135514. **
  135515. ** The mutex on database handle db should be held by the caller. The mutex
  135516. ** associated with the specific b-tree being checkpointed is taken by
  135517. ** this function while the checkpoint is running.
  135518. **
  135519. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  135520. ** checkpointed. If an error is encountered it is returned immediately -
  135521. ** no attempt is made to checkpoint any remaining databases.
  135522. **
  135523. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  135524. ** or TRUNCATE.
  135525. */
  135526. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  135527. int rc = SQLITE_OK; /* Return code */
  135528. int i; /* Used to iterate through attached dbs */
  135529. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  135530. assert( sqlite3_mutex_held(db->mutex) );
  135531. assert( !pnLog || *pnLog==-1 );
  135532. assert( !pnCkpt || *pnCkpt==-1 );
  135533. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  135534. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  135535. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  135536. pnLog = 0;
  135537. pnCkpt = 0;
  135538. if( rc==SQLITE_BUSY ){
  135539. bBusy = 1;
  135540. rc = SQLITE_OK;
  135541. }
  135542. }
  135543. }
  135544. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  135545. }
  135546. #endif /* SQLITE_OMIT_WAL */
  135547. /*
  135548. ** This function returns true if main-memory should be used instead of
  135549. ** a temporary file for transient pager files and statement journals.
  135550. ** The value returned depends on the value of db->temp_store (runtime
  135551. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  135552. ** following table describes the relationship between these two values
  135553. ** and this functions return value.
  135554. **
  135555. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  135556. ** ----------------- -------------- ------------------------------
  135557. ** 0 any file (return 0)
  135558. ** 1 1 file (return 0)
  135559. ** 1 2 memory (return 1)
  135560. ** 1 0 file (return 0)
  135561. ** 2 1 file (return 0)
  135562. ** 2 2 memory (return 1)
  135563. ** 2 0 memory (return 1)
  135564. ** 3 any memory (return 1)
  135565. */
  135566. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  135567. #if SQLITE_TEMP_STORE==1
  135568. return ( db->temp_store==2 );
  135569. #endif
  135570. #if SQLITE_TEMP_STORE==2
  135571. return ( db->temp_store!=1 );
  135572. #endif
  135573. #if SQLITE_TEMP_STORE==3
  135574. UNUSED_PARAMETER(db);
  135575. return 1;
  135576. #endif
  135577. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  135578. UNUSED_PARAMETER(db);
  135579. return 0;
  135580. #endif
  135581. }
  135582. /*
  135583. ** Return UTF-8 encoded English language explanation of the most recent
  135584. ** error.
  135585. */
  135586. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  135587. const char *z;
  135588. if( !db ){
  135589. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  135590. }
  135591. if( !sqlite3SafetyCheckSickOrOk(db) ){
  135592. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  135593. }
  135594. sqlite3_mutex_enter(db->mutex);
  135595. if( db->mallocFailed ){
  135596. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  135597. }else{
  135598. testcase( db->pErr==0 );
  135599. z = (char*)sqlite3_value_text(db->pErr);
  135600. assert( !db->mallocFailed );
  135601. if( z==0 ){
  135602. z = sqlite3ErrStr(db->errCode);
  135603. }
  135604. }
  135605. sqlite3_mutex_leave(db->mutex);
  135606. return z;
  135607. }
  135608. #ifndef SQLITE_OMIT_UTF16
  135609. /*
  135610. ** Return UTF-16 encoded English language explanation of the most recent
  135611. ** error.
  135612. */
  135613. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  135614. static const u16 outOfMem[] = {
  135615. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  135616. };
  135617. static const u16 misuse[] = {
  135618. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  135619. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  135620. 'm', 'i', 's', 'u', 's', 'e', 0
  135621. };
  135622. const void *z;
  135623. if( !db ){
  135624. return (void *)outOfMem;
  135625. }
  135626. if( !sqlite3SafetyCheckSickOrOk(db) ){
  135627. return (void *)misuse;
  135628. }
  135629. sqlite3_mutex_enter(db->mutex);
  135630. if( db->mallocFailed ){
  135631. z = (void *)outOfMem;
  135632. }else{
  135633. z = sqlite3_value_text16(db->pErr);
  135634. if( z==0 ){
  135635. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  135636. z = sqlite3_value_text16(db->pErr);
  135637. }
  135638. /* A malloc() may have failed within the call to sqlite3_value_text16()
  135639. ** above. If this is the case, then the db->mallocFailed flag needs to
  135640. ** be cleared before returning. Do this directly, instead of via
  135641. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  135642. */
  135643. sqlite3OomClear(db);
  135644. }
  135645. sqlite3_mutex_leave(db->mutex);
  135646. return z;
  135647. }
  135648. #endif /* SQLITE_OMIT_UTF16 */
  135649. /*
  135650. ** Return the most recent error code generated by an SQLite routine. If NULL is
  135651. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  135652. */
  135653. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  135654. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  135655. return SQLITE_MISUSE_BKPT;
  135656. }
  135657. if( !db || db->mallocFailed ){
  135658. return SQLITE_NOMEM_BKPT;
  135659. }
  135660. return db->errCode & db->errMask;
  135661. }
  135662. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  135663. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  135664. return SQLITE_MISUSE_BKPT;
  135665. }
  135666. if( !db || db->mallocFailed ){
  135667. return SQLITE_NOMEM_BKPT;
  135668. }
  135669. return db->errCode;
  135670. }
  135671. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  135672. return db ? db->iSysErrno : 0;
  135673. }
  135674. /*
  135675. ** Return a string that describes the kind of error specified in the
  135676. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  135677. ** function.
  135678. */
  135679. SQLITE_API const char *sqlite3_errstr(int rc){
  135680. return sqlite3ErrStr(rc);
  135681. }
  135682. /*
  135683. ** Create a new collating function for database "db". The name is zName
  135684. ** and the encoding is enc.
  135685. */
  135686. static int createCollation(
  135687. sqlite3* db,
  135688. const char *zName,
  135689. u8 enc,
  135690. void* pCtx,
  135691. int(*xCompare)(void*,int,const void*,int,const void*),
  135692. void(*xDel)(void*)
  135693. ){
  135694. CollSeq *pColl;
  135695. int enc2;
  135696. assert( sqlite3_mutex_held(db->mutex) );
  135697. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  135698. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  135699. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  135700. */
  135701. enc2 = enc;
  135702. testcase( enc2==SQLITE_UTF16 );
  135703. testcase( enc2==SQLITE_UTF16_ALIGNED );
  135704. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  135705. enc2 = SQLITE_UTF16NATIVE;
  135706. }
  135707. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  135708. return SQLITE_MISUSE_BKPT;
  135709. }
  135710. /* Check if this call is removing or replacing an existing collation
  135711. ** sequence. If so, and there are active VMs, return busy. If there
  135712. ** are no active VMs, invalidate any pre-compiled statements.
  135713. */
  135714. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  135715. if( pColl && pColl->xCmp ){
  135716. if( db->nVdbeActive ){
  135717. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  135718. "unable to delete/modify collation sequence due to active statements");
  135719. return SQLITE_BUSY;
  135720. }
  135721. sqlite3ExpirePreparedStatements(db);
  135722. /* If collation sequence pColl was created directly by a call to
  135723. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  135724. ** then any copies made by synthCollSeq() need to be invalidated.
  135725. ** Also, collation destructor - CollSeq.xDel() - function may need
  135726. ** to be called.
  135727. */
  135728. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  135729. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  135730. int j;
  135731. for(j=0; j<3; j++){
  135732. CollSeq *p = &aColl[j];
  135733. if( p->enc==pColl->enc ){
  135734. if( p->xDel ){
  135735. p->xDel(p->pUser);
  135736. }
  135737. p->xCmp = 0;
  135738. }
  135739. }
  135740. }
  135741. }
  135742. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  135743. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  135744. pColl->xCmp = xCompare;
  135745. pColl->pUser = pCtx;
  135746. pColl->xDel = xDel;
  135747. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  135748. sqlite3Error(db, SQLITE_OK);
  135749. return SQLITE_OK;
  135750. }
  135751. /*
  135752. ** This array defines hard upper bounds on limit values. The
  135753. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  135754. ** #defines in sqlite3.h.
  135755. */
  135756. static const int aHardLimit[] = {
  135757. SQLITE_MAX_LENGTH,
  135758. SQLITE_MAX_SQL_LENGTH,
  135759. SQLITE_MAX_COLUMN,
  135760. SQLITE_MAX_EXPR_DEPTH,
  135761. SQLITE_MAX_COMPOUND_SELECT,
  135762. SQLITE_MAX_VDBE_OP,
  135763. SQLITE_MAX_FUNCTION_ARG,
  135764. SQLITE_MAX_ATTACHED,
  135765. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  135766. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  135767. SQLITE_MAX_TRIGGER_DEPTH,
  135768. SQLITE_MAX_WORKER_THREADS,
  135769. };
  135770. /*
  135771. ** Make sure the hard limits are set to reasonable values
  135772. */
  135773. #if SQLITE_MAX_LENGTH<100
  135774. # error SQLITE_MAX_LENGTH must be at least 100
  135775. #endif
  135776. #if SQLITE_MAX_SQL_LENGTH<100
  135777. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  135778. #endif
  135779. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  135780. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  135781. #endif
  135782. #if SQLITE_MAX_COMPOUND_SELECT<2
  135783. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  135784. #endif
  135785. #if SQLITE_MAX_VDBE_OP<40
  135786. # error SQLITE_MAX_VDBE_OP must be at least 40
  135787. #endif
  135788. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  135789. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  135790. #endif
  135791. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  135792. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  135793. #endif
  135794. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  135795. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  135796. #endif
  135797. #if SQLITE_MAX_COLUMN>32767
  135798. # error SQLITE_MAX_COLUMN must not exceed 32767
  135799. #endif
  135800. #if SQLITE_MAX_TRIGGER_DEPTH<1
  135801. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  135802. #endif
  135803. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  135804. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  135805. #endif
  135806. /*
  135807. ** Change the value of a limit. Report the old value.
  135808. ** If an invalid limit index is supplied, report -1.
  135809. ** Make no changes but still report the old value if the
  135810. ** new limit is negative.
  135811. **
  135812. ** A new lower limit does not shrink existing constructs.
  135813. ** It merely prevents new constructs that exceed the limit
  135814. ** from forming.
  135815. */
  135816. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  135817. int oldLimit;
  135818. #ifdef SQLITE_ENABLE_API_ARMOR
  135819. if( !sqlite3SafetyCheckOk(db) ){
  135820. (void)SQLITE_MISUSE_BKPT;
  135821. return -1;
  135822. }
  135823. #endif
  135824. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  135825. ** there is a hard upper bound set at compile-time by a C preprocessor
  135826. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  135827. ** "_MAX_".)
  135828. */
  135829. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  135830. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  135831. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  135832. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  135833. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  135834. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  135835. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  135836. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  135837. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  135838. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  135839. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  135840. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  135841. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  135842. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  135843. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  135844. return -1;
  135845. }
  135846. oldLimit = db->aLimit[limitId];
  135847. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  135848. if( newLimit>aHardLimit[limitId] ){
  135849. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  135850. }
  135851. db->aLimit[limitId] = newLimit;
  135852. }
  135853. return oldLimit; /* IMP: R-53341-35419 */
  135854. }
  135855. /*
  135856. ** This function is used to parse both URIs and non-URI filenames passed by the
  135857. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  135858. ** URIs specified as part of ATTACH statements.
  135859. **
  135860. ** The first argument to this function is the name of the VFS to use (or
  135861. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  135862. ** query parameter. The second argument contains the URI (or non-URI filename)
  135863. ** itself. When this function is called the *pFlags variable should contain
  135864. ** the default flags to open the database handle with. The value stored in
  135865. ** *pFlags may be updated before returning if the URI filename contains
  135866. ** "cache=xxx" or "mode=xxx" query parameters.
  135867. **
  135868. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  135869. ** the VFS that should be used to open the database file. *pzFile is set to
  135870. ** point to a buffer containing the name of the file to open. It is the
  135871. ** responsibility of the caller to eventually call sqlite3_free() to release
  135872. ** this buffer.
  135873. **
  135874. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  135875. ** may be set to point to a buffer containing an English language error
  135876. ** message. It is the responsibility of the caller to eventually release
  135877. ** this buffer by calling sqlite3_free().
  135878. */
  135879. SQLITE_PRIVATE int sqlite3ParseUri(
  135880. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  135881. const char *zUri, /* Nul-terminated URI to parse */
  135882. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  135883. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  135884. char **pzFile, /* OUT: Filename component of URI */
  135885. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  135886. ){
  135887. int rc = SQLITE_OK;
  135888. unsigned int flags = *pFlags;
  135889. const char *zVfs = zDefaultVfs;
  135890. char *zFile;
  135891. char c;
  135892. int nUri = sqlite3Strlen30(zUri);
  135893. assert( *pzErrMsg==0 );
  135894. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  135895. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  135896. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  135897. ){
  135898. char *zOpt;
  135899. int eState; /* Parser state when parsing URI */
  135900. int iIn; /* Input character index */
  135901. int iOut = 0; /* Output character index */
  135902. u64 nByte = nUri+2; /* Bytes of space to allocate */
  135903. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  135904. ** method that there may be extra parameters following the file-name. */
  135905. flags |= SQLITE_OPEN_URI;
  135906. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  135907. zFile = sqlite3_malloc64(nByte);
  135908. if( !zFile ) return SQLITE_NOMEM_BKPT;
  135909. iIn = 5;
  135910. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  135911. if( strncmp(zUri+5, "///", 3)==0 ){
  135912. iIn = 7;
  135913. /* The following condition causes URIs with five leading / characters
  135914. ** like file://///host/path to be converted into UNCs like //host/path.
  135915. ** The correct URI for that UNC has only two or four leading / characters
  135916. ** file://host/path or file:////host/path. But 5 leading slashes is a
  135917. ** common error, we are told, so we handle it as a special case. */
  135918. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  135919. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  135920. iIn = 16;
  135921. }
  135922. #else
  135923. /* Discard the scheme and authority segments of the URI. */
  135924. if( zUri[5]=='/' && zUri[6]=='/' ){
  135925. iIn = 7;
  135926. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  135927. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  135928. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  135929. iIn-7, &zUri[7]);
  135930. rc = SQLITE_ERROR;
  135931. goto parse_uri_out;
  135932. }
  135933. }
  135934. #endif
  135935. /* Copy the filename and any query parameters into the zFile buffer.
  135936. ** Decode %HH escape codes along the way.
  135937. **
  135938. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  135939. ** on the parsing context. As follows:
  135940. **
  135941. ** 0: Parsing file-name.
  135942. ** 1: Parsing name section of a name=value query parameter.
  135943. ** 2: Parsing value section of a name=value query parameter.
  135944. */
  135945. eState = 0;
  135946. while( (c = zUri[iIn])!=0 && c!='#' ){
  135947. iIn++;
  135948. if( c=='%'
  135949. && sqlite3Isxdigit(zUri[iIn])
  135950. && sqlite3Isxdigit(zUri[iIn+1])
  135951. ){
  135952. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  135953. octet += sqlite3HexToInt(zUri[iIn++]);
  135954. assert( octet>=0 && octet<256 );
  135955. if( octet==0 ){
  135956. #ifndef SQLITE_ENABLE_URI_00_ERROR
  135957. /* This branch is taken when "%00" appears within the URI. In this
  135958. ** case we ignore all text in the remainder of the path, name or
  135959. ** value currently being parsed. So ignore the current character
  135960. ** and skip to the next "?", "=" or "&", as appropriate. */
  135961. while( (c = zUri[iIn])!=0 && c!='#'
  135962. && (eState!=0 || c!='?')
  135963. && (eState!=1 || (c!='=' && c!='&'))
  135964. && (eState!=2 || c!='&')
  135965. ){
  135966. iIn++;
  135967. }
  135968. continue;
  135969. #else
  135970. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  135971. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  135972. rc = SQLITE_ERROR;
  135973. goto parse_uri_out;
  135974. #endif
  135975. }
  135976. c = octet;
  135977. }else if( eState==1 && (c=='&' || c=='=') ){
  135978. if( zFile[iOut-1]==0 ){
  135979. /* An empty option name. Ignore this option altogether. */
  135980. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  135981. continue;
  135982. }
  135983. if( c=='&' ){
  135984. zFile[iOut++] = '\0';
  135985. }else{
  135986. eState = 2;
  135987. }
  135988. c = 0;
  135989. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  135990. c = 0;
  135991. eState = 1;
  135992. }
  135993. zFile[iOut++] = c;
  135994. }
  135995. if( eState==1 ) zFile[iOut++] = '\0';
  135996. zFile[iOut++] = '\0';
  135997. zFile[iOut++] = '\0';
  135998. /* Check if there were any options specified that should be interpreted
  135999. ** here. Options that are interpreted here include "vfs" and those that
  136000. ** correspond to flags that may be passed to the sqlite3_open_v2()
  136001. ** method. */
  136002. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  136003. while( zOpt[0] ){
  136004. int nOpt = sqlite3Strlen30(zOpt);
  136005. char *zVal = &zOpt[nOpt+1];
  136006. int nVal = sqlite3Strlen30(zVal);
  136007. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  136008. zVfs = zVal;
  136009. }else{
  136010. struct OpenMode {
  136011. const char *z;
  136012. int mode;
  136013. } *aMode = 0;
  136014. char *zModeType = 0;
  136015. int mask = 0;
  136016. int limit = 0;
  136017. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  136018. static struct OpenMode aCacheMode[] = {
  136019. { "shared", SQLITE_OPEN_SHAREDCACHE },
  136020. { "private", SQLITE_OPEN_PRIVATECACHE },
  136021. { 0, 0 }
  136022. };
  136023. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  136024. aMode = aCacheMode;
  136025. limit = mask;
  136026. zModeType = "cache";
  136027. }
  136028. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  136029. static struct OpenMode aOpenMode[] = {
  136030. { "ro", SQLITE_OPEN_READONLY },
  136031. { "rw", SQLITE_OPEN_READWRITE },
  136032. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  136033. { "memory", SQLITE_OPEN_MEMORY },
  136034. { 0, 0 }
  136035. };
  136036. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  136037. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  136038. aMode = aOpenMode;
  136039. limit = mask & flags;
  136040. zModeType = "access";
  136041. }
  136042. if( aMode ){
  136043. int i;
  136044. int mode = 0;
  136045. for(i=0; aMode[i].z; i++){
  136046. const char *z = aMode[i].z;
  136047. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  136048. mode = aMode[i].mode;
  136049. break;
  136050. }
  136051. }
  136052. if( mode==0 ){
  136053. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  136054. rc = SQLITE_ERROR;
  136055. goto parse_uri_out;
  136056. }
  136057. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  136058. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  136059. zModeType, zVal);
  136060. rc = SQLITE_PERM;
  136061. goto parse_uri_out;
  136062. }
  136063. flags = (flags & ~mask) | mode;
  136064. }
  136065. }
  136066. zOpt = &zVal[nVal+1];
  136067. }
  136068. }else{
  136069. zFile = sqlite3_malloc64(nUri+2);
  136070. if( !zFile ) return SQLITE_NOMEM_BKPT;
  136071. if( nUri ){
  136072. memcpy(zFile, zUri, nUri);
  136073. }
  136074. zFile[nUri] = '\0';
  136075. zFile[nUri+1] = '\0';
  136076. flags &= ~SQLITE_OPEN_URI;
  136077. }
  136078. *ppVfs = sqlite3_vfs_find(zVfs);
  136079. if( *ppVfs==0 ){
  136080. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  136081. rc = SQLITE_ERROR;
  136082. }
  136083. parse_uri_out:
  136084. if( rc!=SQLITE_OK ){
  136085. sqlite3_free(zFile);
  136086. zFile = 0;
  136087. }
  136088. *pFlags = flags;
  136089. *pzFile = zFile;
  136090. return rc;
  136091. }
  136092. /*
  136093. ** This routine does the work of opening a database on behalf of
  136094. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  136095. ** is UTF-8 encoded.
  136096. */
  136097. static int openDatabase(
  136098. const char *zFilename, /* Database filename UTF-8 encoded */
  136099. sqlite3 **ppDb, /* OUT: Returned database handle */
  136100. unsigned int flags, /* Operational flags */
  136101. const char *zVfs /* Name of the VFS to use */
  136102. ){
  136103. sqlite3 *db; /* Store allocated handle here */
  136104. int rc; /* Return code */
  136105. int isThreadsafe; /* True for threadsafe connections */
  136106. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  136107. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  136108. #ifdef SQLITE_ENABLE_API_ARMOR
  136109. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  136110. #endif
  136111. *ppDb = 0;
  136112. #ifndef SQLITE_OMIT_AUTOINIT
  136113. rc = sqlite3_initialize();
  136114. if( rc ) return rc;
  136115. #endif
  136116. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  136117. isThreadsafe = 0;
  136118. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  136119. isThreadsafe = 0;
  136120. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  136121. isThreadsafe = 1;
  136122. }else{
  136123. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  136124. }
  136125. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  136126. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  136127. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  136128. flags |= SQLITE_OPEN_SHAREDCACHE;
  136129. }
  136130. /* Remove harmful bits from the flags parameter
  136131. **
  136132. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  136133. ** dealt with in the previous code block. Besides these, the only
  136134. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  136135. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  136136. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  136137. ** off all other flags.
  136138. */
  136139. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  136140. SQLITE_OPEN_EXCLUSIVE |
  136141. SQLITE_OPEN_MAIN_DB |
  136142. SQLITE_OPEN_TEMP_DB |
  136143. SQLITE_OPEN_TRANSIENT_DB |
  136144. SQLITE_OPEN_MAIN_JOURNAL |
  136145. SQLITE_OPEN_TEMP_JOURNAL |
  136146. SQLITE_OPEN_SUBJOURNAL |
  136147. SQLITE_OPEN_MASTER_JOURNAL |
  136148. SQLITE_OPEN_NOMUTEX |
  136149. SQLITE_OPEN_FULLMUTEX |
  136150. SQLITE_OPEN_WAL
  136151. );
  136152. /* Allocate the sqlite data structure */
  136153. db = sqlite3MallocZero( sizeof(sqlite3) );
  136154. if( db==0 ) goto opendb_out;
  136155. if( isThreadsafe ){
  136156. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  136157. if( db->mutex==0 ){
  136158. sqlite3_free(db);
  136159. db = 0;
  136160. goto opendb_out;
  136161. }
  136162. }
  136163. sqlite3_mutex_enter(db->mutex);
  136164. db->errMask = 0xff;
  136165. db->nDb = 2;
  136166. db->magic = SQLITE_MAGIC_BUSY;
  136167. db->aDb = db->aDbStatic;
  136168. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  136169. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  136170. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  136171. db->autoCommit = 1;
  136172. db->nextAutovac = -1;
  136173. db->szMmap = sqlite3GlobalConfig.szMmap;
  136174. db->nextPagesize = 0;
  136175. db->nMaxSorterMmap = 0x7FFFFFFF;
  136176. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  136177. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  136178. | SQLITE_AutoIndex
  136179. #endif
  136180. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  136181. | SQLITE_CkptFullFSync
  136182. #endif
  136183. #if SQLITE_DEFAULT_FILE_FORMAT<4
  136184. | SQLITE_LegacyFileFmt
  136185. #endif
  136186. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  136187. | SQLITE_LoadExtension
  136188. #endif
  136189. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  136190. | SQLITE_RecTriggers
  136191. #endif
  136192. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  136193. | SQLITE_ForeignKeys
  136194. #endif
  136195. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  136196. | SQLITE_ReverseOrder
  136197. #endif
  136198. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  136199. | SQLITE_CellSizeCk
  136200. #endif
  136201. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  136202. | SQLITE_Fts3Tokenizer
  136203. #endif
  136204. #if defined(SQLITE_ENABLE_QPSG)
  136205. | SQLITE_EnableQPSG
  136206. #endif
  136207. ;
  136208. sqlite3HashInit(&db->aCollSeq);
  136209. #ifndef SQLITE_OMIT_VIRTUALTABLE
  136210. sqlite3HashInit(&db->aModule);
  136211. #endif
  136212. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  136213. ** and UTF-16, so add a version for each to avoid any unnecessary
  136214. ** conversions. The only error that can occur here is a malloc() failure.
  136215. **
  136216. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  136217. ** functions:
  136218. */
  136219. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  136220. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  136221. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  136222. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  136223. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  136224. if( db->mallocFailed ){
  136225. goto opendb_out;
  136226. }
  136227. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  136228. ** strings is BINARY.
  136229. */
  136230. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  136231. assert( db->pDfltColl!=0 );
  136232. /* Parse the filename/URI argument
  136233. **
  136234. ** Only allow sensible combinations of bits in the flags argument.
  136235. ** Throw an error if any non-sense combination is used. If we
  136236. ** do not block illegal combinations here, it could trigger
  136237. ** assert() statements in deeper layers. Sensible combinations
  136238. ** are:
  136239. **
  136240. ** 1: SQLITE_OPEN_READONLY
  136241. ** 2: SQLITE_OPEN_READWRITE
  136242. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  136243. */
  136244. db->openFlags = flags;
  136245. assert( SQLITE_OPEN_READONLY == 0x01 );
  136246. assert( SQLITE_OPEN_READWRITE == 0x02 );
  136247. assert( SQLITE_OPEN_CREATE == 0x04 );
  136248. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  136249. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  136250. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  136251. if( ((1<<(flags&7)) & 0x46)==0 ){
  136252. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  136253. }else{
  136254. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  136255. }
  136256. if( rc!=SQLITE_OK ){
  136257. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  136258. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  136259. sqlite3_free(zErrMsg);
  136260. goto opendb_out;
  136261. }
  136262. /* Open the backend database driver */
  136263. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  136264. flags | SQLITE_OPEN_MAIN_DB);
  136265. if( rc!=SQLITE_OK ){
  136266. if( rc==SQLITE_IOERR_NOMEM ){
  136267. rc = SQLITE_NOMEM_BKPT;
  136268. }
  136269. sqlite3Error(db, rc);
  136270. goto opendb_out;
  136271. }
  136272. sqlite3BtreeEnter(db->aDb[0].pBt);
  136273. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  136274. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  136275. sqlite3BtreeLeave(db->aDb[0].pBt);
  136276. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  136277. /* The default safety_level for the main database is FULL; for the temp
  136278. ** database it is OFF. This matches the pager layer defaults.
  136279. */
  136280. db->aDb[0].zDbSName = "main";
  136281. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  136282. db->aDb[1].zDbSName = "temp";
  136283. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  136284. db->magic = SQLITE_MAGIC_OPEN;
  136285. if( db->mallocFailed ){
  136286. goto opendb_out;
  136287. }
  136288. /* Register all built-in functions, but do not attempt to read the
  136289. ** database schema yet. This is delayed until the first time the database
  136290. ** is accessed.
  136291. */
  136292. sqlite3Error(db, SQLITE_OK);
  136293. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  136294. rc = sqlite3_errcode(db);
  136295. #ifdef SQLITE_ENABLE_FTS5
  136296. /* Register any built-in FTS5 module before loading the automatic
  136297. ** extensions. This allows automatic extensions to register FTS5
  136298. ** tokenizers and auxiliary functions. */
  136299. if( !db->mallocFailed && rc==SQLITE_OK ){
  136300. rc = sqlite3Fts5Init(db);
  136301. }
  136302. #endif
  136303. /* Load automatic extensions - extensions that have been registered
  136304. ** using the sqlite3_automatic_extension() API.
  136305. */
  136306. if( rc==SQLITE_OK ){
  136307. sqlite3AutoLoadExtensions(db);
  136308. rc = sqlite3_errcode(db);
  136309. if( rc!=SQLITE_OK ){
  136310. goto opendb_out;
  136311. }
  136312. }
  136313. #ifdef SQLITE_ENABLE_FTS1
  136314. if( !db->mallocFailed ){
  136315. extern int sqlite3Fts1Init(sqlite3*);
  136316. rc = sqlite3Fts1Init(db);
  136317. }
  136318. #endif
  136319. #ifdef SQLITE_ENABLE_FTS2
  136320. if( !db->mallocFailed && rc==SQLITE_OK ){
  136321. extern int sqlite3Fts2Init(sqlite3*);
  136322. rc = sqlite3Fts2Init(db);
  136323. }
  136324. #endif
  136325. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  136326. if( !db->mallocFailed && rc==SQLITE_OK ){
  136327. rc = sqlite3Fts3Init(db);
  136328. }
  136329. #endif
  136330. #ifdef SQLITE_ENABLE_ICU
  136331. if( !db->mallocFailed && rc==SQLITE_OK ){
  136332. rc = sqlite3IcuInit(db);
  136333. }
  136334. #endif
  136335. #ifdef SQLITE_ENABLE_RTREE
  136336. if( !db->mallocFailed && rc==SQLITE_OK){
  136337. rc = sqlite3RtreeInit(db);
  136338. }
  136339. #endif
  136340. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  136341. if( !db->mallocFailed && rc==SQLITE_OK){
  136342. rc = sqlite3DbpageRegister(db);
  136343. }
  136344. #endif
  136345. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  136346. if( !db->mallocFailed && rc==SQLITE_OK){
  136347. rc = sqlite3DbstatRegister(db);
  136348. }
  136349. #endif
  136350. #ifdef SQLITE_ENABLE_JSON1
  136351. if( !db->mallocFailed && rc==SQLITE_OK){
  136352. rc = sqlite3Json1Init(db);
  136353. }
  136354. #endif
  136355. #ifdef SQLITE_ENABLE_STMTVTAB
  136356. if( !db->mallocFailed && rc==SQLITE_OK){
  136357. rc = sqlite3StmtVtabInit(db);
  136358. }
  136359. #endif
  136360. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  136361. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  136362. ** mode. Doing nothing at all also makes NORMAL the default.
  136363. */
  136364. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  136365. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  136366. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  136367. SQLITE_DEFAULT_LOCKING_MODE);
  136368. #endif
  136369. if( rc ) sqlite3Error(db, rc);
  136370. /* Enable the lookaside-malloc subsystem */
  136371. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  136372. sqlite3GlobalConfig.nLookaside);
  136373. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  136374. opendb_out:
  136375. if( db ){
  136376. assert( db->mutex!=0 || isThreadsafe==0
  136377. || sqlite3GlobalConfig.bFullMutex==0 );
  136378. sqlite3_mutex_leave(db->mutex);
  136379. }
  136380. rc = sqlite3_errcode(db);
  136381. assert( db!=0 || rc==SQLITE_NOMEM );
  136382. if( rc==SQLITE_NOMEM ){
  136383. sqlite3_close(db);
  136384. db = 0;
  136385. }else if( rc!=SQLITE_OK ){
  136386. db->magic = SQLITE_MAGIC_SICK;
  136387. }
  136388. *ppDb = db;
  136389. #ifdef SQLITE_ENABLE_SQLLOG
  136390. if( sqlite3GlobalConfig.xSqllog ){
  136391. /* Opening a db handle. Fourth parameter is passed 0. */
  136392. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  136393. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  136394. }
  136395. #endif
  136396. #if defined(SQLITE_HAS_CODEC)
  136397. if( rc==SQLITE_OK ){
  136398. const char *zKey;
  136399. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  136400. u8 iByte;
  136401. int i;
  136402. char zDecoded[40];
  136403. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  136404. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  136405. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  136406. }
  136407. sqlite3_key_v2(db, 0, zDecoded, i/2);
  136408. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  136409. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  136410. }
  136411. }
  136412. #endif
  136413. sqlite3_free(zOpen);
  136414. return rc & 0xff;
  136415. }
  136416. /*
  136417. ** Open a new database handle.
  136418. */
  136419. SQLITE_API int sqlite3_open(
  136420. const char *zFilename,
  136421. sqlite3 **ppDb
  136422. ){
  136423. return openDatabase(zFilename, ppDb,
  136424. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  136425. }
  136426. SQLITE_API int sqlite3_open_v2(
  136427. const char *filename, /* Database filename (UTF-8) */
  136428. sqlite3 **ppDb, /* OUT: SQLite db handle */
  136429. int flags, /* Flags */
  136430. const char *zVfs /* Name of VFS module to use */
  136431. ){
  136432. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  136433. }
  136434. #ifndef SQLITE_OMIT_UTF16
  136435. /*
  136436. ** Open a new database handle.
  136437. */
  136438. SQLITE_API int sqlite3_open16(
  136439. const void *zFilename,
  136440. sqlite3 **ppDb
  136441. ){
  136442. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  136443. sqlite3_value *pVal;
  136444. int rc;
  136445. #ifdef SQLITE_ENABLE_API_ARMOR
  136446. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  136447. #endif
  136448. *ppDb = 0;
  136449. #ifndef SQLITE_OMIT_AUTOINIT
  136450. rc = sqlite3_initialize();
  136451. if( rc ) return rc;
  136452. #endif
  136453. if( zFilename==0 ) zFilename = "\000\000";
  136454. pVal = sqlite3ValueNew(0);
  136455. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  136456. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  136457. if( zFilename8 ){
  136458. rc = openDatabase(zFilename8, ppDb,
  136459. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  136460. assert( *ppDb || rc==SQLITE_NOMEM );
  136461. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  136462. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  136463. }
  136464. }else{
  136465. rc = SQLITE_NOMEM_BKPT;
  136466. }
  136467. sqlite3ValueFree(pVal);
  136468. return rc & 0xff;
  136469. }
  136470. #endif /* SQLITE_OMIT_UTF16 */
  136471. /*
  136472. ** Register a new collation sequence with the database handle db.
  136473. */
  136474. SQLITE_API int sqlite3_create_collation(
  136475. sqlite3* db,
  136476. const char *zName,
  136477. int enc,
  136478. void* pCtx,
  136479. int(*xCompare)(void*,int,const void*,int,const void*)
  136480. ){
  136481. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  136482. }
  136483. /*
  136484. ** Register a new collation sequence with the database handle db.
  136485. */
  136486. SQLITE_API int sqlite3_create_collation_v2(
  136487. sqlite3* db,
  136488. const char *zName,
  136489. int enc,
  136490. void* pCtx,
  136491. int(*xCompare)(void*,int,const void*,int,const void*),
  136492. void(*xDel)(void*)
  136493. ){
  136494. int rc;
  136495. #ifdef SQLITE_ENABLE_API_ARMOR
  136496. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  136497. #endif
  136498. sqlite3_mutex_enter(db->mutex);
  136499. assert( !db->mallocFailed );
  136500. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  136501. rc = sqlite3ApiExit(db, rc);
  136502. sqlite3_mutex_leave(db->mutex);
  136503. return rc;
  136504. }
  136505. #ifndef SQLITE_OMIT_UTF16
  136506. /*
  136507. ** Register a new collation sequence with the database handle db.
  136508. */
  136509. SQLITE_API int sqlite3_create_collation16(
  136510. sqlite3* db,
  136511. const void *zName,
  136512. int enc,
  136513. void* pCtx,
  136514. int(*xCompare)(void*,int,const void*,int,const void*)
  136515. ){
  136516. int rc = SQLITE_OK;
  136517. char *zName8;
  136518. #ifdef SQLITE_ENABLE_API_ARMOR
  136519. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  136520. #endif
  136521. sqlite3_mutex_enter(db->mutex);
  136522. assert( !db->mallocFailed );
  136523. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  136524. if( zName8 ){
  136525. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  136526. sqlite3DbFree(db, zName8);
  136527. }
  136528. rc = sqlite3ApiExit(db, rc);
  136529. sqlite3_mutex_leave(db->mutex);
  136530. return rc;
  136531. }
  136532. #endif /* SQLITE_OMIT_UTF16 */
  136533. /*
  136534. ** Register a collation sequence factory callback with the database handle
  136535. ** db. Replace any previously installed collation sequence factory.
  136536. */
  136537. SQLITE_API int sqlite3_collation_needed(
  136538. sqlite3 *db,
  136539. void *pCollNeededArg,
  136540. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  136541. ){
  136542. #ifdef SQLITE_ENABLE_API_ARMOR
  136543. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  136544. #endif
  136545. sqlite3_mutex_enter(db->mutex);
  136546. db->xCollNeeded = xCollNeeded;
  136547. db->xCollNeeded16 = 0;
  136548. db->pCollNeededArg = pCollNeededArg;
  136549. sqlite3_mutex_leave(db->mutex);
  136550. return SQLITE_OK;
  136551. }
  136552. #ifndef SQLITE_OMIT_UTF16
  136553. /*
  136554. ** Register a collation sequence factory callback with the database handle
  136555. ** db. Replace any previously installed collation sequence factory.
  136556. */
  136557. SQLITE_API int sqlite3_collation_needed16(
  136558. sqlite3 *db,
  136559. void *pCollNeededArg,
  136560. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  136561. ){
  136562. #ifdef SQLITE_ENABLE_API_ARMOR
  136563. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  136564. #endif
  136565. sqlite3_mutex_enter(db->mutex);
  136566. db->xCollNeeded = 0;
  136567. db->xCollNeeded16 = xCollNeeded16;
  136568. db->pCollNeededArg = pCollNeededArg;
  136569. sqlite3_mutex_leave(db->mutex);
  136570. return SQLITE_OK;
  136571. }
  136572. #endif /* SQLITE_OMIT_UTF16 */
  136573. #ifndef SQLITE_OMIT_DEPRECATED
  136574. /*
  136575. ** This function is now an anachronism. It used to be used to recover from a
  136576. ** malloc() failure, but SQLite now does this automatically.
  136577. */
  136578. SQLITE_API int sqlite3_global_recover(void){
  136579. return SQLITE_OK;
  136580. }
  136581. #endif
  136582. /*
  136583. ** Test to see whether or not the database connection is in autocommit
  136584. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  136585. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  136586. ** by the next COMMIT or ROLLBACK.
  136587. */
  136588. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  136589. #ifdef SQLITE_ENABLE_API_ARMOR
  136590. if( !sqlite3SafetyCheckOk(db) ){
  136591. (void)SQLITE_MISUSE_BKPT;
  136592. return 0;
  136593. }
  136594. #endif
  136595. return db->autoCommit;
  136596. }
  136597. /*
  136598. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  136599. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  136600. ** constants. They serve two purposes:
  136601. **
  136602. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  136603. ** to detect when version error conditions occurs.
  136604. **
  136605. ** 2. Invoke sqlite3_log() to provide the source code location where
  136606. ** a low-level error is first detected.
  136607. */
  136608. static int reportError(int iErr, int lineno, const char *zType){
  136609. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  136610. zType, lineno, 20+sqlite3_sourceid());
  136611. return iErr;
  136612. }
  136613. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  136614. testcase( sqlite3GlobalConfig.xLog!=0 );
  136615. return reportError(SQLITE_CORRUPT, lineno, "database corruption");
  136616. }
  136617. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  136618. testcase( sqlite3GlobalConfig.xLog!=0 );
  136619. return reportError(SQLITE_MISUSE, lineno, "misuse");
  136620. }
  136621. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  136622. testcase( sqlite3GlobalConfig.xLog!=0 );
  136623. return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  136624. }
  136625. #ifdef SQLITE_DEBUG
  136626. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  136627. char zMsg[100];
  136628. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  136629. testcase( sqlite3GlobalConfig.xLog!=0 );
  136630. return reportError(SQLITE_CORRUPT, lineno, zMsg);
  136631. }
  136632. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  136633. testcase( sqlite3GlobalConfig.xLog!=0 );
  136634. return reportError(SQLITE_NOMEM, lineno, "OOM");
  136635. }
  136636. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  136637. testcase( sqlite3GlobalConfig.xLog!=0 );
  136638. return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  136639. }
  136640. #endif
  136641. #ifndef SQLITE_OMIT_DEPRECATED
  136642. /*
  136643. ** This is a convenience routine that makes sure that all thread-specific
  136644. ** data for this thread has been deallocated.
  136645. **
  136646. ** SQLite no longer uses thread-specific data so this routine is now a
  136647. ** no-op. It is retained for historical compatibility.
  136648. */
  136649. SQLITE_API void sqlite3_thread_cleanup(void){
  136650. }
  136651. #endif
  136652. /*
  136653. ** Return meta information about a specific column of a database table.
  136654. ** See comment in sqlite3.h (sqlite.h.in) for details.
  136655. */
  136656. SQLITE_API int sqlite3_table_column_metadata(
  136657. sqlite3 *db, /* Connection handle */
  136658. const char *zDbName, /* Database name or NULL */
  136659. const char *zTableName, /* Table name */
  136660. const char *zColumnName, /* Column name */
  136661. char const **pzDataType, /* OUTPUT: Declared data type */
  136662. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  136663. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  136664. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  136665. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  136666. ){
  136667. int rc;
  136668. char *zErrMsg = 0;
  136669. Table *pTab = 0;
  136670. Column *pCol = 0;
  136671. int iCol = 0;
  136672. char const *zDataType = 0;
  136673. char const *zCollSeq = 0;
  136674. int notnull = 0;
  136675. int primarykey = 0;
  136676. int autoinc = 0;
  136677. #ifdef SQLITE_ENABLE_API_ARMOR
  136678. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  136679. return SQLITE_MISUSE_BKPT;
  136680. }
  136681. #endif
  136682. /* Ensure the database schema has been loaded */
  136683. sqlite3_mutex_enter(db->mutex);
  136684. sqlite3BtreeEnterAll(db);
  136685. rc = sqlite3Init(db, &zErrMsg);
  136686. if( SQLITE_OK!=rc ){
  136687. goto error_out;
  136688. }
  136689. /* Locate the table in question */
  136690. pTab = sqlite3FindTable(db, zTableName, zDbName);
  136691. if( !pTab || pTab->pSelect ){
  136692. pTab = 0;
  136693. goto error_out;
  136694. }
  136695. /* Find the column for which info is requested */
  136696. if( zColumnName==0 ){
  136697. /* Query for existance of table only */
  136698. }else{
  136699. for(iCol=0; iCol<pTab->nCol; iCol++){
  136700. pCol = &pTab->aCol[iCol];
  136701. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  136702. break;
  136703. }
  136704. }
  136705. if( iCol==pTab->nCol ){
  136706. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  136707. iCol = pTab->iPKey;
  136708. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  136709. }else{
  136710. pTab = 0;
  136711. goto error_out;
  136712. }
  136713. }
  136714. }
  136715. /* The following block stores the meta information that will be returned
  136716. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  136717. ** and autoinc. At this point there are two possibilities:
  136718. **
  136719. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  136720. ** and there is no explicitly declared IPK column.
  136721. **
  136722. ** 2. The table is not a view and the column name identified an
  136723. ** explicitly declared column. Copy meta information from *pCol.
  136724. */
  136725. if( pCol ){
  136726. zDataType = sqlite3ColumnType(pCol,0);
  136727. zCollSeq = pCol->zColl;
  136728. notnull = pCol->notNull!=0;
  136729. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  136730. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  136731. }else{
  136732. zDataType = "INTEGER";
  136733. primarykey = 1;
  136734. }
  136735. if( !zCollSeq ){
  136736. zCollSeq = sqlite3StrBINARY;
  136737. }
  136738. error_out:
  136739. sqlite3BtreeLeaveAll(db);
  136740. /* Whether the function call succeeded or failed, set the output parameters
  136741. ** to whatever their local counterparts contain. If an error did occur,
  136742. ** this has the effect of zeroing all output parameters.
  136743. */
  136744. if( pzDataType ) *pzDataType = zDataType;
  136745. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  136746. if( pNotNull ) *pNotNull = notnull;
  136747. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  136748. if( pAutoinc ) *pAutoinc = autoinc;
  136749. if( SQLITE_OK==rc && !pTab ){
  136750. sqlite3DbFree(db, zErrMsg);
  136751. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  136752. zColumnName);
  136753. rc = SQLITE_ERROR;
  136754. }
  136755. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  136756. sqlite3DbFree(db, zErrMsg);
  136757. rc = sqlite3ApiExit(db, rc);
  136758. sqlite3_mutex_leave(db->mutex);
  136759. return rc;
  136760. }
  136761. /*
  136762. ** Sleep for a little while. Return the amount of time slept.
  136763. */
  136764. SQLITE_API int sqlite3_sleep(int ms){
  136765. sqlite3_vfs *pVfs;
  136766. int rc;
  136767. pVfs = sqlite3_vfs_find(0);
  136768. if( pVfs==0 ) return 0;
  136769. /* This function works in milliseconds, but the underlying OsSleep()
  136770. ** API uses microseconds. Hence the 1000's.
  136771. */
  136772. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  136773. return rc;
  136774. }
  136775. /*
  136776. ** Enable or disable the extended result codes.
  136777. */
  136778. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  136779. #ifdef SQLITE_ENABLE_API_ARMOR
  136780. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  136781. #endif
  136782. sqlite3_mutex_enter(db->mutex);
  136783. db->errMask = onoff ? 0xffffffff : 0xff;
  136784. sqlite3_mutex_leave(db->mutex);
  136785. return SQLITE_OK;
  136786. }
  136787. /*
  136788. ** Invoke the xFileControl method on a particular database.
  136789. */
  136790. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  136791. int rc = SQLITE_ERROR;
  136792. Btree *pBtree;
  136793. #ifdef SQLITE_ENABLE_API_ARMOR
  136794. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  136795. #endif
  136796. sqlite3_mutex_enter(db->mutex);
  136797. pBtree = sqlite3DbNameToBtree(db, zDbName);
  136798. if( pBtree ){
  136799. Pager *pPager;
  136800. sqlite3_file *fd;
  136801. sqlite3BtreeEnter(pBtree);
  136802. pPager = sqlite3BtreePager(pBtree);
  136803. assert( pPager!=0 );
  136804. fd = sqlite3PagerFile(pPager);
  136805. assert( fd!=0 );
  136806. if( op==SQLITE_FCNTL_FILE_POINTER ){
  136807. *(sqlite3_file**)pArg = fd;
  136808. rc = SQLITE_OK;
  136809. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  136810. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  136811. rc = SQLITE_OK;
  136812. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  136813. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  136814. rc = SQLITE_OK;
  136815. }else if( fd->pMethods ){
  136816. rc = sqlite3OsFileControl(fd, op, pArg);
  136817. }else{
  136818. rc = SQLITE_NOTFOUND;
  136819. }
  136820. sqlite3BtreeLeave(pBtree);
  136821. }
  136822. sqlite3_mutex_leave(db->mutex);
  136823. return rc;
  136824. }
  136825. /*
  136826. ** Interface to the testing logic.
  136827. */
  136828. SQLITE_API int sqlite3_test_control(int op, ...){
  136829. int rc = 0;
  136830. #ifdef SQLITE_UNTESTABLE
  136831. UNUSED_PARAMETER(op);
  136832. #else
  136833. va_list ap;
  136834. va_start(ap, op);
  136835. switch( op ){
  136836. /*
  136837. ** Save the current state of the PRNG.
  136838. */
  136839. case SQLITE_TESTCTRL_PRNG_SAVE: {
  136840. sqlite3PrngSaveState();
  136841. break;
  136842. }
  136843. /*
  136844. ** Restore the state of the PRNG to the last state saved using
  136845. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  136846. ** this verb acts like PRNG_RESET.
  136847. */
  136848. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  136849. sqlite3PrngRestoreState();
  136850. break;
  136851. }
  136852. /*
  136853. ** Reset the PRNG back to its uninitialized state. The next call
  136854. ** to sqlite3_randomness() will reseed the PRNG using a single call
  136855. ** to the xRandomness method of the default VFS.
  136856. */
  136857. case SQLITE_TESTCTRL_PRNG_RESET: {
  136858. sqlite3_randomness(0,0);
  136859. break;
  136860. }
  136861. /*
  136862. ** sqlite3_test_control(BITVEC_TEST, size, program)
  136863. **
  136864. ** Run a test against a Bitvec object of size. The program argument
  136865. ** is an array of integers that defines the test. Return -1 on a
  136866. ** memory allocation error, 0 on success, or non-zero for an error.
  136867. ** See the sqlite3BitvecBuiltinTest() for additional information.
  136868. */
  136869. case SQLITE_TESTCTRL_BITVEC_TEST: {
  136870. int sz = va_arg(ap, int);
  136871. int *aProg = va_arg(ap, int*);
  136872. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  136873. break;
  136874. }
  136875. /*
  136876. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  136877. **
  136878. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  136879. ** if xCallback is not NULL.
  136880. **
  136881. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  136882. ** is called immediately after installing the new callback and the return
  136883. ** value from sqlite3FaultSim(0) becomes the return from
  136884. ** sqlite3_test_control().
  136885. */
  136886. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  136887. /* MSVC is picky about pulling func ptrs from va lists.
  136888. ** http://support.microsoft.com/kb/47961
  136889. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  136890. */
  136891. typedef int(*TESTCALLBACKFUNC_t)(int);
  136892. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  136893. rc = sqlite3FaultSim(0);
  136894. break;
  136895. }
  136896. /*
  136897. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  136898. **
  136899. ** Register hooks to call to indicate which malloc() failures
  136900. ** are benign.
  136901. */
  136902. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  136903. typedef void (*void_function)(void);
  136904. void_function xBenignBegin;
  136905. void_function xBenignEnd;
  136906. xBenignBegin = va_arg(ap, void_function);
  136907. xBenignEnd = va_arg(ap, void_function);
  136908. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  136909. break;
  136910. }
  136911. /*
  136912. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  136913. **
  136914. ** Set the PENDING byte to the value in the argument, if X>0.
  136915. ** Make no changes if X==0. Return the value of the pending byte
  136916. ** as it existing before this routine was called.
  136917. **
  136918. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  136919. ** an incompatible database file format. Changing the PENDING byte
  136920. ** while any database connection is open results in undefined and
  136921. ** deleterious behavior.
  136922. */
  136923. case SQLITE_TESTCTRL_PENDING_BYTE: {
  136924. rc = PENDING_BYTE;
  136925. #ifndef SQLITE_OMIT_WSD
  136926. {
  136927. unsigned int newVal = va_arg(ap, unsigned int);
  136928. if( newVal ) sqlite3PendingByte = newVal;
  136929. }
  136930. #endif
  136931. break;
  136932. }
  136933. /*
  136934. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  136935. **
  136936. ** This action provides a run-time test to see whether or not
  136937. ** assert() was enabled at compile-time. If X is true and assert()
  136938. ** is enabled, then the return value is true. If X is true and
  136939. ** assert() is disabled, then the return value is zero. If X is
  136940. ** false and assert() is enabled, then the assertion fires and the
  136941. ** process aborts. If X is false and assert() is disabled, then the
  136942. ** return value is zero.
  136943. */
  136944. case SQLITE_TESTCTRL_ASSERT: {
  136945. volatile int x = 0;
  136946. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  136947. rc = x;
  136948. break;
  136949. }
  136950. /*
  136951. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  136952. **
  136953. ** This action provides a run-time test to see how the ALWAYS and
  136954. ** NEVER macros were defined at compile-time.
  136955. **
  136956. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  136957. **
  136958. ** The recommended test is X==2. If the return value is 2, that means
  136959. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  136960. ** default setting. If the return value is 1, then ALWAYS() is either
  136961. ** hard-coded to true or else it asserts if its argument is false.
  136962. ** The first behavior (hard-coded to true) is the case if
  136963. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  136964. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  136965. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  136966. **
  136967. ** The run-time test procedure might look something like this:
  136968. **
  136969. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  136970. ** // ALWAYS() and NEVER() are no-op pass-through macros
  136971. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  136972. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  136973. ** }else{
  136974. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  136975. ** }
  136976. */
  136977. case SQLITE_TESTCTRL_ALWAYS: {
  136978. int x = va_arg(ap,int);
  136979. rc = x ? ALWAYS(x) : 0;
  136980. break;
  136981. }
  136982. /*
  136983. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  136984. **
  136985. ** The integer returned reveals the byte-order of the computer on which
  136986. ** SQLite is running:
  136987. **
  136988. ** 1 big-endian, determined at run-time
  136989. ** 10 little-endian, determined at run-time
  136990. ** 432101 big-endian, determined at compile-time
  136991. ** 123410 little-endian, determined at compile-time
  136992. */
  136993. case SQLITE_TESTCTRL_BYTEORDER: {
  136994. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  136995. break;
  136996. }
  136997. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  136998. **
  136999. ** Set the nReserve size to N for the main database on the database
  137000. ** connection db.
  137001. */
  137002. case SQLITE_TESTCTRL_RESERVE: {
  137003. sqlite3 *db = va_arg(ap, sqlite3*);
  137004. int x = va_arg(ap,int);
  137005. sqlite3_mutex_enter(db->mutex);
  137006. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  137007. sqlite3_mutex_leave(db->mutex);
  137008. break;
  137009. }
  137010. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  137011. **
  137012. ** Enable or disable various optimizations for testing purposes. The
  137013. ** argument N is a bitmask of optimizations to be disabled. For normal
  137014. ** operation N should be 0. The idea is that a test program (like the
  137015. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  137016. ** with various optimizations disabled to verify that the same answer
  137017. ** is obtained in every case.
  137018. */
  137019. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  137020. sqlite3 *db = va_arg(ap, sqlite3*);
  137021. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  137022. break;
  137023. }
  137024. #ifdef SQLITE_N_KEYWORD
  137025. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  137026. **
  137027. ** If zWord is a keyword recognized by the parser, then return the
  137028. ** number of keywords. Or if zWord is not a keyword, return 0.
  137029. **
  137030. ** This test feature is only available in the amalgamation since
  137031. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  137032. ** is built using separate source files.
  137033. */
  137034. case SQLITE_TESTCTRL_ISKEYWORD: {
  137035. const char *zWord = va_arg(ap, const char*);
  137036. int n = sqlite3Strlen30(zWord);
  137037. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  137038. break;
  137039. }
  137040. #endif
  137041. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  137042. **
  137043. ** If parameter onoff is non-zero, configure the wrappers so that all
  137044. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  137045. ** undo this setting.
  137046. */
  137047. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  137048. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  137049. break;
  137050. }
  137051. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  137052. **
  137053. ** Set or clear a flag that indicates that the database file is always well-
  137054. ** formed and never corrupt. This flag is clear by default, indicating that
  137055. ** database files might have arbitrary corruption. Setting the flag during
  137056. ** testing causes certain assert() statements in the code to be activated
  137057. ** that demonstrat invariants on well-formed database files.
  137058. */
  137059. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  137060. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  137061. break;
  137062. }
  137063. /* Set the threshold at which OP_Once counters reset back to zero.
  137064. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  137065. ** too big to test in a reasonable amount of time, so this control is
  137066. ** provided to set a small and easily reachable reset value.
  137067. */
  137068. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  137069. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  137070. break;
  137071. }
  137072. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  137073. **
  137074. ** Set the VDBE coverage callback function to xCallback with context
  137075. ** pointer ptr.
  137076. */
  137077. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  137078. #ifdef SQLITE_VDBE_COVERAGE
  137079. typedef void (*branch_callback)(void*,int,u8,u8);
  137080. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  137081. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  137082. #endif
  137083. break;
  137084. }
  137085. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  137086. case SQLITE_TESTCTRL_SORTER_MMAP: {
  137087. sqlite3 *db = va_arg(ap, sqlite3*);
  137088. db->nMaxSorterMmap = va_arg(ap, int);
  137089. break;
  137090. }
  137091. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  137092. **
  137093. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  137094. ** not.
  137095. */
  137096. case SQLITE_TESTCTRL_ISINIT: {
  137097. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  137098. break;
  137099. }
  137100. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  137101. **
  137102. ** This test control is used to create imposter tables. "db" is a pointer
  137103. ** to the database connection. dbName is the database name (ex: "main" or
  137104. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  137105. ** or off. "tnum" is the root page of the b-tree to which the imposter
  137106. ** table should connect.
  137107. **
  137108. ** Enable imposter mode only when the schema has already been parsed. Then
  137109. ** run a single CREATE TABLE statement to construct the imposter table in
  137110. ** the parsed schema. Then turn imposter mode back off again.
  137111. **
  137112. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  137113. ** the schema to be reparsed the next time it is needed. This has the
  137114. ** effect of erasing all imposter tables.
  137115. */
  137116. case SQLITE_TESTCTRL_IMPOSTER: {
  137117. sqlite3 *db = va_arg(ap, sqlite3*);
  137118. sqlite3_mutex_enter(db->mutex);
  137119. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  137120. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  137121. db->init.newTnum = va_arg(ap,int);
  137122. if( db->init.busy==0 && db->init.newTnum>0 ){
  137123. sqlite3ResetAllSchemasOfConnection(db);
  137124. }
  137125. sqlite3_mutex_leave(db->mutex);
  137126. break;
  137127. }
  137128. }
  137129. va_end(ap);
  137130. #endif /* SQLITE_UNTESTABLE */
  137131. return rc;
  137132. }
  137133. /*
  137134. ** This is a utility routine, useful to VFS implementations, that checks
  137135. ** to see if a database file was a URI that contained a specific query
  137136. ** parameter, and if so obtains the value of the query parameter.
  137137. **
  137138. ** The zFilename argument is the filename pointer passed into the xOpen()
  137139. ** method of a VFS implementation. The zParam argument is the name of the
  137140. ** query parameter we seek. This routine returns the value of the zParam
  137141. ** parameter if it exists. If the parameter does not exist, this routine
  137142. ** returns a NULL pointer.
  137143. */
  137144. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  137145. if( zFilename==0 || zParam==0 ) return 0;
  137146. zFilename += sqlite3Strlen30(zFilename) + 1;
  137147. while( zFilename[0] ){
  137148. int x = strcmp(zFilename, zParam);
  137149. zFilename += sqlite3Strlen30(zFilename) + 1;
  137150. if( x==0 ) return zFilename;
  137151. zFilename += sqlite3Strlen30(zFilename) + 1;
  137152. }
  137153. return 0;
  137154. }
  137155. /*
  137156. ** Return a boolean value for a query parameter.
  137157. */
  137158. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  137159. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  137160. bDflt = bDflt!=0;
  137161. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  137162. }
  137163. /*
  137164. ** Return a 64-bit integer value for a query parameter.
  137165. */
  137166. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  137167. const char *zFilename, /* Filename as passed to xOpen */
  137168. const char *zParam, /* URI parameter sought */
  137169. sqlite3_int64 bDflt /* return if parameter is missing */
  137170. ){
  137171. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  137172. sqlite3_int64 v;
  137173. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  137174. bDflt = v;
  137175. }
  137176. return bDflt;
  137177. }
  137178. /*
  137179. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  137180. */
  137181. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  137182. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  137183. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  137184. }
  137185. /*
  137186. ** Return the filename of the database associated with a database
  137187. ** connection.
  137188. */
  137189. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  137190. Btree *pBt;
  137191. #ifdef SQLITE_ENABLE_API_ARMOR
  137192. if( !sqlite3SafetyCheckOk(db) ){
  137193. (void)SQLITE_MISUSE_BKPT;
  137194. return 0;
  137195. }
  137196. #endif
  137197. pBt = sqlite3DbNameToBtree(db, zDbName);
  137198. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  137199. }
  137200. /*
  137201. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  137202. ** no such database exists.
  137203. */
  137204. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  137205. Btree *pBt;
  137206. #ifdef SQLITE_ENABLE_API_ARMOR
  137207. if( !sqlite3SafetyCheckOk(db) ){
  137208. (void)SQLITE_MISUSE_BKPT;
  137209. return -1;
  137210. }
  137211. #endif
  137212. pBt = sqlite3DbNameToBtree(db, zDbName);
  137213. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  137214. }
  137215. #ifdef SQLITE_ENABLE_SNAPSHOT
  137216. /*
  137217. ** Obtain a snapshot handle for the snapshot of database zDb currently
  137218. ** being read by handle db.
  137219. */
  137220. SQLITE_API int sqlite3_snapshot_get(
  137221. sqlite3 *db,
  137222. const char *zDb,
  137223. sqlite3_snapshot **ppSnapshot
  137224. ){
  137225. int rc = SQLITE_ERROR;
  137226. #ifndef SQLITE_OMIT_WAL
  137227. #ifdef SQLITE_ENABLE_API_ARMOR
  137228. if( !sqlite3SafetyCheckOk(db) ){
  137229. return SQLITE_MISUSE_BKPT;
  137230. }
  137231. #endif
  137232. sqlite3_mutex_enter(db->mutex);
  137233. if( db->autoCommit==0 ){
  137234. int iDb = sqlite3FindDbName(db, zDb);
  137235. if( iDb==0 || iDb>1 ){
  137236. Btree *pBt = db->aDb[iDb].pBt;
  137237. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  137238. rc = sqlite3BtreeBeginTrans(pBt, 0);
  137239. if( rc==SQLITE_OK ){
  137240. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  137241. }
  137242. }
  137243. }
  137244. }
  137245. sqlite3_mutex_leave(db->mutex);
  137246. #endif /* SQLITE_OMIT_WAL */
  137247. return rc;
  137248. }
  137249. /*
  137250. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  137251. */
  137252. SQLITE_API int sqlite3_snapshot_open(
  137253. sqlite3 *db,
  137254. const char *zDb,
  137255. sqlite3_snapshot *pSnapshot
  137256. ){
  137257. int rc = SQLITE_ERROR;
  137258. #ifndef SQLITE_OMIT_WAL
  137259. #ifdef SQLITE_ENABLE_API_ARMOR
  137260. if( !sqlite3SafetyCheckOk(db) ){
  137261. return SQLITE_MISUSE_BKPT;
  137262. }
  137263. #endif
  137264. sqlite3_mutex_enter(db->mutex);
  137265. if( db->autoCommit==0 ){
  137266. int iDb;
  137267. iDb = sqlite3FindDbName(db, zDb);
  137268. if( iDb==0 || iDb>1 ){
  137269. Btree *pBt = db->aDb[iDb].pBt;
  137270. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  137271. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  137272. if( rc==SQLITE_OK ){
  137273. rc = sqlite3BtreeBeginTrans(pBt, 0);
  137274. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  137275. }
  137276. }
  137277. }
  137278. }
  137279. sqlite3_mutex_leave(db->mutex);
  137280. #endif /* SQLITE_OMIT_WAL */
  137281. return rc;
  137282. }
  137283. /*
  137284. ** Recover as many snapshots as possible from the wal file associated with
  137285. ** schema zDb of database db.
  137286. */
  137287. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  137288. int rc = SQLITE_ERROR;
  137289. int iDb;
  137290. #ifndef SQLITE_OMIT_WAL
  137291. #ifdef SQLITE_ENABLE_API_ARMOR
  137292. if( !sqlite3SafetyCheckOk(db) ){
  137293. return SQLITE_MISUSE_BKPT;
  137294. }
  137295. #endif
  137296. sqlite3_mutex_enter(db->mutex);
  137297. iDb = sqlite3FindDbName(db, zDb);
  137298. if( iDb==0 || iDb>1 ){
  137299. Btree *pBt = db->aDb[iDb].pBt;
  137300. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  137301. rc = sqlite3BtreeBeginTrans(pBt, 0);
  137302. if( rc==SQLITE_OK ){
  137303. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  137304. sqlite3BtreeCommit(pBt);
  137305. }
  137306. }
  137307. }
  137308. sqlite3_mutex_leave(db->mutex);
  137309. #endif /* SQLITE_OMIT_WAL */
  137310. return rc;
  137311. }
  137312. /*
  137313. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  137314. */
  137315. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  137316. sqlite3_free(pSnapshot);
  137317. }
  137318. #endif /* SQLITE_ENABLE_SNAPSHOT */
  137319. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  137320. /*
  137321. ** Given the name of a compile-time option, return true if that option
  137322. ** was used and false if not.
  137323. **
  137324. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  137325. ** is not required for a match.
  137326. */
  137327. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  137328. int i, n;
  137329. int nOpt;
  137330. const char **azCompileOpt;
  137331. #if SQLITE_ENABLE_API_ARMOR
  137332. if( zOptName==0 ){
  137333. (void)SQLITE_MISUSE_BKPT;
  137334. return 0;
  137335. }
  137336. #endif
  137337. azCompileOpt = sqlite3CompileOptions(&nOpt);
  137338. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  137339. n = sqlite3Strlen30(zOptName);
  137340. /* Since nOpt is normally in single digits, a linear search is
  137341. ** adequate. No need for a binary search. */
  137342. for(i=0; i<nOpt; i++){
  137343. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  137344. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  137345. ){
  137346. return 1;
  137347. }
  137348. }
  137349. return 0;
  137350. }
  137351. /*
  137352. ** Return the N-th compile-time option string. If N is out of range,
  137353. ** return a NULL pointer.
  137354. */
  137355. SQLITE_API const char *sqlite3_compileoption_get(int N){
  137356. int nOpt;
  137357. const char **azCompileOpt;
  137358. azCompileOpt = sqlite3CompileOptions(&nOpt);
  137359. if( N>=0 && N<nOpt ){
  137360. return azCompileOpt[N];
  137361. }
  137362. return 0;
  137363. }
  137364. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  137365. /************** End of main.c ************************************************/
  137366. /************** Begin file notify.c ******************************************/
  137367. /*
  137368. ** 2009 March 3
  137369. **
  137370. ** The author disclaims copyright to this source code. In place of
  137371. ** a legal notice, here is a blessing:
  137372. **
  137373. ** May you do good and not evil.
  137374. ** May you find forgiveness for yourself and forgive others.
  137375. ** May you share freely, never taking more than you give.
  137376. **
  137377. *************************************************************************
  137378. **
  137379. ** This file contains the implementation of the sqlite3_unlock_notify()
  137380. ** API method and its associated functionality.
  137381. */
  137382. /* #include "sqliteInt.h" */
  137383. /* #include "btreeInt.h" */
  137384. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  137385. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  137386. /*
  137387. ** Public interfaces:
  137388. **
  137389. ** sqlite3ConnectionBlocked()
  137390. ** sqlite3ConnectionUnlocked()
  137391. ** sqlite3ConnectionClosed()
  137392. ** sqlite3_unlock_notify()
  137393. */
  137394. #define assertMutexHeld() \
  137395. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  137396. /*
  137397. ** Head of a linked list of all sqlite3 objects created by this process
  137398. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  137399. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  137400. ** mutex is held.
  137401. */
  137402. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  137403. #ifndef NDEBUG
  137404. /*
  137405. ** This function is a complex assert() that verifies the following
  137406. ** properties of the blocked connections list:
  137407. **
  137408. ** 1) Each entry in the list has a non-NULL value for either
  137409. ** pUnlockConnection or pBlockingConnection, or both.
  137410. **
  137411. ** 2) All entries in the list that share a common value for
  137412. ** xUnlockNotify are grouped together.
  137413. **
  137414. ** 3) If the argument db is not NULL, then none of the entries in the
  137415. ** blocked connections list have pUnlockConnection or pBlockingConnection
  137416. ** set to db. This is used when closing connection db.
  137417. */
  137418. static void checkListProperties(sqlite3 *db){
  137419. sqlite3 *p;
  137420. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  137421. int seen = 0;
  137422. sqlite3 *p2;
  137423. /* Verify property (1) */
  137424. assert( p->pUnlockConnection || p->pBlockingConnection );
  137425. /* Verify property (2) */
  137426. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  137427. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  137428. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  137429. assert( db==0 || p->pUnlockConnection!=db );
  137430. assert( db==0 || p->pBlockingConnection!=db );
  137431. }
  137432. }
  137433. }
  137434. #else
  137435. # define checkListProperties(x)
  137436. #endif
  137437. /*
  137438. ** Remove connection db from the blocked connections list. If connection
  137439. ** db is not currently a part of the list, this function is a no-op.
  137440. */
  137441. static void removeFromBlockedList(sqlite3 *db){
  137442. sqlite3 **pp;
  137443. assertMutexHeld();
  137444. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  137445. if( *pp==db ){
  137446. *pp = (*pp)->pNextBlocked;
  137447. break;
  137448. }
  137449. }
  137450. }
  137451. /*
  137452. ** Add connection db to the blocked connections list. It is assumed
  137453. ** that it is not already a part of the list.
  137454. */
  137455. static void addToBlockedList(sqlite3 *db){
  137456. sqlite3 **pp;
  137457. assertMutexHeld();
  137458. for(
  137459. pp=&sqlite3BlockedList;
  137460. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  137461. pp=&(*pp)->pNextBlocked
  137462. );
  137463. db->pNextBlocked = *pp;
  137464. *pp = db;
  137465. }
  137466. /*
  137467. ** Obtain the STATIC_MASTER mutex.
  137468. */
  137469. static void enterMutex(void){
  137470. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  137471. checkListProperties(0);
  137472. }
  137473. /*
  137474. ** Release the STATIC_MASTER mutex.
  137475. */
  137476. static void leaveMutex(void){
  137477. assertMutexHeld();
  137478. checkListProperties(0);
  137479. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  137480. }
  137481. /*
  137482. ** Register an unlock-notify callback.
  137483. **
  137484. ** This is called after connection "db" has attempted some operation
  137485. ** but has received an SQLITE_LOCKED error because another connection
  137486. ** (call it pOther) in the same process was busy using the same shared
  137487. ** cache. pOther is found by looking at db->pBlockingConnection.
  137488. **
  137489. ** If there is no blocking connection, the callback is invoked immediately,
  137490. ** before this routine returns.
  137491. **
  137492. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  137493. ** a deadlock.
  137494. **
  137495. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  137496. ** its locks.
  137497. **
  137498. ** Each call to this routine overrides any prior callbacks registered
  137499. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  137500. ** cancelled.
  137501. */
  137502. SQLITE_API int sqlite3_unlock_notify(
  137503. sqlite3 *db,
  137504. void (*xNotify)(void **, int),
  137505. void *pArg
  137506. ){
  137507. int rc = SQLITE_OK;
  137508. sqlite3_mutex_enter(db->mutex);
  137509. enterMutex();
  137510. if( xNotify==0 ){
  137511. removeFromBlockedList(db);
  137512. db->pBlockingConnection = 0;
  137513. db->pUnlockConnection = 0;
  137514. db->xUnlockNotify = 0;
  137515. db->pUnlockArg = 0;
  137516. }else if( 0==db->pBlockingConnection ){
  137517. /* The blocking transaction has been concluded. Or there never was a
  137518. ** blocking transaction. In either case, invoke the notify callback
  137519. ** immediately.
  137520. */
  137521. xNotify(&pArg, 1);
  137522. }else{
  137523. sqlite3 *p;
  137524. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  137525. if( p ){
  137526. rc = SQLITE_LOCKED; /* Deadlock detected. */
  137527. }else{
  137528. db->pUnlockConnection = db->pBlockingConnection;
  137529. db->xUnlockNotify = xNotify;
  137530. db->pUnlockArg = pArg;
  137531. removeFromBlockedList(db);
  137532. addToBlockedList(db);
  137533. }
  137534. }
  137535. leaveMutex();
  137536. assert( !db->mallocFailed );
  137537. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  137538. sqlite3_mutex_leave(db->mutex);
  137539. return rc;
  137540. }
  137541. /*
  137542. ** This function is called while stepping or preparing a statement
  137543. ** associated with connection db. The operation will return SQLITE_LOCKED
  137544. ** to the user because it requires a lock that will not be available
  137545. ** until connection pBlocker concludes its current transaction.
  137546. */
  137547. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  137548. enterMutex();
  137549. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  137550. addToBlockedList(db);
  137551. }
  137552. db->pBlockingConnection = pBlocker;
  137553. leaveMutex();
  137554. }
  137555. /*
  137556. ** This function is called when
  137557. ** the transaction opened by database db has just finished. Locks held
  137558. ** by database connection db have been released.
  137559. **
  137560. ** This function loops through each entry in the blocked connections
  137561. ** list and does the following:
  137562. **
  137563. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  137564. ** set to db, then set pBlockingConnection=0.
  137565. **
  137566. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  137567. ** set to db, then invoke the configured unlock-notify callback and
  137568. ** set pUnlockConnection=0.
  137569. **
  137570. ** 3) If the two steps above mean that pBlockingConnection==0 and
  137571. ** pUnlockConnection==0, remove the entry from the blocked connections
  137572. ** list.
  137573. */
  137574. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  137575. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  137576. int nArg = 0; /* Number of entries in aArg[] */
  137577. sqlite3 **pp; /* Iterator variable */
  137578. void **aArg; /* Arguments to the unlock callback */
  137579. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  137580. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  137581. aArg = aStatic;
  137582. enterMutex(); /* Enter STATIC_MASTER mutex */
  137583. /* This loop runs once for each entry in the blocked-connections list. */
  137584. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  137585. sqlite3 *p = *pp;
  137586. /* Step 1. */
  137587. if( p->pBlockingConnection==db ){
  137588. p->pBlockingConnection = 0;
  137589. }
  137590. /* Step 2. */
  137591. if( p->pUnlockConnection==db ){
  137592. assert( p->xUnlockNotify );
  137593. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  137594. xUnlockNotify(aArg, nArg);
  137595. nArg = 0;
  137596. }
  137597. sqlite3BeginBenignMalloc();
  137598. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  137599. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  137600. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  137601. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  137602. ){
  137603. /* The aArg[] array needs to grow. */
  137604. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  137605. if( pNew ){
  137606. memcpy(pNew, aArg, nArg*sizeof(void *));
  137607. sqlite3_free(aDyn);
  137608. aDyn = aArg = pNew;
  137609. }else{
  137610. /* This occurs when the array of context pointers that need to
  137611. ** be passed to the unlock-notify callback is larger than the
  137612. ** aStatic[] array allocated on the stack and the attempt to
  137613. ** allocate a larger array from the heap has failed.
  137614. **
  137615. ** This is a difficult situation to handle. Returning an error
  137616. ** code to the caller is insufficient, as even if an error code
  137617. ** is returned the transaction on connection db will still be
  137618. ** closed and the unlock-notify callbacks on blocked connections
  137619. ** will go unissued. This might cause the application to wait
  137620. ** indefinitely for an unlock-notify callback that will never
  137621. ** arrive.
  137622. **
  137623. ** Instead, invoke the unlock-notify callback with the context
  137624. ** array already accumulated. We can then clear the array and
  137625. ** begin accumulating any further context pointers without
  137626. ** requiring any dynamic allocation. This is sub-optimal because
  137627. ** it means that instead of one callback with a large array of
  137628. ** context pointers the application will receive two or more
  137629. ** callbacks with smaller arrays of context pointers, which will
  137630. ** reduce the applications ability to prioritize multiple
  137631. ** connections. But it is the best that can be done under the
  137632. ** circumstances.
  137633. */
  137634. xUnlockNotify(aArg, nArg);
  137635. nArg = 0;
  137636. }
  137637. }
  137638. sqlite3EndBenignMalloc();
  137639. aArg[nArg++] = p->pUnlockArg;
  137640. xUnlockNotify = p->xUnlockNotify;
  137641. p->pUnlockConnection = 0;
  137642. p->xUnlockNotify = 0;
  137643. p->pUnlockArg = 0;
  137644. }
  137645. /* Step 3. */
  137646. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  137647. /* Remove connection p from the blocked connections list. */
  137648. *pp = p->pNextBlocked;
  137649. p->pNextBlocked = 0;
  137650. }else{
  137651. pp = &p->pNextBlocked;
  137652. }
  137653. }
  137654. if( nArg!=0 ){
  137655. xUnlockNotify(aArg, nArg);
  137656. }
  137657. sqlite3_free(aDyn);
  137658. leaveMutex(); /* Leave STATIC_MASTER mutex */
  137659. }
  137660. /*
  137661. ** This is called when the database connection passed as an argument is
  137662. ** being closed. The connection is removed from the blocked list.
  137663. */
  137664. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  137665. sqlite3ConnectionUnlocked(db);
  137666. enterMutex();
  137667. removeFromBlockedList(db);
  137668. checkListProperties(db);
  137669. leaveMutex();
  137670. }
  137671. #endif
  137672. /************** End of notify.c **********************************************/
  137673. /************** Begin file fts3.c ********************************************/
  137674. /*
  137675. ** 2006 Oct 10
  137676. **
  137677. ** The author disclaims copyright to this source code. In place of
  137678. ** a legal notice, here is a blessing:
  137679. **
  137680. ** May you do good and not evil.
  137681. ** May you find forgiveness for yourself and forgive others.
  137682. ** May you share freely, never taking more than you give.
  137683. **
  137684. ******************************************************************************
  137685. **
  137686. ** This is an SQLite module implementing full-text search.
  137687. */
  137688. /*
  137689. ** The code in this file is only compiled if:
  137690. **
  137691. ** * The FTS3 module is being built as an extension
  137692. ** (in which case SQLITE_CORE is not defined), or
  137693. **
  137694. ** * The FTS3 module is being built into the core of
  137695. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  137696. */
  137697. /* The full-text index is stored in a series of b+tree (-like)
  137698. ** structures called segments which map terms to doclists. The
  137699. ** structures are like b+trees in layout, but are constructed from the
  137700. ** bottom up in optimal fashion and are not updatable. Since trees
  137701. ** are built from the bottom up, things will be described from the
  137702. ** bottom up.
  137703. **
  137704. **
  137705. **** Varints ****
  137706. ** The basic unit of encoding is a variable-length integer called a
  137707. ** varint. We encode variable-length integers in little-endian order
  137708. ** using seven bits * per byte as follows:
  137709. **
  137710. ** KEY:
  137711. ** A = 0xxxxxxx 7 bits of data and one flag bit
  137712. ** B = 1xxxxxxx 7 bits of data and one flag bit
  137713. **
  137714. ** 7 bits - A
  137715. ** 14 bits - BA
  137716. ** 21 bits - BBA
  137717. ** and so on.
  137718. **
  137719. ** This is similar in concept to how sqlite encodes "varints" but
  137720. ** the encoding is not the same. SQLite varints are big-endian
  137721. ** are are limited to 9 bytes in length whereas FTS3 varints are
  137722. ** little-endian and can be up to 10 bytes in length (in theory).
  137723. **
  137724. ** Example encodings:
  137725. **
  137726. ** 1: 0x01
  137727. ** 127: 0x7f
  137728. ** 128: 0x81 0x00
  137729. **
  137730. **
  137731. **** Document lists ****
  137732. ** A doclist (document list) holds a docid-sorted list of hits for a
  137733. ** given term. Doclists hold docids and associated token positions.
  137734. ** A docid is the unique integer identifier for a single document.
  137735. ** A position is the index of a word within the document. The first
  137736. ** word of the document has a position of 0.
  137737. **
  137738. ** FTS3 used to optionally store character offsets using a compile-time
  137739. ** option. But that functionality is no longer supported.
  137740. **
  137741. ** A doclist is stored like this:
  137742. **
  137743. ** array {
  137744. ** varint docid; (delta from previous doclist)
  137745. ** array { (position list for column 0)
  137746. ** varint position; (2 more than the delta from previous position)
  137747. ** }
  137748. ** array {
  137749. ** varint POS_COLUMN; (marks start of position list for new column)
  137750. ** varint column; (index of new column)
  137751. ** array {
  137752. ** varint position; (2 more than the delta from previous position)
  137753. ** }
  137754. ** }
  137755. ** varint POS_END; (marks end of positions for this document.
  137756. ** }
  137757. **
  137758. ** Here, array { X } means zero or more occurrences of X, adjacent in
  137759. ** memory. A "position" is an index of a token in the token stream
  137760. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  137761. ** in the same logical place as the position element, and act as sentinals
  137762. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  137763. ** The positions numbers are not stored literally but rather as two more
  137764. ** than the difference from the prior position, or the just the position plus
  137765. ** 2 for the first position. Example:
  137766. **
  137767. ** label: A B C D E F G H I J K
  137768. ** value: 123 5 9 1 1 14 35 0 234 72 0
  137769. **
  137770. ** The 123 value is the first docid. For column zero in this document
  137771. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  137772. ** at D signals the start of a new column; the 1 at E indicates that the
  137773. ** new column is column number 1. There are two positions at 12 and 45
  137774. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  137775. ** 234 at I is the delta to next docid (357). It has one position 70
  137776. ** (72-2) and then terminates with the 0 at K.
  137777. **
  137778. ** A "position-list" is the list of positions for multiple columns for
  137779. ** a single docid. A "column-list" is the set of positions for a single
  137780. ** column. Hence, a position-list consists of one or more column-lists,
  137781. ** a document record consists of a docid followed by a position-list and
  137782. ** a doclist consists of one or more document records.
  137783. **
  137784. ** A bare doclist omits the position information, becoming an
  137785. ** array of varint-encoded docids.
  137786. **
  137787. **** Segment leaf nodes ****
  137788. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  137789. ** nodes are written using LeafWriter, and read using LeafReader (to
  137790. ** iterate through a single leaf node's data) and LeavesReader (to
  137791. ** iterate through a segment's entire leaf layer). Leaf nodes have
  137792. ** the format:
  137793. **
  137794. ** varint iHeight; (height from leaf level, always 0)
  137795. ** varint nTerm; (length of first term)
  137796. ** char pTerm[nTerm]; (content of first term)
  137797. ** varint nDoclist; (length of term's associated doclist)
  137798. ** char pDoclist[nDoclist]; (content of doclist)
  137799. ** array {
  137800. ** (further terms are delta-encoded)
  137801. ** varint nPrefix; (length of prefix shared with previous term)
  137802. ** varint nSuffix; (length of unshared suffix)
  137803. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  137804. ** varint nDoclist; (length of term's associated doclist)
  137805. ** char pDoclist[nDoclist]; (content of doclist)
  137806. ** }
  137807. **
  137808. ** Here, array { X } means zero or more occurrences of X, adjacent in
  137809. ** memory.
  137810. **
  137811. ** Leaf nodes are broken into blocks which are stored contiguously in
  137812. ** the %_segments table in sorted order. This means that when the end
  137813. ** of a node is reached, the next term is in the node with the next
  137814. ** greater node id.
  137815. **
  137816. ** New data is spilled to a new leaf node when the current node
  137817. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  137818. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  137819. ** node (a leaf node with a single term and doclist). The goal of
  137820. ** these settings is to pack together groups of small doclists while
  137821. ** making it efficient to directly access large doclists. The
  137822. ** assumption is that large doclists represent terms which are more
  137823. ** likely to be query targets.
  137824. **
  137825. ** TODO(shess) It may be useful for blocking decisions to be more
  137826. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  137827. ** node rather than splitting into 2k and .5k nodes. My intuition is
  137828. ** that this might extend through 2x or 4x the pagesize.
  137829. **
  137830. **
  137831. **** Segment interior nodes ****
  137832. ** Segment interior nodes store blockids for subtree nodes and terms
  137833. ** to describe what data is stored by the each subtree. Interior
  137834. ** nodes are written using InteriorWriter, and read using
  137835. ** InteriorReader. InteriorWriters are created as needed when
  137836. ** SegmentWriter creates new leaf nodes, or when an interior node
  137837. ** itself grows too big and must be split. The format of interior
  137838. ** nodes:
  137839. **
  137840. ** varint iHeight; (height from leaf level, always >0)
  137841. ** varint iBlockid; (block id of node's leftmost subtree)
  137842. ** optional {
  137843. ** varint nTerm; (length of first term)
  137844. ** char pTerm[nTerm]; (content of first term)
  137845. ** array {
  137846. ** (further terms are delta-encoded)
  137847. ** varint nPrefix; (length of shared prefix with previous term)
  137848. ** varint nSuffix; (length of unshared suffix)
  137849. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  137850. ** }
  137851. ** }
  137852. **
  137853. ** Here, optional { X } means an optional element, while array { X }
  137854. ** means zero or more occurrences of X, adjacent in memory.
  137855. **
  137856. ** An interior node encodes n terms separating n+1 subtrees. The
  137857. ** subtree blocks are contiguous, so only the first subtree's blockid
  137858. ** is encoded. The subtree at iBlockid will contain all terms less
  137859. ** than the first term encoded (or all terms if no term is encoded).
  137860. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  137861. ** than pTerm[i+1], the subtree for that term will be rooted at
  137862. ** iBlockid+i. Interior nodes only store enough term data to
  137863. ** distinguish adjacent children (if the rightmost term of the left
  137864. ** child is "something", and the leftmost term of the right child is
  137865. ** "wicked", only "w" is stored).
  137866. **
  137867. ** New data is spilled to a new interior node at the same height when
  137868. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  137869. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  137870. ** interior nodes and making the tree too skinny. The interior nodes
  137871. ** at a given height are naturally tracked by interior nodes at
  137872. ** height+1, and so on.
  137873. **
  137874. **
  137875. **** Segment directory ****
  137876. ** The segment directory in table %_segdir stores meta-information for
  137877. ** merging and deleting segments, and also the root node of the
  137878. ** segment's tree.
  137879. **
  137880. ** The root node is the top node of the segment's tree after encoding
  137881. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  137882. ** This could be either a leaf node or an interior node. If the top
  137883. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  137884. ** and a new root interior node is generated (which should always fit
  137885. ** within ROOT_MAX because it only needs space for 2 varints, the
  137886. ** height and the blockid of the previous root).
  137887. **
  137888. ** The meta-information in the segment directory is:
  137889. ** level - segment level (see below)
  137890. ** idx - index within level
  137891. ** - (level,idx uniquely identify a segment)
  137892. ** start_block - first leaf node
  137893. ** leaves_end_block - last leaf node
  137894. ** end_block - last block (including interior nodes)
  137895. ** root - contents of root node
  137896. **
  137897. ** If the root node is a leaf node, then start_block,
  137898. ** leaves_end_block, and end_block are all 0.
  137899. **
  137900. **
  137901. **** Segment merging ****
  137902. ** To amortize update costs, segments are grouped into levels and
  137903. ** merged in batches. Each increase in level represents exponentially
  137904. ** more documents.
  137905. **
  137906. ** New documents (actually, document updates) are tokenized and
  137907. ** written individually (using LeafWriter) to a level 0 segment, with
  137908. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  137909. ** level 0 segments are merged into a single level 1 segment. Level 1
  137910. ** is populated like level 0, and eventually MERGE_COUNT level 1
  137911. ** segments are merged to a single level 2 segment (representing
  137912. ** MERGE_COUNT^2 updates), and so on.
  137913. **
  137914. ** A segment merge traverses all segments at a given level in
  137915. ** parallel, performing a straightforward sorted merge. Since segment
  137916. ** leaf nodes are written in to the %_segments table in order, this
  137917. ** merge traverses the underlying sqlite disk structures efficiently.
  137918. ** After the merge, all segment blocks from the merged level are
  137919. ** deleted.
  137920. **
  137921. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  137922. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  137923. ** very similar performance numbers to 16 on insertion, though they're
  137924. ** a tiny bit slower (perhaps due to more overhead in merge-time
  137925. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  137926. ** 16, 2 about 66% slower than 16.
  137927. **
  137928. ** At query time, high MERGE_COUNT increases the number of segments
  137929. ** which need to be scanned and merged. For instance, with 100k docs
  137930. ** inserted:
  137931. **
  137932. ** MERGE_COUNT segments
  137933. ** 16 25
  137934. ** 8 12
  137935. ** 4 10
  137936. ** 2 6
  137937. **
  137938. ** This appears to have only a moderate impact on queries for very
  137939. ** frequent terms (which are somewhat dominated by segment merge
  137940. ** costs), and infrequent and non-existent terms still seem to be fast
  137941. ** even with many segments.
  137942. **
  137943. ** TODO(shess) That said, it would be nice to have a better query-side
  137944. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  137945. ** optimizations to things like doclist merging will swing the sweet
  137946. ** spot around.
  137947. **
  137948. **
  137949. **
  137950. **** Handling of deletions and updates ****
  137951. ** Since we're using a segmented structure, with no docid-oriented
  137952. ** index into the term index, we clearly cannot simply update the term
  137953. ** index when a document is deleted or updated. For deletions, we
  137954. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  137955. ** we simply write the new doclist. Segment merges overwrite older
  137956. ** data for a particular docid with newer data, so deletes or updates
  137957. ** will eventually overtake the earlier data and knock it out. The
  137958. ** query logic likewise merges doclists so that newer data knocks out
  137959. ** older data.
  137960. */
  137961. /************** Include fts3Int.h in the middle of fts3.c ********************/
  137962. /************** Begin file fts3Int.h *****************************************/
  137963. /*
  137964. ** 2009 Nov 12
  137965. **
  137966. ** The author disclaims copyright to this source code. In place of
  137967. ** a legal notice, here is a blessing:
  137968. **
  137969. ** May you do good and not evil.
  137970. ** May you find forgiveness for yourself and forgive others.
  137971. ** May you share freely, never taking more than you give.
  137972. **
  137973. ******************************************************************************
  137974. **
  137975. */
  137976. #ifndef _FTSINT_H
  137977. #define _FTSINT_H
  137978. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  137979. # define NDEBUG 1
  137980. #endif
  137981. /* FTS3/FTS4 require virtual tables */
  137982. #ifdef SQLITE_OMIT_VIRTUALTABLE
  137983. # undef SQLITE_ENABLE_FTS3
  137984. # undef SQLITE_ENABLE_FTS4
  137985. #endif
  137986. /*
  137987. ** FTS4 is really an extension for FTS3. It is enabled using the
  137988. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  137989. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  137990. */
  137991. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  137992. # define SQLITE_ENABLE_FTS3
  137993. #endif
  137994. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137995. /* If not building as part of the core, include sqlite3ext.h. */
  137996. #ifndef SQLITE_CORE
  137997. /* # include "sqlite3ext.h" */
  137998. SQLITE_EXTENSION_INIT3
  137999. #endif
  138000. /* #include "sqlite3.h" */
  138001. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  138002. /************** Begin file fts3_tokenizer.h **********************************/
  138003. /*
  138004. ** 2006 July 10
  138005. **
  138006. ** The author disclaims copyright to this source code.
  138007. **
  138008. *************************************************************************
  138009. ** Defines the interface to tokenizers used by fulltext-search. There
  138010. ** are three basic components:
  138011. **
  138012. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  138013. ** interface functions. This is essentially the class structure for
  138014. ** tokenizers.
  138015. **
  138016. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  138017. ** including customization information defined at creation time.
  138018. **
  138019. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  138020. ** tokens from a particular input.
  138021. */
  138022. #ifndef _FTS3_TOKENIZER_H_
  138023. #define _FTS3_TOKENIZER_H_
  138024. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  138025. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  138026. ** we will need a way to register the API consistently.
  138027. */
  138028. /* #include "sqlite3.h" */
  138029. /*
  138030. ** Structures used by the tokenizer interface. When a new tokenizer
  138031. ** implementation is registered, the caller provides a pointer to
  138032. ** an sqlite3_tokenizer_module containing pointers to the callback
  138033. ** functions that make up an implementation.
  138034. **
  138035. ** When an fts3 table is created, it passes any arguments passed to
  138036. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  138037. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  138038. ** implementation. The xCreate() function in turn returns an
  138039. ** sqlite3_tokenizer structure representing the specific tokenizer to
  138040. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  138041. **
  138042. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  138043. ** method is called. It returns an sqlite3_tokenizer_cursor object
  138044. ** that may be used to tokenize a specific input buffer based on
  138045. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  138046. ** object.
  138047. */
  138048. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  138049. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  138050. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  138051. struct sqlite3_tokenizer_module {
  138052. /*
  138053. ** Structure version. Should always be set to 0 or 1.
  138054. */
  138055. int iVersion;
  138056. /*
  138057. ** Create a new tokenizer. The values in the argv[] array are the
  138058. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  138059. ** TABLE statement that created the fts3 table. For example, if
  138060. ** the following SQL is executed:
  138061. **
  138062. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  138063. **
  138064. ** then argc is set to 2, and the argv[] array contains pointers
  138065. ** to the strings "arg1" and "arg2".
  138066. **
  138067. ** This method should return either SQLITE_OK (0), or an SQLite error
  138068. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  138069. ** to point at the newly created tokenizer structure. The generic
  138070. ** sqlite3_tokenizer.pModule variable should not be initialized by
  138071. ** this callback. The caller will do so.
  138072. */
  138073. int (*xCreate)(
  138074. int argc, /* Size of argv array */
  138075. const char *const*argv, /* Tokenizer argument strings */
  138076. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  138077. );
  138078. /*
  138079. ** Destroy an existing tokenizer. The fts3 module calls this method
  138080. ** exactly once for each successful call to xCreate().
  138081. */
  138082. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  138083. /*
  138084. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  138085. ** is responsible for ensuring that the input buffer remains valid
  138086. ** until the cursor is closed (using the xClose() method).
  138087. */
  138088. int (*xOpen)(
  138089. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  138090. const char *pInput, int nBytes, /* Input buffer */
  138091. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  138092. );
  138093. /*
  138094. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  138095. ** method exactly once for each successful call to xOpen().
  138096. */
  138097. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  138098. /*
  138099. ** Retrieve the next token from the tokenizer cursor pCursor. This
  138100. ** method should either return SQLITE_OK and set the values of the
  138101. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  138102. ** the end of the buffer has been reached, or an SQLite error code.
  138103. **
  138104. ** *ppToken should be set to point at a buffer containing the
  138105. ** normalized version of the token (i.e. after any case-folding and/or
  138106. ** stemming has been performed). *pnBytes should be set to the length
  138107. ** of this buffer in bytes. The input text that generated the token is
  138108. ** identified by the byte offsets returned in *piStartOffset and
  138109. ** *piEndOffset. *piStartOffset should be set to the index of the first
  138110. ** byte of the token in the input buffer. *piEndOffset should be set
  138111. ** to the index of the first byte just past the end of the token in
  138112. ** the input buffer.
  138113. **
  138114. ** The buffer *ppToken is set to point at is managed by the tokenizer
  138115. ** implementation. It is only required to be valid until the next call
  138116. ** to xNext() or xClose().
  138117. */
  138118. /* TODO(shess) current implementation requires pInput to be
  138119. ** nul-terminated. This should either be fixed, or pInput/nBytes
  138120. ** should be converted to zInput.
  138121. */
  138122. int (*xNext)(
  138123. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  138124. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  138125. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  138126. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  138127. int *piPosition /* OUT: Number of tokens returned before this one */
  138128. );
  138129. /***********************************************************************
  138130. ** Methods below this point are only available if iVersion>=1.
  138131. */
  138132. /*
  138133. ** Configure the language id of a tokenizer cursor.
  138134. */
  138135. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  138136. };
  138137. struct sqlite3_tokenizer {
  138138. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  138139. /* Tokenizer implementations will typically add additional fields */
  138140. };
  138141. struct sqlite3_tokenizer_cursor {
  138142. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  138143. /* Tokenizer implementations will typically add additional fields */
  138144. };
  138145. int fts3_global_term_cnt(int iTerm, int iCol);
  138146. int fts3_term_cnt(int iTerm, int iCol);
  138147. #endif /* _FTS3_TOKENIZER_H_ */
  138148. /************** End of fts3_tokenizer.h **************************************/
  138149. /************** Continuing where we left off in fts3Int.h ********************/
  138150. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  138151. /************** Begin file fts3_hash.h ***************************************/
  138152. /*
  138153. ** 2001 September 22
  138154. **
  138155. ** The author disclaims copyright to this source code. In place of
  138156. ** a legal notice, here is a blessing:
  138157. **
  138158. ** May you do good and not evil.
  138159. ** May you find forgiveness for yourself and forgive others.
  138160. ** May you share freely, never taking more than you give.
  138161. **
  138162. *************************************************************************
  138163. ** This is the header file for the generic hash-table implementation
  138164. ** used in SQLite. We've modified it slightly to serve as a standalone
  138165. ** hash table implementation for the full-text indexing module.
  138166. **
  138167. */
  138168. #ifndef _FTS3_HASH_H_
  138169. #define _FTS3_HASH_H_
  138170. /* Forward declarations of structures. */
  138171. typedef struct Fts3Hash Fts3Hash;
  138172. typedef struct Fts3HashElem Fts3HashElem;
  138173. /* A complete hash table is an instance of the following structure.
  138174. ** The internals of this structure are intended to be opaque -- client
  138175. ** code should not attempt to access or modify the fields of this structure
  138176. ** directly. Change this structure only by using the routines below.
  138177. ** However, many of the "procedures" and "functions" for modifying and
  138178. ** accessing this structure are really macros, so we can't really make
  138179. ** this structure opaque.
  138180. */
  138181. struct Fts3Hash {
  138182. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  138183. char copyKey; /* True if copy of key made on insert */
  138184. int count; /* Number of entries in this table */
  138185. Fts3HashElem *first; /* The first element of the array */
  138186. int htsize; /* Number of buckets in the hash table */
  138187. struct _fts3ht { /* the hash table */
  138188. int count; /* Number of entries with this hash */
  138189. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  138190. } *ht;
  138191. };
  138192. /* Each element in the hash table is an instance of the following
  138193. ** structure. All elements are stored on a single doubly-linked list.
  138194. **
  138195. ** Again, this structure is intended to be opaque, but it can't really
  138196. ** be opaque because it is used by macros.
  138197. */
  138198. struct Fts3HashElem {
  138199. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  138200. void *data; /* Data associated with this element */
  138201. void *pKey; int nKey; /* Key associated with this element */
  138202. };
  138203. /*
  138204. ** There are 2 different modes of operation for a hash table:
  138205. **
  138206. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  138207. ** (including the null-terminator, if any). Case
  138208. ** is respected in comparisons.
  138209. **
  138210. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  138211. ** memcmp() is used to compare keys.
  138212. **
  138213. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  138214. */
  138215. #define FTS3_HASH_STRING 1
  138216. #define FTS3_HASH_BINARY 2
  138217. /*
  138218. ** Access routines. To delete, insert a NULL pointer.
  138219. */
  138220. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  138221. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  138222. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  138223. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  138224. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  138225. /*
  138226. ** Shorthand for the functions above
  138227. */
  138228. #define fts3HashInit sqlite3Fts3HashInit
  138229. #define fts3HashInsert sqlite3Fts3HashInsert
  138230. #define fts3HashFind sqlite3Fts3HashFind
  138231. #define fts3HashClear sqlite3Fts3HashClear
  138232. #define fts3HashFindElem sqlite3Fts3HashFindElem
  138233. /*
  138234. ** Macros for looping over all elements of a hash table. The idiom is
  138235. ** like this:
  138236. **
  138237. ** Fts3Hash h;
  138238. ** Fts3HashElem *p;
  138239. ** ...
  138240. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  138241. ** SomeStructure *pData = fts3HashData(p);
  138242. ** // do something with pData
  138243. ** }
  138244. */
  138245. #define fts3HashFirst(H) ((H)->first)
  138246. #define fts3HashNext(E) ((E)->next)
  138247. #define fts3HashData(E) ((E)->data)
  138248. #define fts3HashKey(E) ((E)->pKey)
  138249. #define fts3HashKeysize(E) ((E)->nKey)
  138250. /*
  138251. ** Number of entries in a hash table
  138252. */
  138253. #define fts3HashCount(H) ((H)->count)
  138254. #endif /* _FTS3_HASH_H_ */
  138255. /************** End of fts3_hash.h *******************************************/
  138256. /************** Continuing where we left off in fts3Int.h ********************/
  138257. /*
  138258. ** This constant determines the maximum depth of an FTS expression tree
  138259. ** that the library will create and use. FTS uses recursion to perform
  138260. ** various operations on the query tree, so the disadvantage of a large
  138261. ** limit is that it may allow very large queries to use large amounts
  138262. ** of stack space (perhaps causing a stack overflow).
  138263. */
  138264. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  138265. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  138266. #endif
  138267. /*
  138268. ** This constant controls how often segments are merged. Once there are
  138269. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  138270. ** segment of level N+1.
  138271. */
  138272. #define FTS3_MERGE_COUNT 16
  138273. /*
  138274. ** This is the maximum amount of data (in bytes) to store in the
  138275. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  138276. ** populated as documents are inserted/updated/deleted in a transaction
  138277. ** and used to create a new segment when the transaction is committed.
  138278. ** However if this limit is reached midway through a transaction, a new
  138279. ** segment is created and the hash table cleared immediately.
  138280. */
  138281. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  138282. /*
  138283. ** Macro to return the number of elements in an array. SQLite has a
  138284. ** similar macro called ArraySize(). Use a different name to avoid
  138285. ** a collision when building an amalgamation with built-in FTS3.
  138286. */
  138287. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  138288. #ifndef MIN
  138289. # define MIN(x,y) ((x)<(y)?(x):(y))
  138290. #endif
  138291. #ifndef MAX
  138292. # define MAX(x,y) ((x)>(y)?(x):(y))
  138293. #endif
  138294. /*
  138295. ** Maximum length of a varint encoded integer. The varint format is different
  138296. ** from that used by SQLite, so the maximum length is 10, not 9.
  138297. */
  138298. #define FTS3_VARINT_MAX 10
  138299. /*
  138300. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  138301. ** in the document set and zero or more prefix indexes. All indexes are stored
  138302. ** as one or more b+-trees in the %_segments and %_segdir tables.
  138303. **
  138304. ** It is possible to determine which index a b+-tree belongs to based on the
  138305. ** value stored in the "%_segdir.level" column. Given this value L, the index
  138306. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  138307. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  138308. ** between 1024 and 2047 to index 1, and so on.
  138309. **
  138310. ** It is considered impossible for an index to use more than 1024 levels. In
  138311. ** theory though this may happen, but only after at least
  138312. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  138313. */
  138314. #define FTS3_SEGDIR_MAXLEVEL 1024
  138315. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  138316. /*
  138317. ** The testcase() macro is only used by the amalgamation. If undefined,
  138318. ** make it a no-op.
  138319. */
  138320. #ifndef testcase
  138321. # define testcase(X)
  138322. #endif
  138323. /*
  138324. ** Terminator values for position-lists and column-lists.
  138325. */
  138326. #define POS_COLUMN (1) /* Column-list terminator */
  138327. #define POS_END (0) /* Position-list terminator */
  138328. /*
  138329. ** This section provides definitions to allow the
  138330. ** FTS3 extension to be compiled outside of the
  138331. ** amalgamation.
  138332. */
  138333. #ifndef SQLITE_AMALGAMATION
  138334. /*
  138335. ** Macros indicating that conditional expressions are always true or
  138336. ** false.
  138337. */
  138338. #ifdef SQLITE_COVERAGE_TEST
  138339. # define ALWAYS(x) (1)
  138340. # define NEVER(X) (0)
  138341. #elif defined(SQLITE_DEBUG)
  138342. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  138343. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  138344. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  138345. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  138346. #else
  138347. # define ALWAYS(x) (x)
  138348. # define NEVER(x) (x)
  138349. #endif
  138350. /*
  138351. ** Internal types used by SQLite.
  138352. */
  138353. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  138354. typedef short int i16; /* 2-byte (or larger) signed integer */
  138355. typedef unsigned int u32; /* 4-byte unsigned integer */
  138356. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  138357. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  138358. /*
  138359. ** Macro used to suppress compiler warnings for unused parameters.
  138360. */
  138361. #define UNUSED_PARAMETER(x) (void)(x)
  138362. /*
  138363. ** Activate assert() only if SQLITE_TEST is enabled.
  138364. */
  138365. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  138366. # define NDEBUG 1
  138367. #endif
  138368. /*
  138369. ** The TESTONLY macro is used to enclose variable declarations or
  138370. ** other bits of code that are needed to support the arguments
  138371. ** within testcase() and assert() macros.
  138372. */
  138373. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  138374. # define TESTONLY(X) X
  138375. #else
  138376. # define TESTONLY(X)
  138377. #endif
  138378. #endif /* SQLITE_AMALGAMATION */
  138379. #ifdef SQLITE_DEBUG
  138380. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  138381. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  138382. #else
  138383. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  138384. #endif
  138385. typedef struct Fts3Table Fts3Table;
  138386. typedef struct Fts3Cursor Fts3Cursor;
  138387. typedef struct Fts3Expr Fts3Expr;
  138388. typedef struct Fts3Phrase Fts3Phrase;
  138389. typedef struct Fts3PhraseToken Fts3PhraseToken;
  138390. typedef struct Fts3Doclist Fts3Doclist;
  138391. typedef struct Fts3SegFilter Fts3SegFilter;
  138392. typedef struct Fts3DeferredToken Fts3DeferredToken;
  138393. typedef struct Fts3SegReader Fts3SegReader;
  138394. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  138395. typedef struct MatchinfoBuffer MatchinfoBuffer;
  138396. /*
  138397. ** A connection to a fulltext index is an instance of the following
  138398. ** structure. The xCreate and xConnect methods create an instance
  138399. ** of this structure and xDestroy and xDisconnect free that instance.
  138400. ** All other methods receive a pointer to the structure as one of their
  138401. ** arguments.
  138402. */
  138403. struct Fts3Table {
  138404. sqlite3_vtab base; /* Base class used by SQLite core */
  138405. sqlite3 *db; /* The database connection */
  138406. const char *zDb; /* logical database name */
  138407. const char *zName; /* virtual table name */
  138408. int nColumn; /* number of named columns in virtual table */
  138409. char **azColumn; /* column names. malloced */
  138410. u8 *abNotindexed; /* True for 'notindexed' columns */
  138411. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  138412. char *zContentTbl; /* content=xxx option, or NULL */
  138413. char *zLanguageid; /* languageid=xxx option, or NULL */
  138414. int nAutoincrmerge; /* Value configured by 'automerge' */
  138415. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  138416. /* Precompiled statements used by the implementation. Each of these
  138417. ** statements is run and reset within a single virtual table API call.
  138418. */
  138419. sqlite3_stmt *aStmt[40];
  138420. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  138421. char *zReadExprlist;
  138422. char *zWriteExprlist;
  138423. int nNodeSize; /* Soft limit for node size */
  138424. u8 bFts4; /* True for FTS4, false for FTS3 */
  138425. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  138426. u8 bHasDocsize; /* True if %_docsize table exists */
  138427. u8 bDescIdx; /* True if doclists are in reverse order */
  138428. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  138429. int nPgsz; /* Page size for host database */
  138430. char *zSegmentsTbl; /* Name of %_segments table */
  138431. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  138432. /*
  138433. ** The following array of hash tables is used to buffer pending index
  138434. ** updates during transactions. All pending updates buffered at any one
  138435. ** time must share a common language-id (see the FTS4 langid= feature).
  138436. ** The current language id is stored in variable iPrevLangid.
  138437. **
  138438. ** A single FTS4 table may have multiple full-text indexes. For each index
  138439. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  138440. ** terms that appear in the document set. Each subsequent index in aIndex[]
  138441. ** is an index of prefixes of a specific length.
  138442. **
  138443. ** Variable nPendingData contains an estimate the memory consumed by the
  138444. ** pending data structures, including hash table overhead, but not including
  138445. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  138446. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  138447. ** recently inserted record.
  138448. */
  138449. int nIndex; /* Size of aIndex[] */
  138450. struct Fts3Index {
  138451. int nPrefix; /* Prefix length (0 for main terms index) */
  138452. Fts3Hash hPending; /* Pending terms table for this index */
  138453. } *aIndex;
  138454. int nMaxPendingData; /* Max pending data before flush to disk */
  138455. int nPendingData; /* Current bytes of pending data */
  138456. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  138457. int iPrevLangid; /* Langid of recently inserted document */
  138458. int bPrevDelete; /* True if last operation was a delete */
  138459. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  138460. /* State variables used for validating that the transaction control
  138461. ** methods of the virtual table are called at appropriate times. These
  138462. ** values do not contribute to FTS functionality; they are used for
  138463. ** verifying the operation of the SQLite core.
  138464. */
  138465. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  138466. int mxSavepoint; /* Largest valid xSavepoint integer */
  138467. #endif
  138468. #ifdef SQLITE_TEST
  138469. /* True to disable the incremental doclist optimization. This is controled
  138470. ** by special insert command 'test-no-incr-doclist'. */
  138471. int bNoIncrDoclist;
  138472. #endif
  138473. };
  138474. /*
  138475. ** When the core wants to read from the virtual table, it creates a
  138476. ** virtual table cursor (an instance of the following structure) using
  138477. ** the xOpen method. Cursors are destroyed using the xClose method.
  138478. */
  138479. struct Fts3Cursor {
  138480. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  138481. i16 eSearch; /* Search strategy (see below) */
  138482. u8 isEof; /* True if at End Of Results */
  138483. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  138484. u8 bSeekStmt; /* True if pStmt is a seek */
  138485. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  138486. Fts3Expr *pExpr; /* Parsed MATCH query string */
  138487. int iLangid; /* Language being queried for */
  138488. int nPhrase; /* Number of matchable phrases in query */
  138489. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  138490. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  138491. char *pNextId; /* Pointer into the body of aDoclist */
  138492. char *aDoclist; /* List of docids for full-text queries */
  138493. int nDoclist; /* Size of buffer at aDoclist */
  138494. u8 bDesc; /* True to sort in descending order */
  138495. int eEvalmode; /* An FTS3_EVAL_XX constant */
  138496. int nRowAvg; /* Average size of database rows, in pages */
  138497. sqlite3_int64 nDoc; /* Documents in table */
  138498. i64 iMinDocid; /* Minimum docid to return */
  138499. i64 iMaxDocid; /* Maximum docid to return */
  138500. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  138501. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  138502. };
  138503. #define FTS3_EVAL_FILTER 0
  138504. #define FTS3_EVAL_NEXT 1
  138505. #define FTS3_EVAL_MATCHINFO 2
  138506. /*
  138507. ** The Fts3Cursor.eSearch member is always set to one of the following.
  138508. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  138509. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  138510. ** of the column to be searched. For example, in
  138511. **
  138512. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  138513. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  138514. **
  138515. ** Because the LHS of the MATCH operator is 2nd column "b",
  138516. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  138517. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  138518. ** indicating that all columns should be searched,
  138519. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  138520. */
  138521. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  138522. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  138523. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  138524. /*
  138525. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  138526. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  138527. ** above. The upper 16-bits contain a combination of the following
  138528. ** bits, used to describe extra constraints on full-text searches.
  138529. */
  138530. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  138531. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  138532. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  138533. struct Fts3Doclist {
  138534. char *aAll; /* Array containing doclist (or NULL) */
  138535. int nAll; /* Size of a[] in bytes */
  138536. char *pNextDocid; /* Pointer to next docid */
  138537. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  138538. int bFreeList; /* True if pList should be sqlite3_free()d */
  138539. char *pList; /* Pointer to position list following iDocid */
  138540. int nList; /* Length of position list */
  138541. };
  138542. /*
  138543. ** A "phrase" is a sequence of one or more tokens that must match in
  138544. ** sequence. A single token is the base case and the most common case.
  138545. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  138546. ** nToken will be the number of tokens in the string.
  138547. */
  138548. struct Fts3PhraseToken {
  138549. char *z; /* Text of the token */
  138550. int n; /* Number of bytes in buffer z */
  138551. int isPrefix; /* True if token ends with a "*" character */
  138552. int bFirst; /* True if token must appear at position 0 */
  138553. /* Variables above this point are populated when the expression is
  138554. ** parsed (by code in fts3_expr.c). Below this point the variables are
  138555. ** used when evaluating the expression. */
  138556. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  138557. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  138558. };
  138559. struct Fts3Phrase {
  138560. /* Cache of doclist for this phrase. */
  138561. Fts3Doclist doclist;
  138562. int bIncr; /* True if doclist is loaded incrementally */
  138563. int iDoclistToken;
  138564. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  138565. ** OR condition. */
  138566. char *pOrPoslist;
  138567. i64 iOrDocid;
  138568. /* Variables below this point are populated by fts3_expr.c when parsing
  138569. ** a MATCH expression. Everything above is part of the evaluation phase.
  138570. */
  138571. int nToken; /* Number of tokens in the phrase */
  138572. int iColumn; /* Index of column this phrase must match */
  138573. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  138574. };
  138575. /*
  138576. ** A tree of these objects forms the RHS of a MATCH operator.
  138577. **
  138578. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  138579. ** points to a malloced buffer, size nDoclist bytes, containing the results
  138580. ** of this phrase query in FTS3 doclist format. As usual, the initial
  138581. ** "Length" field found in doclists stored on disk is omitted from this
  138582. ** buffer.
  138583. **
  138584. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  138585. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  138586. ** where nCol is the number of columns in the queried FTS table. The array
  138587. ** is populated as follows:
  138588. **
  138589. ** aMI[iCol*3 + 0] = Undefined
  138590. ** aMI[iCol*3 + 1] = Number of occurrences
  138591. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  138592. **
  138593. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  138594. ** when the expression node is.
  138595. */
  138596. struct Fts3Expr {
  138597. int eType; /* One of the FTSQUERY_XXX values defined below */
  138598. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  138599. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  138600. Fts3Expr *pLeft; /* Left operand */
  138601. Fts3Expr *pRight; /* Right operand */
  138602. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  138603. /* The following are used by the fts3_eval.c module. */
  138604. sqlite3_int64 iDocid; /* Current docid */
  138605. u8 bEof; /* True this expression is at EOF already */
  138606. u8 bStart; /* True if iDocid is valid */
  138607. u8 bDeferred; /* True if this expression is entirely deferred */
  138608. /* The following are used by the fts3_snippet.c module. */
  138609. int iPhrase; /* Index of this phrase in matchinfo() results */
  138610. u32 *aMI; /* See above */
  138611. };
  138612. /*
  138613. ** Candidate values for Fts3Query.eType. Note that the order of the first
  138614. ** four values is in order of precedence when parsing expressions. For
  138615. ** example, the following:
  138616. **
  138617. ** "a OR b AND c NOT d NEAR e"
  138618. **
  138619. ** is equivalent to:
  138620. **
  138621. ** "a OR (b AND (c NOT (d NEAR e)))"
  138622. */
  138623. #define FTSQUERY_NEAR 1
  138624. #define FTSQUERY_NOT 2
  138625. #define FTSQUERY_AND 3
  138626. #define FTSQUERY_OR 4
  138627. #define FTSQUERY_PHRASE 5
  138628. /* fts3_write.c */
  138629. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  138630. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  138631. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  138632. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  138633. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  138634. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  138635. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  138636. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  138637. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  138638. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  138639. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  138640. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  138641. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  138642. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  138643. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  138644. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  138645. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  138646. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  138647. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  138648. #else
  138649. # define sqlite3Fts3FreeDeferredTokens(x)
  138650. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  138651. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  138652. # define sqlite3Fts3FreeDeferredDoclists(x)
  138653. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  138654. #endif
  138655. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  138656. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  138657. /* Special values interpreted by sqlite3SegReaderCursor() */
  138658. #define FTS3_SEGCURSOR_PENDING -1
  138659. #define FTS3_SEGCURSOR_ALL -2
  138660. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  138661. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  138662. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  138663. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  138664. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  138665. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  138666. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  138667. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  138668. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  138669. #define FTS3_SEGMENT_PREFIX 0x00000008
  138670. #define FTS3_SEGMENT_SCAN 0x00000010
  138671. #define FTS3_SEGMENT_FIRST 0x00000020
  138672. /* Type passed as 4th argument to SegmentReaderIterate() */
  138673. struct Fts3SegFilter {
  138674. const char *zTerm;
  138675. int nTerm;
  138676. int iCol;
  138677. int flags;
  138678. };
  138679. struct Fts3MultiSegReader {
  138680. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  138681. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  138682. int nSegment; /* Size of apSegment array */
  138683. int nAdvance; /* How many seg-readers to advance */
  138684. Fts3SegFilter *pFilter; /* Pointer to filter object */
  138685. char *aBuffer; /* Buffer to merge doclists in */
  138686. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  138687. int iColFilter; /* If >=0, filter for this column */
  138688. int bRestart;
  138689. /* Used by fts3.c only. */
  138690. int nCost; /* Cost of running iterator */
  138691. int bLookup; /* True if a lookup of a single entry. */
  138692. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  138693. char *zTerm; /* Pointer to term buffer */
  138694. int nTerm; /* Size of zTerm in bytes */
  138695. char *aDoclist; /* Pointer to doclist buffer */
  138696. int nDoclist; /* Size of aDoclist[] in bytes */
  138697. };
  138698. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  138699. #define fts3GetVarint32(p, piVal) ( \
  138700. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  138701. )
  138702. /* fts3.c */
  138703. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  138704. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  138705. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  138706. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  138707. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  138708. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  138709. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  138710. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  138711. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  138712. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  138713. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  138714. /* fts3_tokenizer.c */
  138715. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  138716. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  138717. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  138718. sqlite3_tokenizer **, char **
  138719. );
  138720. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  138721. /* fts3_snippet.c */
  138722. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  138723. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  138724. const char *, const char *, int, int
  138725. );
  138726. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  138727. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  138728. /* fts3_expr.c */
  138729. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  138730. char **, int, int, int, const char *, int, Fts3Expr **, char **
  138731. );
  138732. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  138733. #ifdef SQLITE_TEST
  138734. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  138735. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  138736. #endif
  138737. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  138738. sqlite3_tokenizer_cursor **
  138739. );
  138740. /* fts3_aux.c */
  138741. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  138742. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  138743. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  138744. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  138745. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  138746. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  138747. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  138748. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  138749. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  138750. /* fts3_tokenize_vtab.c */
  138751. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  138752. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  138753. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  138754. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  138755. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  138756. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  138757. #endif
  138758. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  138759. #endif /* _FTSINT_H */
  138760. /************** End of fts3Int.h *********************************************/
  138761. /************** Continuing where we left off in fts3.c ***********************/
  138762. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  138763. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  138764. # define SQLITE_CORE 1
  138765. #endif
  138766. /* #include <assert.h> */
  138767. /* #include <stdlib.h> */
  138768. /* #include <stddef.h> */
  138769. /* #include <stdio.h> */
  138770. /* #include <string.h> */
  138771. /* #include <stdarg.h> */
  138772. /* #include "fts3.h" */
  138773. #ifndef SQLITE_CORE
  138774. /* # include "sqlite3ext.h" */
  138775. SQLITE_EXTENSION_INIT1
  138776. #endif
  138777. static int fts3EvalNext(Fts3Cursor *pCsr);
  138778. static int fts3EvalStart(Fts3Cursor *pCsr);
  138779. static int fts3TermSegReaderCursor(
  138780. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  138781. #ifndef SQLITE_AMALGAMATION
  138782. # if defined(SQLITE_DEBUG)
  138783. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  138784. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  138785. # endif
  138786. #endif
  138787. /*
  138788. ** Write a 64-bit variable-length integer to memory starting at p[0].
  138789. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  138790. ** The number of bytes written is returned.
  138791. */
  138792. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  138793. unsigned char *q = (unsigned char *) p;
  138794. sqlite_uint64 vu = v;
  138795. do{
  138796. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  138797. vu >>= 7;
  138798. }while( vu!=0 );
  138799. q[-1] &= 0x7f; /* turn off high bit in final byte */
  138800. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  138801. return (int) (q - (unsigned char *)p);
  138802. }
  138803. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  138804. v = (v & mask1) | ( (*ptr++) << shift ); \
  138805. if( (v & mask2)==0 ){ var = v; return ret; }
  138806. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  138807. v = (*ptr++); \
  138808. if( (v & mask2)==0 ){ var = v; return ret; }
  138809. /*
  138810. ** Read a 64-bit variable-length integer from memory starting at p[0].
  138811. ** Return the number of bytes read, or 0 on error.
  138812. ** The value is stored in *v.
  138813. */
  138814. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  138815. const unsigned char *p = (const unsigned char*)pBuf;
  138816. const unsigned char *pStart = p;
  138817. u32 a;
  138818. u64 b;
  138819. int shift;
  138820. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  138821. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  138822. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  138823. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  138824. b = (a & 0x0FFFFFFF );
  138825. for(shift=28; shift<=63; shift+=7){
  138826. u64 c = *p++;
  138827. b += (c&0x7F) << shift;
  138828. if( (c & 0x80)==0 ) break;
  138829. }
  138830. *v = b;
  138831. return (int)(p - pStart);
  138832. }
  138833. /*
  138834. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  138835. ** a non-negative 32-bit integer before it is returned.
  138836. */
  138837. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  138838. u32 a;
  138839. #ifndef fts3GetVarint32
  138840. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  138841. #else
  138842. a = (*p++);
  138843. assert( a & 0x80 );
  138844. #endif
  138845. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  138846. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  138847. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  138848. a = (a & 0x0FFFFFFF );
  138849. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  138850. assert( 0==(a & 0x80000000) );
  138851. assert( *pi>=0 );
  138852. return 5;
  138853. }
  138854. /*
  138855. ** Return the number of bytes required to encode v as a varint
  138856. */
  138857. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  138858. int i = 0;
  138859. do{
  138860. i++;
  138861. v >>= 7;
  138862. }while( v!=0 );
  138863. return i;
  138864. }
  138865. /*
  138866. ** Convert an SQL-style quoted string into a normal string by removing
  138867. ** the quote characters. The conversion is done in-place. If the
  138868. ** input does not begin with a quote character, then this routine
  138869. ** is a no-op.
  138870. **
  138871. ** Examples:
  138872. **
  138873. ** "abc" becomes abc
  138874. ** 'xyz' becomes xyz
  138875. ** [pqr] becomes pqr
  138876. ** `mno` becomes mno
  138877. **
  138878. */
  138879. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  138880. char quote; /* Quote character (if any ) */
  138881. quote = z[0];
  138882. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  138883. int iIn = 1; /* Index of next byte to read from input */
  138884. int iOut = 0; /* Index of next byte to write to output */
  138885. /* If the first byte was a '[', then the close-quote character is a ']' */
  138886. if( quote=='[' ) quote = ']';
  138887. while( z[iIn] ){
  138888. if( z[iIn]==quote ){
  138889. if( z[iIn+1]!=quote ) break;
  138890. z[iOut++] = quote;
  138891. iIn += 2;
  138892. }else{
  138893. z[iOut++] = z[iIn++];
  138894. }
  138895. }
  138896. z[iOut] = '\0';
  138897. }
  138898. }
  138899. /*
  138900. ** Read a single varint from the doclist at *pp and advance *pp to point
  138901. ** to the first byte past the end of the varint. Add the value of the varint
  138902. ** to *pVal.
  138903. */
  138904. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  138905. sqlite3_int64 iVal;
  138906. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  138907. *pVal += iVal;
  138908. }
  138909. /*
  138910. ** When this function is called, *pp points to the first byte following a
  138911. ** varint that is part of a doclist (or position-list, or any other list
  138912. ** of varints). This function moves *pp to point to the start of that varint,
  138913. ** and sets *pVal by the varint value.
  138914. **
  138915. ** Argument pStart points to the first byte of the doclist that the
  138916. ** varint is part of.
  138917. */
  138918. static void fts3GetReverseVarint(
  138919. char **pp,
  138920. char *pStart,
  138921. sqlite3_int64 *pVal
  138922. ){
  138923. sqlite3_int64 iVal;
  138924. char *p;
  138925. /* Pointer p now points at the first byte past the varint we are
  138926. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  138927. ** clear on character p[-1]. */
  138928. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  138929. p++;
  138930. *pp = p;
  138931. sqlite3Fts3GetVarint(p, &iVal);
  138932. *pVal = iVal;
  138933. }
  138934. /*
  138935. ** The xDisconnect() virtual table method.
  138936. */
  138937. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  138938. Fts3Table *p = (Fts3Table *)pVtab;
  138939. int i;
  138940. assert( p->nPendingData==0 );
  138941. assert( p->pSegments==0 );
  138942. /* Free any prepared statements held */
  138943. sqlite3_finalize(p->pSeekStmt);
  138944. for(i=0; i<SizeofArray(p->aStmt); i++){
  138945. sqlite3_finalize(p->aStmt[i]);
  138946. }
  138947. sqlite3_free(p->zSegmentsTbl);
  138948. sqlite3_free(p->zReadExprlist);
  138949. sqlite3_free(p->zWriteExprlist);
  138950. sqlite3_free(p->zContentTbl);
  138951. sqlite3_free(p->zLanguageid);
  138952. /* Invoke the tokenizer destructor to free the tokenizer. */
  138953. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  138954. sqlite3_free(p);
  138955. return SQLITE_OK;
  138956. }
  138957. /*
  138958. ** Write an error message into *pzErr
  138959. */
  138960. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  138961. va_list ap;
  138962. sqlite3_free(*pzErr);
  138963. va_start(ap, zFormat);
  138964. *pzErr = sqlite3_vmprintf(zFormat, ap);
  138965. va_end(ap);
  138966. }
  138967. /*
  138968. ** Construct one or more SQL statements from the format string given
  138969. ** and then evaluate those statements. The success code is written
  138970. ** into *pRc.
  138971. **
  138972. ** If *pRc is initially non-zero then this routine is a no-op.
  138973. */
  138974. static void fts3DbExec(
  138975. int *pRc, /* Success code */
  138976. sqlite3 *db, /* Database in which to run SQL */
  138977. const char *zFormat, /* Format string for SQL */
  138978. ... /* Arguments to the format string */
  138979. ){
  138980. va_list ap;
  138981. char *zSql;
  138982. if( *pRc ) return;
  138983. va_start(ap, zFormat);
  138984. zSql = sqlite3_vmprintf(zFormat, ap);
  138985. va_end(ap);
  138986. if( zSql==0 ){
  138987. *pRc = SQLITE_NOMEM;
  138988. }else{
  138989. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  138990. sqlite3_free(zSql);
  138991. }
  138992. }
  138993. /*
  138994. ** The xDestroy() virtual table method.
  138995. */
  138996. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  138997. Fts3Table *p = (Fts3Table *)pVtab;
  138998. int rc = SQLITE_OK; /* Return code */
  138999. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  139000. sqlite3 *db = p->db; /* Database handle */
  139001. /* Drop the shadow tables */
  139002. if( p->zContentTbl==0 ){
  139003. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  139004. }
  139005. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  139006. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  139007. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  139008. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  139009. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  139010. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  139011. ** Otherwise, return an SQLite error code.
  139012. */
  139013. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  139014. }
  139015. /*
  139016. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  139017. ** passed as the first argument. This is done as part of the xConnect()
  139018. ** and xCreate() methods.
  139019. **
  139020. ** If *pRc is non-zero when this function is called, it is a no-op.
  139021. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  139022. ** before returning.
  139023. */
  139024. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  139025. if( *pRc==SQLITE_OK ){
  139026. int i; /* Iterator variable */
  139027. int rc; /* Return code */
  139028. char *zSql; /* SQL statement passed to declare_vtab() */
  139029. char *zCols; /* List of user defined columns */
  139030. const char *zLanguageid;
  139031. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  139032. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  139033. /* Create a list of user columns for the virtual table */
  139034. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  139035. for(i=1; zCols && i<p->nColumn; i++){
  139036. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  139037. }
  139038. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  139039. zSql = sqlite3_mprintf(
  139040. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  139041. zCols, p->zName, zLanguageid
  139042. );
  139043. if( !zCols || !zSql ){
  139044. rc = SQLITE_NOMEM;
  139045. }else{
  139046. rc = sqlite3_declare_vtab(p->db, zSql);
  139047. }
  139048. sqlite3_free(zSql);
  139049. sqlite3_free(zCols);
  139050. *pRc = rc;
  139051. }
  139052. }
  139053. /*
  139054. ** Create the %_stat table if it does not already exist.
  139055. */
  139056. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  139057. fts3DbExec(pRc, p->db,
  139058. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  139059. "(id INTEGER PRIMARY KEY, value BLOB);",
  139060. p->zDb, p->zName
  139061. );
  139062. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  139063. }
  139064. /*
  139065. ** Create the backing store tables (%_content, %_segments and %_segdir)
  139066. ** required by the FTS3 table passed as the only argument. This is done
  139067. ** as part of the vtab xCreate() method.
  139068. **
  139069. ** If the p->bHasDocsize boolean is true (indicating that this is an
  139070. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  139071. ** %_stat tables required by FTS4.
  139072. */
  139073. static int fts3CreateTables(Fts3Table *p){
  139074. int rc = SQLITE_OK; /* Return code */
  139075. int i; /* Iterator variable */
  139076. sqlite3 *db = p->db; /* The database connection */
  139077. if( p->zContentTbl==0 ){
  139078. const char *zLanguageid = p->zLanguageid;
  139079. char *zContentCols; /* Columns of %_content table */
  139080. /* Create a list of user columns for the content table */
  139081. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  139082. for(i=0; zContentCols && i<p->nColumn; i++){
  139083. char *z = p->azColumn[i];
  139084. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  139085. }
  139086. if( zLanguageid && zContentCols ){
  139087. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  139088. }
  139089. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  139090. /* Create the content table */
  139091. fts3DbExec(&rc, db,
  139092. "CREATE TABLE %Q.'%q_content'(%s)",
  139093. p->zDb, p->zName, zContentCols
  139094. );
  139095. sqlite3_free(zContentCols);
  139096. }
  139097. /* Create other tables */
  139098. fts3DbExec(&rc, db,
  139099. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  139100. p->zDb, p->zName
  139101. );
  139102. fts3DbExec(&rc, db,
  139103. "CREATE TABLE %Q.'%q_segdir'("
  139104. "level INTEGER,"
  139105. "idx INTEGER,"
  139106. "start_block INTEGER,"
  139107. "leaves_end_block INTEGER,"
  139108. "end_block INTEGER,"
  139109. "root BLOB,"
  139110. "PRIMARY KEY(level, idx)"
  139111. ");",
  139112. p->zDb, p->zName
  139113. );
  139114. if( p->bHasDocsize ){
  139115. fts3DbExec(&rc, db,
  139116. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  139117. p->zDb, p->zName
  139118. );
  139119. }
  139120. assert( p->bHasStat==p->bFts4 );
  139121. if( p->bHasStat ){
  139122. sqlite3Fts3CreateStatTable(&rc, p);
  139123. }
  139124. return rc;
  139125. }
  139126. /*
  139127. ** Store the current database page-size in bytes in p->nPgsz.
  139128. **
  139129. ** If *pRc is non-zero when this function is called, it is a no-op.
  139130. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  139131. ** before returning.
  139132. */
  139133. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  139134. if( *pRc==SQLITE_OK ){
  139135. int rc; /* Return code */
  139136. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  139137. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  139138. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  139139. if( !zSql ){
  139140. rc = SQLITE_NOMEM;
  139141. }else{
  139142. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  139143. if( rc==SQLITE_OK ){
  139144. sqlite3_step(pStmt);
  139145. p->nPgsz = sqlite3_column_int(pStmt, 0);
  139146. rc = sqlite3_finalize(pStmt);
  139147. }else if( rc==SQLITE_AUTH ){
  139148. p->nPgsz = 1024;
  139149. rc = SQLITE_OK;
  139150. }
  139151. }
  139152. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  139153. sqlite3_free(zSql);
  139154. *pRc = rc;
  139155. }
  139156. }
  139157. /*
  139158. ** "Special" FTS4 arguments are column specifications of the following form:
  139159. **
  139160. ** <key> = <value>
  139161. **
  139162. ** There may not be whitespace surrounding the "=" character. The <value>
  139163. ** term may be quoted, but the <key> may not.
  139164. */
  139165. static int fts3IsSpecialColumn(
  139166. const char *z,
  139167. int *pnKey,
  139168. char **pzValue
  139169. ){
  139170. char *zValue;
  139171. const char *zCsr = z;
  139172. while( *zCsr!='=' ){
  139173. if( *zCsr=='\0' ) return 0;
  139174. zCsr++;
  139175. }
  139176. *pnKey = (int)(zCsr-z);
  139177. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  139178. if( zValue ){
  139179. sqlite3Fts3Dequote(zValue);
  139180. }
  139181. *pzValue = zValue;
  139182. return 1;
  139183. }
  139184. /*
  139185. ** Append the output of a printf() style formatting to an existing string.
  139186. */
  139187. static void fts3Appendf(
  139188. int *pRc, /* IN/OUT: Error code */
  139189. char **pz, /* IN/OUT: Pointer to string buffer */
  139190. const char *zFormat, /* Printf format string to append */
  139191. ... /* Arguments for printf format string */
  139192. ){
  139193. if( *pRc==SQLITE_OK ){
  139194. va_list ap;
  139195. char *z;
  139196. va_start(ap, zFormat);
  139197. z = sqlite3_vmprintf(zFormat, ap);
  139198. va_end(ap);
  139199. if( z && *pz ){
  139200. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  139201. sqlite3_free(z);
  139202. z = z2;
  139203. }
  139204. if( z==0 ) *pRc = SQLITE_NOMEM;
  139205. sqlite3_free(*pz);
  139206. *pz = z;
  139207. }
  139208. }
  139209. /*
  139210. ** Return a copy of input string zInput enclosed in double-quotes (") and
  139211. ** with all double quote characters escaped. For example:
  139212. **
  139213. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  139214. **
  139215. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  139216. ** is the callers responsibility to call sqlite3_free() to release this
  139217. ** memory.
  139218. */
  139219. static char *fts3QuoteId(char const *zInput){
  139220. int nRet;
  139221. char *zRet;
  139222. nRet = 2 + (int)strlen(zInput)*2 + 1;
  139223. zRet = sqlite3_malloc(nRet);
  139224. if( zRet ){
  139225. int i;
  139226. char *z = zRet;
  139227. *(z++) = '"';
  139228. for(i=0; zInput[i]; i++){
  139229. if( zInput[i]=='"' ) *(z++) = '"';
  139230. *(z++) = zInput[i];
  139231. }
  139232. *(z++) = '"';
  139233. *(z++) = '\0';
  139234. }
  139235. return zRet;
  139236. }
  139237. /*
  139238. ** Return a list of comma separated SQL expressions and a FROM clause that
  139239. ** could be used in a SELECT statement such as the following:
  139240. **
  139241. ** SELECT <list of expressions> FROM %_content AS x ...
  139242. **
  139243. ** to return the docid, followed by each column of text data in order
  139244. ** from left to write. If parameter zFunc is not NULL, then instead of
  139245. ** being returned directly each column of text data is passed to an SQL
  139246. ** function named zFunc first. For example, if zFunc is "unzip" and the
  139247. ** table has the three user-defined columns "a", "b", and "c", the following
  139248. ** string is returned:
  139249. **
  139250. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  139251. **
  139252. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  139253. ** is the responsibility of the caller to eventually free it.
  139254. **
  139255. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  139256. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  139257. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  139258. ** no error occurs, *pRc is left unmodified.
  139259. */
  139260. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  139261. char *zRet = 0;
  139262. char *zFree = 0;
  139263. char *zFunction;
  139264. int i;
  139265. if( p->zContentTbl==0 ){
  139266. if( !zFunc ){
  139267. zFunction = "";
  139268. }else{
  139269. zFree = zFunction = fts3QuoteId(zFunc);
  139270. }
  139271. fts3Appendf(pRc, &zRet, "docid");
  139272. for(i=0; i<p->nColumn; i++){
  139273. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  139274. }
  139275. if( p->zLanguageid ){
  139276. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  139277. }
  139278. sqlite3_free(zFree);
  139279. }else{
  139280. fts3Appendf(pRc, &zRet, "rowid");
  139281. for(i=0; i<p->nColumn; i++){
  139282. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  139283. }
  139284. if( p->zLanguageid ){
  139285. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  139286. }
  139287. }
  139288. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  139289. p->zDb,
  139290. (p->zContentTbl ? p->zContentTbl : p->zName),
  139291. (p->zContentTbl ? "" : "_content")
  139292. );
  139293. return zRet;
  139294. }
  139295. /*
  139296. ** Return a list of N comma separated question marks, where N is the number
  139297. ** of columns in the %_content table (one for the docid plus one for each
  139298. ** user-defined text column).
  139299. **
  139300. ** If argument zFunc is not NULL, then all but the first question mark
  139301. ** is preceded by zFunc and an open bracket, and followed by a closed
  139302. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  139303. ** user-defined text columns, the following string is returned:
  139304. **
  139305. ** "?, zip(?), zip(?), zip(?)"
  139306. **
  139307. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  139308. ** is the responsibility of the caller to eventually free it.
  139309. **
  139310. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  139311. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  139312. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  139313. ** no error occurs, *pRc is left unmodified.
  139314. */
  139315. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  139316. char *zRet = 0;
  139317. char *zFree = 0;
  139318. char *zFunction;
  139319. int i;
  139320. if( !zFunc ){
  139321. zFunction = "";
  139322. }else{
  139323. zFree = zFunction = fts3QuoteId(zFunc);
  139324. }
  139325. fts3Appendf(pRc, &zRet, "?");
  139326. for(i=0; i<p->nColumn; i++){
  139327. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  139328. }
  139329. if( p->zLanguageid ){
  139330. fts3Appendf(pRc, &zRet, ", ?");
  139331. }
  139332. sqlite3_free(zFree);
  139333. return zRet;
  139334. }
  139335. /*
  139336. ** This function interprets the string at (*pp) as a non-negative integer
  139337. ** value. It reads the integer and sets *pnOut to the value read, then
  139338. ** sets *pp to point to the byte immediately following the last byte of
  139339. ** the integer value.
  139340. **
  139341. ** Only decimal digits ('0'..'9') may be part of an integer value.
  139342. **
  139343. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  139344. ** the output value undefined. Otherwise SQLITE_OK is returned.
  139345. **
  139346. ** This function is used when parsing the "prefix=" FTS4 parameter.
  139347. */
  139348. static int fts3GobbleInt(const char **pp, int *pnOut){
  139349. const int MAX_NPREFIX = 10000000;
  139350. const char *p; /* Iterator pointer */
  139351. int nInt = 0; /* Output value */
  139352. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  139353. nInt = nInt * 10 + (p[0] - '0');
  139354. if( nInt>MAX_NPREFIX ){
  139355. nInt = 0;
  139356. break;
  139357. }
  139358. }
  139359. if( p==*pp ) return SQLITE_ERROR;
  139360. *pnOut = nInt;
  139361. *pp = p;
  139362. return SQLITE_OK;
  139363. }
  139364. /*
  139365. ** This function is called to allocate an array of Fts3Index structures
  139366. ** representing the indexes maintained by the current FTS table. FTS tables
  139367. ** always maintain the main "terms" index, but may also maintain one or
  139368. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  139369. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  139370. **
  139371. ** Argument zParam is passed the value of the "prefix=" option if one was
  139372. ** specified, or NULL otherwise.
  139373. **
  139374. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  139375. ** the allocated array. *pnIndex is set to the number of elements in the
  139376. ** array. If an error does occur, an SQLite error code is returned.
  139377. **
  139378. ** Regardless of whether or not an error is returned, it is the responsibility
  139379. ** of the caller to call sqlite3_free() on the output array to free it.
  139380. */
  139381. static int fts3PrefixParameter(
  139382. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  139383. int *pnIndex, /* OUT: size of *apIndex[] array */
  139384. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  139385. ){
  139386. struct Fts3Index *aIndex; /* Allocated array */
  139387. int nIndex = 1; /* Number of entries in array */
  139388. if( zParam && zParam[0] ){
  139389. const char *p;
  139390. nIndex++;
  139391. for(p=zParam; *p; p++){
  139392. if( *p==',' ) nIndex++;
  139393. }
  139394. }
  139395. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  139396. *apIndex = aIndex;
  139397. if( !aIndex ){
  139398. return SQLITE_NOMEM;
  139399. }
  139400. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  139401. if( zParam ){
  139402. const char *p = zParam;
  139403. int i;
  139404. for(i=1; i<nIndex; i++){
  139405. int nPrefix = 0;
  139406. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  139407. assert( nPrefix>=0 );
  139408. if( nPrefix==0 ){
  139409. nIndex--;
  139410. i--;
  139411. }else{
  139412. aIndex[i].nPrefix = nPrefix;
  139413. }
  139414. p++;
  139415. }
  139416. }
  139417. *pnIndex = nIndex;
  139418. return SQLITE_OK;
  139419. }
  139420. /*
  139421. ** This function is called when initializing an FTS4 table that uses the
  139422. ** content=xxx option. It determines the number of and names of the columns
  139423. ** of the new FTS4 table.
  139424. **
  139425. ** The third argument passed to this function is the value passed to the
  139426. ** config=xxx option (i.e. "xxx"). This function queries the database for
  139427. ** a table of that name. If found, the output variables are populated
  139428. ** as follows:
  139429. **
  139430. ** *pnCol: Set to the number of columns table xxx has,
  139431. **
  139432. ** *pnStr: Set to the total amount of space required to store a copy
  139433. ** of each columns name, including the nul-terminator.
  139434. **
  139435. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  139436. ** the name of the corresponding column in table xxx. The array
  139437. ** and its contents are allocated using a single allocation. It
  139438. ** is the responsibility of the caller to free this allocation
  139439. ** by eventually passing the *pazCol value to sqlite3_free().
  139440. **
  139441. ** If the table cannot be found, an error code is returned and the output
  139442. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  139443. ** returned (and the output variables are undefined).
  139444. */
  139445. static int fts3ContentColumns(
  139446. sqlite3 *db, /* Database handle */
  139447. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  139448. const char *zTbl, /* Name of content table */
  139449. const char ***pazCol, /* OUT: Malloc'd array of column names */
  139450. int *pnCol, /* OUT: Size of array *pazCol */
  139451. int *pnStr, /* OUT: Bytes of string content */
  139452. char **pzErr /* OUT: error message */
  139453. ){
  139454. int rc = SQLITE_OK; /* Return code */
  139455. char *zSql; /* "SELECT *" statement on zTbl */
  139456. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  139457. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  139458. if( !zSql ){
  139459. rc = SQLITE_NOMEM;
  139460. }else{
  139461. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  139462. if( rc!=SQLITE_OK ){
  139463. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  139464. }
  139465. }
  139466. sqlite3_free(zSql);
  139467. if( rc==SQLITE_OK ){
  139468. const char **azCol; /* Output array */
  139469. int nStr = 0; /* Size of all column names (incl. 0x00) */
  139470. int nCol; /* Number of table columns */
  139471. int i; /* Used to iterate through columns */
  139472. /* Loop through the returned columns. Set nStr to the number of bytes of
  139473. ** space required to store a copy of each column name, including the
  139474. ** nul-terminator byte. */
  139475. nCol = sqlite3_column_count(pStmt);
  139476. for(i=0; i<nCol; i++){
  139477. const char *zCol = sqlite3_column_name(pStmt, i);
  139478. nStr += (int)strlen(zCol) + 1;
  139479. }
  139480. /* Allocate and populate the array to return. */
  139481. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  139482. if( azCol==0 ){
  139483. rc = SQLITE_NOMEM;
  139484. }else{
  139485. char *p = (char *)&azCol[nCol];
  139486. for(i=0; i<nCol; i++){
  139487. const char *zCol = sqlite3_column_name(pStmt, i);
  139488. int n = (int)strlen(zCol)+1;
  139489. memcpy(p, zCol, n);
  139490. azCol[i] = p;
  139491. p += n;
  139492. }
  139493. }
  139494. sqlite3_finalize(pStmt);
  139495. /* Set the output variables. */
  139496. *pnCol = nCol;
  139497. *pnStr = nStr;
  139498. *pazCol = azCol;
  139499. }
  139500. return rc;
  139501. }
  139502. /*
  139503. ** This function is the implementation of both the xConnect and xCreate
  139504. ** methods of the FTS3 virtual table.
  139505. **
  139506. ** The argv[] array contains the following:
  139507. **
  139508. ** argv[0] -> module name ("fts3" or "fts4")
  139509. ** argv[1] -> database name
  139510. ** argv[2] -> table name
  139511. ** argv[...] -> "column name" and other module argument fields.
  139512. */
  139513. static int fts3InitVtab(
  139514. int isCreate, /* True for xCreate, false for xConnect */
  139515. sqlite3 *db, /* The SQLite database connection */
  139516. void *pAux, /* Hash table containing tokenizers */
  139517. int argc, /* Number of elements in argv array */
  139518. const char * const *argv, /* xCreate/xConnect argument array */
  139519. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  139520. char **pzErr /* Write any error message here */
  139521. ){
  139522. Fts3Hash *pHash = (Fts3Hash *)pAux;
  139523. Fts3Table *p = 0; /* Pointer to allocated vtab */
  139524. int rc = SQLITE_OK; /* Return code */
  139525. int i; /* Iterator variable */
  139526. int nByte; /* Size of allocation used for *p */
  139527. int iCol; /* Column index */
  139528. int nString = 0; /* Bytes required to hold all column names */
  139529. int nCol = 0; /* Number of columns in the FTS table */
  139530. char *zCsr; /* Space for holding column names */
  139531. int nDb; /* Bytes required to hold database name */
  139532. int nName; /* Bytes required to hold table name */
  139533. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  139534. const char **aCol; /* Array of column names */
  139535. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  139536. int nIndex = 0; /* Size of aIndex[] array */
  139537. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  139538. /* The results of parsing supported FTS4 key=value options: */
  139539. int bNoDocsize = 0; /* True to omit %_docsize table */
  139540. int bDescIdx = 0; /* True to store descending indexes */
  139541. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  139542. char *zCompress = 0; /* compress=? parameter (or NULL) */
  139543. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  139544. char *zContent = 0; /* content=? parameter (or NULL) */
  139545. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  139546. char **azNotindexed = 0; /* The set of notindexed= columns */
  139547. int nNotindexed = 0; /* Size of azNotindexed[] array */
  139548. assert( strlen(argv[0])==4 );
  139549. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  139550. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  139551. );
  139552. nDb = (int)strlen(argv[1]) + 1;
  139553. nName = (int)strlen(argv[2]) + 1;
  139554. nByte = sizeof(const char *) * (argc-2);
  139555. aCol = (const char **)sqlite3_malloc(nByte);
  139556. if( aCol ){
  139557. memset((void*)aCol, 0, nByte);
  139558. azNotindexed = (char **)sqlite3_malloc(nByte);
  139559. }
  139560. if( azNotindexed ){
  139561. memset(azNotindexed, 0, nByte);
  139562. }
  139563. if( !aCol || !azNotindexed ){
  139564. rc = SQLITE_NOMEM;
  139565. goto fts3_init_out;
  139566. }
  139567. /* Loop through all of the arguments passed by the user to the FTS3/4
  139568. ** module (i.e. all the column names and special arguments). This loop
  139569. ** does the following:
  139570. **
  139571. ** + Figures out the number of columns the FTSX table will have, and
  139572. ** the number of bytes of space that must be allocated to store copies
  139573. ** of the column names.
  139574. **
  139575. ** + If there is a tokenizer specification included in the arguments,
  139576. ** initializes the tokenizer pTokenizer.
  139577. */
  139578. for(i=3; rc==SQLITE_OK && i<argc; i++){
  139579. char const *z = argv[i];
  139580. int nKey;
  139581. char *zVal;
  139582. /* Check if this is a tokenizer specification */
  139583. if( !pTokenizer
  139584. && strlen(z)>8
  139585. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  139586. && 0==sqlite3Fts3IsIdChar(z[8])
  139587. ){
  139588. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  139589. }
  139590. /* Check if it is an FTS4 special argument. */
  139591. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  139592. struct Fts4Option {
  139593. const char *zOpt;
  139594. int nOpt;
  139595. } aFts4Opt[] = {
  139596. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  139597. { "prefix", 6 }, /* 1 -> PREFIX */
  139598. { "compress", 8 }, /* 2 -> COMPRESS */
  139599. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  139600. { "order", 5 }, /* 4 -> ORDER */
  139601. { "content", 7 }, /* 5 -> CONTENT */
  139602. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  139603. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  139604. };
  139605. int iOpt;
  139606. if( !zVal ){
  139607. rc = SQLITE_NOMEM;
  139608. }else{
  139609. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  139610. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  139611. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  139612. break;
  139613. }
  139614. }
  139615. switch( iOpt ){
  139616. case 0: /* MATCHINFO */
  139617. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  139618. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  139619. rc = SQLITE_ERROR;
  139620. }
  139621. bNoDocsize = 1;
  139622. break;
  139623. case 1: /* PREFIX */
  139624. sqlite3_free(zPrefix);
  139625. zPrefix = zVal;
  139626. zVal = 0;
  139627. break;
  139628. case 2: /* COMPRESS */
  139629. sqlite3_free(zCompress);
  139630. zCompress = zVal;
  139631. zVal = 0;
  139632. break;
  139633. case 3: /* UNCOMPRESS */
  139634. sqlite3_free(zUncompress);
  139635. zUncompress = zVal;
  139636. zVal = 0;
  139637. break;
  139638. case 4: /* ORDER */
  139639. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  139640. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  139641. ){
  139642. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  139643. rc = SQLITE_ERROR;
  139644. }
  139645. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  139646. break;
  139647. case 5: /* CONTENT */
  139648. sqlite3_free(zContent);
  139649. zContent = zVal;
  139650. zVal = 0;
  139651. break;
  139652. case 6: /* LANGUAGEID */
  139653. assert( iOpt==6 );
  139654. sqlite3_free(zLanguageid);
  139655. zLanguageid = zVal;
  139656. zVal = 0;
  139657. break;
  139658. case 7: /* NOTINDEXED */
  139659. azNotindexed[nNotindexed++] = zVal;
  139660. zVal = 0;
  139661. break;
  139662. default:
  139663. assert( iOpt==SizeofArray(aFts4Opt) );
  139664. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  139665. rc = SQLITE_ERROR;
  139666. break;
  139667. }
  139668. sqlite3_free(zVal);
  139669. }
  139670. }
  139671. /* Otherwise, the argument is a column name. */
  139672. else {
  139673. nString += (int)(strlen(z) + 1);
  139674. aCol[nCol++] = z;
  139675. }
  139676. }
  139677. /* If a content=xxx option was specified, the following:
  139678. **
  139679. ** 1. Ignore any compress= and uncompress= options.
  139680. **
  139681. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  139682. ** TABLE statement, use all columns from the content table.
  139683. */
  139684. if( rc==SQLITE_OK && zContent ){
  139685. sqlite3_free(zCompress);
  139686. sqlite3_free(zUncompress);
  139687. zCompress = 0;
  139688. zUncompress = 0;
  139689. if( nCol==0 ){
  139690. sqlite3_free((void*)aCol);
  139691. aCol = 0;
  139692. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  139693. /* If a languageid= option was specified, remove the language id
  139694. ** column from the aCol[] array. */
  139695. if( rc==SQLITE_OK && zLanguageid ){
  139696. int j;
  139697. for(j=0; j<nCol; j++){
  139698. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  139699. int k;
  139700. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  139701. nCol--;
  139702. break;
  139703. }
  139704. }
  139705. }
  139706. }
  139707. }
  139708. if( rc!=SQLITE_OK ) goto fts3_init_out;
  139709. if( nCol==0 ){
  139710. assert( nString==0 );
  139711. aCol[0] = "content";
  139712. nString = 8;
  139713. nCol = 1;
  139714. }
  139715. if( pTokenizer==0 ){
  139716. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  139717. if( rc!=SQLITE_OK ) goto fts3_init_out;
  139718. }
  139719. assert( pTokenizer );
  139720. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  139721. if( rc==SQLITE_ERROR ){
  139722. assert( zPrefix );
  139723. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  139724. }
  139725. if( rc!=SQLITE_OK ) goto fts3_init_out;
  139726. /* Allocate and populate the Fts3Table structure. */
  139727. nByte = sizeof(Fts3Table) + /* Fts3Table */
  139728. nCol * sizeof(char *) + /* azColumn */
  139729. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  139730. nCol * sizeof(u8) + /* abNotindexed */
  139731. nName + /* zName */
  139732. nDb + /* zDb */
  139733. nString; /* Space for azColumn strings */
  139734. p = (Fts3Table*)sqlite3_malloc(nByte);
  139735. if( p==0 ){
  139736. rc = SQLITE_NOMEM;
  139737. goto fts3_init_out;
  139738. }
  139739. memset(p, 0, nByte);
  139740. p->db = db;
  139741. p->nColumn = nCol;
  139742. p->nPendingData = 0;
  139743. p->azColumn = (char **)&p[1];
  139744. p->pTokenizer = pTokenizer;
  139745. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  139746. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  139747. p->bHasStat = (u8)isFts4;
  139748. p->bFts4 = (u8)isFts4;
  139749. p->bDescIdx = (u8)bDescIdx;
  139750. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  139751. p->zContentTbl = zContent;
  139752. p->zLanguageid = zLanguageid;
  139753. zContent = 0;
  139754. zLanguageid = 0;
  139755. TESTONLY( p->inTransaction = -1 );
  139756. TESTONLY( p->mxSavepoint = -1 );
  139757. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  139758. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  139759. p->nIndex = nIndex;
  139760. for(i=0; i<nIndex; i++){
  139761. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  139762. }
  139763. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  139764. /* Fill in the zName and zDb fields of the vtab structure. */
  139765. zCsr = (char *)&p->abNotindexed[nCol];
  139766. p->zName = zCsr;
  139767. memcpy(zCsr, argv[2], nName);
  139768. zCsr += nName;
  139769. p->zDb = zCsr;
  139770. memcpy(zCsr, argv[1], nDb);
  139771. zCsr += nDb;
  139772. /* Fill in the azColumn array */
  139773. for(iCol=0; iCol<nCol; iCol++){
  139774. char *z;
  139775. int n = 0;
  139776. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  139777. if( n>0 ){
  139778. memcpy(zCsr, z, n);
  139779. }
  139780. zCsr[n] = '\0';
  139781. sqlite3Fts3Dequote(zCsr);
  139782. p->azColumn[iCol] = zCsr;
  139783. zCsr += n+1;
  139784. assert( zCsr <= &((char *)p)[nByte] );
  139785. }
  139786. /* Fill in the abNotindexed array */
  139787. for(iCol=0; iCol<nCol; iCol++){
  139788. int n = (int)strlen(p->azColumn[iCol]);
  139789. for(i=0; i<nNotindexed; i++){
  139790. char *zNot = azNotindexed[i];
  139791. if( zNot && n==(int)strlen(zNot)
  139792. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  139793. ){
  139794. p->abNotindexed[iCol] = 1;
  139795. sqlite3_free(zNot);
  139796. azNotindexed[i] = 0;
  139797. }
  139798. }
  139799. }
  139800. for(i=0; i<nNotindexed; i++){
  139801. if( azNotindexed[i] ){
  139802. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  139803. rc = SQLITE_ERROR;
  139804. }
  139805. }
  139806. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  139807. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  139808. rc = SQLITE_ERROR;
  139809. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  139810. }
  139811. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  139812. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  139813. if( rc!=SQLITE_OK ) goto fts3_init_out;
  139814. /* If this is an xCreate call, create the underlying tables in the
  139815. ** database. TODO: For xConnect(), it could verify that said tables exist.
  139816. */
  139817. if( isCreate ){
  139818. rc = fts3CreateTables(p);
  139819. }
  139820. /* Check to see if a legacy fts3 table has been "upgraded" by the
  139821. ** addition of a %_stat table so that it can use incremental merge.
  139822. */
  139823. if( !isFts4 && !isCreate ){
  139824. p->bHasStat = 2;
  139825. }
  139826. /* Figure out the page-size for the database. This is required in order to
  139827. ** estimate the cost of loading large doclists from the database. */
  139828. fts3DatabasePageSize(&rc, p);
  139829. p->nNodeSize = p->nPgsz-35;
  139830. /* Declare the table schema to SQLite. */
  139831. fts3DeclareVtab(&rc, p);
  139832. fts3_init_out:
  139833. sqlite3_free(zPrefix);
  139834. sqlite3_free(aIndex);
  139835. sqlite3_free(zCompress);
  139836. sqlite3_free(zUncompress);
  139837. sqlite3_free(zContent);
  139838. sqlite3_free(zLanguageid);
  139839. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  139840. sqlite3_free((void *)aCol);
  139841. sqlite3_free((void *)azNotindexed);
  139842. if( rc!=SQLITE_OK ){
  139843. if( p ){
  139844. fts3DisconnectMethod((sqlite3_vtab *)p);
  139845. }else if( pTokenizer ){
  139846. pTokenizer->pModule->xDestroy(pTokenizer);
  139847. }
  139848. }else{
  139849. assert( p->pSegments==0 );
  139850. *ppVTab = &p->base;
  139851. }
  139852. return rc;
  139853. }
  139854. /*
  139855. ** The xConnect() and xCreate() methods for the virtual table. All the
  139856. ** work is done in function fts3InitVtab().
  139857. */
  139858. static int fts3ConnectMethod(
  139859. sqlite3 *db, /* Database connection */
  139860. void *pAux, /* Pointer to tokenizer hash table */
  139861. int argc, /* Number of elements in argv array */
  139862. const char * const *argv, /* xCreate/xConnect argument array */
  139863. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  139864. char **pzErr /* OUT: sqlite3_malloc'd error message */
  139865. ){
  139866. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  139867. }
  139868. static int fts3CreateMethod(
  139869. sqlite3 *db, /* Database connection */
  139870. void *pAux, /* Pointer to tokenizer hash table */
  139871. int argc, /* Number of elements in argv array */
  139872. const char * const *argv, /* xCreate/xConnect argument array */
  139873. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  139874. char **pzErr /* OUT: sqlite3_malloc'd error message */
  139875. ){
  139876. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  139877. }
  139878. /*
  139879. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  139880. ** extension is currently being used by a version of SQLite too old to
  139881. ** support estimatedRows. In that case this function is a no-op.
  139882. */
  139883. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  139884. #if SQLITE_VERSION_NUMBER>=3008002
  139885. if( sqlite3_libversion_number()>=3008002 ){
  139886. pIdxInfo->estimatedRows = nRow;
  139887. }
  139888. #endif
  139889. }
  139890. /*
  139891. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  139892. ** extension is currently being used by a version of SQLite too old to
  139893. ** support index-info flags. In that case this function is a no-op.
  139894. */
  139895. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  139896. #if SQLITE_VERSION_NUMBER>=3008012
  139897. if( sqlite3_libversion_number()>=3008012 ){
  139898. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  139899. }
  139900. #endif
  139901. }
  139902. /*
  139903. ** Implementation of the xBestIndex method for FTS3 tables. There
  139904. ** are three possible strategies, in order of preference:
  139905. **
  139906. ** 1. Direct lookup by rowid or docid.
  139907. ** 2. Full-text search using a MATCH operator on a non-docid column.
  139908. ** 3. Linear scan of %_content table.
  139909. */
  139910. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  139911. Fts3Table *p = (Fts3Table *)pVTab;
  139912. int i; /* Iterator variable */
  139913. int iCons = -1; /* Index of constraint to use */
  139914. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  139915. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  139916. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  139917. int iIdx;
  139918. /* By default use a full table scan. This is an expensive option,
  139919. ** so search through the constraints to see if a more efficient
  139920. ** strategy is possible.
  139921. */
  139922. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  139923. pInfo->estimatedCost = 5000000;
  139924. for(i=0; i<pInfo->nConstraint; i++){
  139925. int bDocid; /* True if this constraint is on docid */
  139926. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  139927. if( pCons->usable==0 ){
  139928. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  139929. /* There exists an unusable MATCH constraint. This means that if
  139930. ** the planner does elect to use the results of this call as part
  139931. ** of the overall query plan the user will see an "unable to use
  139932. ** function MATCH in the requested context" error. To discourage
  139933. ** this, return a very high cost here. */
  139934. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  139935. pInfo->estimatedCost = 1e50;
  139936. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  139937. return SQLITE_OK;
  139938. }
  139939. continue;
  139940. }
  139941. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  139942. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  139943. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  139944. pInfo->idxNum = FTS3_DOCID_SEARCH;
  139945. pInfo->estimatedCost = 1.0;
  139946. iCons = i;
  139947. }
  139948. /* A MATCH constraint. Use a full-text search.
  139949. **
  139950. ** If there is more than one MATCH constraint available, use the first
  139951. ** one encountered. If there is both a MATCH constraint and a direct
  139952. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  139953. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  139954. ** it would lead to an "unable to use function MATCH in the requested
  139955. ** context" error.
  139956. */
  139957. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  139958. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  139959. ){
  139960. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  139961. pInfo->estimatedCost = 2.0;
  139962. iCons = i;
  139963. }
  139964. /* Equality constraint on the langid column */
  139965. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  139966. && pCons->iColumn==p->nColumn + 2
  139967. ){
  139968. iLangidCons = i;
  139969. }
  139970. if( bDocid ){
  139971. switch( pCons->op ){
  139972. case SQLITE_INDEX_CONSTRAINT_GE:
  139973. case SQLITE_INDEX_CONSTRAINT_GT:
  139974. iDocidGe = i;
  139975. break;
  139976. case SQLITE_INDEX_CONSTRAINT_LE:
  139977. case SQLITE_INDEX_CONSTRAINT_LT:
  139978. iDocidLe = i;
  139979. break;
  139980. }
  139981. }
  139982. }
  139983. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  139984. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  139985. iIdx = 1;
  139986. if( iCons>=0 ){
  139987. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  139988. pInfo->aConstraintUsage[iCons].omit = 1;
  139989. }
  139990. if( iLangidCons>=0 ){
  139991. pInfo->idxNum |= FTS3_HAVE_LANGID;
  139992. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  139993. }
  139994. if( iDocidGe>=0 ){
  139995. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  139996. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  139997. }
  139998. if( iDocidLe>=0 ){
  139999. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  140000. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  140001. }
  140002. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  140003. ** docid) order. Both ascending and descending are possible.
  140004. */
  140005. if( pInfo->nOrderBy==1 ){
  140006. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  140007. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  140008. if( pOrder->desc ){
  140009. pInfo->idxStr = "DESC";
  140010. }else{
  140011. pInfo->idxStr = "ASC";
  140012. }
  140013. pInfo->orderByConsumed = 1;
  140014. }
  140015. }
  140016. assert( p->pSegments==0 );
  140017. return SQLITE_OK;
  140018. }
  140019. /*
  140020. ** Implementation of xOpen method.
  140021. */
  140022. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  140023. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  140024. UNUSED_PARAMETER(pVTab);
  140025. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  140026. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  140027. ** if the allocation fails, return SQLITE_NOMEM.
  140028. */
  140029. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  140030. if( !pCsr ){
  140031. return SQLITE_NOMEM;
  140032. }
  140033. memset(pCsr, 0, sizeof(Fts3Cursor));
  140034. return SQLITE_OK;
  140035. }
  140036. /*
  140037. ** Finalize the statement handle at pCsr->pStmt.
  140038. **
  140039. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  140040. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  140041. ** pointer there instead of finalizing it.
  140042. */
  140043. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  140044. if( pCsr->bSeekStmt ){
  140045. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  140046. if( p->pSeekStmt==0 ){
  140047. p->pSeekStmt = pCsr->pStmt;
  140048. sqlite3_reset(pCsr->pStmt);
  140049. pCsr->pStmt = 0;
  140050. }
  140051. pCsr->bSeekStmt = 0;
  140052. }
  140053. sqlite3_finalize(pCsr->pStmt);
  140054. }
  140055. /*
  140056. ** Free all resources currently held by the cursor passed as the only
  140057. ** argument.
  140058. */
  140059. static void fts3ClearCursor(Fts3Cursor *pCsr){
  140060. fts3CursorFinalizeStmt(pCsr);
  140061. sqlite3Fts3FreeDeferredTokens(pCsr);
  140062. sqlite3_free(pCsr->aDoclist);
  140063. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  140064. sqlite3Fts3ExprFree(pCsr->pExpr);
  140065. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  140066. }
  140067. /*
  140068. ** Close the cursor. For additional information see the documentation
  140069. ** on the xClose method of the virtual table interface.
  140070. */
  140071. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  140072. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  140073. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  140074. fts3ClearCursor(pCsr);
  140075. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  140076. sqlite3_free(pCsr);
  140077. return SQLITE_OK;
  140078. }
  140079. /*
  140080. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  140081. ** compose and prepare an SQL statement of the form:
  140082. **
  140083. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  140084. **
  140085. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  140086. ** it. If an error occurs, return an SQLite error code.
  140087. */
  140088. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  140089. int rc = SQLITE_OK;
  140090. if( pCsr->pStmt==0 ){
  140091. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  140092. char *zSql;
  140093. if( p->pSeekStmt ){
  140094. pCsr->pStmt = p->pSeekStmt;
  140095. p->pSeekStmt = 0;
  140096. }else{
  140097. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  140098. if( !zSql ) return SQLITE_NOMEM;
  140099. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  140100. sqlite3_free(zSql);
  140101. }
  140102. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  140103. }
  140104. return rc;
  140105. }
  140106. /*
  140107. ** Position the pCsr->pStmt statement so that it is on the row
  140108. ** of the %_content table that contains the last match. Return
  140109. ** SQLITE_OK on success.
  140110. */
  140111. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  140112. int rc = SQLITE_OK;
  140113. if( pCsr->isRequireSeek ){
  140114. rc = fts3CursorSeekStmt(pCsr);
  140115. if( rc==SQLITE_OK ){
  140116. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  140117. pCsr->isRequireSeek = 0;
  140118. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  140119. return SQLITE_OK;
  140120. }else{
  140121. rc = sqlite3_reset(pCsr->pStmt);
  140122. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  140123. /* If no row was found and no error has occurred, then the %_content
  140124. ** table is missing a row that is present in the full-text index.
  140125. ** The data structures are corrupt. */
  140126. rc = FTS_CORRUPT_VTAB;
  140127. pCsr->isEof = 1;
  140128. }
  140129. }
  140130. }
  140131. }
  140132. if( rc!=SQLITE_OK && pContext ){
  140133. sqlite3_result_error_code(pContext, rc);
  140134. }
  140135. return rc;
  140136. }
  140137. /*
  140138. ** This function is used to process a single interior node when searching
  140139. ** a b-tree for a term or term prefix. The node data is passed to this
  140140. ** function via the zNode/nNode parameters. The term to search for is
  140141. ** passed in zTerm/nTerm.
  140142. **
  140143. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  140144. ** of the child node that heads the sub-tree that may contain the term.
  140145. **
  140146. ** If piLast is not NULL, then *piLast is set to the right-most child node
  140147. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  140148. ** a prefix.
  140149. **
  140150. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  140151. */
  140152. static int fts3ScanInteriorNode(
  140153. const char *zTerm, /* Term to select leaves for */
  140154. int nTerm, /* Size of term zTerm in bytes */
  140155. const char *zNode, /* Buffer containing segment interior node */
  140156. int nNode, /* Size of buffer at zNode */
  140157. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  140158. sqlite3_int64 *piLast /* OUT: Selected child node */
  140159. ){
  140160. int rc = SQLITE_OK; /* Return code */
  140161. const char *zCsr = zNode; /* Cursor to iterate through node */
  140162. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  140163. char *zBuffer = 0; /* Buffer to load terms into */
  140164. int nAlloc = 0; /* Size of allocated buffer */
  140165. int isFirstTerm = 1; /* True when processing first term on page */
  140166. sqlite3_int64 iChild; /* Block id of child node to descend to */
  140167. /* Skip over the 'height' varint that occurs at the start of every
  140168. ** interior node. Then load the blockid of the left-child of the b-tree
  140169. ** node into variable iChild.
  140170. **
  140171. ** Even if the data structure on disk is corrupted, this (reading two
  140172. ** varints from the buffer) does not risk an overread. If zNode is a
  140173. ** root node, then the buffer comes from a SELECT statement. SQLite does
  140174. ** not make this guarantee explicitly, but in practice there are always
  140175. ** either more than 20 bytes of allocated space following the nNode bytes of
  140176. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  140177. ** table, then there are always 20 bytes of zeroed padding following the
  140178. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  140179. */
  140180. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  140181. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  140182. if( zCsr>zEnd ){
  140183. return FTS_CORRUPT_VTAB;
  140184. }
  140185. while( zCsr<zEnd && (piFirst || piLast) ){
  140186. int cmp; /* memcmp() result */
  140187. int nSuffix; /* Size of term suffix */
  140188. int nPrefix = 0; /* Size of term prefix */
  140189. int nBuffer; /* Total term size */
  140190. /* Load the next term on the node into zBuffer. Use realloc() to expand
  140191. ** the size of zBuffer if required. */
  140192. if( !isFirstTerm ){
  140193. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  140194. }
  140195. isFirstTerm = 0;
  140196. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  140197. assert( nPrefix>=0 && nSuffix>=0 );
  140198. if( &zCsr[nSuffix]>zEnd ){
  140199. rc = FTS_CORRUPT_VTAB;
  140200. goto finish_scan;
  140201. }
  140202. if( nPrefix+nSuffix>nAlloc ){
  140203. char *zNew;
  140204. nAlloc = (nPrefix+nSuffix) * 2;
  140205. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  140206. if( !zNew ){
  140207. rc = SQLITE_NOMEM;
  140208. goto finish_scan;
  140209. }
  140210. zBuffer = zNew;
  140211. }
  140212. assert( zBuffer );
  140213. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  140214. nBuffer = nPrefix + nSuffix;
  140215. zCsr += nSuffix;
  140216. /* Compare the term we are searching for with the term just loaded from
  140217. ** the interior node. If the specified term is greater than or equal
  140218. ** to the term from the interior node, then all terms on the sub-tree
  140219. ** headed by node iChild are smaller than zTerm. No need to search
  140220. ** iChild.
  140221. **
  140222. ** If the interior node term is larger than the specified term, then
  140223. ** the tree headed by iChild may contain the specified term.
  140224. */
  140225. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  140226. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  140227. *piFirst = iChild;
  140228. piFirst = 0;
  140229. }
  140230. if( piLast && cmp<0 ){
  140231. *piLast = iChild;
  140232. piLast = 0;
  140233. }
  140234. iChild++;
  140235. };
  140236. if( piFirst ) *piFirst = iChild;
  140237. if( piLast ) *piLast = iChild;
  140238. finish_scan:
  140239. sqlite3_free(zBuffer);
  140240. return rc;
  140241. }
  140242. /*
  140243. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  140244. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  140245. ** contains a term. This function searches the sub-tree headed by the zNode
  140246. ** node for the range of leaf nodes that may contain the specified term
  140247. ** or terms for which the specified term is a prefix.
  140248. **
  140249. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  140250. ** left-most leaf node in the tree that may contain the specified term.
  140251. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  140252. ** right-most leaf node that may contain a term for which the specified
  140253. ** term is a prefix.
  140254. **
  140255. ** It is possible that the range of returned leaf nodes does not contain
  140256. ** the specified term or any terms for which it is a prefix. However, if the
  140257. ** segment does contain any such terms, they are stored within the identified
  140258. ** range. Because this function only inspects interior segment nodes (and
  140259. ** never loads leaf nodes into memory), it is not possible to be sure.
  140260. **
  140261. ** If an error occurs, an error code other than SQLITE_OK is returned.
  140262. */
  140263. static int fts3SelectLeaf(
  140264. Fts3Table *p, /* Virtual table handle */
  140265. const char *zTerm, /* Term to select leaves for */
  140266. int nTerm, /* Size of term zTerm in bytes */
  140267. const char *zNode, /* Buffer containing segment interior node */
  140268. int nNode, /* Size of buffer at zNode */
  140269. sqlite3_int64 *piLeaf, /* Selected leaf node */
  140270. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  140271. ){
  140272. int rc = SQLITE_OK; /* Return code */
  140273. int iHeight; /* Height of this node in tree */
  140274. assert( piLeaf || piLeaf2 );
  140275. fts3GetVarint32(zNode, &iHeight);
  140276. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  140277. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  140278. if( rc==SQLITE_OK && iHeight>1 ){
  140279. char *zBlob = 0; /* Blob read from %_segments table */
  140280. int nBlob = 0; /* Size of zBlob in bytes */
  140281. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  140282. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  140283. if( rc==SQLITE_OK ){
  140284. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  140285. }
  140286. sqlite3_free(zBlob);
  140287. piLeaf = 0;
  140288. zBlob = 0;
  140289. }
  140290. if( rc==SQLITE_OK ){
  140291. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  140292. }
  140293. if( rc==SQLITE_OK ){
  140294. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  140295. }
  140296. sqlite3_free(zBlob);
  140297. }
  140298. return rc;
  140299. }
  140300. /*
  140301. ** This function is used to create delta-encoded serialized lists of FTS3
  140302. ** varints. Each call to this function appends a single varint to a list.
  140303. */
  140304. static void fts3PutDeltaVarint(
  140305. char **pp, /* IN/OUT: Output pointer */
  140306. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  140307. sqlite3_int64 iVal /* Write this value to the list */
  140308. ){
  140309. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  140310. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  140311. *piPrev = iVal;
  140312. }
  140313. /*
  140314. ** When this function is called, *ppPoslist is assumed to point to the
  140315. ** start of a position-list. After it returns, *ppPoslist points to the
  140316. ** first byte after the position-list.
  140317. **
  140318. ** A position list is list of positions (delta encoded) and columns for
  140319. ** a single document record of a doclist. So, in other words, this
  140320. ** routine advances *ppPoslist so that it points to the next docid in
  140321. ** the doclist, or to the first byte past the end of the doclist.
  140322. **
  140323. ** If pp is not NULL, then the contents of the position list are copied
  140324. ** to *pp. *pp is set to point to the first byte past the last byte copied
  140325. ** before this function returns.
  140326. */
  140327. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  140328. char *pEnd = *ppPoslist;
  140329. char c = 0;
  140330. /* The end of a position list is marked by a zero encoded as an FTS3
  140331. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  140332. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  140333. ** of some other, multi-byte, value.
  140334. **
  140335. ** The following while-loop moves pEnd to point to the first byte that is not
  140336. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  140337. ** pEnd once more so that it points to the byte immediately following the
  140338. ** last byte in the position-list.
  140339. */
  140340. while( *pEnd | c ){
  140341. c = *pEnd++ & 0x80;
  140342. testcase( c!=0 && (*pEnd)==0 );
  140343. }
  140344. pEnd++; /* Advance past the POS_END terminator byte */
  140345. if( pp ){
  140346. int n = (int)(pEnd - *ppPoslist);
  140347. char *p = *pp;
  140348. memcpy(p, *ppPoslist, n);
  140349. p += n;
  140350. *pp = p;
  140351. }
  140352. *ppPoslist = pEnd;
  140353. }
  140354. /*
  140355. ** When this function is called, *ppPoslist is assumed to point to the
  140356. ** start of a column-list. After it returns, *ppPoslist points to the
  140357. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  140358. **
  140359. ** A column-list is list of delta-encoded positions for a single column
  140360. ** within a single document within a doclist.
  140361. **
  140362. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  140363. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  140364. ** the POS_COLUMN or POS_END that terminates the column-list.
  140365. **
  140366. ** If pp is not NULL, then the contents of the column-list are copied
  140367. ** to *pp. *pp is set to point to the first byte past the last byte copied
  140368. ** before this function returns. The POS_COLUMN or POS_END terminator
  140369. ** is not copied into *pp.
  140370. */
  140371. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  140372. char *pEnd = *ppPoslist;
  140373. char c = 0;
  140374. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  140375. ** not part of a multi-byte varint.
  140376. */
  140377. while( 0xFE & (*pEnd | c) ){
  140378. c = *pEnd++ & 0x80;
  140379. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  140380. }
  140381. if( pp ){
  140382. int n = (int)(pEnd - *ppPoslist);
  140383. char *p = *pp;
  140384. memcpy(p, *ppPoslist, n);
  140385. p += n;
  140386. *pp = p;
  140387. }
  140388. *ppPoslist = pEnd;
  140389. }
  140390. /*
  140391. ** Value used to signify the end of an position-list. This is safe because
  140392. ** it is not possible to have a document with 2^31 terms.
  140393. */
  140394. #define POSITION_LIST_END 0x7fffffff
  140395. /*
  140396. ** This function is used to help parse position-lists. When this function is
  140397. ** called, *pp may point to the start of the next varint in the position-list
  140398. ** being parsed, or it may point to 1 byte past the end of the position-list
  140399. ** (in which case **pp will be a terminator bytes POS_END (0) or
  140400. ** (1)).
  140401. **
  140402. ** If *pp points past the end of the current position-list, set *pi to
  140403. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  140404. ** increment the current value of *pi by the value read, and set *pp to
  140405. ** point to the next value before returning.
  140406. **
  140407. ** Before calling this routine *pi must be initialized to the value of
  140408. ** the previous position, or zero if we are reading the first position
  140409. ** in the position-list. Because positions are delta-encoded, the value
  140410. ** of the previous position is needed in order to compute the value of
  140411. ** the next position.
  140412. */
  140413. static void fts3ReadNextPos(
  140414. char **pp, /* IN/OUT: Pointer into position-list buffer */
  140415. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  140416. ){
  140417. if( (**pp)&0xFE ){
  140418. fts3GetDeltaVarint(pp, pi);
  140419. *pi -= 2;
  140420. }else{
  140421. *pi = POSITION_LIST_END;
  140422. }
  140423. }
  140424. /*
  140425. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  140426. ** the value of iCol encoded as a varint to *pp. This will start a new
  140427. ** column list.
  140428. **
  140429. ** Set *pp to point to the byte just after the last byte written before
  140430. ** returning (do not modify it if iCol==0). Return the total number of bytes
  140431. ** written (0 if iCol==0).
  140432. */
  140433. static int fts3PutColNumber(char **pp, int iCol){
  140434. int n = 0; /* Number of bytes written */
  140435. if( iCol ){
  140436. char *p = *pp; /* Output pointer */
  140437. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  140438. *p = 0x01;
  140439. *pp = &p[n];
  140440. }
  140441. return n;
  140442. }
  140443. /*
  140444. ** Compute the union of two position lists. The output written
  140445. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  140446. ** order and with any duplicates removed. All pointers are
  140447. ** updated appropriately. The caller is responsible for insuring
  140448. ** that there is enough space in *pp to hold the complete output.
  140449. */
  140450. static void fts3PoslistMerge(
  140451. char **pp, /* Output buffer */
  140452. char **pp1, /* Left input list */
  140453. char **pp2 /* Right input list */
  140454. ){
  140455. char *p = *pp;
  140456. char *p1 = *pp1;
  140457. char *p2 = *pp2;
  140458. while( *p1 || *p2 ){
  140459. int iCol1; /* The current column index in pp1 */
  140460. int iCol2; /* The current column index in pp2 */
  140461. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  140462. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  140463. else iCol1 = 0;
  140464. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  140465. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  140466. else iCol2 = 0;
  140467. if( iCol1==iCol2 ){
  140468. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  140469. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  140470. sqlite3_int64 iPrev = 0;
  140471. int n = fts3PutColNumber(&p, iCol1);
  140472. p1 += n;
  140473. p2 += n;
  140474. /* At this point, both p1 and p2 point to the start of column-lists
  140475. ** for the same column (the column with index iCol1 and iCol2).
  140476. ** A column-list is a list of non-negative delta-encoded varints, each
  140477. ** incremented by 2 before being stored. Each list is terminated by a
  140478. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  140479. ** and writes the results to buffer p. p is left pointing to the byte
  140480. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  140481. ** written to the output.
  140482. */
  140483. fts3GetDeltaVarint(&p1, &i1);
  140484. fts3GetDeltaVarint(&p2, &i2);
  140485. do {
  140486. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  140487. iPrev -= 2;
  140488. if( i1==i2 ){
  140489. fts3ReadNextPos(&p1, &i1);
  140490. fts3ReadNextPos(&p2, &i2);
  140491. }else if( i1<i2 ){
  140492. fts3ReadNextPos(&p1, &i1);
  140493. }else{
  140494. fts3ReadNextPos(&p2, &i2);
  140495. }
  140496. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  140497. }else if( iCol1<iCol2 ){
  140498. p1 += fts3PutColNumber(&p, iCol1);
  140499. fts3ColumnlistCopy(&p, &p1);
  140500. }else{
  140501. p2 += fts3PutColNumber(&p, iCol2);
  140502. fts3ColumnlistCopy(&p, &p2);
  140503. }
  140504. }
  140505. *p++ = POS_END;
  140506. *pp = p;
  140507. *pp1 = p1 + 1;
  140508. *pp2 = p2 + 1;
  140509. }
  140510. /*
  140511. ** This function is used to merge two position lists into one. When it is
  140512. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  140513. ** the part of a doclist that follows each document id. For example, if a row
  140514. ** contains:
  140515. **
  140516. ** 'a b c'|'x y z'|'a b b a'
  140517. **
  140518. ** Then the position list for this row for token 'b' would consist of:
  140519. **
  140520. ** 0x02 0x01 0x02 0x03 0x03 0x00
  140521. **
  140522. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  140523. ** byte following the 0x00 terminator of their respective position lists.
  140524. **
  140525. ** If isSaveLeft is 0, an entry is added to the output position list for
  140526. ** each position in *pp2 for which there exists one or more positions in
  140527. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  140528. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  140529. ** slots before it.
  140530. **
  140531. ** e.g. nToken==1 searches for adjacent positions.
  140532. */
  140533. static int fts3PoslistPhraseMerge(
  140534. char **pp, /* IN/OUT: Preallocated output buffer */
  140535. int nToken, /* Maximum difference in token positions */
  140536. int isSaveLeft, /* Save the left position */
  140537. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  140538. char **pp1, /* IN/OUT: Left input list */
  140539. char **pp2 /* IN/OUT: Right input list */
  140540. ){
  140541. char *p = *pp;
  140542. char *p1 = *pp1;
  140543. char *p2 = *pp2;
  140544. int iCol1 = 0;
  140545. int iCol2 = 0;
  140546. /* Never set both isSaveLeft and isExact for the same invocation. */
  140547. assert( isSaveLeft==0 || isExact==0 );
  140548. assert( p!=0 && *p1!=0 && *p2!=0 );
  140549. if( *p1==POS_COLUMN ){
  140550. p1++;
  140551. p1 += fts3GetVarint32(p1, &iCol1);
  140552. }
  140553. if( *p2==POS_COLUMN ){
  140554. p2++;
  140555. p2 += fts3GetVarint32(p2, &iCol2);
  140556. }
  140557. while( 1 ){
  140558. if( iCol1==iCol2 ){
  140559. char *pSave = p;
  140560. sqlite3_int64 iPrev = 0;
  140561. sqlite3_int64 iPos1 = 0;
  140562. sqlite3_int64 iPos2 = 0;
  140563. if( iCol1 ){
  140564. *p++ = POS_COLUMN;
  140565. p += sqlite3Fts3PutVarint(p, iCol1);
  140566. }
  140567. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  140568. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  140569. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  140570. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  140571. while( 1 ){
  140572. if( iPos2==iPos1+nToken
  140573. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  140574. ){
  140575. sqlite3_int64 iSave;
  140576. iSave = isSaveLeft ? iPos1 : iPos2;
  140577. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  140578. pSave = 0;
  140579. assert( p );
  140580. }
  140581. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  140582. if( (*p2&0xFE)==0 ) break;
  140583. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  140584. }else{
  140585. if( (*p1&0xFE)==0 ) break;
  140586. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  140587. }
  140588. }
  140589. if( pSave ){
  140590. assert( pp && p );
  140591. p = pSave;
  140592. }
  140593. fts3ColumnlistCopy(0, &p1);
  140594. fts3ColumnlistCopy(0, &p2);
  140595. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  140596. if( 0==*p1 || 0==*p2 ) break;
  140597. p1++;
  140598. p1 += fts3GetVarint32(p1, &iCol1);
  140599. p2++;
  140600. p2 += fts3GetVarint32(p2, &iCol2);
  140601. }
  140602. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  140603. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  140604. ** end of the position list, or the 0x01 that precedes the next
  140605. ** column-number in the position list.
  140606. */
  140607. else if( iCol1<iCol2 ){
  140608. fts3ColumnlistCopy(0, &p1);
  140609. if( 0==*p1 ) break;
  140610. p1++;
  140611. p1 += fts3GetVarint32(p1, &iCol1);
  140612. }else{
  140613. fts3ColumnlistCopy(0, &p2);
  140614. if( 0==*p2 ) break;
  140615. p2++;
  140616. p2 += fts3GetVarint32(p2, &iCol2);
  140617. }
  140618. }
  140619. fts3PoslistCopy(0, &p2);
  140620. fts3PoslistCopy(0, &p1);
  140621. *pp1 = p1;
  140622. *pp2 = p2;
  140623. if( *pp==p ){
  140624. return 0;
  140625. }
  140626. *p++ = 0x00;
  140627. *pp = p;
  140628. return 1;
  140629. }
  140630. /*
  140631. ** Merge two position-lists as required by the NEAR operator. The argument
  140632. ** position lists correspond to the left and right phrases of an expression
  140633. ** like:
  140634. **
  140635. ** "phrase 1" NEAR "phrase number 2"
  140636. **
  140637. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  140638. ** expression and *pp2 to the right. As usual, the indexes in the position
  140639. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  140640. ** in the example above).
  140641. **
  140642. ** The output position list - written to *pp - is a copy of *pp2 with those
  140643. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  140644. */
  140645. static int fts3PoslistNearMerge(
  140646. char **pp, /* Output buffer */
  140647. char *aTmp, /* Temporary buffer space */
  140648. int nRight, /* Maximum difference in token positions */
  140649. int nLeft, /* Maximum difference in token positions */
  140650. char **pp1, /* IN/OUT: Left input list */
  140651. char **pp2 /* IN/OUT: Right input list */
  140652. ){
  140653. char *p1 = *pp1;
  140654. char *p2 = *pp2;
  140655. char *pTmp1 = aTmp;
  140656. char *pTmp2;
  140657. char *aTmp2;
  140658. int res = 1;
  140659. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  140660. aTmp2 = pTmp2 = pTmp1;
  140661. *pp1 = p1;
  140662. *pp2 = p2;
  140663. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  140664. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  140665. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  140666. }else if( pTmp1!=aTmp ){
  140667. fts3PoslistCopy(pp, &aTmp);
  140668. }else if( pTmp2!=aTmp2 ){
  140669. fts3PoslistCopy(pp, &aTmp2);
  140670. }else{
  140671. res = 0;
  140672. }
  140673. return res;
  140674. }
  140675. /*
  140676. ** An instance of this function is used to merge together the (potentially
  140677. ** large number of) doclists for each term that matches a prefix query.
  140678. ** See function fts3TermSelectMerge() for details.
  140679. */
  140680. typedef struct TermSelect TermSelect;
  140681. struct TermSelect {
  140682. char *aaOutput[16]; /* Malloc'd output buffers */
  140683. int anOutput[16]; /* Size each output buffer in bytes */
  140684. };
  140685. /*
  140686. ** This function is used to read a single varint from a buffer. Parameter
  140687. ** pEnd points 1 byte past the end of the buffer. When this function is
  140688. ** called, if *pp points to pEnd or greater, then the end of the buffer
  140689. ** has been reached. In this case *pp is set to 0 and the function returns.
  140690. **
  140691. ** If *pp does not point to or past pEnd, then a single varint is read
  140692. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  140693. **
  140694. ** If bDescIdx is false, the value read is added to *pVal before returning.
  140695. ** If it is true, the value read is subtracted from *pVal before this
  140696. ** function returns.
  140697. */
  140698. static void fts3GetDeltaVarint3(
  140699. char **pp, /* IN/OUT: Point to read varint from */
  140700. char *pEnd, /* End of buffer */
  140701. int bDescIdx, /* True if docids are descending */
  140702. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  140703. ){
  140704. if( *pp>=pEnd ){
  140705. *pp = 0;
  140706. }else{
  140707. sqlite3_int64 iVal;
  140708. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  140709. if( bDescIdx ){
  140710. *pVal -= iVal;
  140711. }else{
  140712. *pVal += iVal;
  140713. }
  140714. }
  140715. }
  140716. /*
  140717. ** This function is used to write a single varint to a buffer. The varint
  140718. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  140719. ** end of the value written.
  140720. **
  140721. ** If *pbFirst is zero when this function is called, the value written to
  140722. ** the buffer is that of parameter iVal.
  140723. **
  140724. ** If *pbFirst is non-zero when this function is called, then the value
  140725. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  140726. ** (if bDescIdx is non-zero).
  140727. **
  140728. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  140729. ** to the value of parameter iVal.
  140730. */
  140731. static void fts3PutDeltaVarint3(
  140732. char **pp, /* IN/OUT: Output pointer */
  140733. int bDescIdx, /* True for descending docids */
  140734. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  140735. int *pbFirst, /* IN/OUT: True after first int written */
  140736. sqlite3_int64 iVal /* Write this value to the list */
  140737. ){
  140738. sqlite3_int64 iWrite;
  140739. if( bDescIdx==0 || *pbFirst==0 ){
  140740. iWrite = iVal - *piPrev;
  140741. }else{
  140742. iWrite = *piPrev - iVal;
  140743. }
  140744. assert( *pbFirst || *piPrev==0 );
  140745. assert( *pbFirst==0 || iWrite>0 );
  140746. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  140747. *piPrev = iVal;
  140748. *pbFirst = 1;
  140749. }
  140750. /*
  140751. ** This macro is used by various functions that merge doclists. The two
  140752. ** arguments are 64-bit docid values. If the value of the stack variable
  140753. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  140754. ** Otherwise, (i2-i1).
  140755. **
  140756. ** Using this makes it easier to write code that can merge doclists that are
  140757. ** sorted in either ascending or descending order.
  140758. */
  140759. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  140760. /*
  140761. ** This function does an "OR" merge of two doclists (output contains all
  140762. ** positions contained in either argument doclist). If the docids in the
  140763. ** input doclists are sorted in ascending order, parameter bDescDoclist
  140764. ** should be false. If they are sorted in ascending order, it should be
  140765. ** passed a non-zero value.
  140766. **
  140767. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  140768. ** containing the output doclist and SQLITE_OK is returned. In this case
  140769. ** *pnOut is set to the number of bytes in the output doclist.
  140770. **
  140771. ** If an error occurs, an SQLite error code is returned. The output values
  140772. ** are undefined in this case.
  140773. */
  140774. static int fts3DoclistOrMerge(
  140775. int bDescDoclist, /* True if arguments are desc */
  140776. char *a1, int n1, /* First doclist */
  140777. char *a2, int n2, /* Second doclist */
  140778. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  140779. ){
  140780. sqlite3_int64 i1 = 0;
  140781. sqlite3_int64 i2 = 0;
  140782. sqlite3_int64 iPrev = 0;
  140783. char *pEnd1 = &a1[n1];
  140784. char *pEnd2 = &a2[n2];
  140785. char *p1 = a1;
  140786. char *p2 = a2;
  140787. char *p;
  140788. char *aOut;
  140789. int bFirstOut = 0;
  140790. *paOut = 0;
  140791. *pnOut = 0;
  140792. /* Allocate space for the output. Both the input and output doclists
  140793. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  140794. ** then the first docid in each list is simply encoded as a varint. For
  140795. ** each subsequent docid, the varint stored is the difference between the
  140796. ** current and previous docid (a positive number - since the list is in
  140797. ** ascending order).
  140798. **
  140799. ** The first docid written to the output is therefore encoded using the
  140800. ** same number of bytes as it is in whichever of the input lists it is
  140801. ** read from. And each subsequent docid read from the same input list
  140802. ** consumes either the same or less bytes as it did in the input (since
  140803. ** the difference between it and the previous value in the output must
  140804. ** be a positive value less than or equal to the delta value read from
  140805. ** the input list). The same argument applies to all but the first docid
  140806. ** read from the 'other' list. And to the contents of all position lists
  140807. ** that will be copied and merged from the input to the output.
  140808. **
  140809. ** However, if the first docid copied to the output is a negative number,
  140810. ** then the encoding of the first docid from the 'other' input list may
  140811. ** be larger in the output than it was in the input (since the delta value
  140812. ** may be a larger positive integer than the actual docid).
  140813. **
  140814. ** The space required to store the output is therefore the sum of the
  140815. ** sizes of the two inputs, plus enough space for exactly one of the input
  140816. ** docids to grow.
  140817. **
  140818. ** A symetric argument may be made if the doclists are in descending
  140819. ** order.
  140820. */
  140821. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  140822. if( !aOut ) return SQLITE_NOMEM;
  140823. p = aOut;
  140824. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  140825. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  140826. while( p1 || p2 ){
  140827. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  140828. if( p2 && p1 && iDiff==0 ){
  140829. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  140830. fts3PoslistMerge(&p, &p1, &p2);
  140831. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  140832. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  140833. }else if( !p2 || (p1 && iDiff<0) ){
  140834. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  140835. fts3PoslistCopy(&p, &p1);
  140836. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  140837. }else{
  140838. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  140839. fts3PoslistCopy(&p, &p2);
  140840. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  140841. }
  140842. }
  140843. *paOut = aOut;
  140844. *pnOut = (int)(p-aOut);
  140845. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  140846. return SQLITE_OK;
  140847. }
  140848. /*
  140849. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  140850. ** the output contains a copy of each position from the right-hand input
  140851. ** doclist for which there is a position in the left-hand input doclist
  140852. ** exactly nDist tokens before it.
  140853. **
  140854. ** If the docids in the input doclists are sorted in ascending order,
  140855. ** parameter bDescDoclist should be false. If they are sorted in ascending
  140856. ** order, it should be passed a non-zero value.
  140857. **
  140858. ** The right-hand input doclist is overwritten by this function.
  140859. */
  140860. static int fts3DoclistPhraseMerge(
  140861. int bDescDoclist, /* True if arguments are desc */
  140862. int nDist, /* Distance from left to right (1=adjacent) */
  140863. char *aLeft, int nLeft, /* Left doclist */
  140864. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  140865. ){
  140866. sqlite3_int64 i1 = 0;
  140867. sqlite3_int64 i2 = 0;
  140868. sqlite3_int64 iPrev = 0;
  140869. char *aRight = *paRight;
  140870. char *pEnd1 = &aLeft[nLeft];
  140871. char *pEnd2 = &aRight[*pnRight];
  140872. char *p1 = aLeft;
  140873. char *p2 = aRight;
  140874. char *p;
  140875. int bFirstOut = 0;
  140876. char *aOut;
  140877. assert( nDist>0 );
  140878. if( bDescDoclist ){
  140879. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  140880. if( aOut==0 ) return SQLITE_NOMEM;
  140881. }else{
  140882. aOut = aRight;
  140883. }
  140884. p = aOut;
  140885. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  140886. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  140887. while( p1 && p2 ){
  140888. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  140889. if( iDiff==0 ){
  140890. char *pSave = p;
  140891. sqlite3_int64 iPrevSave = iPrev;
  140892. int bFirstOutSave = bFirstOut;
  140893. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  140894. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  140895. p = pSave;
  140896. iPrev = iPrevSave;
  140897. bFirstOut = bFirstOutSave;
  140898. }
  140899. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  140900. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  140901. }else if( iDiff<0 ){
  140902. fts3PoslistCopy(0, &p1);
  140903. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  140904. }else{
  140905. fts3PoslistCopy(0, &p2);
  140906. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  140907. }
  140908. }
  140909. *pnRight = (int)(p - aOut);
  140910. if( bDescDoclist ){
  140911. sqlite3_free(aRight);
  140912. *paRight = aOut;
  140913. }
  140914. return SQLITE_OK;
  140915. }
  140916. /*
  140917. ** Argument pList points to a position list nList bytes in size. This
  140918. ** function checks to see if the position list contains any entries for
  140919. ** a token in position 0 (of any column). If so, it writes argument iDelta
  140920. ** to the output buffer pOut, followed by a position list consisting only
  140921. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  140922. ** The value returned is the number of bytes written to pOut (if any).
  140923. */
  140924. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  140925. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  140926. char *pList, /* Position list (no 0x00 term) */
  140927. int nList, /* Size of pList in bytes */
  140928. char *pOut /* Write output here */
  140929. ){
  140930. int nOut = 0;
  140931. int bWritten = 0; /* True once iDelta has been written */
  140932. char *p = pList;
  140933. char *pEnd = &pList[nList];
  140934. if( *p!=0x01 ){
  140935. if( *p==0x02 ){
  140936. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  140937. pOut[nOut++] = 0x02;
  140938. bWritten = 1;
  140939. }
  140940. fts3ColumnlistCopy(0, &p);
  140941. }
  140942. while( p<pEnd ){
  140943. sqlite3_int64 iCol;
  140944. p++;
  140945. p += sqlite3Fts3GetVarint(p, &iCol);
  140946. if( *p==0x02 ){
  140947. if( bWritten==0 ){
  140948. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  140949. bWritten = 1;
  140950. }
  140951. pOut[nOut++] = 0x01;
  140952. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  140953. pOut[nOut++] = 0x02;
  140954. }
  140955. fts3ColumnlistCopy(0, &p);
  140956. }
  140957. if( bWritten ){
  140958. pOut[nOut++] = 0x00;
  140959. }
  140960. return nOut;
  140961. }
  140962. /*
  140963. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  140964. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  140965. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  140966. **
  140967. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  140968. ** the responsibility of the caller to free any doclists left in the
  140969. ** TermSelect.aaOutput[] array.
  140970. */
  140971. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  140972. char *aOut = 0;
  140973. int nOut = 0;
  140974. int i;
  140975. /* Loop through the doclists in the aaOutput[] array. Merge them all
  140976. ** into a single doclist.
  140977. */
  140978. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  140979. if( pTS->aaOutput[i] ){
  140980. if( !aOut ){
  140981. aOut = pTS->aaOutput[i];
  140982. nOut = pTS->anOutput[i];
  140983. pTS->aaOutput[i] = 0;
  140984. }else{
  140985. int nNew;
  140986. char *aNew;
  140987. int rc = fts3DoclistOrMerge(p->bDescIdx,
  140988. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  140989. );
  140990. if( rc!=SQLITE_OK ){
  140991. sqlite3_free(aOut);
  140992. return rc;
  140993. }
  140994. sqlite3_free(pTS->aaOutput[i]);
  140995. sqlite3_free(aOut);
  140996. pTS->aaOutput[i] = 0;
  140997. aOut = aNew;
  140998. nOut = nNew;
  140999. }
  141000. }
  141001. }
  141002. pTS->aaOutput[0] = aOut;
  141003. pTS->anOutput[0] = nOut;
  141004. return SQLITE_OK;
  141005. }
  141006. /*
  141007. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  141008. ** as the first argument. The merge is an "OR" merge (see function
  141009. ** fts3DoclistOrMerge() for details).
  141010. **
  141011. ** This function is called with the doclist for each term that matches
  141012. ** a queried prefix. It merges all these doclists into one, the doclist
  141013. ** for the specified prefix. Since there can be a very large number of
  141014. ** doclists to merge, the merging is done pair-wise using the TermSelect
  141015. ** object.
  141016. **
  141017. ** This function returns SQLITE_OK if the merge is successful, or an
  141018. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  141019. */
  141020. static int fts3TermSelectMerge(
  141021. Fts3Table *p, /* FTS table handle */
  141022. TermSelect *pTS, /* TermSelect object to merge into */
  141023. char *aDoclist, /* Pointer to doclist */
  141024. int nDoclist /* Size of aDoclist in bytes */
  141025. ){
  141026. if( pTS->aaOutput[0]==0 ){
  141027. /* If this is the first term selected, copy the doclist to the output
  141028. ** buffer using memcpy().
  141029. **
  141030. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  141031. ** allocation. This is so as to ensure that the buffer is big enough
  141032. ** to hold the current doclist AND'd with any other doclist. If the
  141033. ** doclists are stored in order=ASC order, this padding would not be
  141034. ** required (since the size of [doclistA AND doclistB] is always less
  141035. ** than or equal to the size of [doclistA] in that case). But this is
  141036. ** not true for order=DESC. For example, a doclist containing (1, -1)
  141037. ** may be smaller than (-1), as in the first example the -1 may be stored
  141038. ** as a single-byte delta, whereas in the second it must be stored as a
  141039. ** FTS3_VARINT_MAX byte varint.
  141040. **
  141041. ** Similar padding is added in the fts3DoclistOrMerge() function.
  141042. */
  141043. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  141044. pTS->anOutput[0] = nDoclist;
  141045. if( pTS->aaOutput[0] ){
  141046. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  141047. }else{
  141048. return SQLITE_NOMEM;
  141049. }
  141050. }else{
  141051. char *aMerge = aDoclist;
  141052. int nMerge = nDoclist;
  141053. int iOut;
  141054. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  141055. if( pTS->aaOutput[iOut]==0 ){
  141056. assert( iOut>0 );
  141057. pTS->aaOutput[iOut] = aMerge;
  141058. pTS->anOutput[iOut] = nMerge;
  141059. break;
  141060. }else{
  141061. char *aNew;
  141062. int nNew;
  141063. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  141064. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  141065. );
  141066. if( rc!=SQLITE_OK ){
  141067. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  141068. return rc;
  141069. }
  141070. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  141071. sqlite3_free(pTS->aaOutput[iOut]);
  141072. pTS->aaOutput[iOut] = 0;
  141073. aMerge = aNew;
  141074. nMerge = nNew;
  141075. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  141076. pTS->aaOutput[iOut] = aMerge;
  141077. pTS->anOutput[iOut] = nMerge;
  141078. }
  141079. }
  141080. }
  141081. }
  141082. return SQLITE_OK;
  141083. }
  141084. /*
  141085. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  141086. */
  141087. static int fts3SegReaderCursorAppend(
  141088. Fts3MultiSegReader *pCsr,
  141089. Fts3SegReader *pNew
  141090. ){
  141091. if( (pCsr->nSegment%16)==0 ){
  141092. Fts3SegReader **apNew;
  141093. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  141094. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  141095. if( !apNew ){
  141096. sqlite3Fts3SegReaderFree(pNew);
  141097. return SQLITE_NOMEM;
  141098. }
  141099. pCsr->apSegment = apNew;
  141100. }
  141101. pCsr->apSegment[pCsr->nSegment++] = pNew;
  141102. return SQLITE_OK;
  141103. }
  141104. /*
  141105. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  141106. ** 8th argument.
  141107. **
  141108. ** This function returns SQLITE_OK if successful, or an SQLite error code
  141109. ** otherwise.
  141110. */
  141111. static int fts3SegReaderCursor(
  141112. Fts3Table *p, /* FTS3 table handle */
  141113. int iLangid, /* Language id */
  141114. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  141115. int iLevel, /* Level of segments to scan */
  141116. const char *zTerm, /* Term to query for */
  141117. int nTerm, /* Size of zTerm in bytes */
  141118. int isPrefix, /* True for a prefix search */
  141119. int isScan, /* True to scan from zTerm to EOF */
  141120. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  141121. ){
  141122. int rc = SQLITE_OK; /* Error code */
  141123. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  141124. int rc2; /* Result of sqlite3_reset() */
  141125. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  141126. ** for the pending-terms. If this is a scan, then this call must be being
  141127. ** made by an fts4aux module, not an FTS table. In this case calling
  141128. ** Fts3SegReaderPending might segfault, as the data structures used by
  141129. ** fts4aux are not completely populated. So it's easiest to filter these
  141130. ** calls out here. */
  141131. if( iLevel<0 && p->aIndex ){
  141132. Fts3SegReader *pSeg = 0;
  141133. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  141134. if( rc==SQLITE_OK && pSeg ){
  141135. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  141136. }
  141137. }
  141138. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  141139. if( rc==SQLITE_OK ){
  141140. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  141141. }
  141142. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  141143. Fts3SegReader *pSeg = 0;
  141144. /* Read the values returned by the SELECT into local variables. */
  141145. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  141146. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  141147. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  141148. int nRoot = sqlite3_column_bytes(pStmt, 4);
  141149. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  141150. /* If zTerm is not NULL, and this segment is not stored entirely on its
  141151. ** root node, the range of leaves scanned can be reduced. Do this. */
  141152. if( iStartBlock && zTerm ){
  141153. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  141154. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  141155. if( rc!=SQLITE_OK ) goto finished;
  141156. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  141157. }
  141158. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  141159. (isPrefix==0 && isScan==0),
  141160. iStartBlock, iLeavesEndBlock,
  141161. iEndBlock, zRoot, nRoot, &pSeg
  141162. );
  141163. if( rc!=SQLITE_OK ) goto finished;
  141164. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  141165. }
  141166. }
  141167. finished:
  141168. rc2 = sqlite3_reset(pStmt);
  141169. if( rc==SQLITE_DONE ) rc = rc2;
  141170. return rc;
  141171. }
  141172. /*
  141173. ** Set up a cursor object for iterating through a full-text index or a
  141174. ** single level therein.
  141175. */
  141176. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  141177. Fts3Table *p, /* FTS3 table handle */
  141178. int iLangid, /* Language-id to search */
  141179. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  141180. int iLevel, /* Level of segments to scan */
  141181. const char *zTerm, /* Term to query for */
  141182. int nTerm, /* Size of zTerm in bytes */
  141183. int isPrefix, /* True for a prefix search */
  141184. int isScan, /* True to scan from zTerm to EOF */
  141185. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  141186. ){
  141187. assert( iIndex>=0 && iIndex<p->nIndex );
  141188. assert( iLevel==FTS3_SEGCURSOR_ALL
  141189. || iLevel==FTS3_SEGCURSOR_PENDING
  141190. || iLevel>=0
  141191. );
  141192. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  141193. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  141194. assert( isPrefix==0 || isScan==0 );
  141195. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  141196. return fts3SegReaderCursor(
  141197. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  141198. );
  141199. }
  141200. /*
  141201. ** In addition to its current configuration, have the Fts3MultiSegReader
  141202. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  141203. **
  141204. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  141205. */
  141206. static int fts3SegReaderCursorAddZero(
  141207. Fts3Table *p, /* FTS virtual table handle */
  141208. int iLangid,
  141209. const char *zTerm, /* Term to scan doclist of */
  141210. int nTerm, /* Number of bytes in zTerm */
  141211. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  141212. ){
  141213. return fts3SegReaderCursor(p,
  141214. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  141215. );
  141216. }
  141217. /*
  141218. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  141219. ** if isPrefix is true, to scan the doclist for all terms for which
  141220. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  141221. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  141222. ** an SQLite error code.
  141223. **
  141224. ** It is the responsibility of the caller to free this object by eventually
  141225. ** passing it to fts3SegReaderCursorFree()
  141226. **
  141227. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  141228. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  141229. */
  141230. static int fts3TermSegReaderCursor(
  141231. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  141232. const char *zTerm, /* Term to query for */
  141233. int nTerm, /* Size of zTerm in bytes */
  141234. int isPrefix, /* True for a prefix search */
  141235. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  141236. ){
  141237. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  141238. int rc = SQLITE_NOMEM; /* Return code */
  141239. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  141240. if( pSegcsr ){
  141241. int i;
  141242. int bFound = 0; /* True once an index has been found */
  141243. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  141244. if( isPrefix ){
  141245. for(i=1; bFound==0 && i<p->nIndex; i++){
  141246. if( p->aIndex[i].nPrefix==nTerm ){
  141247. bFound = 1;
  141248. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  141249. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  141250. );
  141251. pSegcsr->bLookup = 1;
  141252. }
  141253. }
  141254. for(i=1; bFound==0 && i<p->nIndex; i++){
  141255. if( p->aIndex[i].nPrefix==nTerm+1 ){
  141256. bFound = 1;
  141257. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  141258. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  141259. );
  141260. if( rc==SQLITE_OK ){
  141261. rc = fts3SegReaderCursorAddZero(
  141262. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  141263. );
  141264. }
  141265. }
  141266. }
  141267. }
  141268. if( bFound==0 ){
  141269. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  141270. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  141271. );
  141272. pSegcsr->bLookup = !isPrefix;
  141273. }
  141274. }
  141275. *ppSegcsr = pSegcsr;
  141276. return rc;
  141277. }
  141278. /*
  141279. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  141280. */
  141281. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  141282. sqlite3Fts3SegReaderFinish(pSegcsr);
  141283. sqlite3_free(pSegcsr);
  141284. }
  141285. /*
  141286. ** This function retrieves the doclist for the specified term (or term
  141287. ** prefix) from the database.
  141288. */
  141289. static int fts3TermSelect(
  141290. Fts3Table *p, /* Virtual table handle */
  141291. Fts3PhraseToken *pTok, /* Token to query for */
  141292. int iColumn, /* Column to query (or -ve for all columns) */
  141293. int *pnOut, /* OUT: Size of buffer at *ppOut */
  141294. char **ppOut /* OUT: Malloced result buffer */
  141295. ){
  141296. int rc; /* Return code */
  141297. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  141298. TermSelect tsc; /* Object for pair-wise doclist merging */
  141299. Fts3SegFilter filter; /* Segment term filter configuration */
  141300. pSegcsr = pTok->pSegcsr;
  141301. memset(&tsc, 0, sizeof(TermSelect));
  141302. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  141303. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  141304. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  141305. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  141306. filter.iCol = iColumn;
  141307. filter.zTerm = pTok->z;
  141308. filter.nTerm = pTok->n;
  141309. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  141310. while( SQLITE_OK==rc
  141311. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  141312. ){
  141313. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  141314. }
  141315. if( rc==SQLITE_OK ){
  141316. rc = fts3TermSelectFinishMerge(p, &tsc);
  141317. }
  141318. if( rc==SQLITE_OK ){
  141319. *ppOut = tsc.aaOutput[0];
  141320. *pnOut = tsc.anOutput[0];
  141321. }else{
  141322. int i;
  141323. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  141324. sqlite3_free(tsc.aaOutput[i]);
  141325. }
  141326. }
  141327. fts3SegReaderCursorFree(pSegcsr);
  141328. pTok->pSegcsr = 0;
  141329. return rc;
  141330. }
  141331. /*
  141332. ** This function counts the total number of docids in the doclist stored
  141333. ** in buffer aList[], size nList bytes.
  141334. **
  141335. ** If the isPoslist argument is true, then it is assumed that the doclist
  141336. ** contains a position-list following each docid. Otherwise, it is assumed
  141337. ** that the doclist is simply a list of docids stored as delta encoded
  141338. ** varints.
  141339. */
  141340. static int fts3DoclistCountDocids(char *aList, int nList){
  141341. int nDoc = 0; /* Return value */
  141342. if( aList ){
  141343. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  141344. char *p = aList; /* Cursor */
  141345. while( p<aEnd ){
  141346. nDoc++;
  141347. while( (*p++)&0x80 ); /* Skip docid varint */
  141348. fts3PoslistCopy(0, &p); /* Skip over position list */
  141349. }
  141350. }
  141351. return nDoc;
  141352. }
  141353. /*
  141354. ** Advance the cursor to the next row in the %_content table that
  141355. ** matches the search criteria. For a MATCH search, this will be
  141356. ** the next row that matches. For a full-table scan, this will be
  141357. ** simply the next row in the %_content table. For a docid lookup,
  141358. ** this routine simply sets the EOF flag.
  141359. **
  141360. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  141361. ** even if we reach end-of-file. The fts3EofMethod() will be called
  141362. ** subsequently to determine whether or not an EOF was hit.
  141363. */
  141364. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  141365. int rc;
  141366. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  141367. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  141368. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  141369. pCsr->isEof = 1;
  141370. rc = sqlite3_reset(pCsr->pStmt);
  141371. }else{
  141372. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  141373. rc = SQLITE_OK;
  141374. }
  141375. }else{
  141376. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  141377. }
  141378. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  141379. return rc;
  141380. }
  141381. /*
  141382. ** The following are copied from sqliteInt.h.
  141383. **
  141384. ** Constants for the largest and smallest possible 64-bit signed integers.
  141385. ** These macros are designed to work correctly on both 32-bit and 64-bit
  141386. ** compilers.
  141387. */
  141388. #ifndef SQLITE_AMALGAMATION
  141389. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  141390. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  141391. #endif
  141392. /*
  141393. ** If the numeric type of argument pVal is "integer", then return it
  141394. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  141395. ** the second parameter, iDefault.
  141396. */
  141397. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  141398. if( pVal ){
  141399. int eType = sqlite3_value_numeric_type(pVal);
  141400. if( eType==SQLITE_INTEGER ){
  141401. return sqlite3_value_int64(pVal);
  141402. }
  141403. }
  141404. return iDefault;
  141405. }
  141406. /*
  141407. ** This is the xFilter interface for the virtual table. See
  141408. ** the virtual table xFilter method documentation for additional
  141409. ** information.
  141410. **
  141411. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  141412. ** the %_content table.
  141413. **
  141414. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  141415. ** in the %_content table.
  141416. **
  141417. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  141418. ** column on the left-hand side of the MATCH operator is column
  141419. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  141420. ** side of the MATCH operator.
  141421. */
  141422. static int fts3FilterMethod(
  141423. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  141424. int idxNum, /* Strategy index */
  141425. const char *idxStr, /* Unused */
  141426. int nVal, /* Number of elements in apVal */
  141427. sqlite3_value **apVal /* Arguments for the indexing scheme */
  141428. ){
  141429. int rc = SQLITE_OK;
  141430. char *zSql; /* SQL statement used to access %_content */
  141431. int eSearch;
  141432. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  141433. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  141434. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  141435. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  141436. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  141437. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  141438. int iIdx;
  141439. UNUSED_PARAMETER(idxStr);
  141440. UNUSED_PARAMETER(nVal);
  141441. eSearch = (idxNum & 0x0000FFFF);
  141442. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  141443. assert( p->pSegments==0 );
  141444. /* Collect arguments into local variables */
  141445. iIdx = 0;
  141446. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  141447. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  141448. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  141449. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  141450. assert( iIdx==nVal );
  141451. /* In case the cursor has been used before, clear it now. */
  141452. fts3ClearCursor(pCsr);
  141453. /* Set the lower and upper bounds on docids to return */
  141454. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  141455. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  141456. if( idxStr ){
  141457. pCsr->bDesc = (idxStr[0]=='D');
  141458. }else{
  141459. pCsr->bDesc = p->bDescIdx;
  141460. }
  141461. pCsr->eSearch = (i16)eSearch;
  141462. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  141463. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  141464. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  141465. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  141466. return SQLITE_NOMEM;
  141467. }
  141468. pCsr->iLangid = 0;
  141469. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  141470. assert( p->base.zErrMsg==0 );
  141471. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  141472. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  141473. &p->base.zErrMsg
  141474. );
  141475. if( rc!=SQLITE_OK ){
  141476. return rc;
  141477. }
  141478. rc = fts3EvalStart(pCsr);
  141479. sqlite3Fts3SegmentsClose(p);
  141480. if( rc!=SQLITE_OK ) return rc;
  141481. pCsr->pNextId = pCsr->aDoclist;
  141482. pCsr->iPrevId = 0;
  141483. }
  141484. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  141485. ** statement loops through all rows of the %_content table. For a
  141486. ** full-text query or docid lookup, the statement retrieves a single
  141487. ** row by docid.
  141488. */
  141489. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  141490. if( pDocidGe || pDocidLe ){
  141491. zSql = sqlite3_mprintf(
  141492. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  141493. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  141494. (pCsr->bDesc ? "DESC" : "ASC")
  141495. );
  141496. }else{
  141497. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  141498. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  141499. );
  141500. }
  141501. if( zSql ){
  141502. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  141503. sqlite3_free(zSql);
  141504. }else{
  141505. rc = SQLITE_NOMEM;
  141506. }
  141507. }else if( eSearch==FTS3_DOCID_SEARCH ){
  141508. rc = fts3CursorSeekStmt(pCsr);
  141509. if( rc==SQLITE_OK ){
  141510. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  141511. }
  141512. }
  141513. if( rc!=SQLITE_OK ) return rc;
  141514. return fts3NextMethod(pCursor);
  141515. }
  141516. /*
  141517. ** This is the xEof method of the virtual table. SQLite calls this
  141518. ** routine to find out if it has reached the end of a result set.
  141519. */
  141520. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  141521. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  141522. if( pCsr->isEof ){
  141523. fts3ClearCursor(pCsr);
  141524. pCsr->isEof = 1;
  141525. }
  141526. return pCsr->isEof;
  141527. }
  141528. /*
  141529. ** This is the xRowid method. The SQLite core calls this routine to
  141530. ** retrieve the rowid for the current row of the result set. fts3
  141531. ** exposes %_content.docid as the rowid for the virtual table. The
  141532. ** rowid should be written to *pRowid.
  141533. */
  141534. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  141535. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  141536. *pRowid = pCsr->iPrevId;
  141537. return SQLITE_OK;
  141538. }
  141539. /*
  141540. ** This is the xColumn method, called by SQLite to request a value from
  141541. ** the row that the supplied cursor currently points to.
  141542. **
  141543. ** If:
  141544. **
  141545. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  141546. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  141547. ** (iCol == p->nColumn+1) -> Docid column
  141548. ** (iCol == p->nColumn+2) -> Langid column
  141549. */
  141550. static int fts3ColumnMethod(
  141551. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  141552. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  141553. int iCol /* Index of column to read value from */
  141554. ){
  141555. int rc = SQLITE_OK; /* Return Code */
  141556. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  141557. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  141558. /* The column value supplied by SQLite must be in range. */
  141559. assert( iCol>=0 && iCol<=p->nColumn+2 );
  141560. switch( iCol-p->nColumn ){
  141561. case 0:
  141562. /* The special 'table-name' column */
  141563. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  141564. break;
  141565. case 1:
  141566. /* The docid column */
  141567. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  141568. break;
  141569. case 2:
  141570. if( pCsr->pExpr ){
  141571. sqlite3_result_int64(pCtx, pCsr->iLangid);
  141572. break;
  141573. }else if( p->zLanguageid==0 ){
  141574. sqlite3_result_int(pCtx, 0);
  141575. break;
  141576. }else{
  141577. iCol = p->nColumn;
  141578. /* fall-through */
  141579. }
  141580. default:
  141581. /* A user column. Or, if this is a full-table scan, possibly the
  141582. ** language-id column. Seek the cursor. */
  141583. rc = fts3CursorSeek(0, pCsr);
  141584. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  141585. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  141586. }
  141587. break;
  141588. }
  141589. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  141590. return rc;
  141591. }
  141592. /*
  141593. ** This function is the implementation of the xUpdate callback used by
  141594. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  141595. ** inserted, updated or deleted.
  141596. */
  141597. static int fts3UpdateMethod(
  141598. sqlite3_vtab *pVtab, /* Virtual table handle */
  141599. int nArg, /* Size of argument array */
  141600. sqlite3_value **apVal, /* Array of arguments */
  141601. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  141602. ){
  141603. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  141604. }
  141605. /*
  141606. ** Implementation of xSync() method. Flush the contents of the pending-terms
  141607. ** hash-table to the database.
  141608. */
  141609. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  141610. /* Following an incremental-merge operation, assuming that the input
  141611. ** segments are not completely consumed (the usual case), they are updated
  141612. ** in place to remove the entries that have already been merged. This
  141613. ** involves updating the leaf block that contains the smallest unmerged
  141614. ** entry and each block (if any) between the leaf and the root node. So
  141615. ** if the height of the input segment b-trees is N, and input segments
  141616. ** are merged eight at a time, updating the input segments at the end
  141617. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  141618. ** small - often between 0 and 2. So the overhead of the incremental
  141619. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  141620. ** dwarfing the actual productive work accomplished, the incremental merge
  141621. ** is only attempted if it will write at least 64 leaf blocks. Hence
  141622. ** nMinMerge.
  141623. **
  141624. ** Of course, updating the input segments also involves deleting a bunch
  141625. ** of blocks from the segments table. But this is not considered overhead
  141626. ** as it would also be required by a crisis-merge that used the same input
  141627. ** segments.
  141628. */
  141629. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  141630. Fts3Table *p = (Fts3Table*)pVtab;
  141631. int rc;
  141632. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  141633. rc = sqlite3Fts3PendingTermsFlush(p);
  141634. if( rc==SQLITE_OK
  141635. && p->nLeafAdd>(nMinMerge/16)
  141636. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  141637. ){
  141638. int mxLevel = 0; /* Maximum relative level value in db */
  141639. int A; /* Incr-merge parameter A */
  141640. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  141641. assert( rc==SQLITE_OK || mxLevel==0 );
  141642. A = p->nLeafAdd * mxLevel;
  141643. A += (A/2);
  141644. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  141645. }
  141646. sqlite3Fts3SegmentsClose(p);
  141647. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  141648. return rc;
  141649. }
  141650. /*
  141651. ** If it is currently unknown whether or not the FTS table has an %_stat
  141652. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  141653. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  141654. ** if an error occurs.
  141655. */
  141656. static int fts3SetHasStat(Fts3Table *p){
  141657. int rc = SQLITE_OK;
  141658. if( p->bHasStat==2 ){
  141659. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  141660. if( zTbl ){
  141661. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  141662. sqlite3_free(zTbl);
  141663. p->bHasStat = (res==SQLITE_OK);
  141664. }else{
  141665. rc = SQLITE_NOMEM;
  141666. }
  141667. }
  141668. return rc;
  141669. }
  141670. /*
  141671. ** Implementation of xBegin() method.
  141672. */
  141673. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  141674. Fts3Table *p = (Fts3Table*)pVtab;
  141675. UNUSED_PARAMETER(pVtab);
  141676. assert( p->pSegments==0 );
  141677. assert( p->nPendingData==0 );
  141678. assert( p->inTransaction!=1 );
  141679. TESTONLY( p->inTransaction = 1 );
  141680. TESTONLY( p->mxSavepoint = -1; );
  141681. p->nLeafAdd = 0;
  141682. return fts3SetHasStat(p);
  141683. }
  141684. /*
  141685. ** Implementation of xCommit() method. This is a no-op. The contents of
  141686. ** the pending-terms hash-table have already been flushed into the database
  141687. ** by fts3SyncMethod().
  141688. */
  141689. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  141690. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  141691. UNUSED_PARAMETER(pVtab);
  141692. assert( p->nPendingData==0 );
  141693. assert( p->inTransaction!=0 );
  141694. assert( p->pSegments==0 );
  141695. TESTONLY( p->inTransaction = 0 );
  141696. TESTONLY( p->mxSavepoint = -1; );
  141697. return SQLITE_OK;
  141698. }
  141699. /*
  141700. ** Implementation of xRollback(). Discard the contents of the pending-terms
  141701. ** hash-table. Any changes made to the database are reverted by SQLite.
  141702. */
  141703. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  141704. Fts3Table *p = (Fts3Table*)pVtab;
  141705. sqlite3Fts3PendingTermsClear(p);
  141706. assert( p->inTransaction!=0 );
  141707. TESTONLY( p->inTransaction = 0 );
  141708. TESTONLY( p->mxSavepoint = -1; );
  141709. return SQLITE_OK;
  141710. }
  141711. /*
  141712. ** When called, *ppPoslist must point to the byte immediately following the
  141713. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  141714. ** moves *ppPoslist so that it instead points to the first byte of the
  141715. ** same position list.
  141716. */
  141717. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  141718. char *p = &(*ppPoslist)[-2];
  141719. char c = 0;
  141720. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  141721. while( p>pStart && (c=*p--)==0 );
  141722. /* Search backwards for a varint with value zero (the end of the previous
  141723. ** poslist). This is an 0x00 byte preceded by some byte that does not
  141724. ** have the 0x80 bit set. */
  141725. while( p>pStart && (*p & 0x80) | c ){
  141726. c = *p--;
  141727. }
  141728. assert( p==pStart || c==0 );
  141729. /* At this point p points to that preceding byte without the 0x80 bit
  141730. ** set. So to find the start of the poslist, skip forward 2 bytes then
  141731. ** over a varint.
  141732. **
  141733. ** Normally. The other case is that p==pStart and the poslist to return
  141734. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  141735. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  141736. ** is required for cases where the first byte of a doclist and the
  141737. ** doclist is empty. For example, if the first docid is 10, a doclist
  141738. ** that begins with:
  141739. **
  141740. ** 0x0A 0x00 <next docid delta varint>
  141741. */
  141742. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  141743. while( *p++&0x80 );
  141744. *ppPoslist = p;
  141745. }
  141746. /*
  141747. ** Helper function used by the implementation of the overloaded snippet(),
  141748. ** offsets() and optimize() SQL functions.
  141749. **
  141750. ** If the value passed as the third argument is a blob of size
  141751. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  141752. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  141753. ** message is written to context pContext and SQLITE_ERROR returned. The
  141754. ** string passed via zFunc is used as part of the error message.
  141755. */
  141756. static int fts3FunctionArg(
  141757. sqlite3_context *pContext, /* SQL function call context */
  141758. const char *zFunc, /* Function name */
  141759. sqlite3_value *pVal, /* argv[0] passed to function */
  141760. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  141761. ){
  141762. int rc;
  141763. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  141764. if( (*ppCsr)!=0 ){
  141765. rc = SQLITE_OK;
  141766. }else{
  141767. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  141768. sqlite3_result_error(pContext, zErr, -1);
  141769. sqlite3_free(zErr);
  141770. rc = SQLITE_ERROR;
  141771. }
  141772. return rc;
  141773. }
  141774. /*
  141775. ** Implementation of the snippet() function for FTS3
  141776. */
  141777. static void fts3SnippetFunc(
  141778. sqlite3_context *pContext, /* SQLite function call context */
  141779. int nVal, /* Size of apVal[] array */
  141780. sqlite3_value **apVal /* Array of arguments */
  141781. ){
  141782. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  141783. const char *zStart = "<b>";
  141784. const char *zEnd = "</b>";
  141785. const char *zEllipsis = "<b>...</b>";
  141786. int iCol = -1;
  141787. int nToken = 15; /* Default number of tokens in snippet */
  141788. /* There must be at least one argument passed to this function (otherwise
  141789. ** the non-overloaded version would have been called instead of this one).
  141790. */
  141791. assert( nVal>=1 );
  141792. if( nVal>6 ){
  141793. sqlite3_result_error(pContext,
  141794. "wrong number of arguments to function snippet()", -1);
  141795. return;
  141796. }
  141797. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  141798. switch( nVal ){
  141799. case 6: nToken = sqlite3_value_int(apVal[5]);
  141800. case 5: iCol = sqlite3_value_int(apVal[4]);
  141801. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  141802. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  141803. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  141804. }
  141805. if( !zEllipsis || !zEnd || !zStart ){
  141806. sqlite3_result_error_nomem(pContext);
  141807. }else if( nToken==0 ){
  141808. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  141809. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  141810. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  141811. }
  141812. }
  141813. /*
  141814. ** Implementation of the offsets() function for FTS3
  141815. */
  141816. static void fts3OffsetsFunc(
  141817. sqlite3_context *pContext, /* SQLite function call context */
  141818. int nVal, /* Size of argument array */
  141819. sqlite3_value **apVal /* Array of arguments */
  141820. ){
  141821. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  141822. UNUSED_PARAMETER(nVal);
  141823. assert( nVal==1 );
  141824. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  141825. assert( pCsr );
  141826. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  141827. sqlite3Fts3Offsets(pContext, pCsr);
  141828. }
  141829. }
  141830. /*
  141831. ** Implementation of the special optimize() function for FTS3. This
  141832. ** function merges all segments in the database to a single segment.
  141833. ** Example usage is:
  141834. **
  141835. ** SELECT optimize(t) FROM t LIMIT 1;
  141836. **
  141837. ** where 't' is the name of an FTS3 table.
  141838. */
  141839. static void fts3OptimizeFunc(
  141840. sqlite3_context *pContext, /* SQLite function call context */
  141841. int nVal, /* Size of argument array */
  141842. sqlite3_value **apVal /* Array of arguments */
  141843. ){
  141844. int rc; /* Return code */
  141845. Fts3Table *p; /* Virtual table handle */
  141846. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  141847. UNUSED_PARAMETER(nVal);
  141848. assert( nVal==1 );
  141849. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  141850. p = (Fts3Table *)pCursor->base.pVtab;
  141851. assert( p );
  141852. rc = sqlite3Fts3Optimize(p);
  141853. switch( rc ){
  141854. case SQLITE_OK:
  141855. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  141856. break;
  141857. case SQLITE_DONE:
  141858. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  141859. break;
  141860. default:
  141861. sqlite3_result_error_code(pContext, rc);
  141862. break;
  141863. }
  141864. }
  141865. /*
  141866. ** Implementation of the matchinfo() function for FTS3
  141867. */
  141868. static void fts3MatchinfoFunc(
  141869. sqlite3_context *pContext, /* SQLite function call context */
  141870. int nVal, /* Size of argument array */
  141871. sqlite3_value **apVal /* Array of arguments */
  141872. ){
  141873. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  141874. assert( nVal==1 || nVal==2 );
  141875. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  141876. const char *zArg = 0;
  141877. if( nVal>1 ){
  141878. zArg = (const char *)sqlite3_value_text(apVal[1]);
  141879. }
  141880. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  141881. }
  141882. }
  141883. /*
  141884. ** This routine implements the xFindFunction method for the FTS3
  141885. ** virtual table.
  141886. */
  141887. static int fts3FindFunctionMethod(
  141888. sqlite3_vtab *pVtab, /* Virtual table handle */
  141889. int nArg, /* Number of SQL function arguments */
  141890. const char *zName, /* Name of SQL function */
  141891. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  141892. void **ppArg /* Unused */
  141893. ){
  141894. struct Overloaded {
  141895. const char *zName;
  141896. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  141897. } aOverload[] = {
  141898. { "snippet", fts3SnippetFunc },
  141899. { "offsets", fts3OffsetsFunc },
  141900. { "optimize", fts3OptimizeFunc },
  141901. { "matchinfo", fts3MatchinfoFunc },
  141902. };
  141903. int i; /* Iterator variable */
  141904. UNUSED_PARAMETER(pVtab);
  141905. UNUSED_PARAMETER(nArg);
  141906. UNUSED_PARAMETER(ppArg);
  141907. for(i=0; i<SizeofArray(aOverload); i++){
  141908. if( strcmp(zName, aOverload[i].zName)==0 ){
  141909. *pxFunc = aOverload[i].xFunc;
  141910. return 1;
  141911. }
  141912. }
  141913. /* No function of the specified name was found. Return 0. */
  141914. return 0;
  141915. }
  141916. /*
  141917. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  141918. */
  141919. static int fts3RenameMethod(
  141920. sqlite3_vtab *pVtab, /* Virtual table handle */
  141921. const char *zName /* New name of table */
  141922. ){
  141923. Fts3Table *p = (Fts3Table *)pVtab;
  141924. sqlite3 *db = p->db; /* Database connection */
  141925. int rc; /* Return Code */
  141926. /* At this point it must be known if the %_stat table exists or not.
  141927. ** So bHasStat may not be 2. */
  141928. rc = fts3SetHasStat(p);
  141929. /* As it happens, the pending terms table is always empty here. This is
  141930. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  141931. ** always opens a savepoint transaction. And the xSavepoint() method
  141932. ** flushes the pending terms table. But leave the (no-op) call to
  141933. ** PendingTermsFlush() in in case that changes.
  141934. */
  141935. assert( p->nPendingData==0 );
  141936. if( rc==SQLITE_OK ){
  141937. rc = sqlite3Fts3PendingTermsFlush(p);
  141938. }
  141939. if( p->zContentTbl==0 ){
  141940. fts3DbExec(&rc, db,
  141941. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  141942. p->zDb, p->zName, zName
  141943. );
  141944. }
  141945. if( p->bHasDocsize ){
  141946. fts3DbExec(&rc, db,
  141947. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  141948. p->zDb, p->zName, zName
  141949. );
  141950. }
  141951. if( p->bHasStat ){
  141952. fts3DbExec(&rc, db,
  141953. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  141954. p->zDb, p->zName, zName
  141955. );
  141956. }
  141957. fts3DbExec(&rc, db,
  141958. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  141959. p->zDb, p->zName, zName
  141960. );
  141961. fts3DbExec(&rc, db,
  141962. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  141963. p->zDb, p->zName, zName
  141964. );
  141965. return rc;
  141966. }
  141967. /*
  141968. ** The xSavepoint() method.
  141969. **
  141970. ** Flush the contents of the pending-terms table to disk.
  141971. */
  141972. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  141973. int rc = SQLITE_OK;
  141974. UNUSED_PARAMETER(iSavepoint);
  141975. assert( ((Fts3Table *)pVtab)->inTransaction );
  141976. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  141977. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  141978. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  141979. rc = fts3SyncMethod(pVtab);
  141980. }
  141981. return rc;
  141982. }
  141983. /*
  141984. ** The xRelease() method.
  141985. **
  141986. ** This is a no-op.
  141987. */
  141988. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  141989. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  141990. UNUSED_PARAMETER(iSavepoint);
  141991. UNUSED_PARAMETER(pVtab);
  141992. assert( p->inTransaction );
  141993. assert( p->mxSavepoint >= iSavepoint );
  141994. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  141995. return SQLITE_OK;
  141996. }
  141997. /*
  141998. ** The xRollbackTo() method.
  141999. **
  142000. ** Discard the contents of the pending terms table.
  142001. */
  142002. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  142003. Fts3Table *p = (Fts3Table*)pVtab;
  142004. UNUSED_PARAMETER(iSavepoint);
  142005. assert( p->inTransaction );
  142006. assert( p->mxSavepoint >= iSavepoint );
  142007. TESTONLY( p->mxSavepoint = iSavepoint );
  142008. sqlite3Fts3PendingTermsClear(p);
  142009. return SQLITE_OK;
  142010. }
  142011. static const sqlite3_module fts3Module = {
  142012. /* iVersion */ 2,
  142013. /* xCreate */ fts3CreateMethod,
  142014. /* xConnect */ fts3ConnectMethod,
  142015. /* xBestIndex */ fts3BestIndexMethod,
  142016. /* xDisconnect */ fts3DisconnectMethod,
  142017. /* xDestroy */ fts3DestroyMethod,
  142018. /* xOpen */ fts3OpenMethod,
  142019. /* xClose */ fts3CloseMethod,
  142020. /* xFilter */ fts3FilterMethod,
  142021. /* xNext */ fts3NextMethod,
  142022. /* xEof */ fts3EofMethod,
  142023. /* xColumn */ fts3ColumnMethod,
  142024. /* xRowid */ fts3RowidMethod,
  142025. /* xUpdate */ fts3UpdateMethod,
  142026. /* xBegin */ fts3BeginMethod,
  142027. /* xSync */ fts3SyncMethod,
  142028. /* xCommit */ fts3CommitMethod,
  142029. /* xRollback */ fts3RollbackMethod,
  142030. /* xFindFunction */ fts3FindFunctionMethod,
  142031. /* xRename */ fts3RenameMethod,
  142032. /* xSavepoint */ fts3SavepointMethod,
  142033. /* xRelease */ fts3ReleaseMethod,
  142034. /* xRollbackTo */ fts3RollbackToMethod,
  142035. };
  142036. /*
  142037. ** This function is registered as the module destructor (called when an
  142038. ** FTS3 enabled database connection is closed). It frees the memory
  142039. ** allocated for the tokenizer hash table.
  142040. */
  142041. static void hashDestroy(void *p){
  142042. Fts3Hash *pHash = (Fts3Hash *)p;
  142043. sqlite3Fts3HashClear(pHash);
  142044. sqlite3_free(pHash);
  142045. }
  142046. /*
  142047. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  142048. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  142049. ** respectively. The following three forward declarations are for functions
  142050. ** declared in these files used to retrieve the respective implementations.
  142051. **
  142052. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  142053. ** to by the argument to point to the "simple" tokenizer implementation.
  142054. ** And so on.
  142055. */
  142056. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  142057. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  142058. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  142059. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  142060. #endif
  142061. #ifdef SQLITE_ENABLE_ICU
  142062. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  142063. #endif
  142064. /*
  142065. ** Initialize the fts3 extension. If this extension is built as part
  142066. ** of the sqlite library, then this function is called directly by
  142067. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  142068. ** function is called by the sqlite3_extension_init() entry point.
  142069. */
  142070. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  142071. int rc = SQLITE_OK;
  142072. Fts3Hash *pHash = 0;
  142073. const sqlite3_tokenizer_module *pSimple = 0;
  142074. const sqlite3_tokenizer_module *pPorter = 0;
  142075. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  142076. const sqlite3_tokenizer_module *pUnicode = 0;
  142077. #endif
  142078. #ifdef SQLITE_ENABLE_ICU
  142079. const sqlite3_tokenizer_module *pIcu = 0;
  142080. sqlite3Fts3IcuTokenizerModule(&pIcu);
  142081. #endif
  142082. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  142083. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  142084. #endif
  142085. #ifdef SQLITE_TEST
  142086. rc = sqlite3Fts3InitTerm(db);
  142087. if( rc!=SQLITE_OK ) return rc;
  142088. #endif
  142089. rc = sqlite3Fts3InitAux(db);
  142090. if( rc!=SQLITE_OK ) return rc;
  142091. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  142092. sqlite3Fts3PorterTokenizerModule(&pPorter);
  142093. /* Allocate and initialize the hash-table used to store tokenizers. */
  142094. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  142095. if( !pHash ){
  142096. rc = SQLITE_NOMEM;
  142097. }else{
  142098. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  142099. }
  142100. /* Load the built-in tokenizers into the hash table */
  142101. if( rc==SQLITE_OK ){
  142102. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  142103. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  142104. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  142105. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  142106. #endif
  142107. #ifdef SQLITE_ENABLE_ICU
  142108. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  142109. #endif
  142110. ){
  142111. rc = SQLITE_NOMEM;
  142112. }
  142113. }
  142114. #ifdef SQLITE_TEST
  142115. if( rc==SQLITE_OK ){
  142116. rc = sqlite3Fts3ExprInitTestInterface(db);
  142117. }
  142118. #endif
  142119. /* Create the virtual table wrapper around the hash-table and overload
  142120. ** the four scalar functions. If this is successful, register the
  142121. ** module with sqlite.
  142122. */
  142123. if( SQLITE_OK==rc
  142124. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  142125. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  142126. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  142127. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  142128. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  142129. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  142130. ){
  142131. rc = sqlite3_create_module_v2(
  142132. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  142133. );
  142134. if( rc==SQLITE_OK ){
  142135. rc = sqlite3_create_module_v2(
  142136. db, "fts4", &fts3Module, (void *)pHash, 0
  142137. );
  142138. }
  142139. if( rc==SQLITE_OK ){
  142140. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  142141. }
  142142. return rc;
  142143. }
  142144. /* An error has occurred. Delete the hash table and return the error code. */
  142145. assert( rc!=SQLITE_OK );
  142146. if( pHash ){
  142147. sqlite3Fts3HashClear(pHash);
  142148. sqlite3_free(pHash);
  142149. }
  142150. return rc;
  142151. }
  142152. /*
  142153. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  142154. ** by pExpr.
  142155. **
  142156. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  142157. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  142158. ** Fts3SegReader objects internally to provide an interface to seek or scan
  142159. ** within the union of all segments of a b-tree. Hence the name.
  142160. **
  142161. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  142162. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  142163. ** there exists prefix b-tree of the right length) then it may be traversed
  142164. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  142165. ** doclist and then traversed.
  142166. */
  142167. static void fts3EvalAllocateReaders(
  142168. Fts3Cursor *pCsr, /* FTS cursor handle */
  142169. Fts3Expr *pExpr, /* Allocate readers for this expression */
  142170. int *pnToken, /* OUT: Total number of tokens in phrase. */
  142171. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  142172. int *pRc /* IN/OUT: Error code */
  142173. ){
  142174. if( pExpr && SQLITE_OK==*pRc ){
  142175. if( pExpr->eType==FTSQUERY_PHRASE ){
  142176. int i;
  142177. int nToken = pExpr->pPhrase->nToken;
  142178. *pnToken += nToken;
  142179. for(i=0; i<nToken; i++){
  142180. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  142181. int rc = fts3TermSegReaderCursor(pCsr,
  142182. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  142183. );
  142184. if( rc!=SQLITE_OK ){
  142185. *pRc = rc;
  142186. return;
  142187. }
  142188. }
  142189. assert( pExpr->pPhrase->iDoclistToken==0 );
  142190. pExpr->pPhrase->iDoclistToken = -1;
  142191. }else{
  142192. *pnOr += (pExpr->eType==FTSQUERY_OR);
  142193. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  142194. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  142195. }
  142196. }
  142197. }
  142198. /*
  142199. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  142200. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  142201. **
  142202. ** This function assumes that pList points to a buffer allocated using
  142203. ** sqlite3_malloc(). This function takes responsibility for eventually
  142204. ** freeing the buffer.
  142205. **
  142206. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  142207. */
  142208. static int fts3EvalPhraseMergeToken(
  142209. Fts3Table *pTab, /* FTS Table pointer */
  142210. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  142211. int iToken, /* Token pList/nList corresponds to */
  142212. char *pList, /* Pointer to doclist */
  142213. int nList /* Number of bytes in pList */
  142214. ){
  142215. int rc = SQLITE_OK;
  142216. assert( iToken!=p->iDoclistToken );
  142217. if( pList==0 ){
  142218. sqlite3_free(p->doclist.aAll);
  142219. p->doclist.aAll = 0;
  142220. p->doclist.nAll = 0;
  142221. }
  142222. else if( p->iDoclistToken<0 ){
  142223. p->doclist.aAll = pList;
  142224. p->doclist.nAll = nList;
  142225. }
  142226. else if( p->doclist.aAll==0 ){
  142227. sqlite3_free(pList);
  142228. }
  142229. else {
  142230. char *pLeft;
  142231. char *pRight;
  142232. int nLeft;
  142233. int nRight;
  142234. int nDiff;
  142235. if( p->iDoclistToken<iToken ){
  142236. pLeft = p->doclist.aAll;
  142237. nLeft = p->doclist.nAll;
  142238. pRight = pList;
  142239. nRight = nList;
  142240. nDiff = iToken - p->iDoclistToken;
  142241. }else{
  142242. pRight = p->doclist.aAll;
  142243. nRight = p->doclist.nAll;
  142244. pLeft = pList;
  142245. nLeft = nList;
  142246. nDiff = p->iDoclistToken - iToken;
  142247. }
  142248. rc = fts3DoclistPhraseMerge(
  142249. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  142250. );
  142251. sqlite3_free(pLeft);
  142252. p->doclist.aAll = pRight;
  142253. p->doclist.nAll = nRight;
  142254. }
  142255. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  142256. return rc;
  142257. }
  142258. /*
  142259. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  142260. ** does not take deferred tokens into account.
  142261. **
  142262. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  142263. */
  142264. static int fts3EvalPhraseLoad(
  142265. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142266. Fts3Phrase *p /* Phrase object */
  142267. ){
  142268. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142269. int iToken;
  142270. int rc = SQLITE_OK;
  142271. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  142272. Fts3PhraseToken *pToken = &p->aToken[iToken];
  142273. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  142274. if( pToken->pSegcsr ){
  142275. int nThis = 0;
  142276. char *pThis = 0;
  142277. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  142278. if( rc==SQLITE_OK ){
  142279. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  142280. }
  142281. }
  142282. assert( pToken->pSegcsr==0 );
  142283. }
  142284. return rc;
  142285. }
  142286. /*
  142287. ** This function is called on each phrase after the position lists for
  142288. ** any deferred tokens have been loaded into memory. It updates the phrases
  142289. ** current position list to include only those positions that are really
  142290. ** instances of the phrase (after considering deferred tokens). If this
  142291. ** means that the phrase does not appear in the current row, doclist.pList
  142292. ** and doclist.nList are both zeroed.
  142293. **
  142294. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  142295. */
  142296. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  142297. int iToken; /* Used to iterate through phrase tokens */
  142298. char *aPoslist = 0; /* Position list for deferred tokens */
  142299. int nPoslist = 0; /* Number of bytes in aPoslist */
  142300. int iPrev = -1; /* Token number of previous deferred token */
  142301. assert( pPhrase->doclist.bFreeList==0 );
  142302. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  142303. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  142304. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  142305. if( pDeferred ){
  142306. char *pList;
  142307. int nList;
  142308. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  142309. if( rc!=SQLITE_OK ) return rc;
  142310. if( pList==0 ){
  142311. sqlite3_free(aPoslist);
  142312. pPhrase->doclist.pList = 0;
  142313. pPhrase->doclist.nList = 0;
  142314. return SQLITE_OK;
  142315. }else if( aPoslist==0 ){
  142316. aPoslist = pList;
  142317. nPoslist = nList;
  142318. }else{
  142319. char *aOut = pList;
  142320. char *p1 = aPoslist;
  142321. char *p2 = aOut;
  142322. assert( iPrev>=0 );
  142323. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  142324. sqlite3_free(aPoslist);
  142325. aPoslist = pList;
  142326. nPoslist = (int)(aOut - aPoslist);
  142327. if( nPoslist==0 ){
  142328. sqlite3_free(aPoslist);
  142329. pPhrase->doclist.pList = 0;
  142330. pPhrase->doclist.nList = 0;
  142331. return SQLITE_OK;
  142332. }
  142333. }
  142334. iPrev = iToken;
  142335. }
  142336. }
  142337. if( iPrev>=0 ){
  142338. int nMaxUndeferred = pPhrase->iDoclistToken;
  142339. if( nMaxUndeferred<0 ){
  142340. pPhrase->doclist.pList = aPoslist;
  142341. pPhrase->doclist.nList = nPoslist;
  142342. pPhrase->doclist.iDocid = pCsr->iPrevId;
  142343. pPhrase->doclist.bFreeList = 1;
  142344. }else{
  142345. int nDistance;
  142346. char *p1;
  142347. char *p2;
  142348. char *aOut;
  142349. if( nMaxUndeferred>iPrev ){
  142350. p1 = aPoslist;
  142351. p2 = pPhrase->doclist.pList;
  142352. nDistance = nMaxUndeferred - iPrev;
  142353. }else{
  142354. p1 = pPhrase->doclist.pList;
  142355. p2 = aPoslist;
  142356. nDistance = iPrev - nMaxUndeferred;
  142357. }
  142358. aOut = (char *)sqlite3_malloc(nPoslist+8);
  142359. if( !aOut ){
  142360. sqlite3_free(aPoslist);
  142361. return SQLITE_NOMEM;
  142362. }
  142363. pPhrase->doclist.pList = aOut;
  142364. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  142365. pPhrase->doclist.bFreeList = 1;
  142366. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  142367. }else{
  142368. sqlite3_free(aOut);
  142369. pPhrase->doclist.pList = 0;
  142370. pPhrase->doclist.nList = 0;
  142371. }
  142372. sqlite3_free(aPoslist);
  142373. }
  142374. }
  142375. return SQLITE_OK;
  142376. }
  142377. /*
  142378. ** Maximum number of tokens a phrase may have to be considered for the
  142379. ** incremental doclists strategy.
  142380. */
  142381. #define MAX_INCR_PHRASE_TOKENS 4
  142382. /*
  142383. ** This function is called for each Fts3Phrase in a full-text query
  142384. ** expression to initialize the mechanism for returning rows. Once this
  142385. ** function has been called successfully on an Fts3Phrase, it may be
  142386. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  142387. **
  142388. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  142389. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  142390. ** memory within this call.
  142391. **
  142392. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  142393. */
  142394. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  142395. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142396. int rc = SQLITE_OK; /* Error code */
  142397. int i;
  142398. /* Determine if doclists may be loaded from disk incrementally. This is
  142399. ** possible if the bOptOk argument is true, the FTS doclists will be
  142400. ** scanned in forward order, and the phrase consists of
  142401. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  142402. ** tokens or prefix tokens that cannot use a prefix-index. */
  142403. int bHaveIncr = 0;
  142404. int bIncrOk = (bOptOk
  142405. && pCsr->bDesc==pTab->bDescIdx
  142406. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  142407. #ifdef SQLITE_TEST
  142408. && pTab->bNoIncrDoclist==0
  142409. #endif
  142410. );
  142411. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  142412. Fts3PhraseToken *pToken = &p->aToken[i];
  142413. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  142414. bIncrOk = 0;
  142415. }
  142416. if( pToken->pSegcsr ) bHaveIncr = 1;
  142417. }
  142418. if( bIncrOk && bHaveIncr ){
  142419. /* Use the incremental approach. */
  142420. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  142421. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  142422. Fts3PhraseToken *pToken = &p->aToken[i];
  142423. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  142424. if( pSegcsr ){
  142425. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  142426. }
  142427. }
  142428. p->bIncr = 1;
  142429. }else{
  142430. /* Load the full doclist for the phrase into memory. */
  142431. rc = fts3EvalPhraseLoad(pCsr, p);
  142432. p->bIncr = 0;
  142433. }
  142434. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  142435. return rc;
  142436. }
  142437. /*
  142438. ** This function is used to iterate backwards (from the end to start)
  142439. ** through doclists. It is used by this module to iterate through phrase
  142440. ** doclists in reverse and by the fts3_write.c module to iterate through
  142441. ** pending-terms lists when writing to databases with "order=desc".
  142442. **
  142443. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  142444. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  142445. ** function iterates from the end of the doclist to the beginning.
  142446. */
  142447. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  142448. int bDescIdx, /* True if the doclist is desc */
  142449. char *aDoclist, /* Pointer to entire doclist */
  142450. int nDoclist, /* Length of aDoclist in bytes */
  142451. char **ppIter, /* IN/OUT: Iterator pointer */
  142452. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  142453. int *pnList, /* OUT: List length pointer */
  142454. u8 *pbEof /* OUT: End-of-file flag */
  142455. ){
  142456. char *p = *ppIter;
  142457. assert( nDoclist>0 );
  142458. assert( *pbEof==0 );
  142459. assert( p || *piDocid==0 );
  142460. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  142461. if( p==0 ){
  142462. sqlite3_int64 iDocid = 0;
  142463. char *pNext = 0;
  142464. char *pDocid = aDoclist;
  142465. char *pEnd = &aDoclist[nDoclist];
  142466. int iMul = 1;
  142467. while( pDocid<pEnd ){
  142468. sqlite3_int64 iDelta;
  142469. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  142470. iDocid += (iMul * iDelta);
  142471. pNext = pDocid;
  142472. fts3PoslistCopy(0, &pDocid);
  142473. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  142474. iMul = (bDescIdx ? -1 : 1);
  142475. }
  142476. *pnList = (int)(pEnd - pNext);
  142477. *ppIter = pNext;
  142478. *piDocid = iDocid;
  142479. }else{
  142480. int iMul = (bDescIdx ? -1 : 1);
  142481. sqlite3_int64 iDelta;
  142482. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  142483. *piDocid -= (iMul * iDelta);
  142484. if( p==aDoclist ){
  142485. *pbEof = 1;
  142486. }else{
  142487. char *pSave = p;
  142488. fts3ReversePoslist(aDoclist, &p);
  142489. *pnList = (int)(pSave - p);
  142490. }
  142491. *ppIter = p;
  142492. }
  142493. }
  142494. /*
  142495. ** Iterate forwards through a doclist.
  142496. */
  142497. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  142498. int bDescIdx, /* True if the doclist is desc */
  142499. char *aDoclist, /* Pointer to entire doclist */
  142500. int nDoclist, /* Length of aDoclist in bytes */
  142501. char **ppIter, /* IN/OUT: Iterator pointer */
  142502. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  142503. u8 *pbEof /* OUT: End-of-file flag */
  142504. ){
  142505. char *p = *ppIter;
  142506. assert( nDoclist>0 );
  142507. assert( *pbEof==0 );
  142508. assert( p || *piDocid==0 );
  142509. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  142510. if( p==0 ){
  142511. p = aDoclist;
  142512. p += sqlite3Fts3GetVarint(p, piDocid);
  142513. }else{
  142514. fts3PoslistCopy(0, &p);
  142515. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  142516. if( p>=&aDoclist[nDoclist] ){
  142517. *pbEof = 1;
  142518. }else{
  142519. sqlite3_int64 iVar;
  142520. p += sqlite3Fts3GetVarint(p, &iVar);
  142521. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  142522. }
  142523. }
  142524. *ppIter = p;
  142525. }
  142526. /*
  142527. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  142528. ** to true if EOF is reached.
  142529. */
  142530. static void fts3EvalDlPhraseNext(
  142531. Fts3Table *pTab,
  142532. Fts3Doclist *pDL,
  142533. u8 *pbEof
  142534. ){
  142535. char *pIter; /* Used to iterate through aAll */
  142536. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  142537. if( pDL->pNextDocid ){
  142538. pIter = pDL->pNextDocid;
  142539. }else{
  142540. pIter = pDL->aAll;
  142541. }
  142542. if( pIter>=pEnd ){
  142543. /* We have already reached the end of this doclist. EOF. */
  142544. *pbEof = 1;
  142545. }else{
  142546. sqlite3_int64 iDelta;
  142547. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  142548. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  142549. pDL->iDocid += iDelta;
  142550. }else{
  142551. pDL->iDocid -= iDelta;
  142552. }
  142553. pDL->pList = pIter;
  142554. fts3PoslistCopy(0, &pIter);
  142555. pDL->nList = (int)(pIter - pDL->pList);
  142556. /* pIter now points just past the 0x00 that terminates the position-
  142557. ** list for document pDL->iDocid. However, if this position-list was
  142558. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  142559. ** point to the start of the next docid value. The following line deals
  142560. ** with this case by advancing pIter past the zero-padding added by
  142561. ** fts3EvalNearTrim(). */
  142562. while( pIter<pEnd && *pIter==0 ) pIter++;
  142563. pDL->pNextDocid = pIter;
  142564. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  142565. *pbEof = 0;
  142566. }
  142567. }
  142568. /*
  142569. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  142570. */
  142571. typedef struct TokenDoclist TokenDoclist;
  142572. struct TokenDoclist {
  142573. int bIgnore;
  142574. sqlite3_int64 iDocid;
  142575. char *pList;
  142576. int nList;
  142577. };
  142578. /*
  142579. ** Token pToken is an incrementally loaded token that is part of a
  142580. ** multi-token phrase. Advance it to the next matching document in the
  142581. ** database and populate output variable *p with the details of the new
  142582. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  142583. **
  142584. ** If an error occurs, return an SQLite error code. Otherwise, return
  142585. ** SQLITE_OK.
  142586. */
  142587. static int incrPhraseTokenNext(
  142588. Fts3Table *pTab, /* Virtual table handle */
  142589. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  142590. int iToken, /* Specific token to advance */
  142591. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  142592. u8 *pbEof /* OUT: True if iterator is at EOF */
  142593. ){
  142594. int rc = SQLITE_OK;
  142595. if( pPhrase->iDoclistToken==iToken ){
  142596. assert( p->bIgnore==0 );
  142597. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  142598. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  142599. p->pList = pPhrase->doclist.pList;
  142600. p->nList = pPhrase->doclist.nList;
  142601. p->iDocid = pPhrase->doclist.iDocid;
  142602. }else{
  142603. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  142604. assert( pToken->pDeferred==0 );
  142605. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  142606. if( pToken->pSegcsr ){
  142607. assert( p->bIgnore==0 );
  142608. rc = sqlite3Fts3MsrIncrNext(
  142609. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  142610. );
  142611. if( p->pList==0 ) *pbEof = 1;
  142612. }else{
  142613. p->bIgnore = 1;
  142614. }
  142615. }
  142616. return rc;
  142617. }
  142618. /*
  142619. ** The phrase iterator passed as the second argument:
  142620. **
  142621. ** * features at least one token that uses an incremental doclist, and
  142622. **
  142623. ** * does not contain any deferred tokens.
  142624. **
  142625. ** Advance it to the next matching documnent in the database and populate
  142626. ** the Fts3Doclist.pList and nList fields.
  142627. **
  142628. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  142629. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  142630. ** successfully advanced, *pbEof is set to 0.
  142631. **
  142632. ** If an error occurs, return an SQLite error code. Otherwise, return
  142633. ** SQLITE_OK.
  142634. */
  142635. static int fts3EvalIncrPhraseNext(
  142636. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142637. Fts3Phrase *p, /* Phrase object to advance to next docid */
  142638. u8 *pbEof /* OUT: Set to 1 if EOF */
  142639. ){
  142640. int rc = SQLITE_OK;
  142641. Fts3Doclist *pDL = &p->doclist;
  142642. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142643. u8 bEof = 0;
  142644. /* This is only called if it is guaranteed that the phrase has at least
  142645. ** one incremental token. In which case the bIncr flag is set. */
  142646. assert( p->bIncr==1 );
  142647. if( p->nToken==1 ){
  142648. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  142649. &pDL->iDocid, &pDL->pList, &pDL->nList
  142650. );
  142651. if( pDL->pList==0 ) bEof = 1;
  142652. }else{
  142653. int bDescDoclist = pCsr->bDesc;
  142654. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  142655. memset(a, 0, sizeof(a));
  142656. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  142657. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  142658. while( bEof==0 ){
  142659. int bMaxSet = 0;
  142660. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  142661. int i; /* Used to iterate through tokens */
  142662. /* Advance the iterator for each token in the phrase once. */
  142663. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  142664. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  142665. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  142666. iMax = a[i].iDocid;
  142667. bMaxSet = 1;
  142668. }
  142669. }
  142670. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  142671. assert( rc!=SQLITE_OK || bMaxSet );
  142672. /* Keep advancing iterators until they all point to the same document */
  142673. for(i=0; i<p->nToken; i++){
  142674. while( rc==SQLITE_OK && bEof==0
  142675. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  142676. ){
  142677. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  142678. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  142679. iMax = a[i].iDocid;
  142680. i = 0;
  142681. }
  142682. }
  142683. }
  142684. /* Check if the current entries really are a phrase match */
  142685. if( bEof==0 ){
  142686. int nList = 0;
  142687. int nByte = a[p->nToken-1].nList;
  142688. char *aDoclist = sqlite3_malloc(nByte+1);
  142689. if( !aDoclist ) return SQLITE_NOMEM;
  142690. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  142691. for(i=0; i<(p->nToken-1); i++){
  142692. if( a[i].bIgnore==0 ){
  142693. char *pL = a[i].pList;
  142694. char *pR = aDoclist;
  142695. char *pOut = aDoclist;
  142696. int nDist = p->nToken-1-i;
  142697. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  142698. if( res==0 ) break;
  142699. nList = (int)(pOut - aDoclist);
  142700. }
  142701. }
  142702. if( i==(p->nToken-1) ){
  142703. pDL->iDocid = iMax;
  142704. pDL->pList = aDoclist;
  142705. pDL->nList = nList;
  142706. pDL->bFreeList = 1;
  142707. break;
  142708. }
  142709. sqlite3_free(aDoclist);
  142710. }
  142711. }
  142712. }
  142713. *pbEof = bEof;
  142714. return rc;
  142715. }
  142716. /*
  142717. ** Attempt to move the phrase iterator to point to the next matching docid.
  142718. ** If an error occurs, return an SQLite error code. Otherwise, return
  142719. ** SQLITE_OK.
  142720. **
  142721. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  142722. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  142723. ** successfully advanced, *pbEof is set to 0.
  142724. */
  142725. static int fts3EvalPhraseNext(
  142726. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142727. Fts3Phrase *p, /* Phrase object to advance to next docid */
  142728. u8 *pbEof /* OUT: Set to 1 if EOF */
  142729. ){
  142730. int rc = SQLITE_OK;
  142731. Fts3Doclist *pDL = &p->doclist;
  142732. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142733. if( p->bIncr ){
  142734. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  142735. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  142736. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  142737. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  142738. );
  142739. pDL->pList = pDL->pNextDocid;
  142740. }else{
  142741. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  142742. }
  142743. return rc;
  142744. }
  142745. /*
  142746. **
  142747. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  142748. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  142749. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  142750. ** expressions for which all descendent tokens are deferred.
  142751. **
  142752. ** If parameter bOptOk is zero, then it is guaranteed that the
  142753. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  142754. ** each phrase in the expression (subject to deferred token processing).
  142755. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  142756. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  142757. **
  142758. ** If an error occurs within this function, *pRc is set to an SQLite error
  142759. ** code before returning.
  142760. */
  142761. static void fts3EvalStartReaders(
  142762. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142763. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  142764. int *pRc /* IN/OUT: Error code */
  142765. ){
  142766. if( pExpr && SQLITE_OK==*pRc ){
  142767. if( pExpr->eType==FTSQUERY_PHRASE ){
  142768. int nToken = pExpr->pPhrase->nToken;
  142769. if( nToken ){
  142770. int i;
  142771. for(i=0; i<nToken; i++){
  142772. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  142773. }
  142774. pExpr->bDeferred = (i==nToken);
  142775. }
  142776. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  142777. }else{
  142778. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  142779. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  142780. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  142781. }
  142782. }
  142783. }
  142784. /*
  142785. ** An array of the following structures is assembled as part of the process
  142786. ** of selecting tokens to defer before the query starts executing (as part
  142787. ** of the xFilter() method). There is one element in the array for each
  142788. ** token in the FTS expression.
  142789. **
  142790. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  142791. ** to phrases that are connected only by AND and NEAR operators (not OR or
  142792. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  142793. ** separately. The root of a tokens AND/NEAR cluster is stored in
  142794. ** Fts3TokenAndCost.pRoot.
  142795. */
  142796. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  142797. struct Fts3TokenAndCost {
  142798. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  142799. int iToken; /* Position of token in phrase */
  142800. Fts3PhraseToken *pToken; /* The token itself */
  142801. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  142802. int nOvfl; /* Number of overflow pages to load doclist */
  142803. int iCol; /* The column the token must match */
  142804. };
  142805. /*
  142806. ** This function is used to populate an allocated Fts3TokenAndCost array.
  142807. **
  142808. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  142809. ** Otherwise, if an error occurs during execution, *pRc is set to an
  142810. ** SQLite error code.
  142811. */
  142812. static void fts3EvalTokenCosts(
  142813. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142814. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  142815. Fts3Expr *pExpr, /* Expression to consider */
  142816. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  142817. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  142818. int *pRc /* IN/OUT: Error code */
  142819. ){
  142820. if( *pRc==SQLITE_OK ){
  142821. if( pExpr->eType==FTSQUERY_PHRASE ){
  142822. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142823. int i;
  142824. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  142825. Fts3TokenAndCost *pTC = (*ppTC)++;
  142826. pTC->pPhrase = pPhrase;
  142827. pTC->iToken = i;
  142828. pTC->pRoot = pRoot;
  142829. pTC->pToken = &pPhrase->aToken[i];
  142830. pTC->iCol = pPhrase->iColumn;
  142831. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  142832. }
  142833. }else if( pExpr->eType!=FTSQUERY_NOT ){
  142834. assert( pExpr->eType==FTSQUERY_OR
  142835. || pExpr->eType==FTSQUERY_AND
  142836. || pExpr->eType==FTSQUERY_NEAR
  142837. );
  142838. assert( pExpr->pLeft && pExpr->pRight );
  142839. if( pExpr->eType==FTSQUERY_OR ){
  142840. pRoot = pExpr->pLeft;
  142841. **ppOr = pRoot;
  142842. (*ppOr)++;
  142843. }
  142844. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  142845. if( pExpr->eType==FTSQUERY_OR ){
  142846. pRoot = pExpr->pRight;
  142847. **ppOr = pRoot;
  142848. (*ppOr)++;
  142849. }
  142850. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  142851. }
  142852. }
  142853. }
  142854. /*
  142855. ** Determine the average document (row) size in pages. If successful,
  142856. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  142857. ** an SQLite error code.
  142858. **
  142859. ** The average document size in pages is calculated by first calculating
  142860. ** determining the average size in bytes, B. If B is less than the amount
  142861. ** of data that will fit on a single leaf page of an intkey table in
  142862. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  142863. ** the number of overflow pages consumed by a record B bytes in size.
  142864. */
  142865. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  142866. int rc = SQLITE_OK;
  142867. if( pCsr->nRowAvg==0 ){
  142868. /* The average document size, which is required to calculate the cost
  142869. ** of each doclist, has not yet been determined. Read the required
  142870. ** data from the %_stat table to calculate it.
  142871. **
  142872. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  142873. ** varints, where nCol is the number of columns in the FTS3 table.
  142874. ** The first varint is the number of documents currently stored in
  142875. ** the table. The following nCol varints contain the total amount of
  142876. ** data stored in all rows of each column of the table, from left
  142877. ** to right.
  142878. */
  142879. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  142880. sqlite3_stmt *pStmt;
  142881. sqlite3_int64 nDoc = 0;
  142882. sqlite3_int64 nByte = 0;
  142883. const char *pEnd;
  142884. const char *a;
  142885. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  142886. if( rc!=SQLITE_OK ) return rc;
  142887. a = sqlite3_column_blob(pStmt, 0);
  142888. assert( a );
  142889. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  142890. a += sqlite3Fts3GetVarint(a, &nDoc);
  142891. while( a<pEnd ){
  142892. a += sqlite3Fts3GetVarint(a, &nByte);
  142893. }
  142894. if( nDoc==0 || nByte==0 ){
  142895. sqlite3_reset(pStmt);
  142896. return FTS_CORRUPT_VTAB;
  142897. }
  142898. pCsr->nDoc = nDoc;
  142899. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  142900. assert( pCsr->nRowAvg>0 );
  142901. rc = sqlite3_reset(pStmt);
  142902. }
  142903. *pnPage = pCsr->nRowAvg;
  142904. return rc;
  142905. }
  142906. /*
  142907. ** This function is called to select the tokens (if any) that will be
  142908. ** deferred. The array aTC[] has already been populated when this is
  142909. ** called.
  142910. **
  142911. ** This function is called once for each AND/NEAR cluster in the
  142912. ** expression. Each invocation determines which tokens to defer within
  142913. ** the cluster with root node pRoot. See comments above the definition
  142914. ** of struct Fts3TokenAndCost for more details.
  142915. **
  142916. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  142917. ** called on each token to defer. Otherwise, an SQLite error code is
  142918. ** returned.
  142919. */
  142920. static int fts3EvalSelectDeferred(
  142921. Fts3Cursor *pCsr, /* FTS Cursor handle */
  142922. Fts3Expr *pRoot, /* Consider tokens with this root node */
  142923. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  142924. int nTC /* Number of entries in aTC[] */
  142925. ){
  142926. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142927. int nDocSize = 0; /* Number of pages per doc loaded */
  142928. int rc = SQLITE_OK; /* Return code */
  142929. int ii; /* Iterator variable for various purposes */
  142930. int nOvfl = 0; /* Total overflow pages used by doclists */
  142931. int nToken = 0; /* Total number of tokens in cluster */
  142932. int nMinEst = 0; /* The minimum count for any phrase so far. */
  142933. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  142934. /* Tokens are never deferred for FTS tables created using the content=xxx
  142935. ** option. The reason being that it is not guaranteed that the content
  142936. ** table actually contains the same data as the index. To prevent this from
  142937. ** causing any problems, the deferred token optimization is completely
  142938. ** disabled for content=xxx tables. */
  142939. if( pTab->zContentTbl ){
  142940. return SQLITE_OK;
  142941. }
  142942. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  142943. ** associated with the tokens spill onto overflow pages, or if there is
  142944. ** only 1 token, exit early. No tokens to defer in this case. */
  142945. for(ii=0; ii<nTC; ii++){
  142946. if( aTC[ii].pRoot==pRoot ){
  142947. nOvfl += aTC[ii].nOvfl;
  142948. nToken++;
  142949. }
  142950. }
  142951. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  142952. /* Obtain the average docsize (in pages). */
  142953. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  142954. assert( rc!=SQLITE_OK || nDocSize>0 );
  142955. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  142956. ** of the number of overflow pages that will be loaded by the pager layer
  142957. ** to retrieve the entire doclist for the token from the full-text index.
  142958. ** Load the doclists for tokens that are either:
  142959. **
  142960. ** a. The cheapest token in the entire query (i.e. the one visited by the
  142961. ** first iteration of this loop), or
  142962. **
  142963. ** b. Part of a multi-token phrase.
  142964. **
  142965. ** After each token doclist is loaded, merge it with the others from the
  142966. ** same phrase and count the number of documents that the merged doclist
  142967. ** contains. Set variable "nMinEst" to the smallest number of documents in
  142968. ** any phrase doclist for which 1 or more token doclists have been loaded.
  142969. ** Let nOther be the number of other phrases for which it is certain that
  142970. ** one or more tokens will not be deferred.
  142971. **
  142972. ** Then, for each token, defer it if loading the doclist would result in
  142973. ** loading N or more overflow pages into memory, where N is computed as:
  142974. **
  142975. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  142976. */
  142977. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  142978. int iTC; /* Used to iterate through aTC[] array. */
  142979. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  142980. /* Set pTC to point to the cheapest remaining token. */
  142981. for(iTC=0; iTC<nTC; iTC++){
  142982. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  142983. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  142984. ){
  142985. pTC = &aTC[iTC];
  142986. }
  142987. }
  142988. assert( pTC );
  142989. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  142990. /* The number of overflow pages to load for this (and therefore all
  142991. ** subsequent) tokens is greater than the estimated number of pages
  142992. ** that will be loaded if all subsequent tokens are deferred.
  142993. */
  142994. Fts3PhraseToken *pToken = pTC->pToken;
  142995. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  142996. fts3SegReaderCursorFree(pToken->pSegcsr);
  142997. pToken->pSegcsr = 0;
  142998. }else{
  142999. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  143000. ** for-loop. Except, limit the value to 2^24 to prevent it from
  143001. ** overflowing the 32-bit integer it is stored in. */
  143002. if( ii<12 ) nLoad4 = nLoad4*4;
  143003. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  143004. /* Either this is the cheapest token in the entire query, or it is
  143005. ** part of a multi-token phrase. Either way, the entire doclist will
  143006. ** (eventually) be loaded into memory. It may as well be now. */
  143007. Fts3PhraseToken *pToken = pTC->pToken;
  143008. int nList = 0;
  143009. char *pList = 0;
  143010. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  143011. assert( rc==SQLITE_OK || pList==0 );
  143012. if( rc==SQLITE_OK ){
  143013. rc = fts3EvalPhraseMergeToken(
  143014. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  143015. );
  143016. }
  143017. if( rc==SQLITE_OK ){
  143018. int nCount;
  143019. nCount = fts3DoclistCountDocids(
  143020. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  143021. );
  143022. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  143023. }
  143024. }
  143025. }
  143026. pTC->pToken = 0;
  143027. }
  143028. return rc;
  143029. }
  143030. /*
  143031. ** This function is called from within the xFilter method. It initializes
  143032. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  143033. ** the results of a query, the caller does:
  143034. **
  143035. ** fts3EvalStart(pCsr);
  143036. ** while( 1 ){
  143037. ** fts3EvalNext(pCsr);
  143038. ** if( pCsr->bEof ) break;
  143039. ** ... return row pCsr->iPrevId to the caller ...
  143040. ** }
  143041. */
  143042. static int fts3EvalStart(Fts3Cursor *pCsr){
  143043. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143044. int rc = SQLITE_OK;
  143045. int nToken = 0;
  143046. int nOr = 0;
  143047. /* Allocate a MultiSegReader for each token in the expression. */
  143048. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  143049. /* Determine which, if any, tokens in the expression should be deferred. */
  143050. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  143051. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  143052. Fts3TokenAndCost *aTC;
  143053. Fts3Expr **apOr;
  143054. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  143055. sizeof(Fts3TokenAndCost) * nToken
  143056. + sizeof(Fts3Expr *) * nOr * 2
  143057. );
  143058. apOr = (Fts3Expr **)&aTC[nToken];
  143059. if( !aTC ){
  143060. rc = SQLITE_NOMEM;
  143061. }else{
  143062. int ii;
  143063. Fts3TokenAndCost *pTC = aTC;
  143064. Fts3Expr **ppOr = apOr;
  143065. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  143066. nToken = (int)(pTC-aTC);
  143067. nOr = (int)(ppOr-apOr);
  143068. if( rc==SQLITE_OK ){
  143069. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  143070. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  143071. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  143072. }
  143073. }
  143074. sqlite3_free(aTC);
  143075. }
  143076. }
  143077. #endif
  143078. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  143079. return rc;
  143080. }
  143081. /*
  143082. ** Invalidate the current position list for phrase pPhrase.
  143083. */
  143084. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  143085. if( pPhrase->doclist.bFreeList ){
  143086. sqlite3_free(pPhrase->doclist.pList);
  143087. }
  143088. pPhrase->doclist.pList = 0;
  143089. pPhrase->doclist.nList = 0;
  143090. pPhrase->doclist.bFreeList = 0;
  143091. }
  143092. /*
  143093. ** This function is called to edit the position list associated with
  143094. ** the phrase object passed as the fifth argument according to a NEAR
  143095. ** condition. For example:
  143096. **
  143097. ** abc NEAR/5 "def ghi"
  143098. **
  143099. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  143100. ** the example above). When this function is called, *paPoslist points to
  143101. ** the position list, and *pnToken is the number of phrase tokens in, the
  143102. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  143103. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  143104. ** the position list associated with phrase "abc".
  143105. **
  143106. ** All positions in the pPhrase position list that are not sufficiently
  143107. ** close to a position in the *paPoslist position list are removed. If this
  143108. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  143109. **
  143110. ** Before returning, *paPoslist is set to point to the position lsit
  143111. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  143112. ** pPhrase.
  143113. */
  143114. static int fts3EvalNearTrim(
  143115. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  143116. char *aTmp, /* Temporary space to use */
  143117. char **paPoslist, /* IN/OUT: Position list */
  143118. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  143119. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  143120. ){
  143121. int nParam1 = nNear + pPhrase->nToken;
  143122. int nParam2 = nNear + *pnToken;
  143123. int nNew;
  143124. char *p2;
  143125. char *pOut;
  143126. int res;
  143127. assert( pPhrase->doclist.pList );
  143128. p2 = pOut = pPhrase->doclist.pList;
  143129. res = fts3PoslistNearMerge(
  143130. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  143131. );
  143132. if( res ){
  143133. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  143134. assert( pPhrase->doclist.pList[nNew]=='\0' );
  143135. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  143136. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  143137. pPhrase->doclist.nList = nNew;
  143138. *paPoslist = pPhrase->doclist.pList;
  143139. *pnToken = pPhrase->nToken;
  143140. }
  143141. return res;
  143142. }
  143143. /*
  143144. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  143145. ** Otherwise, it advances the expression passed as the second argument to
  143146. ** point to the next matching row in the database. Expressions iterate through
  143147. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  143148. ** or descending if it is non-zero.
  143149. **
  143150. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  143151. ** successful, the following variables in pExpr are set:
  143152. **
  143153. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  143154. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  143155. **
  143156. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  143157. ** at EOF, then the following variables are populated with the position list
  143158. ** for the phrase for the visited row:
  143159. **
  143160. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  143161. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  143162. **
  143163. ** It says above that this function advances the expression to the next
  143164. ** matching row. This is usually true, but there are the following exceptions:
  143165. **
  143166. ** 1. Deferred tokens are not taken into account. If a phrase consists
  143167. ** entirely of deferred tokens, it is assumed to match every row in
  143168. ** the db. In this case the position-list is not populated at all.
  143169. **
  143170. ** Or, if a phrase contains one or more deferred tokens and one or
  143171. ** more non-deferred tokens, then the expression is advanced to the
  143172. ** next possible match, considering only non-deferred tokens. In other
  143173. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  143174. ** is advanced to the next row that contains an instance of "A * C",
  143175. ** where "*" may match any single token. The position list in this case
  143176. ** is populated as for "A * C" before returning.
  143177. **
  143178. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  143179. ** advanced to point to the next row that matches "x AND y".
  143180. **
  143181. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  143182. ** really a match, taking into account deferred tokens and NEAR operators.
  143183. */
  143184. static void fts3EvalNextRow(
  143185. Fts3Cursor *pCsr, /* FTS Cursor handle */
  143186. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  143187. int *pRc /* IN/OUT: Error code */
  143188. ){
  143189. if( *pRc==SQLITE_OK ){
  143190. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  143191. assert( pExpr->bEof==0 );
  143192. pExpr->bStart = 1;
  143193. switch( pExpr->eType ){
  143194. case FTSQUERY_NEAR:
  143195. case FTSQUERY_AND: {
  143196. Fts3Expr *pLeft = pExpr->pLeft;
  143197. Fts3Expr *pRight = pExpr->pRight;
  143198. assert( !pLeft->bDeferred || !pRight->bDeferred );
  143199. if( pLeft->bDeferred ){
  143200. /* LHS is entirely deferred. So we assume it matches every row.
  143201. ** Advance the RHS iterator to find the next row visited. */
  143202. fts3EvalNextRow(pCsr, pRight, pRc);
  143203. pExpr->iDocid = pRight->iDocid;
  143204. pExpr->bEof = pRight->bEof;
  143205. }else if( pRight->bDeferred ){
  143206. /* RHS is entirely deferred. So we assume it matches every row.
  143207. ** Advance the LHS iterator to find the next row visited. */
  143208. fts3EvalNextRow(pCsr, pLeft, pRc);
  143209. pExpr->iDocid = pLeft->iDocid;
  143210. pExpr->bEof = pLeft->bEof;
  143211. }else{
  143212. /* Neither the RHS or LHS are deferred. */
  143213. fts3EvalNextRow(pCsr, pLeft, pRc);
  143214. fts3EvalNextRow(pCsr, pRight, pRc);
  143215. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  143216. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  143217. if( iDiff==0 ) break;
  143218. if( iDiff<0 ){
  143219. fts3EvalNextRow(pCsr, pLeft, pRc);
  143220. }else{
  143221. fts3EvalNextRow(pCsr, pRight, pRc);
  143222. }
  143223. }
  143224. pExpr->iDocid = pLeft->iDocid;
  143225. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  143226. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  143227. assert( pRight->eType==FTSQUERY_PHRASE );
  143228. if( pRight->pPhrase->doclist.aAll ){
  143229. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  143230. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  143231. memset(pDl->pList, 0, pDl->nList);
  143232. fts3EvalNextRow(pCsr, pRight, pRc);
  143233. }
  143234. }
  143235. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  143236. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  143237. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  143238. memset(pDl->pList, 0, pDl->nList);
  143239. fts3EvalNextRow(pCsr, pLeft, pRc);
  143240. }
  143241. }
  143242. }
  143243. }
  143244. break;
  143245. }
  143246. case FTSQUERY_OR: {
  143247. Fts3Expr *pLeft = pExpr->pLeft;
  143248. Fts3Expr *pRight = pExpr->pRight;
  143249. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  143250. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  143251. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  143252. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  143253. fts3EvalNextRow(pCsr, pLeft, pRc);
  143254. }else if( pLeft->bEof || iCmp>0 ){
  143255. fts3EvalNextRow(pCsr, pRight, pRc);
  143256. }else{
  143257. fts3EvalNextRow(pCsr, pLeft, pRc);
  143258. fts3EvalNextRow(pCsr, pRight, pRc);
  143259. }
  143260. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  143261. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  143262. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  143263. pExpr->iDocid = pLeft->iDocid;
  143264. }else{
  143265. pExpr->iDocid = pRight->iDocid;
  143266. }
  143267. break;
  143268. }
  143269. case FTSQUERY_NOT: {
  143270. Fts3Expr *pLeft = pExpr->pLeft;
  143271. Fts3Expr *pRight = pExpr->pRight;
  143272. if( pRight->bStart==0 ){
  143273. fts3EvalNextRow(pCsr, pRight, pRc);
  143274. assert( *pRc!=SQLITE_OK || pRight->bStart );
  143275. }
  143276. fts3EvalNextRow(pCsr, pLeft, pRc);
  143277. if( pLeft->bEof==0 ){
  143278. while( !*pRc
  143279. && !pRight->bEof
  143280. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  143281. ){
  143282. fts3EvalNextRow(pCsr, pRight, pRc);
  143283. }
  143284. }
  143285. pExpr->iDocid = pLeft->iDocid;
  143286. pExpr->bEof = pLeft->bEof;
  143287. break;
  143288. }
  143289. default: {
  143290. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143291. fts3EvalInvalidatePoslist(pPhrase);
  143292. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  143293. pExpr->iDocid = pPhrase->doclist.iDocid;
  143294. break;
  143295. }
  143296. }
  143297. }
  143298. }
  143299. /*
  143300. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  143301. ** cluster, then this function returns 1 immediately.
  143302. **
  143303. ** Otherwise, it checks if the current row really does match the NEAR
  143304. ** expression, using the data currently stored in the position lists
  143305. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  143306. **
  143307. ** If the current row is a match, the position list associated with each
  143308. ** phrase in the NEAR expression is edited in place to contain only those
  143309. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  143310. ** constraints. In this case it returns 1. If the NEAR expression does not
  143311. ** match the current row, 0 is returned. The position lists may or may not
  143312. ** be edited if 0 is returned.
  143313. */
  143314. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  143315. int res = 1;
  143316. /* The following block runs if pExpr is the root of a NEAR query.
  143317. ** For example, the query:
  143318. **
  143319. ** "w" NEAR "x" NEAR "y" NEAR "z"
  143320. **
  143321. ** which is represented in tree form as:
  143322. **
  143323. ** |
  143324. ** +--NEAR--+ <-- root of NEAR query
  143325. ** | |
  143326. ** +--NEAR--+ "z"
  143327. ** | |
  143328. ** +--NEAR--+ "y"
  143329. ** | |
  143330. ** "w" "x"
  143331. **
  143332. ** The right-hand child of a NEAR node is always a phrase. The
  143333. ** left-hand child may be either a phrase or a NEAR node. There are
  143334. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  143335. */
  143336. if( *pRc==SQLITE_OK
  143337. && pExpr->eType==FTSQUERY_NEAR
  143338. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  143339. ){
  143340. Fts3Expr *p;
  143341. int nTmp = 0; /* Bytes of temp space */
  143342. char *aTmp; /* Temp space for PoslistNearMerge() */
  143343. /* Allocate temporary working space. */
  143344. for(p=pExpr; p->pLeft; p=p->pLeft){
  143345. assert( p->pRight->pPhrase->doclist.nList>0 );
  143346. nTmp += p->pRight->pPhrase->doclist.nList;
  143347. }
  143348. nTmp += p->pPhrase->doclist.nList;
  143349. aTmp = sqlite3_malloc(nTmp*2);
  143350. if( !aTmp ){
  143351. *pRc = SQLITE_NOMEM;
  143352. res = 0;
  143353. }else{
  143354. char *aPoslist = p->pPhrase->doclist.pList;
  143355. int nToken = p->pPhrase->nToken;
  143356. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  143357. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  143358. int nNear = p->nNear;
  143359. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  143360. }
  143361. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  143362. nToken = pExpr->pRight->pPhrase->nToken;
  143363. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  143364. int nNear;
  143365. Fts3Phrase *pPhrase;
  143366. assert( p->pParent && p->pParent->pLeft==p );
  143367. nNear = p->pParent->nNear;
  143368. pPhrase = (
  143369. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  143370. );
  143371. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  143372. }
  143373. }
  143374. sqlite3_free(aTmp);
  143375. }
  143376. return res;
  143377. }
  143378. /*
  143379. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  143380. ** Assuming no error occurs or has occurred, It returns non-zero if the
  143381. ** expression passed as the second argument matches the row that pCsr
  143382. ** currently points to, or zero if it does not.
  143383. **
  143384. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  143385. ** If an error occurs during execution of this function, *pRc is set to
  143386. ** the appropriate SQLite error code. In this case the returned value is
  143387. ** undefined.
  143388. */
  143389. static int fts3EvalTestExpr(
  143390. Fts3Cursor *pCsr, /* FTS cursor handle */
  143391. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  143392. int *pRc /* IN/OUT: Error code */
  143393. ){
  143394. int bHit = 1; /* Return value */
  143395. if( *pRc==SQLITE_OK ){
  143396. switch( pExpr->eType ){
  143397. case FTSQUERY_NEAR:
  143398. case FTSQUERY_AND:
  143399. bHit = (
  143400. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  143401. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  143402. && fts3EvalNearTest(pExpr, pRc)
  143403. );
  143404. /* If the NEAR expression does not match any rows, zero the doclist for
  143405. ** all phrases involved in the NEAR. This is because the snippet(),
  143406. ** offsets() and matchinfo() functions are not supposed to recognize
  143407. ** any instances of phrases that are part of unmatched NEAR queries.
  143408. ** For example if this expression:
  143409. **
  143410. ** ... MATCH 'a OR (b NEAR c)'
  143411. **
  143412. ** is matched against a row containing:
  143413. **
  143414. ** 'a b d e'
  143415. **
  143416. ** then any snippet() should ony highlight the "a" term, not the "b"
  143417. ** (as "b" is part of a non-matching NEAR clause).
  143418. */
  143419. if( bHit==0
  143420. && pExpr->eType==FTSQUERY_NEAR
  143421. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  143422. ){
  143423. Fts3Expr *p;
  143424. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  143425. if( p->pRight->iDocid==pCsr->iPrevId ){
  143426. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  143427. }
  143428. }
  143429. if( p->iDocid==pCsr->iPrevId ){
  143430. fts3EvalInvalidatePoslist(p->pPhrase);
  143431. }
  143432. }
  143433. break;
  143434. case FTSQUERY_OR: {
  143435. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  143436. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  143437. bHit = bHit1 || bHit2;
  143438. break;
  143439. }
  143440. case FTSQUERY_NOT:
  143441. bHit = (
  143442. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  143443. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  143444. );
  143445. break;
  143446. default: {
  143447. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  143448. if( pCsr->pDeferred
  143449. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  143450. ){
  143451. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143452. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  143453. if( pExpr->bDeferred ){
  143454. fts3EvalInvalidatePoslist(pPhrase);
  143455. }
  143456. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  143457. bHit = (pPhrase->doclist.pList!=0);
  143458. pExpr->iDocid = pCsr->iPrevId;
  143459. }else
  143460. #endif
  143461. {
  143462. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  143463. }
  143464. break;
  143465. }
  143466. }
  143467. }
  143468. return bHit;
  143469. }
  143470. /*
  143471. ** This function is called as the second part of each xNext operation when
  143472. ** iterating through the results of a full-text query. At this point the
  143473. ** cursor points to a row that matches the query expression, with the
  143474. ** following caveats:
  143475. **
  143476. ** * Up until this point, "NEAR" operators in the expression have been
  143477. ** treated as "AND".
  143478. **
  143479. ** * Deferred tokens have not yet been considered.
  143480. **
  143481. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  143482. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  143483. ** operators and deferred tokens the current row is still a match for the
  143484. ** expression. It returns 1 if both of the following are true:
  143485. **
  143486. ** 1. *pRc is SQLITE_OK when this function returns, and
  143487. **
  143488. ** 2. After scanning the current FTS table row for the deferred tokens,
  143489. ** it is determined that the row does *not* match the query.
  143490. **
  143491. ** Or, if no error occurs and it seems the current row does match the FTS
  143492. ** query, return 0.
  143493. */
  143494. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  143495. int rc = *pRc;
  143496. int bMiss = 0;
  143497. if( rc==SQLITE_OK ){
  143498. /* If there are one or more deferred tokens, load the current row into
  143499. ** memory and scan it to determine the position list for each deferred
  143500. ** token. Then, see if this row is really a match, considering deferred
  143501. ** tokens and NEAR operators (neither of which were taken into account
  143502. ** earlier, by fts3EvalNextRow()).
  143503. */
  143504. if( pCsr->pDeferred ){
  143505. rc = fts3CursorSeek(0, pCsr);
  143506. if( rc==SQLITE_OK ){
  143507. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  143508. }
  143509. }
  143510. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  143511. /* Free the position-lists accumulated for each deferred token above. */
  143512. sqlite3Fts3FreeDeferredDoclists(pCsr);
  143513. *pRc = rc;
  143514. }
  143515. return (rc==SQLITE_OK && bMiss);
  143516. }
  143517. /*
  143518. ** Advance to the next document that matches the FTS expression in
  143519. ** Fts3Cursor.pExpr.
  143520. */
  143521. static int fts3EvalNext(Fts3Cursor *pCsr){
  143522. int rc = SQLITE_OK; /* Return Code */
  143523. Fts3Expr *pExpr = pCsr->pExpr;
  143524. assert( pCsr->isEof==0 );
  143525. if( pExpr==0 ){
  143526. pCsr->isEof = 1;
  143527. }else{
  143528. do {
  143529. if( pCsr->isRequireSeek==0 ){
  143530. sqlite3_reset(pCsr->pStmt);
  143531. }
  143532. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  143533. fts3EvalNextRow(pCsr, pExpr, &rc);
  143534. pCsr->isEof = pExpr->bEof;
  143535. pCsr->isRequireSeek = 1;
  143536. pCsr->isMatchinfoNeeded = 1;
  143537. pCsr->iPrevId = pExpr->iDocid;
  143538. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  143539. }
  143540. /* Check if the cursor is past the end of the docid range specified
  143541. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  143542. if( rc==SQLITE_OK && (
  143543. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  143544. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  143545. )){
  143546. pCsr->isEof = 1;
  143547. }
  143548. return rc;
  143549. }
  143550. /*
  143551. ** Restart interation for expression pExpr so that the next call to
  143552. ** fts3EvalNext() visits the first row. Do not allow incremental
  143553. ** loading or merging of phrase doclists for this iteration.
  143554. **
  143555. ** If *pRc is other than SQLITE_OK when this function is called, it is
  143556. ** a no-op. If an error occurs within this function, *pRc is set to an
  143557. ** SQLite error code before returning.
  143558. */
  143559. static void fts3EvalRestart(
  143560. Fts3Cursor *pCsr,
  143561. Fts3Expr *pExpr,
  143562. int *pRc
  143563. ){
  143564. if( pExpr && *pRc==SQLITE_OK ){
  143565. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143566. if( pPhrase ){
  143567. fts3EvalInvalidatePoslist(pPhrase);
  143568. if( pPhrase->bIncr ){
  143569. int i;
  143570. for(i=0; i<pPhrase->nToken; i++){
  143571. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  143572. assert( pToken->pDeferred==0 );
  143573. if( pToken->pSegcsr ){
  143574. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  143575. }
  143576. }
  143577. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  143578. }
  143579. pPhrase->doclist.pNextDocid = 0;
  143580. pPhrase->doclist.iDocid = 0;
  143581. pPhrase->pOrPoslist = 0;
  143582. }
  143583. pExpr->iDocid = 0;
  143584. pExpr->bEof = 0;
  143585. pExpr->bStart = 0;
  143586. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  143587. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  143588. }
  143589. }
  143590. /*
  143591. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  143592. ** expression rooted at pExpr, the cursor iterates through all rows matched
  143593. ** by pExpr, calling this function for each row. This function increments
  143594. ** the values in Fts3Expr.aMI[] according to the position-list currently
  143595. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  143596. ** expression nodes.
  143597. */
  143598. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  143599. if( pExpr ){
  143600. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143601. if( pPhrase && pPhrase->doclist.pList ){
  143602. int iCol = 0;
  143603. char *p = pPhrase->doclist.pList;
  143604. assert( *p );
  143605. while( 1 ){
  143606. u8 c = 0;
  143607. int iCnt = 0;
  143608. while( 0xFE & (*p | c) ){
  143609. if( (c&0x80)==0 ) iCnt++;
  143610. c = *p++ & 0x80;
  143611. }
  143612. /* aMI[iCol*3 + 1] = Number of occurrences
  143613. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  143614. */
  143615. pExpr->aMI[iCol*3 + 1] += iCnt;
  143616. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  143617. if( *p==0x00 ) break;
  143618. p++;
  143619. p += fts3GetVarint32(p, &iCol);
  143620. }
  143621. }
  143622. fts3EvalUpdateCounts(pExpr->pLeft);
  143623. fts3EvalUpdateCounts(pExpr->pRight);
  143624. }
  143625. }
  143626. /*
  143627. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  143628. **
  143629. ** If it is not already allocated and populated, this function allocates and
  143630. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  143631. ** of a NEAR expression, then it also allocates and populates the same array
  143632. ** for all other phrases that are part of the NEAR expression.
  143633. **
  143634. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  143635. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  143636. */
  143637. static int fts3EvalGatherStats(
  143638. Fts3Cursor *pCsr, /* Cursor object */
  143639. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  143640. ){
  143641. int rc = SQLITE_OK; /* Return code */
  143642. assert( pExpr->eType==FTSQUERY_PHRASE );
  143643. if( pExpr->aMI==0 ){
  143644. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143645. Fts3Expr *pRoot; /* Root of NEAR expression */
  143646. Fts3Expr *p; /* Iterator used for several purposes */
  143647. sqlite3_int64 iPrevId = pCsr->iPrevId;
  143648. sqlite3_int64 iDocid;
  143649. u8 bEof;
  143650. /* Find the root of the NEAR expression */
  143651. pRoot = pExpr;
  143652. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  143653. pRoot = pRoot->pParent;
  143654. }
  143655. iDocid = pRoot->iDocid;
  143656. bEof = pRoot->bEof;
  143657. assert( pRoot->bStart );
  143658. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  143659. for(p=pRoot; p; p=p->pLeft){
  143660. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  143661. assert( pE->aMI==0 );
  143662. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  143663. if( !pE->aMI ) return SQLITE_NOMEM;
  143664. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  143665. }
  143666. fts3EvalRestart(pCsr, pRoot, &rc);
  143667. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  143668. do {
  143669. /* Ensure the %_content statement is reset. */
  143670. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  143671. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  143672. /* Advance to the next document */
  143673. fts3EvalNextRow(pCsr, pRoot, &rc);
  143674. pCsr->isEof = pRoot->bEof;
  143675. pCsr->isRequireSeek = 1;
  143676. pCsr->isMatchinfoNeeded = 1;
  143677. pCsr->iPrevId = pRoot->iDocid;
  143678. }while( pCsr->isEof==0
  143679. && pRoot->eType==FTSQUERY_NEAR
  143680. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  143681. );
  143682. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  143683. fts3EvalUpdateCounts(pRoot);
  143684. }
  143685. }
  143686. pCsr->isEof = 0;
  143687. pCsr->iPrevId = iPrevId;
  143688. if( bEof ){
  143689. pRoot->bEof = bEof;
  143690. }else{
  143691. /* Caution: pRoot may iterate through docids in ascending or descending
  143692. ** order. For this reason, even though it seems more defensive, the
  143693. ** do loop can not be written:
  143694. **
  143695. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  143696. */
  143697. fts3EvalRestart(pCsr, pRoot, &rc);
  143698. do {
  143699. fts3EvalNextRow(pCsr, pRoot, &rc);
  143700. assert( pRoot->bEof==0 );
  143701. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  143702. }
  143703. }
  143704. return rc;
  143705. }
  143706. /*
  143707. ** This function is used by the matchinfo() module to query a phrase
  143708. ** expression node for the following information:
  143709. **
  143710. ** 1. The total number of occurrences of the phrase in each column of
  143711. ** the FTS table (considering all rows), and
  143712. **
  143713. ** 2. For each column, the number of rows in the table for which the
  143714. ** column contains at least one instance of the phrase.
  143715. **
  143716. ** If no error occurs, SQLITE_OK is returned and the values for each column
  143717. ** written into the array aiOut as follows:
  143718. **
  143719. ** aiOut[iCol*3 + 1] = Number of occurrences
  143720. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  143721. **
  143722. ** Caveats:
  143723. **
  143724. ** * If a phrase consists entirely of deferred tokens, then all output
  143725. ** values are set to the number of documents in the table. In other
  143726. ** words we assume that very common tokens occur exactly once in each
  143727. ** column of each row of the table.
  143728. **
  143729. ** * If a phrase contains some deferred tokens (and some non-deferred
  143730. ** tokens), count the potential occurrence identified by considering
  143731. ** the non-deferred tokens instead of actual phrase occurrences.
  143732. **
  143733. ** * If the phrase is part of a NEAR expression, then only phrase instances
  143734. ** that meet the NEAR constraint are included in the counts.
  143735. */
  143736. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  143737. Fts3Cursor *pCsr, /* FTS cursor handle */
  143738. Fts3Expr *pExpr, /* Phrase expression */
  143739. u32 *aiOut /* Array to write results into (see above) */
  143740. ){
  143741. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143742. int rc = SQLITE_OK;
  143743. int iCol;
  143744. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  143745. assert( pCsr->nDoc>0 );
  143746. for(iCol=0; iCol<pTab->nColumn; iCol++){
  143747. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  143748. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  143749. }
  143750. }else{
  143751. rc = fts3EvalGatherStats(pCsr, pExpr);
  143752. if( rc==SQLITE_OK ){
  143753. assert( pExpr->aMI );
  143754. for(iCol=0; iCol<pTab->nColumn; iCol++){
  143755. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  143756. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  143757. }
  143758. }
  143759. }
  143760. return rc;
  143761. }
  143762. /*
  143763. ** The expression pExpr passed as the second argument to this function
  143764. ** must be of type FTSQUERY_PHRASE.
  143765. **
  143766. ** The returned value is either NULL or a pointer to a buffer containing
  143767. ** a position-list indicating the occurrences of the phrase in column iCol
  143768. ** of the current row.
  143769. **
  143770. ** More specifically, the returned buffer contains 1 varint for each
  143771. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  143772. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  143773. ** if the requested column contains "a b X c d X X" and the position-list
  143774. ** for 'X' is requested, the buffer returned may contain:
  143775. **
  143776. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  143777. **
  143778. ** This function works regardless of whether or not the phrase is deferred,
  143779. ** incremental, or neither.
  143780. */
  143781. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  143782. Fts3Cursor *pCsr, /* FTS3 cursor object */
  143783. Fts3Expr *pExpr, /* Phrase to return doclist for */
  143784. int iCol, /* Column to return position list for */
  143785. char **ppOut /* OUT: Pointer to position list */
  143786. ){
  143787. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143788. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143789. char *pIter;
  143790. int iThis;
  143791. sqlite3_int64 iDocid;
  143792. /* If this phrase is applies specifically to some column other than
  143793. ** column iCol, return a NULL pointer. */
  143794. *ppOut = 0;
  143795. assert( iCol>=0 && iCol<pTab->nColumn );
  143796. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  143797. return SQLITE_OK;
  143798. }
  143799. iDocid = pExpr->iDocid;
  143800. pIter = pPhrase->doclist.pList;
  143801. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  143802. int rc = SQLITE_OK;
  143803. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  143804. int bOr = 0;
  143805. u8 bTreeEof = 0;
  143806. Fts3Expr *p; /* Used to iterate from pExpr to root */
  143807. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  143808. int bMatch;
  143809. /* Check if this phrase descends from an OR expression node. If not,
  143810. ** return NULL. Otherwise, the entry that corresponds to docid
  143811. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  143812. ** tree that the node is part of has been marked as EOF, but the node
  143813. ** itself is not EOF, then it may point to an earlier entry. */
  143814. pNear = pExpr;
  143815. for(p=pExpr->pParent; p; p=p->pParent){
  143816. if( p->eType==FTSQUERY_OR ) bOr = 1;
  143817. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  143818. if( p->bEof ) bTreeEof = 1;
  143819. }
  143820. if( bOr==0 ) return SQLITE_OK;
  143821. /* This is the descendent of an OR node. In this case we cannot use
  143822. ** an incremental phrase. Load the entire doclist for the phrase
  143823. ** into memory in this case. */
  143824. if( pPhrase->bIncr ){
  143825. int bEofSave = pNear->bEof;
  143826. fts3EvalRestart(pCsr, pNear, &rc);
  143827. while( rc==SQLITE_OK && !pNear->bEof ){
  143828. fts3EvalNextRow(pCsr, pNear, &rc);
  143829. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  143830. }
  143831. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  143832. }
  143833. if( bTreeEof ){
  143834. while( rc==SQLITE_OK && !pNear->bEof ){
  143835. fts3EvalNextRow(pCsr, pNear, &rc);
  143836. }
  143837. }
  143838. if( rc!=SQLITE_OK ) return rc;
  143839. bMatch = 1;
  143840. for(p=pNear; p; p=p->pLeft){
  143841. u8 bEof = 0;
  143842. Fts3Expr *pTest = p;
  143843. Fts3Phrase *pPh;
  143844. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  143845. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  143846. assert( pTest->eType==FTSQUERY_PHRASE );
  143847. pPh = pTest->pPhrase;
  143848. pIter = pPh->pOrPoslist;
  143849. iDocid = pPh->iOrDocid;
  143850. if( pCsr->bDesc==bDescDoclist ){
  143851. bEof = !pPh->doclist.nAll ||
  143852. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  143853. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  143854. sqlite3Fts3DoclistNext(
  143855. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  143856. &pIter, &iDocid, &bEof
  143857. );
  143858. }
  143859. }else{
  143860. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  143861. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  143862. int dummy;
  143863. sqlite3Fts3DoclistPrev(
  143864. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  143865. &pIter, &iDocid, &dummy, &bEof
  143866. );
  143867. }
  143868. }
  143869. pPh->pOrPoslist = pIter;
  143870. pPh->iOrDocid = iDocid;
  143871. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  143872. }
  143873. if( bMatch ){
  143874. pIter = pPhrase->pOrPoslist;
  143875. }else{
  143876. pIter = 0;
  143877. }
  143878. }
  143879. if( pIter==0 ) return SQLITE_OK;
  143880. if( *pIter==0x01 ){
  143881. pIter++;
  143882. pIter += fts3GetVarint32(pIter, &iThis);
  143883. }else{
  143884. iThis = 0;
  143885. }
  143886. while( iThis<iCol ){
  143887. fts3ColumnlistCopy(0, &pIter);
  143888. if( *pIter==0x00 ) return SQLITE_OK;
  143889. pIter++;
  143890. pIter += fts3GetVarint32(pIter, &iThis);
  143891. }
  143892. if( *pIter==0x00 ){
  143893. pIter = 0;
  143894. }
  143895. *ppOut = ((iCol==iThis)?pIter:0);
  143896. return SQLITE_OK;
  143897. }
  143898. /*
  143899. ** Free all components of the Fts3Phrase structure that were allocated by
  143900. ** the eval module. Specifically, this means to free:
  143901. **
  143902. ** * the contents of pPhrase->doclist, and
  143903. ** * any Fts3MultiSegReader objects held by phrase tokens.
  143904. */
  143905. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  143906. if( pPhrase ){
  143907. int i;
  143908. sqlite3_free(pPhrase->doclist.aAll);
  143909. fts3EvalInvalidatePoslist(pPhrase);
  143910. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  143911. for(i=0; i<pPhrase->nToken; i++){
  143912. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  143913. pPhrase->aToken[i].pSegcsr = 0;
  143914. }
  143915. }
  143916. }
  143917. /*
  143918. ** Return SQLITE_CORRUPT_VTAB.
  143919. */
  143920. #ifdef SQLITE_DEBUG
  143921. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  143922. return SQLITE_CORRUPT_VTAB;
  143923. }
  143924. #endif
  143925. #if !SQLITE_CORE
  143926. /*
  143927. ** Initialize API pointer table, if required.
  143928. */
  143929. #ifdef _WIN32
  143930. __declspec(dllexport)
  143931. #endif
  143932. SQLITE_API int sqlite3_fts3_init(
  143933. sqlite3 *db,
  143934. char **pzErrMsg,
  143935. const sqlite3_api_routines *pApi
  143936. ){
  143937. SQLITE_EXTENSION_INIT2(pApi)
  143938. return sqlite3Fts3Init(db);
  143939. }
  143940. #endif
  143941. #endif
  143942. /************** End of fts3.c ************************************************/
  143943. /************** Begin file fts3_aux.c ****************************************/
  143944. /*
  143945. ** 2011 Jan 27
  143946. **
  143947. ** The author disclaims copyright to this source code. In place of
  143948. ** a legal notice, here is a blessing:
  143949. **
  143950. ** May you do good and not evil.
  143951. ** May you find forgiveness for yourself and forgive others.
  143952. ** May you share freely, never taking more than you give.
  143953. **
  143954. ******************************************************************************
  143955. **
  143956. */
  143957. /* #include "fts3Int.h" */
  143958. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  143959. /* #include <string.h> */
  143960. /* #include <assert.h> */
  143961. typedef struct Fts3auxTable Fts3auxTable;
  143962. typedef struct Fts3auxCursor Fts3auxCursor;
  143963. struct Fts3auxTable {
  143964. sqlite3_vtab base; /* Base class used by SQLite core */
  143965. Fts3Table *pFts3Tab;
  143966. };
  143967. struct Fts3auxCursor {
  143968. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  143969. Fts3MultiSegReader csr; /* Must be right after "base" */
  143970. Fts3SegFilter filter;
  143971. char *zStop;
  143972. int nStop; /* Byte-length of string zStop */
  143973. int iLangid; /* Language id to query */
  143974. int isEof; /* True if cursor is at EOF */
  143975. sqlite3_int64 iRowid; /* Current rowid */
  143976. int iCol; /* Current value of 'col' column */
  143977. int nStat; /* Size of aStat[] array */
  143978. struct Fts3auxColstats {
  143979. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  143980. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  143981. } *aStat;
  143982. };
  143983. /*
  143984. ** Schema of the terms table.
  143985. */
  143986. #define FTS3_AUX_SCHEMA \
  143987. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  143988. /*
  143989. ** This function does all the work for both the xConnect and xCreate methods.
  143990. ** These tables have no persistent representation of their own, so xConnect
  143991. ** and xCreate are identical operations.
  143992. */
  143993. static int fts3auxConnectMethod(
  143994. sqlite3 *db, /* Database connection */
  143995. void *pUnused, /* Unused */
  143996. int argc, /* Number of elements in argv array */
  143997. const char * const *argv, /* xCreate/xConnect argument array */
  143998. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  143999. char **pzErr /* OUT: sqlite3_malloc'd error message */
  144000. ){
  144001. char const *zDb; /* Name of database (e.g. "main") */
  144002. char const *zFts3; /* Name of fts3 table */
  144003. int nDb; /* Result of strlen(zDb) */
  144004. int nFts3; /* Result of strlen(zFts3) */
  144005. int nByte; /* Bytes of space to allocate here */
  144006. int rc; /* value returned by declare_vtab() */
  144007. Fts3auxTable *p; /* Virtual table object to return */
  144008. UNUSED_PARAMETER(pUnused);
  144009. /* The user should invoke this in one of two forms:
  144010. **
  144011. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  144012. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  144013. */
  144014. if( argc!=4 && argc!=5 ) goto bad_args;
  144015. zDb = argv[1];
  144016. nDb = (int)strlen(zDb);
  144017. if( argc==5 ){
  144018. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  144019. zDb = argv[3];
  144020. nDb = (int)strlen(zDb);
  144021. zFts3 = argv[4];
  144022. }else{
  144023. goto bad_args;
  144024. }
  144025. }else{
  144026. zFts3 = argv[3];
  144027. }
  144028. nFts3 = (int)strlen(zFts3);
  144029. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  144030. if( rc!=SQLITE_OK ) return rc;
  144031. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  144032. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  144033. if( !p ) return SQLITE_NOMEM;
  144034. memset(p, 0, nByte);
  144035. p->pFts3Tab = (Fts3Table *)&p[1];
  144036. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  144037. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  144038. p->pFts3Tab->db = db;
  144039. p->pFts3Tab->nIndex = 1;
  144040. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  144041. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  144042. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  144043. *ppVtab = (sqlite3_vtab *)p;
  144044. return SQLITE_OK;
  144045. bad_args:
  144046. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  144047. return SQLITE_ERROR;
  144048. }
  144049. /*
  144050. ** This function does the work for both the xDisconnect and xDestroy methods.
  144051. ** These tables have no persistent representation of their own, so xDisconnect
  144052. ** and xDestroy are identical operations.
  144053. */
  144054. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  144055. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  144056. Fts3Table *pFts3 = p->pFts3Tab;
  144057. int i;
  144058. /* Free any prepared statements held */
  144059. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  144060. sqlite3_finalize(pFts3->aStmt[i]);
  144061. }
  144062. sqlite3_free(pFts3->zSegmentsTbl);
  144063. sqlite3_free(p);
  144064. return SQLITE_OK;
  144065. }
  144066. #define FTS4AUX_EQ_CONSTRAINT 1
  144067. #define FTS4AUX_GE_CONSTRAINT 2
  144068. #define FTS4AUX_LE_CONSTRAINT 4
  144069. /*
  144070. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  144071. */
  144072. static int fts3auxBestIndexMethod(
  144073. sqlite3_vtab *pVTab,
  144074. sqlite3_index_info *pInfo
  144075. ){
  144076. int i;
  144077. int iEq = -1;
  144078. int iGe = -1;
  144079. int iLe = -1;
  144080. int iLangid = -1;
  144081. int iNext = 1; /* Next free argvIndex value */
  144082. UNUSED_PARAMETER(pVTab);
  144083. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  144084. if( pInfo->nOrderBy==1
  144085. && pInfo->aOrderBy[0].iColumn==0
  144086. && pInfo->aOrderBy[0].desc==0
  144087. ){
  144088. pInfo->orderByConsumed = 1;
  144089. }
  144090. /* Search for equality and range constraints on the "term" column.
  144091. ** And equality constraints on the hidden "languageid" column. */
  144092. for(i=0; i<pInfo->nConstraint; i++){
  144093. if( pInfo->aConstraint[i].usable ){
  144094. int op = pInfo->aConstraint[i].op;
  144095. int iCol = pInfo->aConstraint[i].iColumn;
  144096. if( iCol==0 ){
  144097. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  144098. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  144099. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  144100. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  144101. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  144102. }
  144103. if( iCol==4 ){
  144104. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  144105. }
  144106. }
  144107. }
  144108. if( iEq>=0 ){
  144109. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  144110. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  144111. pInfo->estimatedCost = 5;
  144112. }else{
  144113. pInfo->idxNum = 0;
  144114. pInfo->estimatedCost = 20000;
  144115. if( iGe>=0 ){
  144116. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  144117. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  144118. pInfo->estimatedCost /= 2;
  144119. }
  144120. if( iLe>=0 ){
  144121. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  144122. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  144123. pInfo->estimatedCost /= 2;
  144124. }
  144125. }
  144126. if( iLangid>=0 ){
  144127. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  144128. pInfo->estimatedCost--;
  144129. }
  144130. return SQLITE_OK;
  144131. }
  144132. /*
  144133. ** xOpen - Open a cursor.
  144134. */
  144135. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  144136. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  144137. UNUSED_PARAMETER(pVTab);
  144138. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  144139. if( !pCsr ) return SQLITE_NOMEM;
  144140. memset(pCsr, 0, sizeof(Fts3auxCursor));
  144141. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  144142. return SQLITE_OK;
  144143. }
  144144. /*
  144145. ** xClose - Close a cursor.
  144146. */
  144147. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  144148. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  144149. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  144150. sqlite3Fts3SegmentsClose(pFts3);
  144151. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  144152. sqlite3_free((void *)pCsr->filter.zTerm);
  144153. sqlite3_free(pCsr->zStop);
  144154. sqlite3_free(pCsr->aStat);
  144155. sqlite3_free(pCsr);
  144156. return SQLITE_OK;
  144157. }
  144158. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  144159. if( nSize>pCsr->nStat ){
  144160. struct Fts3auxColstats *aNew;
  144161. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  144162. sizeof(struct Fts3auxColstats) * nSize
  144163. );
  144164. if( aNew==0 ) return SQLITE_NOMEM;
  144165. memset(&aNew[pCsr->nStat], 0,
  144166. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  144167. );
  144168. pCsr->aStat = aNew;
  144169. pCsr->nStat = nSize;
  144170. }
  144171. return SQLITE_OK;
  144172. }
  144173. /*
  144174. ** xNext - Advance the cursor to the next row, if any.
  144175. */
  144176. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  144177. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  144178. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  144179. int rc;
  144180. /* Increment our pretend rowid value. */
  144181. pCsr->iRowid++;
  144182. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  144183. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  144184. }
  144185. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  144186. if( rc==SQLITE_ROW ){
  144187. int i = 0;
  144188. int nDoclist = pCsr->csr.nDoclist;
  144189. char *aDoclist = pCsr->csr.aDoclist;
  144190. int iCol;
  144191. int eState = 0;
  144192. if( pCsr->zStop ){
  144193. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  144194. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  144195. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  144196. pCsr->isEof = 1;
  144197. return SQLITE_OK;
  144198. }
  144199. }
  144200. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  144201. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  144202. iCol = 0;
  144203. while( i<nDoclist ){
  144204. sqlite3_int64 v = 0;
  144205. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  144206. switch( eState ){
  144207. /* State 0. In this state the integer just read was a docid. */
  144208. case 0:
  144209. pCsr->aStat[0].nDoc++;
  144210. eState = 1;
  144211. iCol = 0;
  144212. break;
  144213. /* State 1. In this state we are expecting either a 1, indicating
  144214. ** that the following integer will be a column number, or the
  144215. ** start of a position list for column 0.
  144216. **
  144217. ** The only difference between state 1 and state 2 is that if the
  144218. ** integer encountered in state 1 is not 0 or 1, then we need to
  144219. ** increment the column 0 "nDoc" count for this term.
  144220. */
  144221. case 1:
  144222. assert( iCol==0 );
  144223. if( v>1 ){
  144224. pCsr->aStat[1].nDoc++;
  144225. }
  144226. eState = 2;
  144227. /* fall through */
  144228. case 2:
  144229. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  144230. eState = 0;
  144231. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  144232. eState = 3;
  144233. }else{ /* 2 or greater. A position. */
  144234. pCsr->aStat[iCol+1].nOcc++;
  144235. pCsr->aStat[0].nOcc++;
  144236. }
  144237. break;
  144238. /* State 3. The integer just read is a column number. */
  144239. default: assert( eState==3 );
  144240. iCol = (int)v;
  144241. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  144242. pCsr->aStat[iCol+1].nDoc++;
  144243. eState = 2;
  144244. break;
  144245. }
  144246. }
  144247. pCsr->iCol = 0;
  144248. rc = SQLITE_OK;
  144249. }else{
  144250. pCsr->isEof = 1;
  144251. }
  144252. return rc;
  144253. }
  144254. /*
  144255. ** xFilter - Initialize a cursor to point at the start of its data.
  144256. */
  144257. static int fts3auxFilterMethod(
  144258. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  144259. int idxNum, /* Strategy index */
  144260. const char *idxStr, /* Unused */
  144261. int nVal, /* Number of elements in apVal */
  144262. sqlite3_value **apVal /* Arguments for the indexing scheme */
  144263. ){
  144264. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  144265. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  144266. int rc;
  144267. int isScan = 0;
  144268. int iLangVal = 0; /* Language id to query */
  144269. int iEq = -1; /* Index of term=? value in apVal */
  144270. int iGe = -1; /* Index of term>=? value in apVal */
  144271. int iLe = -1; /* Index of term<=? value in apVal */
  144272. int iLangid = -1; /* Index of languageid=? value in apVal */
  144273. int iNext = 0;
  144274. UNUSED_PARAMETER(nVal);
  144275. UNUSED_PARAMETER(idxStr);
  144276. assert( idxStr==0 );
  144277. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  144278. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  144279. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  144280. );
  144281. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  144282. iEq = iNext++;
  144283. }else{
  144284. isScan = 1;
  144285. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  144286. iGe = iNext++;
  144287. }
  144288. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  144289. iLe = iNext++;
  144290. }
  144291. }
  144292. if( iNext<nVal ){
  144293. iLangid = iNext++;
  144294. }
  144295. /* In case this cursor is being reused, close and zero it. */
  144296. testcase(pCsr->filter.zTerm);
  144297. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  144298. sqlite3_free((void *)pCsr->filter.zTerm);
  144299. sqlite3_free(pCsr->aStat);
  144300. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  144301. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  144302. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  144303. if( iEq>=0 || iGe>=0 ){
  144304. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  144305. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  144306. if( zStr ){
  144307. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  144308. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  144309. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  144310. }
  144311. }
  144312. if( iLe>=0 ){
  144313. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  144314. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  144315. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  144316. }
  144317. if( iLangid>=0 ){
  144318. iLangVal = sqlite3_value_int(apVal[iLangid]);
  144319. /* If the user specified a negative value for the languageid, use zero
  144320. ** instead. This works, as the "languageid=?" constraint will also
  144321. ** be tested by the VDBE layer. The test will always be false (since
  144322. ** this module will not return a row with a negative languageid), and
  144323. ** so the overall query will return zero rows. */
  144324. if( iLangVal<0 ) iLangVal = 0;
  144325. }
  144326. pCsr->iLangid = iLangVal;
  144327. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  144328. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  144329. );
  144330. if( rc==SQLITE_OK ){
  144331. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  144332. }
  144333. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  144334. return rc;
  144335. }
  144336. /*
  144337. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  144338. */
  144339. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  144340. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  144341. return pCsr->isEof;
  144342. }
  144343. /*
  144344. ** xColumn - Return a column value.
  144345. */
  144346. static int fts3auxColumnMethod(
  144347. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  144348. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  144349. int iCol /* Index of column to read value from */
  144350. ){
  144351. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  144352. assert( p->isEof==0 );
  144353. switch( iCol ){
  144354. case 0: /* term */
  144355. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  144356. break;
  144357. case 1: /* col */
  144358. if( p->iCol ){
  144359. sqlite3_result_int(pCtx, p->iCol-1);
  144360. }else{
  144361. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  144362. }
  144363. break;
  144364. case 2: /* documents */
  144365. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  144366. break;
  144367. case 3: /* occurrences */
  144368. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  144369. break;
  144370. default: /* languageid */
  144371. assert( iCol==4 );
  144372. sqlite3_result_int(pCtx, p->iLangid);
  144373. break;
  144374. }
  144375. return SQLITE_OK;
  144376. }
  144377. /*
  144378. ** xRowid - Return the current rowid for the cursor.
  144379. */
  144380. static int fts3auxRowidMethod(
  144381. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  144382. sqlite_int64 *pRowid /* OUT: Rowid value */
  144383. ){
  144384. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  144385. *pRowid = pCsr->iRowid;
  144386. return SQLITE_OK;
  144387. }
  144388. /*
  144389. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  144390. ** if successful or an error code if sqlite3_create_module() fails.
  144391. */
  144392. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  144393. static const sqlite3_module fts3aux_module = {
  144394. 0, /* iVersion */
  144395. fts3auxConnectMethod, /* xCreate */
  144396. fts3auxConnectMethod, /* xConnect */
  144397. fts3auxBestIndexMethod, /* xBestIndex */
  144398. fts3auxDisconnectMethod, /* xDisconnect */
  144399. fts3auxDisconnectMethod, /* xDestroy */
  144400. fts3auxOpenMethod, /* xOpen */
  144401. fts3auxCloseMethod, /* xClose */
  144402. fts3auxFilterMethod, /* xFilter */
  144403. fts3auxNextMethod, /* xNext */
  144404. fts3auxEofMethod, /* xEof */
  144405. fts3auxColumnMethod, /* xColumn */
  144406. fts3auxRowidMethod, /* xRowid */
  144407. 0, /* xUpdate */
  144408. 0, /* xBegin */
  144409. 0, /* xSync */
  144410. 0, /* xCommit */
  144411. 0, /* xRollback */
  144412. 0, /* xFindFunction */
  144413. 0, /* xRename */
  144414. 0, /* xSavepoint */
  144415. 0, /* xRelease */
  144416. 0 /* xRollbackTo */
  144417. };
  144418. int rc; /* Return code */
  144419. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  144420. return rc;
  144421. }
  144422. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144423. /************** End of fts3_aux.c ********************************************/
  144424. /************** Begin file fts3_expr.c ***************************************/
  144425. /*
  144426. ** 2008 Nov 28
  144427. **
  144428. ** The author disclaims copyright to this source code. In place of
  144429. ** a legal notice, here is a blessing:
  144430. **
  144431. ** May you do good and not evil.
  144432. ** May you find forgiveness for yourself and forgive others.
  144433. ** May you share freely, never taking more than you give.
  144434. **
  144435. ******************************************************************************
  144436. **
  144437. ** This module contains code that implements a parser for fts3 query strings
  144438. ** (the right-hand argument to the MATCH operator). Because the supported
  144439. ** syntax is relatively simple, the whole tokenizer/parser system is
  144440. ** hand-coded.
  144441. */
  144442. /* #include "fts3Int.h" */
  144443. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144444. /*
  144445. ** By default, this module parses the legacy syntax that has been
  144446. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  144447. ** is defined, then it uses the new syntax. The differences between
  144448. ** the new and the old syntaxes are:
  144449. **
  144450. ** a) The new syntax supports parenthesis. The old does not.
  144451. **
  144452. ** b) The new syntax supports the AND and NOT operators. The old does not.
  144453. **
  144454. ** c) The old syntax supports the "-" token qualifier. This is not
  144455. ** supported by the new syntax (it is replaced by the NOT operator).
  144456. **
  144457. ** d) When using the old syntax, the OR operator has a greater precedence
  144458. ** than an implicit AND. When using the new, both implicity and explicit
  144459. ** AND operators have a higher precedence than OR.
  144460. **
  144461. ** If compiled with SQLITE_TEST defined, then this module exports the
  144462. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  144463. ** to zero causes the module to use the old syntax. If it is set to
  144464. ** non-zero the new syntax is activated. This is so both syntaxes can
  144465. ** be tested using a single build of testfixture.
  144466. **
  144467. ** The following describes the syntax supported by the fts3 MATCH
  144468. ** operator in a similar format to that used by the lemon parser
  144469. ** generator. This module does not use actually lemon, it uses a
  144470. ** custom parser.
  144471. **
  144472. ** query ::= andexpr (OR andexpr)*.
  144473. **
  144474. ** andexpr ::= notexpr (AND? notexpr)*.
  144475. **
  144476. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  144477. ** notexpr ::= LP query RP.
  144478. **
  144479. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  144480. **
  144481. ** distance_opt ::= .
  144482. ** distance_opt ::= / INTEGER.
  144483. **
  144484. ** phrase ::= TOKEN.
  144485. ** phrase ::= COLUMN:TOKEN.
  144486. ** phrase ::= "TOKEN TOKEN TOKEN...".
  144487. */
  144488. #ifdef SQLITE_TEST
  144489. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  144490. #else
  144491. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  144492. # define sqlite3_fts3_enable_parentheses 1
  144493. # else
  144494. # define sqlite3_fts3_enable_parentheses 0
  144495. # endif
  144496. #endif
  144497. /*
  144498. ** Default span for NEAR operators.
  144499. */
  144500. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  144501. /* #include <string.h> */
  144502. /* #include <assert.h> */
  144503. /*
  144504. ** isNot:
  144505. ** This variable is used by function getNextNode(). When getNextNode() is
  144506. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  144507. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  144508. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  144509. ** zero.
  144510. */
  144511. typedef struct ParseContext ParseContext;
  144512. struct ParseContext {
  144513. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  144514. int iLangid; /* Language id used with tokenizer */
  144515. const char **azCol; /* Array of column names for fts3 table */
  144516. int bFts4; /* True to allow FTS4-only syntax */
  144517. int nCol; /* Number of entries in azCol[] */
  144518. int iDefaultCol; /* Default column to query */
  144519. int isNot; /* True if getNextNode() sees a unary - */
  144520. sqlite3_context *pCtx; /* Write error message here */
  144521. int nNest; /* Number of nested brackets */
  144522. };
  144523. /*
  144524. ** This function is equivalent to the standard isspace() function.
  144525. **
  144526. ** The standard isspace() can be awkward to use safely, because although it
  144527. ** is defined to accept an argument of type int, its behavior when passed
  144528. ** an integer that falls outside of the range of the unsigned char type
  144529. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  144530. ** is defined to accept an argument of type char, and always returns 0 for
  144531. ** any values that fall outside of the range of the unsigned char type (i.e.
  144532. ** negative values).
  144533. */
  144534. static int fts3isspace(char c){
  144535. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  144536. }
  144537. /*
  144538. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  144539. ** zero the memory before returning a pointer to it. If unsuccessful,
  144540. ** return NULL.
  144541. */
  144542. static void *fts3MallocZero(int nByte){
  144543. void *pRet = sqlite3_malloc(nByte);
  144544. if( pRet ) memset(pRet, 0, nByte);
  144545. return pRet;
  144546. }
  144547. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  144548. sqlite3_tokenizer *pTokenizer,
  144549. int iLangid,
  144550. const char *z,
  144551. int n,
  144552. sqlite3_tokenizer_cursor **ppCsr
  144553. ){
  144554. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  144555. sqlite3_tokenizer_cursor *pCsr = 0;
  144556. int rc;
  144557. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  144558. assert( rc==SQLITE_OK || pCsr==0 );
  144559. if( rc==SQLITE_OK ){
  144560. pCsr->pTokenizer = pTokenizer;
  144561. if( pModule->iVersion>=1 ){
  144562. rc = pModule->xLanguageid(pCsr, iLangid);
  144563. if( rc!=SQLITE_OK ){
  144564. pModule->xClose(pCsr);
  144565. pCsr = 0;
  144566. }
  144567. }
  144568. }
  144569. *ppCsr = pCsr;
  144570. return rc;
  144571. }
  144572. /*
  144573. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  144574. ** call fts3ExprParse(). So this forward declaration is required.
  144575. */
  144576. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  144577. /*
  144578. ** Extract the next token from buffer z (length n) using the tokenizer
  144579. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  144580. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  144581. ** single token and set *ppExpr to point to it. If the end of the buffer is
  144582. ** reached before a token is found, set *ppExpr to zero. It is the
  144583. ** responsibility of the caller to eventually deallocate the allocated
  144584. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  144585. **
  144586. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  144587. ** fails.
  144588. */
  144589. static int getNextToken(
  144590. ParseContext *pParse, /* fts3 query parse context */
  144591. int iCol, /* Value for Fts3Phrase.iColumn */
  144592. const char *z, int n, /* Input string */
  144593. Fts3Expr **ppExpr, /* OUT: expression */
  144594. int *pnConsumed /* OUT: Number of bytes consumed */
  144595. ){
  144596. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  144597. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  144598. int rc;
  144599. sqlite3_tokenizer_cursor *pCursor;
  144600. Fts3Expr *pRet = 0;
  144601. int i = 0;
  144602. /* Set variable i to the maximum number of bytes of input to tokenize. */
  144603. for(i=0; i<n; i++){
  144604. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  144605. if( z[i]=='"' ) break;
  144606. }
  144607. *pnConsumed = i;
  144608. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  144609. if( rc==SQLITE_OK ){
  144610. const char *zToken;
  144611. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  144612. int nByte; /* total space to allocate */
  144613. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  144614. if( rc==SQLITE_OK ){
  144615. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  144616. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  144617. if( !pRet ){
  144618. rc = SQLITE_NOMEM;
  144619. }else{
  144620. pRet->eType = FTSQUERY_PHRASE;
  144621. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  144622. pRet->pPhrase->nToken = 1;
  144623. pRet->pPhrase->iColumn = iCol;
  144624. pRet->pPhrase->aToken[0].n = nToken;
  144625. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  144626. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  144627. if( iEnd<n && z[iEnd]=='*' ){
  144628. pRet->pPhrase->aToken[0].isPrefix = 1;
  144629. iEnd++;
  144630. }
  144631. while( 1 ){
  144632. if( !sqlite3_fts3_enable_parentheses
  144633. && iStart>0 && z[iStart-1]=='-'
  144634. ){
  144635. pParse->isNot = 1;
  144636. iStart--;
  144637. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  144638. pRet->pPhrase->aToken[0].bFirst = 1;
  144639. iStart--;
  144640. }else{
  144641. break;
  144642. }
  144643. }
  144644. }
  144645. *pnConsumed = iEnd;
  144646. }else if( i && rc==SQLITE_DONE ){
  144647. rc = SQLITE_OK;
  144648. }
  144649. pModule->xClose(pCursor);
  144650. }
  144651. *ppExpr = pRet;
  144652. return rc;
  144653. }
  144654. /*
  144655. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  144656. ** then free the old allocation.
  144657. */
  144658. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  144659. void *pRet = sqlite3_realloc(pOrig, nNew);
  144660. if( !pRet ){
  144661. sqlite3_free(pOrig);
  144662. }
  144663. return pRet;
  144664. }
  144665. /*
  144666. ** Buffer zInput, length nInput, contains the contents of a quoted string
  144667. ** that appeared as part of an fts3 query expression. Neither quote character
  144668. ** is included in the buffer. This function attempts to tokenize the entire
  144669. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  144670. ** containing the results.
  144671. **
  144672. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  144673. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  144674. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  144675. ** to 0.
  144676. */
  144677. static int getNextString(
  144678. ParseContext *pParse, /* fts3 query parse context */
  144679. const char *zInput, int nInput, /* Input string */
  144680. Fts3Expr **ppExpr /* OUT: expression */
  144681. ){
  144682. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  144683. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  144684. int rc;
  144685. Fts3Expr *p = 0;
  144686. sqlite3_tokenizer_cursor *pCursor = 0;
  144687. char *zTemp = 0;
  144688. int nTemp = 0;
  144689. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  144690. int nToken = 0;
  144691. /* The final Fts3Expr data structure, including the Fts3Phrase,
  144692. ** Fts3PhraseToken structures token buffers are all stored as a single
  144693. ** allocation so that the expression can be freed with a single call to
  144694. ** sqlite3_free(). Setting this up requires a two pass approach.
  144695. **
  144696. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  144697. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  144698. ** to assemble data in two dynamic buffers:
  144699. **
  144700. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  144701. ** structure, followed by the array of Fts3PhraseToken
  144702. ** structures. This pass only populates the Fts3PhraseToken array.
  144703. **
  144704. ** Buffer zTemp: Contains copies of all tokens.
  144705. **
  144706. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  144707. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  144708. ** structures.
  144709. */
  144710. rc = sqlite3Fts3OpenTokenizer(
  144711. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  144712. if( rc==SQLITE_OK ){
  144713. int ii;
  144714. for(ii=0; rc==SQLITE_OK; ii++){
  144715. const char *zByte;
  144716. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  144717. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  144718. if( rc==SQLITE_OK ){
  144719. Fts3PhraseToken *pToken;
  144720. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  144721. if( !p ) goto no_mem;
  144722. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  144723. if( !zTemp ) goto no_mem;
  144724. assert( nToken==ii );
  144725. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  144726. memset(pToken, 0, sizeof(Fts3PhraseToken));
  144727. memcpy(&zTemp[nTemp], zByte, nByte);
  144728. nTemp += nByte;
  144729. pToken->n = nByte;
  144730. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  144731. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  144732. nToken = ii+1;
  144733. }
  144734. }
  144735. pModule->xClose(pCursor);
  144736. pCursor = 0;
  144737. }
  144738. if( rc==SQLITE_DONE ){
  144739. int jj;
  144740. char *zBuf = 0;
  144741. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  144742. if( !p ) goto no_mem;
  144743. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  144744. p->eType = FTSQUERY_PHRASE;
  144745. p->pPhrase = (Fts3Phrase *)&p[1];
  144746. p->pPhrase->iColumn = pParse->iDefaultCol;
  144747. p->pPhrase->nToken = nToken;
  144748. zBuf = (char *)&p->pPhrase->aToken[nToken];
  144749. if( zTemp ){
  144750. memcpy(zBuf, zTemp, nTemp);
  144751. sqlite3_free(zTemp);
  144752. }else{
  144753. assert( nTemp==0 );
  144754. }
  144755. for(jj=0; jj<p->pPhrase->nToken; jj++){
  144756. p->pPhrase->aToken[jj].z = zBuf;
  144757. zBuf += p->pPhrase->aToken[jj].n;
  144758. }
  144759. rc = SQLITE_OK;
  144760. }
  144761. *ppExpr = p;
  144762. return rc;
  144763. no_mem:
  144764. if( pCursor ){
  144765. pModule->xClose(pCursor);
  144766. }
  144767. sqlite3_free(zTemp);
  144768. sqlite3_free(p);
  144769. *ppExpr = 0;
  144770. return SQLITE_NOMEM;
  144771. }
  144772. /*
  144773. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  144774. ** structure, or set to 0 if the end of the input buffer is reached.
  144775. **
  144776. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  144777. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  144778. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  144779. */
  144780. static int getNextNode(
  144781. ParseContext *pParse, /* fts3 query parse context */
  144782. const char *z, int n, /* Input string */
  144783. Fts3Expr **ppExpr, /* OUT: expression */
  144784. int *pnConsumed /* OUT: Number of bytes consumed */
  144785. ){
  144786. static const struct Fts3Keyword {
  144787. char *z; /* Keyword text */
  144788. unsigned char n; /* Length of the keyword */
  144789. unsigned char parenOnly; /* Only valid in paren mode */
  144790. unsigned char eType; /* Keyword code */
  144791. } aKeyword[] = {
  144792. { "OR" , 2, 0, FTSQUERY_OR },
  144793. { "AND", 3, 1, FTSQUERY_AND },
  144794. { "NOT", 3, 1, FTSQUERY_NOT },
  144795. { "NEAR", 4, 0, FTSQUERY_NEAR }
  144796. };
  144797. int ii;
  144798. int iCol;
  144799. int iColLen;
  144800. int rc;
  144801. Fts3Expr *pRet = 0;
  144802. const char *zInput = z;
  144803. int nInput = n;
  144804. pParse->isNot = 0;
  144805. /* Skip over any whitespace before checking for a keyword, an open or
  144806. ** close bracket, or a quoted string.
  144807. */
  144808. while( nInput>0 && fts3isspace(*zInput) ){
  144809. nInput--;
  144810. zInput++;
  144811. }
  144812. if( nInput==0 ){
  144813. return SQLITE_DONE;
  144814. }
  144815. /* See if we are dealing with a keyword. */
  144816. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  144817. const struct Fts3Keyword *pKey = &aKeyword[ii];
  144818. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  144819. continue;
  144820. }
  144821. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  144822. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  144823. int nKey = pKey->n;
  144824. char cNext;
  144825. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  144826. if( pKey->eType==FTSQUERY_NEAR ){
  144827. assert( nKey==4 );
  144828. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  144829. nNear = 0;
  144830. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  144831. nNear = nNear * 10 + (zInput[nKey] - '0');
  144832. }
  144833. }
  144834. }
  144835. /* At this point this is probably a keyword. But for that to be true,
  144836. ** the next byte must contain either whitespace, an open or close
  144837. ** parenthesis, a quote character, or EOF.
  144838. */
  144839. cNext = zInput[nKey];
  144840. if( fts3isspace(cNext)
  144841. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  144842. ){
  144843. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  144844. if( !pRet ){
  144845. return SQLITE_NOMEM;
  144846. }
  144847. pRet->eType = pKey->eType;
  144848. pRet->nNear = nNear;
  144849. *ppExpr = pRet;
  144850. *pnConsumed = (int)((zInput - z) + nKey);
  144851. return SQLITE_OK;
  144852. }
  144853. /* Turns out that wasn't a keyword after all. This happens if the
  144854. ** user has supplied a token such as "ORacle". Continue.
  144855. */
  144856. }
  144857. }
  144858. /* See if we are dealing with a quoted phrase. If this is the case, then
  144859. ** search for the closing quote and pass the whole string to getNextString()
  144860. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  144861. ** a quote character embedded in a string.
  144862. */
  144863. if( *zInput=='"' ){
  144864. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  144865. *pnConsumed = (int)((zInput - z) + ii + 1);
  144866. if( ii==nInput ){
  144867. return SQLITE_ERROR;
  144868. }
  144869. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  144870. }
  144871. if( sqlite3_fts3_enable_parentheses ){
  144872. if( *zInput=='(' ){
  144873. int nConsumed = 0;
  144874. pParse->nNest++;
  144875. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  144876. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  144877. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  144878. return rc;
  144879. }else if( *zInput==')' ){
  144880. pParse->nNest--;
  144881. *pnConsumed = (int)((zInput - z) + 1);
  144882. *ppExpr = 0;
  144883. return SQLITE_DONE;
  144884. }
  144885. }
  144886. /* If control flows to this point, this must be a regular token, or
  144887. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  144888. ** interface. Before doing so, figure out if there is an explicit
  144889. ** column specifier for the token.
  144890. **
  144891. ** TODO: Strangely, it is not possible to associate a column specifier
  144892. ** with a quoted phrase, only with a single token. Not sure if this was
  144893. ** an implementation artifact or an intentional decision when fts3 was
  144894. ** first implemented. Whichever it was, this module duplicates the
  144895. ** limitation.
  144896. */
  144897. iCol = pParse->iDefaultCol;
  144898. iColLen = 0;
  144899. for(ii=0; ii<pParse->nCol; ii++){
  144900. const char *zStr = pParse->azCol[ii];
  144901. int nStr = (int)strlen(zStr);
  144902. if( nInput>nStr && zInput[nStr]==':'
  144903. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  144904. ){
  144905. iCol = ii;
  144906. iColLen = (int)((zInput - z) + nStr + 1);
  144907. break;
  144908. }
  144909. }
  144910. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  144911. *pnConsumed += iColLen;
  144912. return rc;
  144913. }
  144914. /*
  144915. ** The argument is an Fts3Expr structure for a binary operator (any type
  144916. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  144917. ** precedence of the operator. Lower values have a higher precedence (i.e.
  144918. ** group more tightly). For example, in the C language, the == operator
  144919. ** groups more tightly than ||, and would therefore have a higher precedence.
  144920. **
  144921. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  144922. ** is defined), the order of the operators in precedence from highest to
  144923. ** lowest is:
  144924. **
  144925. ** NEAR
  144926. ** NOT
  144927. ** AND (including implicit ANDs)
  144928. ** OR
  144929. **
  144930. ** Note that when using the old query syntax, the OR operator has a higher
  144931. ** precedence than the AND operator.
  144932. */
  144933. static int opPrecedence(Fts3Expr *p){
  144934. assert( p->eType!=FTSQUERY_PHRASE );
  144935. if( sqlite3_fts3_enable_parentheses ){
  144936. return p->eType;
  144937. }else if( p->eType==FTSQUERY_NEAR ){
  144938. return 1;
  144939. }else if( p->eType==FTSQUERY_OR ){
  144940. return 2;
  144941. }
  144942. assert( p->eType==FTSQUERY_AND );
  144943. return 3;
  144944. }
  144945. /*
  144946. ** Argument ppHead contains a pointer to the current head of a query
  144947. ** expression tree being parsed. pPrev is the expression node most recently
  144948. ** inserted into the tree. This function adds pNew, which is always a binary
  144949. ** operator node, into the expression tree based on the relative precedence
  144950. ** of pNew and the existing nodes of the tree. This may result in the head
  144951. ** of the tree changing, in which case *ppHead is set to the new root node.
  144952. */
  144953. static void insertBinaryOperator(
  144954. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  144955. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  144956. Fts3Expr *pNew /* New binary node to insert into expression tree */
  144957. ){
  144958. Fts3Expr *pSplit = pPrev;
  144959. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  144960. pSplit = pSplit->pParent;
  144961. }
  144962. if( pSplit->pParent ){
  144963. assert( pSplit->pParent->pRight==pSplit );
  144964. pSplit->pParent->pRight = pNew;
  144965. pNew->pParent = pSplit->pParent;
  144966. }else{
  144967. *ppHead = pNew;
  144968. }
  144969. pNew->pLeft = pSplit;
  144970. pSplit->pParent = pNew;
  144971. }
  144972. /*
  144973. ** Parse the fts3 query expression found in buffer z, length n. This function
  144974. ** returns either when the end of the buffer is reached or an unmatched
  144975. ** closing bracket - ')' - is encountered.
  144976. **
  144977. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  144978. ** parsed form of the expression and *pnConsumed is set to the number of
  144979. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  144980. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  144981. */
  144982. static int fts3ExprParse(
  144983. ParseContext *pParse, /* fts3 query parse context */
  144984. const char *z, int n, /* Text of MATCH query */
  144985. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  144986. int *pnConsumed /* OUT: Number of bytes consumed */
  144987. ){
  144988. Fts3Expr *pRet = 0;
  144989. Fts3Expr *pPrev = 0;
  144990. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  144991. int nIn = n;
  144992. const char *zIn = z;
  144993. int rc = SQLITE_OK;
  144994. int isRequirePhrase = 1;
  144995. while( rc==SQLITE_OK ){
  144996. Fts3Expr *p = 0;
  144997. int nByte = 0;
  144998. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  144999. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  145000. if( rc==SQLITE_OK ){
  145001. if( p ){
  145002. int isPhrase;
  145003. if( !sqlite3_fts3_enable_parentheses
  145004. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  145005. ){
  145006. /* Create an implicit NOT operator. */
  145007. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  145008. if( !pNot ){
  145009. sqlite3Fts3ExprFree(p);
  145010. rc = SQLITE_NOMEM;
  145011. goto exprparse_out;
  145012. }
  145013. pNot->eType = FTSQUERY_NOT;
  145014. pNot->pRight = p;
  145015. p->pParent = pNot;
  145016. if( pNotBranch ){
  145017. pNot->pLeft = pNotBranch;
  145018. pNotBranch->pParent = pNot;
  145019. }
  145020. pNotBranch = pNot;
  145021. p = pPrev;
  145022. }else{
  145023. int eType = p->eType;
  145024. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  145025. /* The isRequirePhrase variable is set to true if a phrase or
  145026. ** an expression contained in parenthesis is required. If a
  145027. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  145028. ** isRequirePhrase is set, this is a syntax error.
  145029. */
  145030. if( !isPhrase && isRequirePhrase ){
  145031. sqlite3Fts3ExprFree(p);
  145032. rc = SQLITE_ERROR;
  145033. goto exprparse_out;
  145034. }
  145035. if( isPhrase && !isRequirePhrase ){
  145036. /* Insert an implicit AND operator. */
  145037. Fts3Expr *pAnd;
  145038. assert( pRet && pPrev );
  145039. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  145040. if( !pAnd ){
  145041. sqlite3Fts3ExprFree(p);
  145042. rc = SQLITE_NOMEM;
  145043. goto exprparse_out;
  145044. }
  145045. pAnd->eType = FTSQUERY_AND;
  145046. insertBinaryOperator(&pRet, pPrev, pAnd);
  145047. pPrev = pAnd;
  145048. }
  145049. /* This test catches attempts to make either operand of a NEAR
  145050. ** operator something other than a phrase. For example, either of
  145051. ** the following:
  145052. **
  145053. ** (bracketed expression) NEAR phrase
  145054. ** phrase NEAR (bracketed expression)
  145055. **
  145056. ** Return an error in either case.
  145057. */
  145058. if( pPrev && (
  145059. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  145060. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  145061. )){
  145062. sqlite3Fts3ExprFree(p);
  145063. rc = SQLITE_ERROR;
  145064. goto exprparse_out;
  145065. }
  145066. if( isPhrase ){
  145067. if( pRet ){
  145068. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  145069. pPrev->pRight = p;
  145070. p->pParent = pPrev;
  145071. }else{
  145072. pRet = p;
  145073. }
  145074. }else{
  145075. insertBinaryOperator(&pRet, pPrev, p);
  145076. }
  145077. isRequirePhrase = !isPhrase;
  145078. }
  145079. pPrev = p;
  145080. }
  145081. assert( nByte>0 );
  145082. }
  145083. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  145084. nIn -= nByte;
  145085. zIn += nByte;
  145086. }
  145087. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  145088. rc = SQLITE_ERROR;
  145089. }
  145090. if( rc==SQLITE_DONE ){
  145091. rc = SQLITE_OK;
  145092. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  145093. if( !pRet ){
  145094. rc = SQLITE_ERROR;
  145095. }else{
  145096. Fts3Expr *pIter = pNotBranch;
  145097. while( pIter->pLeft ){
  145098. pIter = pIter->pLeft;
  145099. }
  145100. pIter->pLeft = pRet;
  145101. pRet->pParent = pIter;
  145102. pRet = pNotBranch;
  145103. }
  145104. }
  145105. }
  145106. *pnConsumed = n - nIn;
  145107. exprparse_out:
  145108. if( rc!=SQLITE_OK ){
  145109. sqlite3Fts3ExprFree(pRet);
  145110. sqlite3Fts3ExprFree(pNotBranch);
  145111. pRet = 0;
  145112. }
  145113. *ppExpr = pRet;
  145114. return rc;
  145115. }
  145116. /*
  145117. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  145118. ** as the only argument is more than nMaxDepth.
  145119. */
  145120. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  145121. int rc = SQLITE_OK;
  145122. if( p ){
  145123. if( nMaxDepth<0 ){
  145124. rc = SQLITE_TOOBIG;
  145125. }else{
  145126. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  145127. if( rc==SQLITE_OK ){
  145128. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  145129. }
  145130. }
  145131. }
  145132. return rc;
  145133. }
  145134. /*
  145135. ** This function attempts to transform the expression tree at (*pp) to
  145136. ** an equivalent but more balanced form. The tree is modified in place.
  145137. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  145138. ** new root expression node.
  145139. **
  145140. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  145141. **
  145142. ** Otherwise, if an error occurs, an SQLite error code is returned and
  145143. ** expression (*pp) freed.
  145144. */
  145145. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  145146. int rc = SQLITE_OK; /* Return code */
  145147. Fts3Expr *pRoot = *pp; /* Initial root node */
  145148. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  145149. int eType = pRoot->eType; /* Type of node in this tree */
  145150. if( nMaxDepth==0 ){
  145151. rc = SQLITE_ERROR;
  145152. }
  145153. if( rc==SQLITE_OK ){
  145154. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  145155. Fts3Expr **apLeaf;
  145156. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  145157. if( 0==apLeaf ){
  145158. rc = SQLITE_NOMEM;
  145159. }else{
  145160. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  145161. }
  145162. if( rc==SQLITE_OK ){
  145163. int i;
  145164. Fts3Expr *p;
  145165. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  145166. for(p=pRoot; p->eType==eType; p=p->pLeft){
  145167. assert( p->pParent==0 || p->pParent->pLeft==p );
  145168. assert( p->pLeft && p->pRight );
  145169. }
  145170. /* This loop runs once for each leaf in the tree of eType nodes. */
  145171. while( 1 ){
  145172. int iLvl;
  145173. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  145174. assert( pParent==0 || pParent->pLeft==p );
  145175. p->pParent = 0;
  145176. if( pParent ){
  145177. pParent->pLeft = 0;
  145178. }else{
  145179. pRoot = 0;
  145180. }
  145181. rc = fts3ExprBalance(&p, nMaxDepth-1);
  145182. if( rc!=SQLITE_OK ) break;
  145183. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  145184. if( apLeaf[iLvl]==0 ){
  145185. apLeaf[iLvl] = p;
  145186. p = 0;
  145187. }else{
  145188. assert( pFree );
  145189. pFree->pLeft = apLeaf[iLvl];
  145190. pFree->pRight = p;
  145191. pFree->pLeft->pParent = pFree;
  145192. pFree->pRight->pParent = pFree;
  145193. p = pFree;
  145194. pFree = pFree->pParent;
  145195. p->pParent = 0;
  145196. apLeaf[iLvl] = 0;
  145197. }
  145198. }
  145199. if( p ){
  145200. sqlite3Fts3ExprFree(p);
  145201. rc = SQLITE_TOOBIG;
  145202. break;
  145203. }
  145204. /* If that was the last leaf node, break out of the loop */
  145205. if( pParent==0 ) break;
  145206. /* Set $p to point to the next leaf in the tree of eType nodes */
  145207. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  145208. /* Remove pParent from the original tree. */
  145209. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  145210. pParent->pRight->pParent = pParent->pParent;
  145211. if( pParent->pParent ){
  145212. pParent->pParent->pLeft = pParent->pRight;
  145213. }else{
  145214. assert( pParent==pRoot );
  145215. pRoot = pParent->pRight;
  145216. }
  145217. /* Link pParent into the free node list. It will be used as an
  145218. ** internal node of the new tree. */
  145219. pParent->pParent = pFree;
  145220. pFree = pParent;
  145221. }
  145222. if( rc==SQLITE_OK ){
  145223. p = 0;
  145224. for(i=0; i<nMaxDepth; i++){
  145225. if( apLeaf[i] ){
  145226. if( p==0 ){
  145227. p = apLeaf[i];
  145228. p->pParent = 0;
  145229. }else{
  145230. assert( pFree!=0 );
  145231. pFree->pRight = p;
  145232. pFree->pLeft = apLeaf[i];
  145233. pFree->pLeft->pParent = pFree;
  145234. pFree->pRight->pParent = pFree;
  145235. p = pFree;
  145236. pFree = pFree->pParent;
  145237. p->pParent = 0;
  145238. }
  145239. }
  145240. }
  145241. pRoot = p;
  145242. }else{
  145243. /* An error occurred. Delete the contents of the apLeaf[] array
  145244. ** and pFree list. Everything else is cleaned up by the call to
  145245. ** sqlite3Fts3ExprFree(pRoot) below. */
  145246. Fts3Expr *pDel;
  145247. for(i=0; i<nMaxDepth; i++){
  145248. sqlite3Fts3ExprFree(apLeaf[i]);
  145249. }
  145250. while( (pDel=pFree)!=0 ){
  145251. pFree = pDel->pParent;
  145252. sqlite3_free(pDel);
  145253. }
  145254. }
  145255. assert( pFree==0 );
  145256. sqlite3_free( apLeaf );
  145257. }
  145258. }else if( eType==FTSQUERY_NOT ){
  145259. Fts3Expr *pLeft = pRoot->pLeft;
  145260. Fts3Expr *pRight = pRoot->pRight;
  145261. pRoot->pLeft = 0;
  145262. pRoot->pRight = 0;
  145263. pLeft->pParent = 0;
  145264. pRight->pParent = 0;
  145265. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  145266. if( rc==SQLITE_OK ){
  145267. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  145268. }
  145269. if( rc!=SQLITE_OK ){
  145270. sqlite3Fts3ExprFree(pRight);
  145271. sqlite3Fts3ExprFree(pLeft);
  145272. }else{
  145273. assert( pLeft && pRight );
  145274. pRoot->pLeft = pLeft;
  145275. pLeft->pParent = pRoot;
  145276. pRoot->pRight = pRight;
  145277. pRight->pParent = pRoot;
  145278. }
  145279. }
  145280. }
  145281. if( rc!=SQLITE_OK ){
  145282. sqlite3Fts3ExprFree(pRoot);
  145283. pRoot = 0;
  145284. }
  145285. *pp = pRoot;
  145286. return rc;
  145287. }
  145288. /*
  145289. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  145290. ** differences:
  145291. **
  145292. ** 1. It does not do expression rebalancing.
  145293. ** 2. It does not check that the expression does not exceed the
  145294. ** maximum allowable depth.
  145295. ** 3. Even if it fails, *ppExpr may still be set to point to an
  145296. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  145297. ** in this case.
  145298. */
  145299. static int fts3ExprParseUnbalanced(
  145300. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  145301. int iLangid, /* Language id for tokenizer */
  145302. char **azCol, /* Array of column names for fts3 table */
  145303. int bFts4, /* True to allow FTS4-only syntax */
  145304. int nCol, /* Number of entries in azCol[] */
  145305. int iDefaultCol, /* Default column to query */
  145306. const char *z, int n, /* Text of MATCH query */
  145307. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  145308. ){
  145309. int nParsed;
  145310. int rc;
  145311. ParseContext sParse;
  145312. memset(&sParse, 0, sizeof(ParseContext));
  145313. sParse.pTokenizer = pTokenizer;
  145314. sParse.iLangid = iLangid;
  145315. sParse.azCol = (const char **)azCol;
  145316. sParse.nCol = nCol;
  145317. sParse.iDefaultCol = iDefaultCol;
  145318. sParse.bFts4 = bFts4;
  145319. if( z==0 ){
  145320. *ppExpr = 0;
  145321. return SQLITE_OK;
  145322. }
  145323. if( n<0 ){
  145324. n = (int)strlen(z);
  145325. }
  145326. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  145327. assert( rc==SQLITE_OK || *ppExpr==0 );
  145328. /* Check for mismatched parenthesis */
  145329. if( rc==SQLITE_OK && sParse.nNest ){
  145330. rc = SQLITE_ERROR;
  145331. }
  145332. return rc;
  145333. }
  145334. /*
  145335. ** Parameters z and n contain a pointer to and length of a buffer containing
  145336. ** an fts3 query expression, respectively. This function attempts to parse the
  145337. ** query expression and create a tree of Fts3Expr structures representing the
  145338. ** parsed expression. If successful, *ppExpr is set to point to the head
  145339. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  145340. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  145341. ** error) is returned and *ppExpr is set to 0.
  145342. **
  145343. ** If parameter n is a negative number, then z is assumed to point to a
  145344. ** nul-terminated string and the length is determined using strlen().
  145345. **
  145346. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  145347. ** use to normalize query tokens while parsing the expression. The azCol[]
  145348. ** array, which is assumed to contain nCol entries, should contain the names
  145349. ** of each column in the target fts3 table, in order from left to right.
  145350. ** Column names must be nul-terminated strings.
  145351. **
  145352. ** The iDefaultCol parameter should be passed the index of the table column
  145353. ** that appears on the left-hand-side of the MATCH operator (the default
  145354. ** column to match against for tokens for which a column name is not explicitly
  145355. ** specified as part of the query string), or -1 if tokens may by default
  145356. ** match any table column.
  145357. */
  145358. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  145359. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  145360. int iLangid, /* Language id for tokenizer */
  145361. char **azCol, /* Array of column names for fts3 table */
  145362. int bFts4, /* True to allow FTS4-only syntax */
  145363. int nCol, /* Number of entries in azCol[] */
  145364. int iDefaultCol, /* Default column to query */
  145365. const char *z, int n, /* Text of MATCH query */
  145366. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  145367. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  145368. ){
  145369. int rc = fts3ExprParseUnbalanced(
  145370. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  145371. );
  145372. /* Rebalance the expression. And check that its depth does not exceed
  145373. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  145374. if( rc==SQLITE_OK && *ppExpr ){
  145375. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  145376. if( rc==SQLITE_OK ){
  145377. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  145378. }
  145379. }
  145380. if( rc!=SQLITE_OK ){
  145381. sqlite3Fts3ExprFree(*ppExpr);
  145382. *ppExpr = 0;
  145383. if( rc==SQLITE_TOOBIG ){
  145384. sqlite3Fts3ErrMsg(pzErr,
  145385. "FTS expression tree is too large (maximum depth %d)",
  145386. SQLITE_FTS3_MAX_EXPR_DEPTH
  145387. );
  145388. rc = SQLITE_ERROR;
  145389. }else if( rc==SQLITE_ERROR ){
  145390. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  145391. }
  145392. }
  145393. return rc;
  145394. }
  145395. /*
  145396. ** Free a single node of an expression tree.
  145397. */
  145398. static void fts3FreeExprNode(Fts3Expr *p){
  145399. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  145400. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  145401. sqlite3_free(p->aMI);
  145402. sqlite3_free(p);
  145403. }
  145404. /*
  145405. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  145406. **
  145407. ** This function would be simpler if it recursively called itself. But
  145408. ** that would mean passing a sufficiently large expression to ExprParse()
  145409. ** could cause a stack overflow.
  145410. */
  145411. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  145412. Fts3Expr *p;
  145413. assert( pDel==0 || pDel->pParent==0 );
  145414. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  145415. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  145416. }
  145417. while( p ){
  145418. Fts3Expr *pParent = p->pParent;
  145419. fts3FreeExprNode(p);
  145420. if( pParent && p==pParent->pLeft && pParent->pRight ){
  145421. p = pParent->pRight;
  145422. while( p && (p->pLeft || p->pRight) ){
  145423. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  145424. p = (p->pLeft ? p->pLeft : p->pRight);
  145425. }
  145426. }else{
  145427. p = pParent;
  145428. }
  145429. }
  145430. }
  145431. /****************************************************************************
  145432. *****************************************************************************
  145433. ** Everything after this point is just test code.
  145434. */
  145435. #ifdef SQLITE_TEST
  145436. /* #include <stdio.h> */
  145437. /*
  145438. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  145439. */
  145440. static int queryTestTokenizer(
  145441. sqlite3 *db,
  145442. const char *zName,
  145443. const sqlite3_tokenizer_module **pp
  145444. ){
  145445. int rc;
  145446. sqlite3_stmt *pStmt;
  145447. const char zSql[] = "SELECT fts3_tokenizer(?)";
  145448. *pp = 0;
  145449. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145450. if( rc!=SQLITE_OK ){
  145451. return rc;
  145452. }
  145453. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  145454. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  145455. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  145456. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  145457. }
  145458. }
  145459. return sqlite3_finalize(pStmt);
  145460. }
  145461. /*
  145462. ** Return a pointer to a buffer containing a text representation of the
  145463. ** expression passed as the first argument. The buffer is obtained from
  145464. ** sqlite3_malloc(). It is the responsibility of the caller to use
  145465. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  145466. ** NULL is returned.
  145467. **
  145468. ** If the second argument is not NULL, then its contents are prepended to
  145469. ** the returned expression text and then freed using sqlite3_free().
  145470. */
  145471. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  145472. if( pExpr==0 ){
  145473. return sqlite3_mprintf("");
  145474. }
  145475. switch( pExpr->eType ){
  145476. case FTSQUERY_PHRASE: {
  145477. Fts3Phrase *pPhrase = pExpr->pPhrase;
  145478. int i;
  145479. zBuf = sqlite3_mprintf(
  145480. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  145481. for(i=0; zBuf && i<pPhrase->nToken; i++){
  145482. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  145483. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  145484. (pPhrase->aToken[i].isPrefix?"+":"")
  145485. );
  145486. }
  145487. return zBuf;
  145488. }
  145489. case FTSQUERY_NEAR:
  145490. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  145491. break;
  145492. case FTSQUERY_NOT:
  145493. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  145494. break;
  145495. case FTSQUERY_AND:
  145496. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  145497. break;
  145498. case FTSQUERY_OR:
  145499. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  145500. break;
  145501. }
  145502. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  145503. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  145504. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  145505. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  145506. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  145507. return zBuf;
  145508. }
  145509. /*
  145510. ** This is the implementation of a scalar SQL function used to test the
  145511. ** expression parser. It should be called as follows:
  145512. **
  145513. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  145514. **
  145515. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  145516. ** to parse the query expression (see README.tokenizers). The second argument
  145517. ** is the query expression to parse. Each subsequent argument is the name
  145518. ** of a column of the fts3 table that the query expression may refer to.
  145519. ** For example:
  145520. **
  145521. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  145522. */
  145523. static void fts3ExprTest(
  145524. sqlite3_context *context,
  145525. int argc,
  145526. sqlite3_value **argv
  145527. ){
  145528. sqlite3_tokenizer_module const *pModule = 0;
  145529. sqlite3_tokenizer *pTokenizer = 0;
  145530. int rc;
  145531. char **azCol = 0;
  145532. const char *zExpr;
  145533. int nExpr;
  145534. int nCol;
  145535. int ii;
  145536. Fts3Expr *pExpr;
  145537. char *zBuf = 0;
  145538. sqlite3 *db = sqlite3_context_db_handle(context);
  145539. if( argc<3 ){
  145540. sqlite3_result_error(context,
  145541. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  145542. );
  145543. return;
  145544. }
  145545. rc = queryTestTokenizer(db,
  145546. (const char *)sqlite3_value_text(argv[0]), &pModule);
  145547. if( rc==SQLITE_NOMEM ){
  145548. sqlite3_result_error_nomem(context);
  145549. goto exprtest_out;
  145550. }else if( !pModule ){
  145551. sqlite3_result_error(context, "No such tokenizer module", -1);
  145552. goto exprtest_out;
  145553. }
  145554. rc = pModule->xCreate(0, 0, &pTokenizer);
  145555. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  145556. if( rc==SQLITE_NOMEM ){
  145557. sqlite3_result_error_nomem(context);
  145558. goto exprtest_out;
  145559. }
  145560. pTokenizer->pModule = pModule;
  145561. zExpr = (const char *)sqlite3_value_text(argv[1]);
  145562. nExpr = sqlite3_value_bytes(argv[1]);
  145563. nCol = argc-2;
  145564. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  145565. if( !azCol ){
  145566. sqlite3_result_error_nomem(context);
  145567. goto exprtest_out;
  145568. }
  145569. for(ii=0; ii<nCol; ii++){
  145570. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  145571. }
  145572. if( sqlite3_user_data(context) ){
  145573. char *zDummy = 0;
  145574. rc = sqlite3Fts3ExprParse(
  145575. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  145576. );
  145577. assert( rc==SQLITE_OK || pExpr==0 );
  145578. sqlite3_free(zDummy);
  145579. }else{
  145580. rc = fts3ExprParseUnbalanced(
  145581. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  145582. );
  145583. }
  145584. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  145585. sqlite3Fts3ExprFree(pExpr);
  145586. sqlite3_result_error(context, "Error parsing expression", -1);
  145587. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  145588. sqlite3_result_error_nomem(context);
  145589. }else{
  145590. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  145591. sqlite3_free(zBuf);
  145592. }
  145593. sqlite3Fts3ExprFree(pExpr);
  145594. exprtest_out:
  145595. if( pModule && pTokenizer ){
  145596. rc = pModule->xDestroy(pTokenizer);
  145597. }
  145598. sqlite3_free(azCol);
  145599. }
  145600. /*
  145601. ** Register the query expression parser test function fts3_exprtest()
  145602. ** with database connection db.
  145603. */
  145604. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  145605. int rc = sqlite3_create_function(
  145606. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  145607. );
  145608. if( rc==SQLITE_OK ){
  145609. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  145610. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  145611. );
  145612. }
  145613. return rc;
  145614. }
  145615. #endif
  145616. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145617. /************** End of fts3_expr.c *******************************************/
  145618. /************** Begin file fts3_hash.c ***************************************/
  145619. /*
  145620. ** 2001 September 22
  145621. **
  145622. ** The author disclaims copyright to this source code. In place of
  145623. ** a legal notice, here is a blessing:
  145624. **
  145625. ** May you do good and not evil.
  145626. ** May you find forgiveness for yourself and forgive others.
  145627. ** May you share freely, never taking more than you give.
  145628. **
  145629. *************************************************************************
  145630. ** This is the implementation of generic hash-tables used in SQLite.
  145631. ** We've modified it slightly to serve as a standalone hash table
  145632. ** implementation for the full-text indexing module.
  145633. */
  145634. /*
  145635. ** The code in this file is only compiled if:
  145636. **
  145637. ** * The FTS3 module is being built as an extension
  145638. ** (in which case SQLITE_CORE is not defined), or
  145639. **
  145640. ** * The FTS3 module is being built into the core of
  145641. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  145642. */
  145643. /* #include "fts3Int.h" */
  145644. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145645. /* #include <assert.h> */
  145646. /* #include <stdlib.h> */
  145647. /* #include <string.h> */
  145648. /* #include "fts3_hash.h" */
  145649. /*
  145650. ** Malloc and Free functions
  145651. */
  145652. static void *fts3HashMalloc(int n){
  145653. void *p = sqlite3_malloc(n);
  145654. if( p ){
  145655. memset(p, 0, n);
  145656. }
  145657. return p;
  145658. }
  145659. static void fts3HashFree(void *p){
  145660. sqlite3_free(p);
  145661. }
  145662. /* Turn bulk memory into a hash table object by initializing the
  145663. ** fields of the Hash structure.
  145664. **
  145665. ** "pNew" is a pointer to the hash table that is to be initialized.
  145666. ** keyClass is one of the constants
  145667. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  145668. ** determines what kind of key the hash table will use. "copyKey" is
  145669. ** true if the hash table should make its own private copy of keys and
  145670. ** false if it should just use the supplied pointer.
  145671. */
  145672. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  145673. assert( pNew!=0 );
  145674. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  145675. pNew->keyClass = keyClass;
  145676. pNew->copyKey = copyKey;
  145677. pNew->first = 0;
  145678. pNew->count = 0;
  145679. pNew->htsize = 0;
  145680. pNew->ht = 0;
  145681. }
  145682. /* Remove all entries from a hash table. Reclaim all memory.
  145683. ** Call this routine to delete a hash table or to reset a hash table
  145684. ** to the empty state.
  145685. */
  145686. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  145687. Fts3HashElem *elem; /* For looping over all elements of the table */
  145688. assert( pH!=0 );
  145689. elem = pH->first;
  145690. pH->first = 0;
  145691. fts3HashFree(pH->ht);
  145692. pH->ht = 0;
  145693. pH->htsize = 0;
  145694. while( elem ){
  145695. Fts3HashElem *next_elem = elem->next;
  145696. if( pH->copyKey && elem->pKey ){
  145697. fts3HashFree(elem->pKey);
  145698. }
  145699. fts3HashFree(elem);
  145700. elem = next_elem;
  145701. }
  145702. pH->count = 0;
  145703. }
  145704. /*
  145705. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  145706. */
  145707. static int fts3StrHash(const void *pKey, int nKey){
  145708. const char *z = (const char *)pKey;
  145709. unsigned h = 0;
  145710. if( nKey<=0 ) nKey = (int) strlen(z);
  145711. while( nKey > 0 ){
  145712. h = (h<<3) ^ h ^ *z++;
  145713. nKey--;
  145714. }
  145715. return (int)(h & 0x7fffffff);
  145716. }
  145717. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  145718. if( n1!=n2 ) return 1;
  145719. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  145720. }
  145721. /*
  145722. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  145723. */
  145724. static int fts3BinHash(const void *pKey, int nKey){
  145725. int h = 0;
  145726. const char *z = (const char *)pKey;
  145727. while( nKey-- > 0 ){
  145728. h = (h<<3) ^ h ^ *(z++);
  145729. }
  145730. return h & 0x7fffffff;
  145731. }
  145732. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  145733. if( n1!=n2 ) return 1;
  145734. return memcmp(pKey1,pKey2,n1);
  145735. }
  145736. /*
  145737. ** Return a pointer to the appropriate hash function given the key class.
  145738. **
  145739. ** The C syntax in this function definition may be unfamilar to some
  145740. ** programmers, so we provide the following additional explanation:
  145741. **
  145742. ** The name of the function is "ftsHashFunction". The function takes a
  145743. ** single parameter "keyClass". The return value of ftsHashFunction()
  145744. ** is a pointer to another function. Specifically, the return value
  145745. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  145746. ** with types "const void*" and "int" and returns an "int".
  145747. */
  145748. static int (*ftsHashFunction(int keyClass))(const void*,int){
  145749. if( keyClass==FTS3_HASH_STRING ){
  145750. return &fts3StrHash;
  145751. }else{
  145752. assert( keyClass==FTS3_HASH_BINARY );
  145753. return &fts3BinHash;
  145754. }
  145755. }
  145756. /*
  145757. ** Return a pointer to the appropriate hash function given the key class.
  145758. **
  145759. ** For help in interpreted the obscure C code in the function definition,
  145760. ** see the header comment on the previous function.
  145761. */
  145762. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  145763. if( keyClass==FTS3_HASH_STRING ){
  145764. return &fts3StrCompare;
  145765. }else{
  145766. assert( keyClass==FTS3_HASH_BINARY );
  145767. return &fts3BinCompare;
  145768. }
  145769. }
  145770. /* Link an element into the hash table
  145771. */
  145772. static void fts3HashInsertElement(
  145773. Fts3Hash *pH, /* The complete hash table */
  145774. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  145775. Fts3HashElem *pNew /* The element to be inserted */
  145776. ){
  145777. Fts3HashElem *pHead; /* First element already in pEntry */
  145778. pHead = pEntry->chain;
  145779. if( pHead ){
  145780. pNew->next = pHead;
  145781. pNew->prev = pHead->prev;
  145782. if( pHead->prev ){ pHead->prev->next = pNew; }
  145783. else { pH->first = pNew; }
  145784. pHead->prev = pNew;
  145785. }else{
  145786. pNew->next = pH->first;
  145787. if( pH->first ){ pH->first->prev = pNew; }
  145788. pNew->prev = 0;
  145789. pH->first = pNew;
  145790. }
  145791. pEntry->count++;
  145792. pEntry->chain = pNew;
  145793. }
  145794. /* Resize the hash table so that it cantains "new_size" buckets.
  145795. ** "new_size" must be a power of 2. The hash table might fail
  145796. ** to resize if sqliteMalloc() fails.
  145797. **
  145798. ** Return non-zero if a memory allocation error occurs.
  145799. */
  145800. static int fts3Rehash(Fts3Hash *pH, int new_size){
  145801. struct _fts3ht *new_ht; /* The new hash table */
  145802. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  145803. int (*xHash)(const void*,int); /* The hash function */
  145804. assert( (new_size & (new_size-1))==0 );
  145805. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  145806. if( new_ht==0 ) return 1;
  145807. fts3HashFree(pH->ht);
  145808. pH->ht = new_ht;
  145809. pH->htsize = new_size;
  145810. xHash = ftsHashFunction(pH->keyClass);
  145811. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  145812. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  145813. next_elem = elem->next;
  145814. fts3HashInsertElement(pH, &new_ht[h], elem);
  145815. }
  145816. return 0;
  145817. }
  145818. /* This function (for internal use only) locates an element in an
  145819. ** hash table that matches the given key. The hash for this key has
  145820. ** already been computed and is passed as the 4th parameter.
  145821. */
  145822. static Fts3HashElem *fts3FindElementByHash(
  145823. const Fts3Hash *pH, /* The pH to be searched */
  145824. const void *pKey, /* The key we are searching for */
  145825. int nKey,
  145826. int h /* The hash for this key. */
  145827. ){
  145828. Fts3HashElem *elem; /* Used to loop thru the element list */
  145829. int count; /* Number of elements left to test */
  145830. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  145831. if( pH->ht ){
  145832. struct _fts3ht *pEntry = &pH->ht[h];
  145833. elem = pEntry->chain;
  145834. count = pEntry->count;
  145835. xCompare = ftsCompareFunction(pH->keyClass);
  145836. while( count-- && elem ){
  145837. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  145838. return elem;
  145839. }
  145840. elem = elem->next;
  145841. }
  145842. }
  145843. return 0;
  145844. }
  145845. /* Remove a single entry from the hash table given a pointer to that
  145846. ** element and a hash on the element's key.
  145847. */
  145848. static void fts3RemoveElementByHash(
  145849. Fts3Hash *pH, /* The pH containing "elem" */
  145850. Fts3HashElem* elem, /* The element to be removed from the pH */
  145851. int h /* Hash value for the element */
  145852. ){
  145853. struct _fts3ht *pEntry;
  145854. if( elem->prev ){
  145855. elem->prev->next = elem->next;
  145856. }else{
  145857. pH->first = elem->next;
  145858. }
  145859. if( elem->next ){
  145860. elem->next->prev = elem->prev;
  145861. }
  145862. pEntry = &pH->ht[h];
  145863. if( pEntry->chain==elem ){
  145864. pEntry->chain = elem->next;
  145865. }
  145866. pEntry->count--;
  145867. if( pEntry->count<=0 ){
  145868. pEntry->chain = 0;
  145869. }
  145870. if( pH->copyKey && elem->pKey ){
  145871. fts3HashFree(elem->pKey);
  145872. }
  145873. fts3HashFree( elem );
  145874. pH->count--;
  145875. if( pH->count<=0 ){
  145876. assert( pH->first==0 );
  145877. assert( pH->count==0 );
  145878. fts3HashClear(pH);
  145879. }
  145880. }
  145881. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  145882. const Fts3Hash *pH,
  145883. const void *pKey,
  145884. int nKey
  145885. ){
  145886. int h; /* A hash on key */
  145887. int (*xHash)(const void*,int); /* The hash function */
  145888. if( pH==0 || pH->ht==0 ) return 0;
  145889. xHash = ftsHashFunction(pH->keyClass);
  145890. assert( xHash!=0 );
  145891. h = (*xHash)(pKey,nKey);
  145892. assert( (pH->htsize & (pH->htsize-1))==0 );
  145893. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  145894. }
  145895. /*
  145896. ** Attempt to locate an element of the hash table pH with a key
  145897. ** that matches pKey,nKey. Return the data for this element if it is
  145898. ** found, or NULL if there is no match.
  145899. */
  145900. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  145901. Fts3HashElem *pElem; /* The element that matches key (if any) */
  145902. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  145903. return pElem ? pElem->data : 0;
  145904. }
  145905. /* Insert an element into the hash table pH. The key is pKey,nKey
  145906. ** and the data is "data".
  145907. **
  145908. ** If no element exists with a matching key, then a new
  145909. ** element is created. A copy of the key is made if the copyKey
  145910. ** flag is set. NULL is returned.
  145911. **
  145912. ** If another element already exists with the same key, then the
  145913. ** new data replaces the old data and the old data is returned.
  145914. ** The key is not copied in this instance. If a malloc fails, then
  145915. ** the new data is returned and the hash table is unchanged.
  145916. **
  145917. ** If the "data" parameter to this function is NULL, then the
  145918. ** element corresponding to "key" is removed from the hash table.
  145919. */
  145920. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  145921. Fts3Hash *pH, /* The hash table to insert into */
  145922. const void *pKey, /* The key */
  145923. int nKey, /* Number of bytes in the key */
  145924. void *data /* The data */
  145925. ){
  145926. int hraw; /* Raw hash value of the key */
  145927. int h; /* the hash of the key modulo hash table size */
  145928. Fts3HashElem *elem; /* Used to loop thru the element list */
  145929. Fts3HashElem *new_elem; /* New element added to the pH */
  145930. int (*xHash)(const void*,int); /* The hash function */
  145931. assert( pH!=0 );
  145932. xHash = ftsHashFunction(pH->keyClass);
  145933. assert( xHash!=0 );
  145934. hraw = (*xHash)(pKey, nKey);
  145935. assert( (pH->htsize & (pH->htsize-1))==0 );
  145936. h = hraw & (pH->htsize-1);
  145937. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  145938. if( elem ){
  145939. void *old_data = elem->data;
  145940. if( data==0 ){
  145941. fts3RemoveElementByHash(pH,elem,h);
  145942. }else{
  145943. elem->data = data;
  145944. }
  145945. return old_data;
  145946. }
  145947. if( data==0 ) return 0;
  145948. if( (pH->htsize==0 && fts3Rehash(pH,8))
  145949. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  145950. ){
  145951. pH->count = 0;
  145952. return data;
  145953. }
  145954. assert( pH->htsize>0 );
  145955. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  145956. if( new_elem==0 ) return data;
  145957. if( pH->copyKey && pKey!=0 ){
  145958. new_elem->pKey = fts3HashMalloc( nKey );
  145959. if( new_elem->pKey==0 ){
  145960. fts3HashFree(new_elem);
  145961. return data;
  145962. }
  145963. memcpy((void*)new_elem->pKey, pKey, nKey);
  145964. }else{
  145965. new_elem->pKey = (void*)pKey;
  145966. }
  145967. new_elem->nKey = nKey;
  145968. pH->count++;
  145969. assert( pH->htsize>0 );
  145970. assert( (pH->htsize & (pH->htsize-1))==0 );
  145971. h = hraw & (pH->htsize-1);
  145972. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  145973. new_elem->data = data;
  145974. return 0;
  145975. }
  145976. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145977. /************** End of fts3_hash.c *******************************************/
  145978. /************** Begin file fts3_porter.c *************************************/
  145979. /*
  145980. ** 2006 September 30
  145981. **
  145982. ** The author disclaims copyright to this source code. In place of
  145983. ** a legal notice, here is a blessing:
  145984. **
  145985. ** May you do good and not evil.
  145986. ** May you find forgiveness for yourself and forgive others.
  145987. ** May you share freely, never taking more than you give.
  145988. **
  145989. *************************************************************************
  145990. ** Implementation of the full-text-search tokenizer that implements
  145991. ** a Porter stemmer.
  145992. */
  145993. /*
  145994. ** The code in this file is only compiled if:
  145995. **
  145996. ** * The FTS3 module is being built as an extension
  145997. ** (in which case SQLITE_CORE is not defined), or
  145998. **
  145999. ** * The FTS3 module is being built into the core of
  146000. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  146001. */
  146002. /* #include "fts3Int.h" */
  146003. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146004. /* #include <assert.h> */
  146005. /* #include <stdlib.h> */
  146006. /* #include <stdio.h> */
  146007. /* #include <string.h> */
  146008. /* #include "fts3_tokenizer.h" */
  146009. /*
  146010. ** Class derived from sqlite3_tokenizer
  146011. */
  146012. typedef struct porter_tokenizer {
  146013. sqlite3_tokenizer base; /* Base class */
  146014. } porter_tokenizer;
  146015. /*
  146016. ** Class derived from sqlite3_tokenizer_cursor
  146017. */
  146018. typedef struct porter_tokenizer_cursor {
  146019. sqlite3_tokenizer_cursor base;
  146020. const char *zInput; /* input we are tokenizing */
  146021. int nInput; /* size of the input */
  146022. int iOffset; /* current position in zInput */
  146023. int iToken; /* index of next token to be returned */
  146024. char *zToken; /* storage for current token */
  146025. int nAllocated; /* space allocated to zToken buffer */
  146026. } porter_tokenizer_cursor;
  146027. /*
  146028. ** Create a new tokenizer instance.
  146029. */
  146030. static int porterCreate(
  146031. int argc, const char * const *argv,
  146032. sqlite3_tokenizer **ppTokenizer
  146033. ){
  146034. porter_tokenizer *t;
  146035. UNUSED_PARAMETER(argc);
  146036. UNUSED_PARAMETER(argv);
  146037. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  146038. if( t==NULL ) return SQLITE_NOMEM;
  146039. memset(t, 0, sizeof(*t));
  146040. *ppTokenizer = &t->base;
  146041. return SQLITE_OK;
  146042. }
  146043. /*
  146044. ** Destroy a tokenizer
  146045. */
  146046. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  146047. sqlite3_free(pTokenizer);
  146048. return SQLITE_OK;
  146049. }
  146050. /*
  146051. ** Prepare to begin tokenizing a particular string. The input
  146052. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  146053. ** used to incrementally tokenize this string is returned in
  146054. ** *ppCursor.
  146055. */
  146056. static int porterOpen(
  146057. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  146058. const char *zInput, int nInput, /* String to be tokenized */
  146059. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  146060. ){
  146061. porter_tokenizer_cursor *c;
  146062. UNUSED_PARAMETER(pTokenizer);
  146063. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  146064. if( c==NULL ) return SQLITE_NOMEM;
  146065. c->zInput = zInput;
  146066. if( zInput==0 ){
  146067. c->nInput = 0;
  146068. }else if( nInput<0 ){
  146069. c->nInput = (int)strlen(zInput);
  146070. }else{
  146071. c->nInput = nInput;
  146072. }
  146073. c->iOffset = 0; /* start tokenizing at the beginning */
  146074. c->iToken = 0;
  146075. c->zToken = NULL; /* no space allocated, yet. */
  146076. c->nAllocated = 0;
  146077. *ppCursor = &c->base;
  146078. return SQLITE_OK;
  146079. }
  146080. /*
  146081. ** Close a tokenization cursor previously opened by a call to
  146082. ** porterOpen() above.
  146083. */
  146084. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  146085. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  146086. sqlite3_free(c->zToken);
  146087. sqlite3_free(c);
  146088. return SQLITE_OK;
  146089. }
  146090. /*
  146091. ** Vowel or consonant
  146092. */
  146093. static const char cType[] = {
  146094. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  146095. 1, 1, 1, 2, 1
  146096. };
  146097. /*
  146098. ** isConsonant() and isVowel() determine if their first character in
  146099. ** the string they point to is a consonant or a vowel, according
  146100. ** to Porter ruls.
  146101. **
  146102. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  146103. ** 'Y' is a consonant unless it follows another consonant,
  146104. ** in which case it is a vowel.
  146105. **
  146106. ** In these routine, the letters are in reverse order. So the 'y' rule
  146107. ** is that 'y' is a consonant unless it is followed by another
  146108. ** consonent.
  146109. */
  146110. static int isVowel(const char*);
  146111. static int isConsonant(const char *z){
  146112. int j;
  146113. char x = *z;
  146114. if( x==0 ) return 0;
  146115. assert( x>='a' && x<='z' );
  146116. j = cType[x-'a'];
  146117. if( j<2 ) return j;
  146118. return z[1]==0 || isVowel(z + 1);
  146119. }
  146120. static int isVowel(const char *z){
  146121. int j;
  146122. char x = *z;
  146123. if( x==0 ) return 0;
  146124. assert( x>='a' && x<='z' );
  146125. j = cType[x-'a'];
  146126. if( j<2 ) return 1-j;
  146127. return isConsonant(z + 1);
  146128. }
  146129. /*
  146130. ** Let any sequence of one or more vowels be represented by V and let
  146131. ** C be sequence of one or more consonants. Then every word can be
  146132. ** represented as:
  146133. **
  146134. ** [C] (VC){m} [V]
  146135. **
  146136. ** In prose: A word is an optional consonant followed by zero or
  146137. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  146138. ** number of vowel consonant pairs. This routine computes the value
  146139. ** of m for the first i bytes of a word.
  146140. **
  146141. ** Return true if the m-value for z is 1 or more. In other words,
  146142. ** return true if z contains at least one vowel that is followed
  146143. ** by a consonant.
  146144. **
  146145. ** In this routine z[] is in reverse order. So we are really looking
  146146. ** for an instance of a consonant followed by a vowel.
  146147. */
  146148. static int m_gt_0(const char *z){
  146149. while( isVowel(z) ){ z++; }
  146150. if( *z==0 ) return 0;
  146151. while( isConsonant(z) ){ z++; }
  146152. return *z!=0;
  146153. }
  146154. /* Like mgt0 above except we are looking for a value of m which is
  146155. ** exactly 1
  146156. */
  146157. static int m_eq_1(const char *z){
  146158. while( isVowel(z) ){ z++; }
  146159. if( *z==0 ) return 0;
  146160. while( isConsonant(z) ){ z++; }
  146161. if( *z==0 ) return 0;
  146162. while( isVowel(z) ){ z++; }
  146163. if( *z==0 ) return 1;
  146164. while( isConsonant(z) ){ z++; }
  146165. return *z==0;
  146166. }
  146167. /* Like mgt0 above except we are looking for a value of m>1 instead
  146168. ** or m>0
  146169. */
  146170. static int m_gt_1(const char *z){
  146171. while( isVowel(z) ){ z++; }
  146172. if( *z==0 ) return 0;
  146173. while( isConsonant(z) ){ z++; }
  146174. if( *z==0 ) return 0;
  146175. while( isVowel(z) ){ z++; }
  146176. if( *z==0 ) return 0;
  146177. while( isConsonant(z) ){ z++; }
  146178. return *z!=0;
  146179. }
  146180. /*
  146181. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  146182. */
  146183. static int hasVowel(const char *z){
  146184. while( isConsonant(z) ){ z++; }
  146185. return *z!=0;
  146186. }
  146187. /*
  146188. ** Return TRUE if the word ends in a double consonant.
  146189. **
  146190. ** The text is reversed here. So we are really looking at
  146191. ** the first two characters of z[].
  146192. */
  146193. static int doubleConsonant(const char *z){
  146194. return isConsonant(z) && z[0]==z[1];
  146195. }
  146196. /*
  146197. ** Return TRUE if the word ends with three letters which
  146198. ** are consonant-vowel-consonent and where the final consonant
  146199. ** is not 'w', 'x', or 'y'.
  146200. **
  146201. ** The word is reversed here. So we are really checking the
  146202. ** first three letters and the first one cannot be in [wxy].
  146203. */
  146204. static int star_oh(const char *z){
  146205. return
  146206. isConsonant(z) &&
  146207. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  146208. isVowel(z+1) &&
  146209. isConsonant(z+2);
  146210. }
  146211. /*
  146212. ** If the word ends with zFrom and xCond() is true for the stem
  146213. ** of the word that preceeds the zFrom ending, then change the
  146214. ** ending to zTo.
  146215. **
  146216. ** The input word *pz and zFrom are both in reverse order. zTo
  146217. ** is in normal order.
  146218. **
  146219. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  146220. ** match. Not that TRUE is returned even if xCond() fails and
  146221. ** no substitution occurs.
  146222. */
  146223. static int stem(
  146224. char **pz, /* The word being stemmed (Reversed) */
  146225. const char *zFrom, /* If the ending matches this... (Reversed) */
  146226. const char *zTo, /* ... change the ending to this (not reversed) */
  146227. int (*xCond)(const char*) /* Condition that must be true */
  146228. ){
  146229. char *z = *pz;
  146230. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  146231. if( *zFrom!=0 ) return 0;
  146232. if( xCond && !xCond(z) ) return 1;
  146233. while( *zTo ){
  146234. *(--z) = *(zTo++);
  146235. }
  146236. *pz = z;
  146237. return 1;
  146238. }
  146239. /*
  146240. ** This is the fallback stemmer used when the porter stemmer is
  146241. ** inappropriate. The input word is copied into the output with
  146242. ** US-ASCII case folding. If the input word is too long (more
  146243. ** than 20 bytes if it contains no digits or more than 6 bytes if
  146244. ** it contains digits) then word is truncated to 20 or 6 bytes
  146245. ** by taking 10 or 3 bytes from the beginning and end.
  146246. */
  146247. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  146248. int i, mx, j;
  146249. int hasDigit = 0;
  146250. for(i=0; i<nIn; i++){
  146251. char c = zIn[i];
  146252. if( c>='A' && c<='Z' ){
  146253. zOut[i] = c - 'A' + 'a';
  146254. }else{
  146255. if( c>='0' && c<='9' ) hasDigit = 1;
  146256. zOut[i] = c;
  146257. }
  146258. }
  146259. mx = hasDigit ? 3 : 10;
  146260. if( nIn>mx*2 ){
  146261. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  146262. zOut[j] = zOut[i];
  146263. }
  146264. i = j;
  146265. }
  146266. zOut[i] = 0;
  146267. *pnOut = i;
  146268. }
  146269. /*
  146270. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  146271. ** zOut is at least big enough to hold nIn bytes. Write the actual
  146272. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  146273. **
  146274. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  146275. ** are converted to lower case. Upper-case UTF characters are
  146276. ** unchanged.
  146277. **
  146278. ** Words that are longer than about 20 bytes are stemmed by retaining
  146279. ** a few bytes from the beginning and the end of the word. If the
  146280. ** word contains digits, 3 bytes are taken from the beginning and
  146281. ** 3 bytes from the end. For long words without digits, 10 bytes
  146282. ** are taken from each end. US-ASCII case folding still applies.
  146283. **
  146284. ** If the input word contains not digits but does characters not
  146285. ** in [a-zA-Z] then no stemming is attempted and this routine just
  146286. ** copies the input into the input into the output with US-ASCII
  146287. ** case folding.
  146288. **
  146289. ** Stemming never increases the length of the word. So there is
  146290. ** no chance of overflowing the zOut buffer.
  146291. */
  146292. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  146293. int i, j;
  146294. char zReverse[28];
  146295. char *z, *z2;
  146296. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  146297. /* The word is too big or too small for the porter stemmer.
  146298. ** Fallback to the copy stemmer */
  146299. copy_stemmer(zIn, nIn, zOut, pnOut);
  146300. return;
  146301. }
  146302. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  146303. char c = zIn[i];
  146304. if( c>='A' && c<='Z' ){
  146305. zReverse[j] = c + 'a' - 'A';
  146306. }else if( c>='a' && c<='z' ){
  146307. zReverse[j] = c;
  146308. }else{
  146309. /* The use of a character not in [a-zA-Z] means that we fallback
  146310. ** to the copy stemmer */
  146311. copy_stemmer(zIn, nIn, zOut, pnOut);
  146312. return;
  146313. }
  146314. }
  146315. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  146316. z = &zReverse[j+1];
  146317. /* Step 1a */
  146318. if( z[0]=='s' ){
  146319. if(
  146320. !stem(&z, "sess", "ss", 0) &&
  146321. !stem(&z, "sei", "i", 0) &&
  146322. !stem(&z, "ss", "ss", 0)
  146323. ){
  146324. z++;
  146325. }
  146326. }
  146327. /* Step 1b */
  146328. z2 = z;
  146329. if( stem(&z, "dee", "ee", m_gt_0) ){
  146330. /* Do nothing. The work was all in the test */
  146331. }else if(
  146332. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  146333. && z!=z2
  146334. ){
  146335. if( stem(&z, "ta", "ate", 0) ||
  146336. stem(&z, "lb", "ble", 0) ||
  146337. stem(&z, "zi", "ize", 0) ){
  146338. /* Do nothing. The work was all in the test */
  146339. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  146340. z++;
  146341. }else if( m_eq_1(z) && star_oh(z) ){
  146342. *(--z) = 'e';
  146343. }
  146344. }
  146345. /* Step 1c */
  146346. if( z[0]=='y' && hasVowel(z+1) ){
  146347. z[0] = 'i';
  146348. }
  146349. /* Step 2 */
  146350. switch( z[1] ){
  146351. case 'a':
  146352. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  146353. stem(&z, "lanoit", "tion", m_gt_0);
  146354. }
  146355. break;
  146356. case 'c':
  146357. if( !stem(&z, "icne", "ence", m_gt_0) ){
  146358. stem(&z, "icna", "ance", m_gt_0);
  146359. }
  146360. break;
  146361. case 'e':
  146362. stem(&z, "rezi", "ize", m_gt_0);
  146363. break;
  146364. case 'g':
  146365. stem(&z, "igol", "log", m_gt_0);
  146366. break;
  146367. case 'l':
  146368. if( !stem(&z, "ilb", "ble", m_gt_0)
  146369. && !stem(&z, "illa", "al", m_gt_0)
  146370. && !stem(&z, "iltne", "ent", m_gt_0)
  146371. && !stem(&z, "ile", "e", m_gt_0)
  146372. ){
  146373. stem(&z, "ilsuo", "ous", m_gt_0);
  146374. }
  146375. break;
  146376. case 'o':
  146377. if( !stem(&z, "noitazi", "ize", m_gt_0)
  146378. && !stem(&z, "noita", "ate", m_gt_0)
  146379. ){
  146380. stem(&z, "rota", "ate", m_gt_0);
  146381. }
  146382. break;
  146383. case 's':
  146384. if( !stem(&z, "msila", "al", m_gt_0)
  146385. && !stem(&z, "ssenevi", "ive", m_gt_0)
  146386. && !stem(&z, "ssenluf", "ful", m_gt_0)
  146387. ){
  146388. stem(&z, "ssensuo", "ous", m_gt_0);
  146389. }
  146390. break;
  146391. case 't':
  146392. if( !stem(&z, "itila", "al", m_gt_0)
  146393. && !stem(&z, "itivi", "ive", m_gt_0)
  146394. ){
  146395. stem(&z, "itilib", "ble", m_gt_0);
  146396. }
  146397. break;
  146398. }
  146399. /* Step 3 */
  146400. switch( z[0] ){
  146401. case 'e':
  146402. if( !stem(&z, "etaci", "ic", m_gt_0)
  146403. && !stem(&z, "evita", "", m_gt_0)
  146404. ){
  146405. stem(&z, "ezila", "al", m_gt_0);
  146406. }
  146407. break;
  146408. case 'i':
  146409. stem(&z, "itici", "ic", m_gt_0);
  146410. break;
  146411. case 'l':
  146412. if( !stem(&z, "laci", "ic", m_gt_0) ){
  146413. stem(&z, "luf", "", m_gt_0);
  146414. }
  146415. break;
  146416. case 's':
  146417. stem(&z, "ssen", "", m_gt_0);
  146418. break;
  146419. }
  146420. /* Step 4 */
  146421. switch( z[1] ){
  146422. case 'a':
  146423. if( z[0]=='l' && m_gt_1(z+2) ){
  146424. z += 2;
  146425. }
  146426. break;
  146427. case 'c':
  146428. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  146429. z += 4;
  146430. }
  146431. break;
  146432. case 'e':
  146433. if( z[0]=='r' && m_gt_1(z+2) ){
  146434. z += 2;
  146435. }
  146436. break;
  146437. case 'i':
  146438. if( z[0]=='c' && m_gt_1(z+2) ){
  146439. z += 2;
  146440. }
  146441. break;
  146442. case 'l':
  146443. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  146444. z += 4;
  146445. }
  146446. break;
  146447. case 'n':
  146448. if( z[0]=='t' ){
  146449. if( z[2]=='a' ){
  146450. if( m_gt_1(z+3) ){
  146451. z += 3;
  146452. }
  146453. }else if( z[2]=='e' ){
  146454. if( !stem(&z, "tneme", "", m_gt_1)
  146455. && !stem(&z, "tnem", "", m_gt_1)
  146456. ){
  146457. stem(&z, "tne", "", m_gt_1);
  146458. }
  146459. }
  146460. }
  146461. break;
  146462. case 'o':
  146463. if( z[0]=='u' ){
  146464. if( m_gt_1(z+2) ){
  146465. z += 2;
  146466. }
  146467. }else if( z[3]=='s' || z[3]=='t' ){
  146468. stem(&z, "noi", "", m_gt_1);
  146469. }
  146470. break;
  146471. case 's':
  146472. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  146473. z += 3;
  146474. }
  146475. break;
  146476. case 't':
  146477. if( !stem(&z, "eta", "", m_gt_1) ){
  146478. stem(&z, "iti", "", m_gt_1);
  146479. }
  146480. break;
  146481. case 'u':
  146482. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  146483. z += 3;
  146484. }
  146485. break;
  146486. case 'v':
  146487. case 'z':
  146488. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  146489. z += 3;
  146490. }
  146491. break;
  146492. }
  146493. /* Step 5a */
  146494. if( z[0]=='e' ){
  146495. if( m_gt_1(z+1) ){
  146496. z++;
  146497. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  146498. z++;
  146499. }
  146500. }
  146501. /* Step 5b */
  146502. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  146503. z++;
  146504. }
  146505. /* z[] is now the stemmed word in reverse order. Flip it back
  146506. ** around into forward order and return.
  146507. */
  146508. *pnOut = i = (int)strlen(z);
  146509. zOut[i] = 0;
  146510. while( *z ){
  146511. zOut[--i] = *(z++);
  146512. }
  146513. }
  146514. /*
  146515. ** Characters that can be part of a token. We assume any character
  146516. ** whose value is greater than 0x80 (any UTF character) can be
  146517. ** part of a token. In other words, delimiters all must have
  146518. ** values of 0x7f or lower.
  146519. */
  146520. static const char porterIdChar[] = {
  146521. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  146522. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  146523. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  146524. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  146525. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  146526. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  146527. };
  146528. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  146529. /*
  146530. ** Extract the next token from a tokenization cursor. The cursor must
  146531. ** have been opened by a prior call to porterOpen().
  146532. */
  146533. static int porterNext(
  146534. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  146535. const char **pzToken, /* OUT: *pzToken is the token text */
  146536. int *pnBytes, /* OUT: Number of bytes in token */
  146537. int *piStartOffset, /* OUT: Starting offset of token */
  146538. int *piEndOffset, /* OUT: Ending offset of token */
  146539. int *piPosition /* OUT: Position integer of token */
  146540. ){
  146541. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  146542. const char *z = c->zInput;
  146543. while( c->iOffset<c->nInput ){
  146544. int iStartOffset, ch;
  146545. /* Scan past delimiter characters */
  146546. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  146547. c->iOffset++;
  146548. }
  146549. /* Count non-delimiter characters. */
  146550. iStartOffset = c->iOffset;
  146551. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  146552. c->iOffset++;
  146553. }
  146554. if( c->iOffset>iStartOffset ){
  146555. int n = c->iOffset-iStartOffset;
  146556. if( n>c->nAllocated ){
  146557. char *pNew;
  146558. c->nAllocated = n+20;
  146559. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  146560. if( !pNew ) return SQLITE_NOMEM;
  146561. c->zToken = pNew;
  146562. }
  146563. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  146564. *pzToken = c->zToken;
  146565. *piStartOffset = iStartOffset;
  146566. *piEndOffset = c->iOffset;
  146567. *piPosition = c->iToken++;
  146568. return SQLITE_OK;
  146569. }
  146570. }
  146571. return SQLITE_DONE;
  146572. }
  146573. /*
  146574. ** The set of routines that implement the porter-stemmer tokenizer
  146575. */
  146576. static const sqlite3_tokenizer_module porterTokenizerModule = {
  146577. 0,
  146578. porterCreate,
  146579. porterDestroy,
  146580. porterOpen,
  146581. porterClose,
  146582. porterNext,
  146583. 0
  146584. };
  146585. /*
  146586. ** Allocate a new porter tokenizer. Return a pointer to the new
  146587. ** tokenizer in *ppModule
  146588. */
  146589. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  146590. sqlite3_tokenizer_module const**ppModule
  146591. ){
  146592. *ppModule = &porterTokenizerModule;
  146593. }
  146594. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  146595. /************** End of fts3_porter.c *****************************************/
  146596. /************** Begin file fts3_tokenizer.c **********************************/
  146597. /*
  146598. ** 2007 June 22
  146599. **
  146600. ** The author disclaims copyright to this source code. In place of
  146601. ** a legal notice, here is a blessing:
  146602. **
  146603. ** May you do good and not evil.
  146604. ** May you find forgiveness for yourself and forgive others.
  146605. ** May you share freely, never taking more than you give.
  146606. **
  146607. ******************************************************************************
  146608. **
  146609. ** This is part of an SQLite module implementing full-text search.
  146610. ** This particular file implements the generic tokenizer interface.
  146611. */
  146612. /*
  146613. ** The code in this file is only compiled if:
  146614. **
  146615. ** * The FTS3 module is being built as an extension
  146616. ** (in which case SQLITE_CORE is not defined), or
  146617. **
  146618. ** * The FTS3 module is being built into the core of
  146619. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  146620. */
  146621. /* #include "fts3Int.h" */
  146622. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146623. /* #include <assert.h> */
  146624. /* #include <string.h> */
  146625. /*
  146626. ** Return true if the two-argument version of fts3_tokenizer()
  146627. ** has been activated via a prior call to sqlite3_db_config(db,
  146628. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  146629. */
  146630. static int fts3TokenizerEnabled(sqlite3_context *context){
  146631. sqlite3 *db = sqlite3_context_db_handle(context);
  146632. int isEnabled = 0;
  146633. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  146634. return isEnabled;
  146635. }
  146636. /*
  146637. ** Implementation of the SQL scalar function for accessing the underlying
  146638. ** hash table. This function may be called as follows:
  146639. **
  146640. ** SELECT <function-name>(<key-name>);
  146641. ** SELECT <function-name>(<key-name>, <pointer>);
  146642. **
  146643. ** where <function-name> is the name passed as the second argument
  146644. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  146645. **
  146646. ** If the <pointer> argument is specified, it must be a blob value
  146647. ** containing a pointer to be stored as the hash data corresponding
  146648. ** to the string <key-name>. If <pointer> is not specified, then
  146649. ** the string <key-name> must already exist in the has table. Otherwise,
  146650. ** an error is returned.
  146651. **
  146652. ** Whether or not the <pointer> argument is specified, the value returned
  146653. ** is a blob containing the pointer stored as the hash data corresponding
  146654. ** to string <key-name> (after the hash-table is updated, if applicable).
  146655. */
  146656. static void fts3TokenizerFunc(
  146657. sqlite3_context *context,
  146658. int argc,
  146659. sqlite3_value **argv
  146660. ){
  146661. Fts3Hash *pHash;
  146662. void *pPtr = 0;
  146663. const unsigned char *zName;
  146664. int nName;
  146665. assert( argc==1 || argc==2 );
  146666. pHash = (Fts3Hash *)sqlite3_user_data(context);
  146667. zName = sqlite3_value_text(argv[0]);
  146668. nName = sqlite3_value_bytes(argv[0])+1;
  146669. if( argc==2 ){
  146670. if( fts3TokenizerEnabled(context) ){
  146671. void *pOld;
  146672. int n = sqlite3_value_bytes(argv[1]);
  146673. if( zName==0 || n!=sizeof(pPtr) ){
  146674. sqlite3_result_error(context, "argument type mismatch", -1);
  146675. return;
  146676. }
  146677. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  146678. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  146679. if( pOld==pPtr ){
  146680. sqlite3_result_error(context, "out of memory", -1);
  146681. }
  146682. }else{
  146683. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  146684. return;
  146685. }
  146686. }else{
  146687. if( zName ){
  146688. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  146689. }
  146690. if( !pPtr ){
  146691. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  146692. sqlite3_result_error(context, zErr, -1);
  146693. sqlite3_free(zErr);
  146694. return;
  146695. }
  146696. }
  146697. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  146698. }
  146699. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  146700. static const char isFtsIdChar[] = {
  146701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  146702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  146703. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  146704. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  146705. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  146706. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  146707. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  146708. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  146709. };
  146710. return (c&0x80 || isFtsIdChar[(int)(c)]);
  146711. }
  146712. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  146713. const char *z1;
  146714. const char *z2 = 0;
  146715. /* Find the start of the next token. */
  146716. z1 = zStr;
  146717. while( z2==0 ){
  146718. char c = *z1;
  146719. switch( c ){
  146720. case '\0': return 0; /* No more tokens here */
  146721. case '\'':
  146722. case '"':
  146723. case '`': {
  146724. z2 = z1;
  146725. while( *++z2 && (*z2!=c || *++z2==c) );
  146726. break;
  146727. }
  146728. case '[':
  146729. z2 = &z1[1];
  146730. while( *z2 && z2[0]!=']' ) z2++;
  146731. if( *z2 ) z2++;
  146732. break;
  146733. default:
  146734. if( sqlite3Fts3IsIdChar(*z1) ){
  146735. z2 = &z1[1];
  146736. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  146737. }else{
  146738. z1++;
  146739. }
  146740. }
  146741. }
  146742. *pn = (int)(z2-z1);
  146743. return z1;
  146744. }
  146745. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  146746. Fts3Hash *pHash, /* Tokenizer hash table */
  146747. const char *zArg, /* Tokenizer name */
  146748. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  146749. char **pzErr /* OUT: Set to malloced error message */
  146750. ){
  146751. int rc;
  146752. char *z = (char *)zArg;
  146753. int n = 0;
  146754. char *zCopy;
  146755. char *zEnd; /* Pointer to nul-term of zCopy */
  146756. sqlite3_tokenizer_module *m;
  146757. zCopy = sqlite3_mprintf("%s", zArg);
  146758. if( !zCopy ) return SQLITE_NOMEM;
  146759. zEnd = &zCopy[strlen(zCopy)];
  146760. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  146761. if( z==0 ){
  146762. assert( n==0 );
  146763. z = zCopy;
  146764. }
  146765. z[n] = '\0';
  146766. sqlite3Fts3Dequote(z);
  146767. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  146768. if( !m ){
  146769. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  146770. rc = SQLITE_ERROR;
  146771. }else{
  146772. char const **aArg = 0;
  146773. int iArg = 0;
  146774. z = &z[n+1];
  146775. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  146776. int nNew = sizeof(char *)*(iArg+1);
  146777. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  146778. if( !aNew ){
  146779. sqlite3_free(zCopy);
  146780. sqlite3_free((void *)aArg);
  146781. return SQLITE_NOMEM;
  146782. }
  146783. aArg = aNew;
  146784. aArg[iArg++] = z;
  146785. z[n] = '\0';
  146786. sqlite3Fts3Dequote(z);
  146787. z = &z[n+1];
  146788. }
  146789. rc = m->xCreate(iArg, aArg, ppTok);
  146790. assert( rc!=SQLITE_OK || *ppTok );
  146791. if( rc!=SQLITE_OK ){
  146792. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  146793. }else{
  146794. (*ppTok)->pModule = m;
  146795. }
  146796. sqlite3_free((void *)aArg);
  146797. }
  146798. sqlite3_free(zCopy);
  146799. return rc;
  146800. }
  146801. #ifdef SQLITE_TEST
  146802. #if defined(INCLUDE_SQLITE_TCL_H)
  146803. # include "sqlite_tcl.h"
  146804. #else
  146805. # include "tcl.h"
  146806. #endif
  146807. /* #include <string.h> */
  146808. /*
  146809. ** Implementation of a special SQL scalar function for testing tokenizers
  146810. ** designed to be used in concert with the Tcl testing framework. This
  146811. ** function must be called with two or more arguments:
  146812. **
  146813. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  146814. **
  146815. ** where <function-name> is the name passed as the second argument
  146816. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  146817. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  146818. **
  146819. ** The return value is a string that may be interpreted as a Tcl
  146820. ** list. For each token in the <input-string>, three elements are
  146821. ** added to the returned list. The first is the token position, the
  146822. ** second is the token text (folded, stemmed, etc.) and the third is the
  146823. ** substring of <input-string> associated with the token. For example,
  146824. ** using the built-in "simple" tokenizer:
  146825. **
  146826. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  146827. **
  146828. ** will return the string:
  146829. **
  146830. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  146831. **
  146832. */
  146833. static void testFunc(
  146834. sqlite3_context *context,
  146835. int argc,
  146836. sqlite3_value **argv
  146837. ){
  146838. Fts3Hash *pHash;
  146839. sqlite3_tokenizer_module *p;
  146840. sqlite3_tokenizer *pTokenizer = 0;
  146841. sqlite3_tokenizer_cursor *pCsr = 0;
  146842. const char *zErr = 0;
  146843. const char *zName;
  146844. int nName;
  146845. const char *zInput;
  146846. int nInput;
  146847. const char *azArg[64];
  146848. const char *zToken;
  146849. int nToken = 0;
  146850. int iStart = 0;
  146851. int iEnd = 0;
  146852. int iPos = 0;
  146853. int i;
  146854. Tcl_Obj *pRet;
  146855. if( argc<2 ){
  146856. sqlite3_result_error(context, "insufficient arguments", -1);
  146857. return;
  146858. }
  146859. nName = sqlite3_value_bytes(argv[0]);
  146860. zName = (const char *)sqlite3_value_text(argv[0]);
  146861. nInput = sqlite3_value_bytes(argv[argc-1]);
  146862. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  146863. pHash = (Fts3Hash *)sqlite3_user_data(context);
  146864. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  146865. if( !p ){
  146866. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  146867. sqlite3_result_error(context, zErr2, -1);
  146868. sqlite3_free(zErr2);
  146869. return;
  146870. }
  146871. pRet = Tcl_NewObj();
  146872. Tcl_IncrRefCount(pRet);
  146873. for(i=1; i<argc-1; i++){
  146874. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  146875. }
  146876. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  146877. zErr = "error in xCreate()";
  146878. goto finish;
  146879. }
  146880. pTokenizer->pModule = p;
  146881. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  146882. zErr = "error in xOpen()";
  146883. goto finish;
  146884. }
  146885. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  146886. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  146887. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  146888. zToken = &zInput[iStart];
  146889. nToken = iEnd-iStart;
  146890. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  146891. }
  146892. if( SQLITE_OK!=p->xClose(pCsr) ){
  146893. zErr = "error in xClose()";
  146894. goto finish;
  146895. }
  146896. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  146897. zErr = "error in xDestroy()";
  146898. goto finish;
  146899. }
  146900. finish:
  146901. if( zErr ){
  146902. sqlite3_result_error(context, zErr, -1);
  146903. }else{
  146904. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  146905. }
  146906. Tcl_DecrRefCount(pRet);
  146907. }
  146908. static
  146909. int registerTokenizer(
  146910. sqlite3 *db,
  146911. char *zName,
  146912. const sqlite3_tokenizer_module *p
  146913. ){
  146914. int rc;
  146915. sqlite3_stmt *pStmt;
  146916. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  146917. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  146918. if( rc!=SQLITE_OK ){
  146919. return rc;
  146920. }
  146921. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  146922. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  146923. sqlite3_step(pStmt);
  146924. return sqlite3_finalize(pStmt);
  146925. }
  146926. static
  146927. int queryTokenizer(
  146928. sqlite3 *db,
  146929. char *zName,
  146930. const sqlite3_tokenizer_module **pp
  146931. ){
  146932. int rc;
  146933. sqlite3_stmt *pStmt;
  146934. const char zSql[] = "SELECT fts3_tokenizer(?)";
  146935. *pp = 0;
  146936. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  146937. if( rc!=SQLITE_OK ){
  146938. return rc;
  146939. }
  146940. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  146941. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  146942. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  146943. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  146944. }
  146945. }
  146946. return sqlite3_finalize(pStmt);
  146947. }
  146948. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  146949. /*
  146950. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  146951. ** This function is used for testing only, it is not included in the
  146952. ** build unless SQLITE_TEST is defined.
  146953. **
  146954. ** The purpose of this is to test that the fts3_tokenizer() function
  146955. ** can be used as designed by the C-code in the queryTokenizer and
  146956. ** registerTokenizer() functions above. These two functions are repeated
  146957. ** in the README.tokenizer file as an example, so it is important to
  146958. ** test them.
  146959. **
  146960. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  146961. ** function with no arguments. An assert() will fail if a problem is
  146962. ** detected. i.e.:
  146963. **
  146964. ** SELECT fts3_tokenizer_internal_test();
  146965. **
  146966. */
  146967. static void intTestFunc(
  146968. sqlite3_context *context,
  146969. int argc,
  146970. sqlite3_value **argv
  146971. ){
  146972. int rc;
  146973. const sqlite3_tokenizer_module *p1;
  146974. const sqlite3_tokenizer_module *p2;
  146975. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  146976. UNUSED_PARAMETER(argc);
  146977. UNUSED_PARAMETER(argv);
  146978. /* Test the query function */
  146979. sqlite3Fts3SimpleTokenizerModule(&p1);
  146980. rc = queryTokenizer(db, "simple", &p2);
  146981. assert( rc==SQLITE_OK );
  146982. assert( p1==p2 );
  146983. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  146984. assert( rc==SQLITE_ERROR );
  146985. assert( p2==0 );
  146986. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  146987. /* Test the storage function */
  146988. if( fts3TokenizerEnabled(context) ){
  146989. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  146990. assert( rc==SQLITE_OK );
  146991. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  146992. assert( rc==SQLITE_OK );
  146993. assert( p2==p1 );
  146994. }
  146995. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  146996. }
  146997. #endif
  146998. /*
  146999. ** Set up SQL objects in database db used to access the contents of
  147000. ** the hash table pointed to by argument pHash. The hash table must
  147001. ** been initialized to use string keys, and to take a private copy
  147002. ** of the key when a value is inserted. i.e. by a call similar to:
  147003. **
  147004. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  147005. **
  147006. ** This function adds a scalar function (see header comment above
  147007. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  147008. ** defined at compilation time, a temporary virtual table (see header
  147009. ** comment above struct HashTableVtab) to the database schema. Both
  147010. ** provide read/write access to the contents of *pHash.
  147011. **
  147012. ** The third argument to this function, zName, is used as the name
  147013. ** of both the scalar and, if created, the virtual table.
  147014. */
  147015. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  147016. sqlite3 *db,
  147017. Fts3Hash *pHash,
  147018. const char *zName
  147019. ){
  147020. int rc = SQLITE_OK;
  147021. void *p = (void *)pHash;
  147022. const int any = SQLITE_ANY;
  147023. #ifdef SQLITE_TEST
  147024. char *zTest = 0;
  147025. char *zTest2 = 0;
  147026. void *pdb = (void *)db;
  147027. zTest = sqlite3_mprintf("%s_test", zName);
  147028. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  147029. if( !zTest || !zTest2 ){
  147030. rc = SQLITE_NOMEM;
  147031. }
  147032. #endif
  147033. if( SQLITE_OK==rc ){
  147034. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  147035. }
  147036. if( SQLITE_OK==rc ){
  147037. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  147038. }
  147039. #ifdef SQLITE_TEST
  147040. if( SQLITE_OK==rc ){
  147041. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  147042. }
  147043. if( SQLITE_OK==rc ){
  147044. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  147045. }
  147046. #endif
  147047. #ifdef SQLITE_TEST
  147048. sqlite3_free(zTest);
  147049. sqlite3_free(zTest2);
  147050. #endif
  147051. return rc;
  147052. }
  147053. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  147054. /************** End of fts3_tokenizer.c **************************************/
  147055. /************** Begin file fts3_tokenizer1.c *********************************/
  147056. /*
  147057. ** 2006 Oct 10
  147058. **
  147059. ** The author disclaims copyright to this source code. In place of
  147060. ** a legal notice, here is a blessing:
  147061. **
  147062. ** May you do good and not evil.
  147063. ** May you find forgiveness for yourself and forgive others.
  147064. ** May you share freely, never taking more than you give.
  147065. **
  147066. ******************************************************************************
  147067. **
  147068. ** Implementation of the "simple" full-text-search tokenizer.
  147069. */
  147070. /*
  147071. ** The code in this file is only compiled if:
  147072. **
  147073. ** * The FTS3 module is being built as an extension
  147074. ** (in which case SQLITE_CORE is not defined), or
  147075. **
  147076. ** * The FTS3 module is being built into the core of
  147077. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  147078. */
  147079. /* #include "fts3Int.h" */
  147080. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  147081. /* #include <assert.h> */
  147082. /* #include <stdlib.h> */
  147083. /* #include <stdio.h> */
  147084. /* #include <string.h> */
  147085. /* #include "fts3_tokenizer.h" */
  147086. typedef struct simple_tokenizer {
  147087. sqlite3_tokenizer base;
  147088. char delim[128]; /* flag ASCII delimiters */
  147089. } simple_tokenizer;
  147090. typedef struct simple_tokenizer_cursor {
  147091. sqlite3_tokenizer_cursor base;
  147092. const char *pInput; /* input we are tokenizing */
  147093. int nBytes; /* size of the input */
  147094. int iOffset; /* current position in pInput */
  147095. int iToken; /* index of next token to be returned */
  147096. char *pToken; /* storage for current token */
  147097. int nTokenAllocated; /* space allocated to zToken buffer */
  147098. } simple_tokenizer_cursor;
  147099. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  147100. return c<0x80 && t->delim[c];
  147101. }
  147102. static int fts3_isalnum(int x){
  147103. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  147104. }
  147105. /*
  147106. ** Create a new tokenizer instance.
  147107. */
  147108. static int simpleCreate(
  147109. int argc, const char * const *argv,
  147110. sqlite3_tokenizer **ppTokenizer
  147111. ){
  147112. simple_tokenizer *t;
  147113. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  147114. if( t==NULL ) return SQLITE_NOMEM;
  147115. memset(t, 0, sizeof(*t));
  147116. /* TODO(shess) Delimiters need to remain the same from run to run,
  147117. ** else we need to reindex. One solution would be a meta-table to
  147118. ** track such information in the database, then we'd only want this
  147119. ** information on the initial create.
  147120. */
  147121. if( argc>1 ){
  147122. int i, n = (int)strlen(argv[1]);
  147123. for(i=0; i<n; i++){
  147124. unsigned char ch = argv[1][i];
  147125. /* We explicitly don't support UTF-8 delimiters for now. */
  147126. if( ch>=0x80 ){
  147127. sqlite3_free(t);
  147128. return SQLITE_ERROR;
  147129. }
  147130. t->delim[ch] = 1;
  147131. }
  147132. } else {
  147133. /* Mark non-alphanumeric ASCII characters as delimiters */
  147134. int i;
  147135. for(i=1; i<0x80; i++){
  147136. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  147137. }
  147138. }
  147139. *ppTokenizer = &t->base;
  147140. return SQLITE_OK;
  147141. }
  147142. /*
  147143. ** Destroy a tokenizer
  147144. */
  147145. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  147146. sqlite3_free(pTokenizer);
  147147. return SQLITE_OK;
  147148. }
  147149. /*
  147150. ** Prepare to begin tokenizing a particular string. The input
  147151. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  147152. ** used to incrementally tokenize this string is returned in
  147153. ** *ppCursor.
  147154. */
  147155. static int simpleOpen(
  147156. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  147157. const char *pInput, int nBytes, /* String to be tokenized */
  147158. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  147159. ){
  147160. simple_tokenizer_cursor *c;
  147161. UNUSED_PARAMETER(pTokenizer);
  147162. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  147163. if( c==NULL ) return SQLITE_NOMEM;
  147164. c->pInput = pInput;
  147165. if( pInput==0 ){
  147166. c->nBytes = 0;
  147167. }else if( nBytes<0 ){
  147168. c->nBytes = (int)strlen(pInput);
  147169. }else{
  147170. c->nBytes = nBytes;
  147171. }
  147172. c->iOffset = 0; /* start tokenizing at the beginning */
  147173. c->iToken = 0;
  147174. c->pToken = NULL; /* no space allocated, yet. */
  147175. c->nTokenAllocated = 0;
  147176. *ppCursor = &c->base;
  147177. return SQLITE_OK;
  147178. }
  147179. /*
  147180. ** Close a tokenization cursor previously opened by a call to
  147181. ** simpleOpen() above.
  147182. */
  147183. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  147184. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  147185. sqlite3_free(c->pToken);
  147186. sqlite3_free(c);
  147187. return SQLITE_OK;
  147188. }
  147189. /*
  147190. ** Extract the next token from a tokenization cursor. The cursor must
  147191. ** have been opened by a prior call to simpleOpen().
  147192. */
  147193. static int simpleNext(
  147194. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  147195. const char **ppToken, /* OUT: *ppToken is the token text */
  147196. int *pnBytes, /* OUT: Number of bytes in token */
  147197. int *piStartOffset, /* OUT: Starting offset of token */
  147198. int *piEndOffset, /* OUT: Ending offset of token */
  147199. int *piPosition /* OUT: Position integer of token */
  147200. ){
  147201. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  147202. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  147203. unsigned char *p = (unsigned char *)c->pInput;
  147204. while( c->iOffset<c->nBytes ){
  147205. int iStartOffset;
  147206. /* Scan past delimiter characters */
  147207. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  147208. c->iOffset++;
  147209. }
  147210. /* Count non-delimiter characters. */
  147211. iStartOffset = c->iOffset;
  147212. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  147213. c->iOffset++;
  147214. }
  147215. if( c->iOffset>iStartOffset ){
  147216. int i, n = c->iOffset-iStartOffset;
  147217. if( n>c->nTokenAllocated ){
  147218. char *pNew;
  147219. c->nTokenAllocated = n+20;
  147220. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  147221. if( !pNew ) return SQLITE_NOMEM;
  147222. c->pToken = pNew;
  147223. }
  147224. for(i=0; i<n; i++){
  147225. /* TODO(shess) This needs expansion to handle UTF-8
  147226. ** case-insensitivity.
  147227. */
  147228. unsigned char ch = p[iStartOffset+i];
  147229. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  147230. }
  147231. *ppToken = c->pToken;
  147232. *pnBytes = n;
  147233. *piStartOffset = iStartOffset;
  147234. *piEndOffset = c->iOffset;
  147235. *piPosition = c->iToken++;
  147236. return SQLITE_OK;
  147237. }
  147238. }
  147239. return SQLITE_DONE;
  147240. }
  147241. /*
  147242. ** The set of routines that implement the simple tokenizer
  147243. */
  147244. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  147245. 0,
  147246. simpleCreate,
  147247. simpleDestroy,
  147248. simpleOpen,
  147249. simpleClose,
  147250. simpleNext,
  147251. 0,
  147252. };
  147253. /*
  147254. ** Allocate a new simple tokenizer. Return a pointer to the new
  147255. ** tokenizer in *ppModule
  147256. */
  147257. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  147258. sqlite3_tokenizer_module const**ppModule
  147259. ){
  147260. *ppModule = &simpleTokenizerModule;
  147261. }
  147262. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  147263. /************** End of fts3_tokenizer1.c *************************************/
  147264. /************** Begin file fts3_tokenize_vtab.c ******************************/
  147265. /*
  147266. ** 2013 Apr 22
  147267. **
  147268. ** The author disclaims copyright to this source code. In place of
  147269. ** a legal notice, here is a blessing:
  147270. **
  147271. ** May you do good and not evil.
  147272. ** May you find forgiveness for yourself and forgive others.
  147273. ** May you share freely, never taking more than you give.
  147274. **
  147275. ******************************************************************************
  147276. **
  147277. ** This file contains code for the "fts3tokenize" virtual table module.
  147278. ** An fts3tokenize virtual table is created as follows:
  147279. **
  147280. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  147281. ** <tokenizer-name>, <arg-1>, ...
  147282. ** );
  147283. **
  147284. ** The table created has the following schema:
  147285. **
  147286. ** CREATE TABLE <tbl>(input, token, start, end, position)
  147287. **
  147288. ** When queried, the query must include a WHERE clause of type:
  147289. **
  147290. ** input = <string>
  147291. **
  147292. ** The virtual table module tokenizes this <string>, using the FTS3
  147293. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  147294. ** statement and returns one row for each token in the result. With
  147295. ** fields set as follows:
  147296. **
  147297. ** input: Always set to a copy of <string>
  147298. ** token: A token from the input.
  147299. ** start: Byte offset of the token within the input <string>.
  147300. ** end: Byte offset of the byte immediately following the end of the
  147301. ** token within the input string.
  147302. ** pos: Token offset of token within input.
  147303. **
  147304. */
  147305. /* #include "fts3Int.h" */
  147306. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  147307. /* #include <string.h> */
  147308. /* #include <assert.h> */
  147309. typedef struct Fts3tokTable Fts3tokTable;
  147310. typedef struct Fts3tokCursor Fts3tokCursor;
  147311. /*
  147312. ** Virtual table structure.
  147313. */
  147314. struct Fts3tokTable {
  147315. sqlite3_vtab base; /* Base class used by SQLite core */
  147316. const sqlite3_tokenizer_module *pMod;
  147317. sqlite3_tokenizer *pTok;
  147318. };
  147319. /*
  147320. ** Virtual table cursor structure.
  147321. */
  147322. struct Fts3tokCursor {
  147323. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  147324. char *zInput; /* Input string */
  147325. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  147326. int iRowid; /* Current 'rowid' value */
  147327. const char *zToken; /* Current 'token' value */
  147328. int nToken; /* Size of zToken in bytes */
  147329. int iStart; /* Current 'start' value */
  147330. int iEnd; /* Current 'end' value */
  147331. int iPos; /* Current 'pos' value */
  147332. };
  147333. /*
  147334. ** Query FTS for the tokenizer implementation named zName.
  147335. */
  147336. static int fts3tokQueryTokenizer(
  147337. Fts3Hash *pHash,
  147338. const char *zName,
  147339. const sqlite3_tokenizer_module **pp,
  147340. char **pzErr
  147341. ){
  147342. sqlite3_tokenizer_module *p;
  147343. int nName = (int)strlen(zName);
  147344. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  147345. if( !p ){
  147346. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  147347. return SQLITE_ERROR;
  147348. }
  147349. *pp = p;
  147350. return SQLITE_OK;
  147351. }
  147352. /*
  147353. ** The second argument, argv[], is an array of pointers to nul-terminated
  147354. ** strings. This function makes a copy of the array and strings into a
  147355. ** single block of memory. It then dequotes any of the strings that appear
  147356. ** to be quoted.
  147357. **
  147358. ** If successful, output parameter *pazDequote is set to point at the
  147359. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  147360. ** responsible for eventually calling sqlite3_free() to free the array
  147361. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  147362. ** The final value of *pazDequote is undefined in this case.
  147363. */
  147364. static int fts3tokDequoteArray(
  147365. int argc, /* Number of elements in argv[] */
  147366. const char * const *argv, /* Input array */
  147367. char ***pazDequote /* Output array */
  147368. ){
  147369. int rc = SQLITE_OK; /* Return code */
  147370. if( argc==0 ){
  147371. *pazDequote = 0;
  147372. }else{
  147373. int i;
  147374. int nByte = 0;
  147375. char **azDequote;
  147376. for(i=0; i<argc; i++){
  147377. nByte += (int)(strlen(argv[i]) + 1);
  147378. }
  147379. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  147380. if( azDequote==0 ){
  147381. rc = SQLITE_NOMEM;
  147382. }else{
  147383. char *pSpace = (char *)&azDequote[argc];
  147384. for(i=0; i<argc; i++){
  147385. int n = (int)strlen(argv[i]);
  147386. azDequote[i] = pSpace;
  147387. memcpy(pSpace, argv[i], n+1);
  147388. sqlite3Fts3Dequote(pSpace);
  147389. pSpace += (n+1);
  147390. }
  147391. }
  147392. }
  147393. return rc;
  147394. }
  147395. /*
  147396. ** Schema of the tokenizer table.
  147397. */
  147398. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  147399. /*
  147400. ** This function does all the work for both the xConnect and xCreate methods.
  147401. ** These tables have no persistent representation of their own, so xConnect
  147402. ** and xCreate are identical operations.
  147403. **
  147404. ** argv[0]: module name
  147405. ** argv[1]: database name
  147406. ** argv[2]: table name
  147407. ** argv[3]: first argument (tokenizer name)
  147408. */
  147409. static int fts3tokConnectMethod(
  147410. sqlite3 *db, /* Database connection */
  147411. void *pHash, /* Hash table of tokenizers */
  147412. int argc, /* Number of elements in argv array */
  147413. const char * const *argv, /* xCreate/xConnect argument array */
  147414. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  147415. char **pzErr /* OUT: sqlite3_malloc'd error message */
  147416. ){
  147417. Fts3tokTable *pTab = 0;
  147418. const sqlite3_tokenizer_module *pMod = 0;
  147419. sqlite3_tokenizer *pTok = 0;
  147420. int rc;
  147421. char **azDequote = 0;
  147422. int nDequote;
  147423. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  147424. if( rc!=SQLITE_OK ) return rc;
  147425. nDequote = argc-3;
  147426. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  147427. if( rc==SQLITE_OK ){
  147428. const char *zModule;
  147429. if( nDequote<1 ){
  147430. zModule = "simple";
  147431. }else{
  147432. zModule = azDequote[0];
  147433. }
  147434. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  147435. }
  147436. assert( (rc==SQLITE_OK)==(pMod!=0) );
  147437. if( rc==SQLITE_OK ){
  147438. const char * const *azArg = (const char * const *)&azDequote[1];
  147439. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  147440. }
  147441. if( rc==SQLITE_OK ){
  147442. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  147443. if( pTab==0 ){
  147444. rc = SQLITE_NOMEM;
  147445. }
  147446. }
  147447. if( rc==SQLITE_OK ){
  147448. memset(pTab, 0, sizeof(Fts3tokTable));
  147449. pTab->pMod = pMod;
  147450. pTab->pTok = pTok;
  147451. *ppVtab = &pTab->base;
  147452. }else{
  147453. if( pTok ){
  147454. pMod->xDestroy(pTok);
  147455. }
  147456. }
  147457. sqlite3_free(azDequote);
  147458. return rc;
  147459. }
  147460. /*
  147461. ** This function does the work for both the xDisconnect and xDestroy methods.
  147462. ** These tables have no persistent representation of their own, so xDisconnect
  147463. ** and xDestroy are identical operations.
  147464. */
  147465. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  147466. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  147467. pTab->pMod->xDestroy(pTab->pTok);
  147468. sqlite3_free(pTab);
  147469. return SQLITE_OK;
  147470. }
  147471. /*
  147472. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  147473. */
  147474. static int fts3tokBestIndexMethod(
  147475. sqlite3_vtab *pVTab,
  147476. sqlite3_index_info *pInfo
  147477. ){
  147478. int i;
  147479. UNUSED_PARAMETER(pVTab);
  147480. for(i=0; i<pInfo->nConstraint; i++){
  147481. if( pInfo->aConstraint[i].usable
  147482. && pInfo->aConstraint[i].iColumn==0
  147483. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  147484. ){
  147485. pInfo->idxNum = 1;
  147486. pInfo->aConstraintUsage[i].argvIndex = 1;
  147487. pInfo->aConstraintUsage[i].omit = 1;
  147488. pInfo->estimatedCost = 1;
  147489. return SQLITE_OK;
  147490. }
  147491. }
  147492. pInfo->idxNum = 0;
  147493. assert( pInfo->estimatedCost>1000000.0 );
  147494. return SQLITE_OK;
  147495. }
  147496. /*
  147497. ** xOpen - Open a cursor.
  147498. */
  147499. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  147500. Fts3tokCursor *pCsr;
  147501. UNUSED_PARAMETER(pVTab);
  147502. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  147503. if( pCsr==0 ){
  147504. return SQLITE_NOMEM;
  147505. }
  147506. memset(pCsr, 0, sizeof(Fts3tokCursor));
  147507. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  147508. return SQLITE_OK;
  147509. }
  147510. /*
  147511. ** Reset the tokenizer cursor passed as the only argument. As if it had
  147512. ** just been returned by fts3tokOpenMethod().
  147513. */
  147514. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  147515. if( pCsr->pCsr ){
  147516. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  147517. pTab->pMod->xClose(pCsr->pCsr);
  147518. pCsr->pCsr = 0;
  147519. }
  147520. sqlite3_free(pCsr->zInput);
  147521. pCsr->zInput = 0;
  147522. pCsr->zToken = 0;
  147523. pCsr->nToken = 0;
  147524. pCsr->iStart = 0;
  147525. pCsr->iEnd = 0;
  147526. pCsr->iPos = 0;
  147527. pCsr->iRowid = 0;
  147528. }
  147529. /*
  147530. ** xClose - Close a cursor.
  147531. */
  147532. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  147533. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147534. fts3tokResetCursor(pCsr);
  147535. sqlite3_free(pCsr);
  147536. return SQLITE_OK;
  147537. }
  147538. /*
  147539. ** xNext - Advance the cursor to the next row, if any.
  147540. */
  147541. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  147542. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147543. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  147544. int rc; /* Return code */
  147545. pCsr->iRowid++;
  147546. rc = pTab->pMod->xNext(pCsr->pCsr,
  147547. &pCsr->zToken, &pCsr->nToken,
  147548. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  147549. );
  147550. if( rc!=SQLITE_OK ){
  147551. fts3tokResetCursor(pCsr);
  147552. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  147553. }
  147554. return rc;
  147555. }
  147556. /*
  147557. ** xFilter - Initialize a cursor to point at the start of its data.
  147558. */
  147559. static int fts3tokFilterMethod(
  147560. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  147561. int idxNum, /* Strategy index */
  147562. const char *idxStr, /* Unused */
  147563. int nVal, /* Number of elements in apVal */
  147564. sqlite3_value **apVal /* Arguments for the indexing scheme */
  147565. ){
  147566. int rc = SQLITE_ERROR;
  147567. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147568. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  147569. UNUSED_PARAMETER(idxStr);
  147570. UNUSED_PARAMETER(nVal);
  147571. fts3tokResetCursor(pCsr);
  147572. if( idxNum==1 ){
  147573. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  147574. int nByte = sqlite3_value_bytes(apVal[0]);
  147575. pCsr->zInput = sqlite3_malloc(nByte+1);
  147576. if( pCsr->zInput==0 ){
  147577. rc = SQLITE_NOMEM;
  147578. }else{
  147579. memcpy(pCsr->zInput, zByte, nByte);
  147580. pCsr->zInput[nByte] = 0;
  147581. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  147582. if( rc==SQLITE_OK ){
  147583. pCsr->pCsr->pTokenizer = pTab->pTok;
  147584. }
  147585. }
  147586. }
  147587. if( rc!=SQLITE_OK ) return rc;
  147588. return fts3tokNextMethod(pCursor);
  147589. }
  147590. /*
  147591. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  147592. */
  147593. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  147594. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147595. return (pCsr->zToken==0);
  147596. }
  147597. /*
  147598. ** xColumn - Return a column value.
  147599. */
  147600. static int fts3tokColumnMethod(
  147601. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  147602. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  147603. int iCol /* Index of column to read value from */
  147604. ){
  147605. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147606. /* CREATE TABLE x(input, token, start, end, position) */
  147607. switch( iCol ){
  147608. case 0:
  147609. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  147610. break;
  147611. case 1:
  147612. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  147613. break;
  147614. case 2:
  147615. sqlite3_result_int(pCtx, pCsr->iStart);
  147616. break;
  147617. case 3:
  147618. sqlite3_result_int(pCtx, pCsr->iEnd);
  147619. break;
  147620. default:
  147621. assert( iCol==4 );
  147622. sqlite3_result_int(pCtx, pCsr->iPos);
  147623. break;
  147624. }
  147625. return SQLITE_OK;
  147626. }
  147627. /*
  147628. ** xRowid - Return the current rowid for the cursor.
  147629. */
  147630. static int fts3tokRowidMethod(
  147631. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  147632. sqlite_int64 *pRowid /* OUT: Rowid value */
  147633. ){
  147634. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  147635. *pRowid = (sqlite3_int64)pCsr->iRowid;
  147636. return SQLITE_OK;
  147637. }
  147638. /*
  147639. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  147640. ** if successful or an error code if sqlite3_create_module() fails.
  147641. */
  147642. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  147643. static const sqlite3_module fts3tok_module = {
  147644. 0, /* iVersion */
  147645. fts3tokConnectMethod, /* xCreate */
  147646. fts3tokConnectMethod, /* xConnect */
  147647. fts3tokBestIndexMethod, /* xBestIndex */
  147648. fts3tokDisconnectMethod, /* xDisconnect */
  147649. fts3tokDisconnectMethod, /* xDestroy */
  147650. fts3tokOpenMethod, /* xOpen */
  147651. fts3tokCloseMethod, /* xClose */
  147652. fts3tokFilterMethod, /* xFilter */
  147653. fts3tokNextMethod, /* xNext */
  147654. fts3tokEofMethod, /* xEof */
  147655. fts3tokColumnMethod, /* xColumn */
  147656. fts3tokRowidMethod, /* xRowid */
  147657. 0, /* xUpdate */
  147658. 0, /* xBegin */
  147659. 0, /* xSync */
  147660. 0, /* xCommit */
  147661. 0, /* xRollback */
  147662. 0, /* xFindFunction */
  147663. 0, /* xRename */
  147664. 0, /* xSavepoint */
  147665. 0, /* xRelease */
  147666. 0 /* xRollbackTo */
  147667. };
  147668. int rc; /* Return code */
  147669. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  147670. return rc;
  147671. }
  147672. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  147673. /************** End of fts3_tokenize_vtab.c **********************************/
  147674. /************** Begin file fts3_write.c **************************************/
  147675. /*
  147676. ** 2009 Oct 23
  147677. **
  147678. ** The author disclaims copyright to this source code. In place of
  147679. ** a legal notice, here is a blessing:
  147680. **
  147681. ** May you do good and not evil.
  147682. ** May you find forgiveness for yourself and forgive others.
  147683. ** May you share freely, never taking more than you give.
  147684. **
  147685. ******************************************************************************
  147686. **
  147687. ** This file is part of the SQLite FTS3 extension module. Specifically,
  147688. ** this file contains code to insert, update and delete rows from FTS3
  147689. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  147690. ** of the sub-routines used to merge segments are also used by the query
  147691. ** code in fts3.c.
  147692. */
  147693. /* #include "fts3Int.h" */
  147694. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  147695. /* #include <string.h> */
  147696. /* #include <assert.h> */
  147697. /* #include <stdlib.h> */
  147698. #define FTS_MAX_APPENDABLE_HEIGHT 16
  147699. /*
  147700. ** When full-text index nodes are loaded from disk, the buffer that they
  147701. ** are loaded into has the following number of bytes of padding at the end
  147702. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  147703. ** of 920 bytes is allocated for it.
  147704. **
  147705. ** This means that if we have a pointer into a buffer containing node data,
  147706. ** it is always safe to read up to two varints from it without risking an
  147707. ** overread, even if the node data is corrupted.
  147708. */
  147709. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  147710. /*
  147711. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  147712. ** memory incrementally instead of all at once. This can be a big performance
  147713. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  147714. ** method before retrieving all query results (as may happen, for example,
  147715. ** if a query has a LIMIT clause).
  147716. **
  147717. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  147718. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  147719. ** The code is written so that the hard lower-limit for each of these values
  147720. ** is 1. Clearly such small values would be inefficient, but can be useful
  147721. ** for testing purposes.
  147722. **
  147723. ** If this module is built with SQLITE_TEST defined, these constants may
  147724. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  147725. ** a Tcl interface to read and write the values.
  147726. */
  147727. #ifdef SQLITE_TEST
  147728. int test_fts3_node_chunksize = (4*1024);
  147729. int test_fts3_node_chunk_threshold = (4*1024)*4;
  147730. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  147731. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  147732. #else
  147733. # define FTS3_NODE_CHUNKSIZE (4*1024)
  147734. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  147735. #endif
  147736. /*
  147737. ** The two values that may be meaningfully bound to the :1 parameter in
  147738. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  147739. */
  147740. #define FTS_STAT_DOCTOTAL 0
  147741. #define FTS_STAT_INCRMERGEHINT 1
  147742. #define FTS_STAT_AUTOINCRMERGE 2
  147743. /*
  147744. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  147745. ** and incremental merge operation that takes place. This is used for
  147746. ** debugging FTS only, it should not usually be turned on in production
  147747. ** systems.
  147748. */
  147749. #ifdef FTS3_LOG_MERGES
  147750. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  147751. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  147752. }
  147753. #else
  147754. #define fts3LogMerge(x, y)
  147755. #endif
  147756. typedef struct PendingList PendingList;
  147757. typedef struct SegmentNode SegmentNode;
  147758. typedef struct SegmentWriter SegmentWriter;
  147759. /*
  147760. ** An instance of the following data structure is used to build doclists
  147761. ** incrementally. See function fts3PendingListAppend() for details.
  147762. */
  147763. struct PendingList {
  147764. int nData;
  147765. char *aData;
  147766. int nSpace;
  147767. sqlite3_int64 iLastDocid;
  147768. sqlite3_int64 iLastCol;
  147769. sqlite3_int64 iLastPos;
  147770. };
  147771. /*
  147772. ** Each cursor has a (possibly empty) linked list of the following objects.
  147773. */
  147774. struct Fts3DeferredToken {
  147775. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  147776. int iCol; /* Column token must occur in */
  147777. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  147778. PendingList *pList; /* Doclist is assembled here */
  147779. };
  147780. /*
  147781. ** An instance of this structure is used to iterate through the terms on
  147782. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  147783. ** this structure are only manipulated by code in this file, opaque handles
  147784. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  147785. ** terms when querying the full-text index. See functions:
  147786. **
  147787. ** sqlite3Fts3SegReaderNew()
  147788. ** sqlite3Fts3SegReaderFree()
  147789. ** sqlite3Fts3SegReaderIterate()
  147790. **
  147791. ** Methods used to manipulate Fts3SegReader structures:
  147792. **
  147793. ** fts3SegReaderNext()
  147794. ** fts3SegReaderFirstDocid()
  147795. ** fts3SegReaderNextDocid()
  147796. */
  147797. struct Fts3SegReader {
  147798. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  147799. u8 bLookup; /* True for a lookup only */
  147800. u8 rootOnly; /* True for a root-only reader */
  147801. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  147802. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  147803. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  147804. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  147805. char *aNode; /* Pointer to node data (or NULL) */
  147806. int nNode; /* Size of buffer at aNode (or 0) */
  147807. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  147808. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  147809. Fts3HashElem **ppNextElem;
  147810. /* Variables set by fts3SegReaderNext(). These may be read directly
  147811. ** by the caller. They are valid from the time SegmentReaderNew() returns
  147812. ** until SegmentReaderNext() returns something other than SQLITE_OK
  147813. ** (i.e. SQLITE_DONE).
  147814. */
  147815. int nTerm; /* Number of bytes in current term */
  147816. char *zTerm; /* Pointer to current term */
  147817. int nTermAlloc; /* Allocated size of zTerm buffer */
  147818. char *aDoclist; /* Pointer to doclist of current entry */
  147819. int nDoclist; /* Size of doclist in current entry */
  147820. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  147821. ** through the current doclist (aDoclist/nDoclist).
  147822. */
  147823. char *pOffsetList;
  147824. int nOffsetList; /* For descending pending seg-readers only */
  147825. sqlite3_int64 iDocid;
  147826. };
  147827. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  147828. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  147829. /*
  147830. ** An instance of this structure is used to create a segment b-tree in the
  147831. ** database. The internal details of this type are only accessed by the
  147832. ** following functions:
  147833. **
  147834. ** fts3SegWriterAdd()
  147835. ** fts3SegWriterFlush()
  147836. ** fts3SegWriterFree()
  147837. */
  147838. struct SegmentWriter {
  147839. SegmentNode *pTree; /* Pointer to interior tree structure */
  147840. sqlite3_int64 iFirst; /* First slot in %_segments written */
  147841. sqlite3_int64 iFree; /* Next free slot in %_segments */
  147842. char *zTerm; /* Pointer to previous term buffer */
  147843. int nTerm; /* Number of bytes in zTerm */
  147844. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  147845. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  147846. int nSize; /* Size of allocation at aData */
  147847. int nData; /* Bytes of data in aData */
  147848. char *aData; /* Pointer to block from malloc() */
  147849. i64 nLeafData; /* Number of bytes of leaf data written */
  147850. };
  147851. /*
  147852. ** Type SegmentNode is used by the following three functions to create
  147853. ** the interior part of the segment b+-tree structures (everything except
  147854. ** the leaf nodes). These functions and type are only ever used by code
  147855. ** within the fts3SegWriterXXX() family of functions described above.
  147856. **
  147857. ** fts3NodeAddTerm()
  147858. ** fts3NodeWrite()
  147859. ** fts3NodeFree()
  147860. **
  147861. ** When a b+tree is written to the database (either as a result of a merge
  147862. ** or the pending-terms table being flushed), leaves are written into the
  147863. ** database file as soon as they are completely populated. The interior of
  147864. ** the tree is assembled in memory and written out only once all leaves have
  147865. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  147866. ** very large, meaning that the interior of the tree consumes relatively
  147867. ** little memory.
  147868. */
  147869. struct SegmentNode {
  147870. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  147871. SegmentNode *pRight; /* Pointer to right-sibling */
  147872. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  147873. int nEntry; /* Number of terms written to node so far */
  147874. char *zTerm; /* Pointer to previous term buffer */
  147875. int nTerm; /* Number of bytes in zTerm */
  147876. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  147877. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  147878. int nData; /* Bytes of valid data so far */
  147879. char *aData; /* Node data */
  147880. };
  147881. /*
  147882. ** Valid values for the second argument to fts3SqlStmt().
  147883. */
  147884. #define SQL_DELETE_CONTENT 0
  147885. #define SQL_IS_EMPTY 1
  147886. #define SQL_DELETE_ALL_CONTENT 2
  147887. #define SQL_DELETE_ALL_SEGMENTS 3
  147888. #define SQL_DELETE_ALL_SEGDIR 4
  147889. #define SQL_DELETE_ALL_DOCSIZE 5
  147890. #define SQL_DELETE_ALL_STAT 6
  147891. #define SQL_SELECT_CONTENT_BY_ROWID 7
  147892. #define SQL_NEXT_SEGMENT_INDEX 8
  147893. #define SQL_INSERT_SEGMENTS 9
  147894. #define SQL_NEXT_SEGMENTS_ID 10
  147895. #define SQL_INSERT_SEGDIR 11
  147896. #define SQL_SELECT_LEVEL 12
  147897. #define SQL_SELECT_LEVEL_RANGE 13
  147898. #define SQL_SELECT_LEVEL_COUNT 14
  147899. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  147900. #define SQL_DELETE_SEGDIR_LEVEL 16
  147901. #define SQL_DELETE_SEGMENTS_RANGE 17
  147902. #define SQL_CONTENT_INSERT 18
  147903. #define SQL_DELETE_DOCSIZE 19
  147904. #define SQL_REPLACE_DOCSIZE 20
  147905. #define SQL_SELECT_DOCSIZE 21
  147906. #define SQL_SELECT_STAT 22
  147907. #define SQL_REPLACE_STAT 23
  147908. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  147909. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  147910. #define SQL_DELETE_SEGDIR_RANGE 26
  147911. #define SQL_SELECT_ALL_LANGID 27
  147912. #define SQL_FIND_MERGE_LEVEL 28
  147913. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  147914. #define SQL_DELETE_SEGDIR_ENTRY 30
  147915. #define SQL_SHIFT_SEGDIR_ENTRY 31
  147916. #define SQL_SELECT_SEGDIR 32
  147917. #define SQL_CHOMP_SEGDIR 33
  147918. #define SQL_SEGMENT_IS_APPENDABLE 34
  147919. #define SQL_SELECT_INDEXES 35
  147920. #define SQL_SELECT_MXLEVEL 36
  147921. #define SQL_SELECT_LEVEL_RANGE2 37
  147922. #define SQL_UPDATE_LEVEL_IDX 38
  147923. #define SQL_UPDATE_LEVEL 39
  147924. /*
  147925. ** This function is used to obtain an SQLite prepared statement handle
  147926. ** for the statement identified by the second argument. If successful,
  147927. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  147928. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  147929. **
  147930. ** If argument apVal is not NULL, then it must point to an array with
  147931. ** at least as many entries as the requested statement has bound
  147932. ** parameters. The values are bound to the statements parameters before
  147933. ** returning.
  147934. */
  147935. static int fts3SqlStmt(
  147936. Fts3Table *p, /* Virtual table handle */
  147937. int eStmt, /* One of the SQL_XXX constants above */
  147938. sqlite3_stmt **pp, /* OUT: Statement handle */
  147939. sqlite3_value **apVal /* Values to bind to statement */
  147940. ){
  147941. const char *azSql[] = {
  147942. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  147943. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  147944. /* 2 */ "DELETE FROM %Q.'%q_content'",
  147945. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  147946. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  147947. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  147948. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  147949. /* 7 */ "SELECT %s WHERE rowid=?",
  147950. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  147951. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  147952. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  147953. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  147954. /* Return segments in order from oldest to newest.*/
  147955. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  147956. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  147957. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  147958. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  147959. "ORDER BY level DESC, idx ASC",
  147960. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  147961. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  147962. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  147963. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  147964. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  147965. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  147966. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  147967. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  147968. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  147969. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  147970. /* 24 */ "",
  147971. /* 25 */ "",
  147972. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  147973. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  147974. /* This statement is used to determine which level to read the input from
  147975. ** when performing an incremental merge. It returns the absolute level number
  147976. ** of the oldest level in the db that contains at least ? segments. Or,
  147977. ** if no level in the FTS index contains more than ? segments, the statement
  147978. ** returns zero rows. */
  147979. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  147980. " GROUP BY level HAVING cnt>=?"
  147981. " ORDER BY (level %% 1024) ASC LIMIT 1",
  147982. /* Estimate the upper limit on the number of leaf nodes in a new segment
  147983. ** created by merging the oldest :2 segments from absolute level :1. See
  147984. ** function sqlite3Fts3Incrmerge() for details. */
  147985. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  147986. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  147987. /* SQL_DELETE_SEGDIR_ENTRY
  147988. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  147989. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  147990. /* SQL_SHIFT_SEGDIR_ENTRY
  147991. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  147992. ** to :1. */
  147993. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  147994. /* SQL_SELECT_SEGDIR
  147995. ** Read a single entry from the %_segdir table. The entry from absolute
  147996. ** level :1 with index value :2. */
  147997. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  147998. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  147999. /* SQL_CHOMP_SEGDIR
  148000. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  148001. ** entry located on absolute level :3 with index :4. */
  148002. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  148003. "WHERE level = ? AND idx = ?",
  148004. /* SQL_SEGMENT_IS_APPENDABLE
  148005. ** Return a single row if the segment with end_block=? is appendable. Or
  148006. ** no rows otherwise. */
  148007. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  148008. /* SQL_SELECT_INDEXES
  148009. ** Return the list of valid segment indexes for absolute level ? */
  148010. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  148011. /* SQL_SELECT_MXLEVEL
  148012. ** Return the largest relative level in the FTS index or indexes. */
  148013. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  148014. /* Return segments in order from oldest to newest.*/
  148015. /* 37 */ "SELECT level, idx, end_block "
  148016. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  148017. "ORDER BY level DESC, idx ASC",
  148018. /* Update statements used while promoting segments */
  148019. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  148020. "WHERE level=? AND idx=?",
  148021. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  148022. };
  148023. int rc = SQLITE_OK;
  148024. sqlite3_stmt *pStmt;
  148025. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  148026. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  148027. pStmt = p->aStmt[eStmt];
  148028. if( !pStmt ){
  148029. char *zSql;
  148030. if( eStmt==SQL_CONTENT_INSERT ){
  148031. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  148032. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  148033. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  148034. }else{
  148035. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  148036. }
  148037. if( !zSql ){
  148038. rc = SQLITE_NOMEM;
  148039. }else{
  148040. rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  148041. &pStmt, NULL);
  148042. sqlite3_free(zSql);
  148043. assert( rc==SQLITE_OK || pStmt==0 );
  148044. p->aStmt[eStmt] = pStmt;
  148045. }
  148046. }
  148047. if( apVal ){
  148048. int i;
  148049. int nParam = sqlite3_bind_parameter_count(pStmt);
  148050. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  148051. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  148052. }
  148053. }
  148054. *pp = pStmt;
  148055. return rc;
  148056. }
  148057. static int fts3SelectDocsize(
  148058. Fts3Table *pTab, /* FTS3 table handle */
  148059. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  148060. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  148061. ){
  148062. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  148063. int rc; /* Return code */
  148064. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  148065. if( rc==SQLITE_OK ){
  148066. sqlite3_bind_int64(pStmt, 1, iDocid);
  148067. rc = sqlite3_step(pStmt);
  148068. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  148069. rc = sqlite3_reset(pStmt);
  148070. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  148071. pStmt = 0;
  148072. }else{
  148073. rc = SQLITE_OK;
  148074. }
  148075. }
  148076. *ppStmt = pStmt;
  148077. return rc;
  148078. }
  148079. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  148080. Fts3Table *pTab, /* Fts3 table handle */
  148081. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  148082. ){
  148083. sqlite3_stmt *pStmt = 0;
  148084. int rc;
  148085. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  148086. if( rc==SQLITE_OK ){
  148087. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  148088. if( sqlite3_step(pStmt)!=SQLITE_ROW
  148089. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  148090. ){
  148091. rc = sqlite3_reset(pStmt);
  148092. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  148093. pStmt = 0;
  148094. }
  148095. }
  148096. *ppStmt = pStmt;
  148097. return rc;
  148098. }
  148099. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  148100. Fts3Table *pTab, /* Fts3 table handle */
  148101. sqlite3_int64 iDocid, /* Docid to read size data for */
  148102. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  148103. ){
  148104. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  148105. }
  148106. /*
  148107. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  148108. ** array apVal[] to the SQL statement identified by eStmt, the statement
  148109. ** is executed.
  148110. **
  148111. ** Returns SQLITE_OK if the statement is successfully executed, or an
  148112. ** SQLite error code otherwise.
  148113. */
  148114. static void fts3SqlExec(
  148115. int *pRC, /* Result code */
  148116. Fts3Table *p, /* The FTS3 table */
  148117. int eStmt, /* Index of statement to evaluate */
  148118. sqlite3_value **apVal /* Parameters to bind */
  148119. ){
  148120. sqlite3_stmt *pStmt;
  148121. int rc;
  148122. if( *pRC ) return;
  148123. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  148124. if( rc==SQLITE_OK ){
  148125. sqlite3_step(pStmt);
  148126. rc = sqlite3_reset(pStmt);
  148127. }
  148128. *pRC = rc;
  148129. }
  148130. /*
  148131. ** This function ensures that the caller has obtained an exclusive
  148132. ** shared-cache table-lock on the %_segdir table. This is required before
  148133. ** writing data to the fts3 table. If this lock is not acquired first, then
  148134. ** the caller may end up attempting to take this lock as part of committing
  148135. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  148136. ** LOCKED_SHAREDCACHEto a COMMIT command.
  148137. **
  148138. ** It is best to avoid this because if FTS3 returns any error when
  148139. ** committing a transaction, the whole transaction will be rolled back.
  148140. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  148141. ** It can still happen if the user locks the underlying tables directly
  148142. ** instead of accessing them via FTS.
  148143. */
  148144. static int fts3Writelock(Fts3Table *p){
  148145. int rc = SQLITE_OK;
  148146. if( p->nPendingData==0 ){
  148147. sqlite3_stmt *pStmt;
  148148. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  148149. if( rc==SQLITE_OK ){
  148150. sqlite3_bind_null(pStmt, 1);
  148151. sqlite3_step(pStmt);
  148152. rc = sqlite3_reset(pStmt);
  148153. }
  148154. }
  148155. return rc;
  148156. }
  148157. /*
  148158. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  148159. ** Within each language id, a separate index is maintained to store the
  148160. ** document terms, and each configured prefix size (configured the FTS
  148161. ** "prefix=" option). And each index consists of multiple levels ("relative
  148162. ** levels").
  148163. **
  148164. ** All three of these values (the language id, the specific index and the
  148165. ** level within the index) are encoded in 64-bit integer values stored
  148166. ** in the %_segdir table on disk. This function is used to convert three
  148167. ** separate component values into the single 64-bit integer value that
  148168. ** can be used to query the %_segdir table.
  148169. **
  148170. ** Specifically, each language-id/index combination is allocated 1024
  148171. ** 64-bit integer level values ("absolute levels"). The main terms index
  148172. ** for language-id 0 is allocate values 0-1023. The first prefix index
  148173. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  148174. ** Language 1 indexes are allocated immediately following language 0.
  148175. **
  148176. ** So, for a system with nPrefix prefix indexes configured, the block of
  148177. ** absolute levels that corresponds to language-id iLangid and index
  148178. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  148179. */
  148180. static sqlite3_int64 getAbsoluteLevel(
  148181. Fts3Table *p, /* FTS3 table handle */
  148182. int iLangid, /* Language id */
  148183. int iIndex, /* Index in p->aIndex[] */
  148184. int iLevel /* Level of segments */
  148185. ){
  148186. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  148187. assert( iLangid>=0 );
  148188. assert( p->nIndex>0 );
  148189. assert( iIndex>=0 && iIndex<p->nIndex );
  148190. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  148191. return iBase + iLevel;
  148192. }
  148193. /*
  148194. ** Set *ppStmt to a statement handle that may be used to iterate through
  148195. ** all rows in the %_segdir table, from oldest to newest. If successful,
  148196. ** return SQLITE_OK. If an error occurs while preparing the statement,
  148197. ** return an SQLite error code.
  148198. **
  148199. ** There is only ever one instance of this SQL statement compiled for
  148200. ** each FTS3 table.
  148201. **
  148202. ** The statement returns the following columns from the %_segdir table:
  148203. **
  148204. ** 0: idx
  148205. ** 1: start_block
  148206. ** 2: leaves_end_block
  148207. ** 3: end_block
  148208. ** 4: root
  148209. */
  148210. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  148211. Fts3Table *p, /* FTS3 table */
  148212. int iLangid, /* Language being queried */
  148213. int iIndex, /* Index for p->aIndex[] */
  148214. int iLevel, /* Level to select (relative level) */
  148215. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  148216. ){
  148217. int rc;
  148218. sqlite3_stmt *pStmt = 0;
  148219. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  148220. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  148221. assert( iIndex>=0 && iIndex<p->nIndex );
  148222. if( iLevel<0 ){
  148223. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  148224. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  148225. if( rc==SQLITE_OK ){
  148226. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  148227. sqlite3_bind_int64(pStmt, 2,
  148228. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  148229. );
  148230. }
  148231. }else{
  148232. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  148233. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  148234. if( rc==SQLITE_OK ){
  148235. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  148236. }
  148237. }
  148238. *ppStmt = pStmt;
  148239. return rc;
  148240. }
  148241. /*
  148242. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  148243. ** if successful, or an SQLite error code otherwise.
  148244. **
  148245. ** This function also serves to allocate the PendingList structure itself.
  148246. ** For example, to create a new PendingList structure containing two
  148247. ** varints:
  148248. **
  148249. ** PendingList *p = 0;
  148250. ** fts3PendingListAppendVarint(&p, 1);
  148251. ** fts3PendingListAppendVarint(&p, 2);
  148252. */
  148253. static int fts3PendingListAppendVarint(
  148254. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  148255. sqlite3_int64 i /* Value to append to data */
  148256. ){
  148257. PendingList *p = *pp;
  148258. /* Allocate or grow the PendingList as required. */
  148259. if( !p ){
  148260. p = sqlite3_malloc(sizeof(*p) + 100);
  148261. if( !p ){
  148262. return SQLITE_NOMEM;
  148263. }
  148264. p->nSpace = 100;
  148265. p->aData = (char *)&p[1];
  148266. p->nData = 0;
  148267. }
  148268. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  148269. int nNew = p->nSpace * 2;
  148270. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  148271. if( !p ){
  148272. sqlite3_free(*pp);
  148273. *pp = 0;
  148274. return SQLITE_NOMEM;
  148275. }
  148276. p->nSpace = nNew;
  148277. p->aData = (char *)&p[1];
  148278. }
  148279. /* Append the new serialized varint to the end of the list. */
  148280. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  148281. p->aData[p->nData] = '\0';
  148282. *pp = p;
  148283. return SQLITE_OK;
  148284. }
  148285. /*
  148286. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  148287. ** is returned if the structure is sqlite3_realloced as part of adding
  148288. ** the entry. Otherwise, zero.
  148289. **
  148290. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  148291. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  148292. ** it is set to SQLITE_OK.
  148293. */
  148294. static int fts3PendingListAppend(
  148295. PendingList **pp, /* IN/OUT: PendingList structure */
  148296. sqlite3_int64 iDocid, /* Docid for entry to add */
  148297. sqlite3_int64 iCol, /* Column for entry to add */
  148298. sqlite3_int64 iPos, /* Position of term for entry to add */
  148299. int *pRc /* OUT: Return code */
  148300. ){
  148301. PendingList *p = *pp;
  148302. int rc = SQLITE_OK;
  148303. assert( !p || p->iLastDocid<=iDocid );
  148304. if( !p || p->iLastDocid!=iDocid ){
  148305. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  148306. if( p ){
  148307. assert( p->nData<p->nSpace );
  148308. assert( p->aData[p->nData]==0 );
  148309. p->nData++;
  148310. }
  148311. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  148312. goto pendinglistappend_out;
  148313. }
  148314. p->iLastCol = -1;
  148315. p->iLastPos = 0;
  148316. p->iLastDocid = iDocid;
  148317. }
  148318. if( iCol>0 && p->iLastCol!=iCol ){
  148319. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  148320. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  148321. ){
  148322. goto pendinglistappend_out;
  148323. }
  148324. p->iLastCol = iCol;
  148325. p->iLastPos = 0;
  148326. }
  148327. if( iCol>=0 ){
  148328. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  148329. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  148330. if( rc==SQLITE_OK ){
  148331. p->iLastPos = iPos;
  148332. }
  148333. }
  148334. pendinglistappend_out:
  148335. *pRc = rc;
  148336. if( p!=*pp ){
  148337. *pp = p;
  148338. return 1;
  148339. }
  148340. return 0;
  148341. }
  148342. /*
  148343. ** Free a PendingList object allocated by fts3PendingListAppend().
  148344. */
  148345. static void fts3PendingListDelete(PendingList *pList){
  148346. sqlite3_free(pList);
  148347. }
  148348. /*
  148349. ** Add an entry to one of the pending-terms hash tables.
  148350. */
  148351. static int fts3PendingTermsAddOne(
  148352. Fts3Table *p,
  148353. int iCol,
  148354. int iPos,
  148355. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  148356. const char *zToken,
  148357. int nToken
  148358. ){
  148359. PendingList *pList;
  148360. int rc = SQLITE_OK;
  148361. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  148362. if( pList ){
  148363. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  148364. }
  148365. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  148366. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  148367. /* Malloc failed while inserting the new entry. This can only
  148368. ** happen if there was no previous entry for this token.
  148369. */
  148370. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  148371. sqlite3_free(pList);
  148372. rc = SQLITE_NOMEM;
  148373. }
  148374. }
  148375. if( rc==SQLITE_OK ){
  148376. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  148377. }
  148378. return rc;
  148379. }
  148380. /*
  148381. ** Tokenize the nul-terminated string zText and add all tokens to the
  148382. ** pending-terms hash-table. The docid used is that currently stored in
  148383. ** p->iPrevDocid, and the column is specified by argument iCol.
  148384. **
  148385. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  148386. */
  148387. static int fts3PendingTermsAdd(
  148388. Fts3Table *p, /* Table into which text will be inserted */
  148389. int iLangid, /* Language id to use */
  148390. const char *zText, /* Text of document to be inserted */
  148391. int iCol, /* Column into which text is being inserted */
  148392. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  148393. ){
  148394. int rc;
  148395. int iStart = 0;
  148396. int iEnd = 0;
  148397. int iPos = 0;
  148398. int nWord = 0;
  148399. char const *zToken;
  148400. int nToken = 0;
  148401. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  148402. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  148403. sqlite3_tokenizer_cursor *pCsr;
  148404. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  148405. const char**,int*,int*,int*,int*);
  148406. assert( pTokenizer && pModule );
  148407. /* If the user has inserted a NULL value, this function may be called with
  148408. ** zText==0. In this case, add zero token entries to the hash table and
  148409. ** return early. */
  148410. if( zText==0 ){
  148411. *pnWord = 0;
  148412. return SQLITE_OK;
  148413. }
  148414. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  148415. if( rc!=SQLITE_OK ){
  148416. return rc;
  148417. }
  148418. xNext = pModule->xNext;
  148419. while( SQLITE_OK==rc
  148420. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  148421. ){
  148422. int i;
  148423. if( iPos>=nWord ) nWord = iPos+1;
  148424. /* Positions cannot be negative; we use -1 as a terminator internally.
  148425. ** Tokens must have a non-zero length.
  148426. */
  148427. if( iPos<0 || !zToken || nToken<=0 ){
  148428. rc = SQLITE_ERROR;
  148429. break;
  148430. }
  148431. /* Add the term to the terms index */
  148432. rc = fts3PendingTermsAddOne(
  148433. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  148434. );
  148435. /* Add the term to each of the prefix indexes that it is not too
  148436. ** short for. */
  148437. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  148438. struct Fts3Index *pIndex = &p->aIndex[i];
  148439. if( nToken<pIndex->nPrefix ) continue;
  148440. rc = fts3PendingTermsAddOne(
  148441. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  148442. );
  148443. }
  148444. }
  148445. pModule->xClose(pCsr);
  148446. *pnWord += nWord;
  148447. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  148448. }
  148449. /*
  148450. ** Calling this function indicates that subsequent calls to
  148451. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  148452. ** contents of the document with docid iDocid.
  148453. */
  148454. static int fts3PendingTermsDocid(
  148455. Fts3Table *p, /* Full-text table handle */
  148456. int bDelete, /* True if this op is a delete */
  148457. int iLangid, /* Language id of row being written */
  148458. sqlite_int64 iDocid /* Docid of row being written */
  148459. ){
  148460. assert( iLangid>=0 );
  148461. assert( bDelete==1 || bDelete==0 );
  148462. /* TODO(shess) Explore whether partially flushing the buffer on
  148463. ** forced-flush would provide better performance. I suspect that if
  148464. ** we ordered the doclists by size and flushed the largest until the
  148465. ** buffer was half empty, that would let the less frequent terms
  148466. ** generate longer doclists.
  148467. */
  148468. if( iDocid<p->iPrevDocid
  148469. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  148470. || p->iPrevLangid!=iLangid
  148471. || p->nPendingData>p->nMaxPendingData
  148472. ){
  148473. int rc = sqlite3Fts3PendingTermsFlush(p);
  148474. if( rc!=SQLITE_OK ) return rc;
  148475. }
  148476. p->iPrevDocid = iDocid;
  148477. p->iPrevLangid = iLangid;
  148478. p->bPrevDelete = bDelete;
  148479. return SQLITE_OK;
  148480. }
  148481. /*
  148482. ** Discard the contents of the pending-terms hash tables.
  148483. */
  148484. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  148485. int i;
  148486. for(i=0; i<p->nIndex; i++){
  148487. Fts3HashElem *pElem;
  148488. Fts3Hash *pHash = &p->aIndex[i].hPending;
  148489. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  148490. PendingList *pList = (PendingList *)fts3HashData(pElem);
  148491. fts3PendingListDelete(pList);
  148492. }
  148493. fts3HashClear(pHash);
  148494. }
  148495. p->nPendingData = 0;
  148496. }
  148497. /*
  148498. ** This function is called by the xUpdate() method as part of an INSERT
  148499. ** operation. It adds entries for each term in the new record to the
  148500. ** pendingTerms hash table.
  148501. **
  148502. ** Argument apVal is the same as the similarly named argument passed to
  148503. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  148504. */
  148505. static int fts3InsertTerms(
  148506. Fts3Table *p,
  148507. int iLangid,
  148508. sqlite3_value **apVal,
  148509. u32 *aSz
  148510. ){
  148511. int i; /* Iterator variable */
  148512. for(i=2; i<p->nColumn+2; i++){
  148513. int iCol = i-2;
  148514. if( p->abNotindexed[iCol]==0 ){
  148515. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  148516. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  148517. if( rc!=SQLITE_OK ){
  148518. return rc;
  148519. }
  148520. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  148521. }
  148522. }
  148523. return SQLITE_OK;
  148524. }
  148525. /*
  148526. ** This function is called by the xUpdate() method for an INSERT operation.
  148527. ** The apVal parameter is passed a copy of the apVal argument passed by
  148528. ** SQLite to the xUpdate() method. i.e:
  148529. **
  148530. ** apVal[0] Not used for INSERT.
  148531. ** apVal[1] rowid
  148532. ** apVal[2] Left-most user-defined column
  148533. ** ...
  148534. ** apVal[p->nColumn+1] Right-most user-defined column
  148535. ** apVal[p->nColumn+2] Hidden column with same name as table
  148536. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  148537. ** apVal[p->nColumn+4] Hidden languageid column
  148538. */
  148539. static int fts3InsertData(
  148540. Fts3Table *p, /* Full-text table */
  148541. sqlite3_value **apVal, /* Array of values to insert */
  148542. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  148543. ){
  148544. int rc; /* Return code */
  148545. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  148546. if( p->zContentTbl ){
  148547. sqlite3_value *pRowid = apVal[p->nColumn+3];
  148548. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  148549. pRowid = apVal[1];
  148550. }
  148551. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  148552. return SQLITE_CONSTRAINT;
  148553. }
  148554. *piDocid = sqlite3_value_int64(pRowid);
  148555. return SQLITE_OK;
  148556. }
  148557. /* Locate the statement handle used to insert data into the %_content
  148558. ** table. The SQL for this statement is:
  148559. **
  148560. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  148561. **
  148562. ** The statement features N '?' variables, where N is the number of user
  148563. ** defined columns in the FTS3 table, plus one for the docid field.
  148564. */
  148565. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  148566. if( rc==SQLITE_OK && p->zLanguageid ){
  148567. rc = sqlite3_bind_int(
  148568. pContentInsert, p->nColumn+2,
  148569. sqlite3_value_int(apVal[p->nColumn+4])
  148570. );
  148571. }
  148572. if( rc!=SQLITE_OK ) return rc;
  148573. /* There is a quirk here. The users INSERT statement may have specified
  148574. ** a value for the "rowid" field, for the "docid" field, or for both.
  148575. ** Which is a problem, since "rowid" and "docid" are aliases for the
  148576. ** same value. For example:
  148577. **
  148578. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  148579. **
  148580. ** In FTS3, this is an error. It is an error to specify non-NULL values
  148581. ** for both docid and some other rowid alias.
  148582. */
  148583. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  148584. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  148585. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  148586. ){
  148587. /* A rowid/docid conflict. */
  148588. return SQLITE_ERROR;
  148589. }
  148590. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  148591. if( rc!=SQLITE_OK ) return rc;
  148592. }
  148593. /* Execute the statement to insert the record. Set *piDocid to the
  148594. ** new docid value.
  148595. */
  148596. sqlite3_step(pContentInsert);
  148597. rc = sqlite3_reset(pContentInsert);
  148598. *piDocid = sqlite3_last_insert_rowid(p->db);
  148599. return rc;
  148600. }
  148601. /*
  148602. ** Remove all data from the FTS3 table. Clear the hash table containing
  148603. ** pending terms.
  148604. */
  148605. static int fts3DeleteAll(Fts3Table *p, int bContent){
  148606. int rc = SQLITE_OK; /* Return code */
  148607. /* Discard the contents of the pending-terms hash table. */
  148608. sqlite3Fts3PendingTermsClear(p);
  148609. /* Delete everything from the shadow tables. Except, leave %_content as
  148610. ** is if bContent is false. */
  148611. assert( p->zContentTbl==0 || bContent==0 );
  148612. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  148613. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  148614. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  148615. if( p->bHasDocsize ){
  148616. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  148617. }
  148618. if( p->bHasStat ){
  148619. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  148620. }
  148621. return rc;
  148622. }
  148623. /*
  148624. **
  148625. */
  148626. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  148627. int iLangid = 0;
  148628. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  148629. return iLangid;
  148630. }
  148631. /*
  148632. ** The first element in the apVal[] array is assumed to contain the docid
  148633. ** (an integer) of a row about to be deleted. Remove all terms from the
  148634. ** full-text index.
  148635. */
  148636. static void fts3DeleteTerms(
  148637. int *pRC, /* Result code */
  148638. Fts3Table *p, /* The FTS table to delete from */
  148639. sqlite3_value *pRowid, /* The docid to be deleted */
  148640. u32 *aSz, /* Sizes of deleted document written here */
  148641. int *pbFound /* OUT: Set to true if row really does exist */
  148642. ){
  148643. int rc;
  148644. sqlite3_stmt *pSelect;
  148645. assert( *pbFound==0 );
  148646. if( *pRC ) return;
  148647. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  148648. if( rc==SQLITE_OK ){
  148649. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  148650. int i;
  148651. int iLangid = langidFromSelect(p, pSelect);
  148652. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  148653. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  148654. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  148655. int iCol = i-1;
  148656. if( p->abNotindexed[iCol]==0 ){
  148657. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  148658. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  148659. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  148660. }
  148661. }
  148662. if( rc!=SQLITE_OK ){
  148663. sqlite3_reset(pSelect);
  148664. *pRC = rc;
  148665. return;
  148666. }
  148667. *pbFound = 1;
  148668. }
  148669. rc = sqlite3_reset(pSelect);
  148670. }else{
  148671. sqlite3_reset(pSelect);
  148672. }
  148673. *pRC = rc;
  148674. }
  148675. /*
  148676. ** Forward declaration to account for the circular dependency between
  148677. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  148678. */
  148679. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  148680. /*
  148681. ** This function allocates a new level iLevel index in the segdir table.
  148682. ** Usually, indexes are allocated within a level sequentially starting
  148683. ** with 0, so the allocated index is one greater than the value returned
  148684. ** by:
  148685. **
  148686. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  148687. **
  148688. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  148689. ** level, they are merged into a single level (iLevel+1) segment and the
  148690. ** allocated index is 0.
  148691. **
  148692. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  148693. ** returned. Otherwise, an SQLite error code is returned.
  148694. */
  148695. static int fts3AllocateSegdirIdx(
  148696. Fts3Table *p,
  148697. int iLangid, /* Language id */
  148698. int iIndex, /* Index for p->aIndex */
  148699. int iLevel,
  148700. int *piIdx
  148701. ){
  148702. int rc; /* Return Code */
  148703. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  148704. int iNext = 0; /* Result of query pNextIdx */
  148705. assert( iLangid>=0 );
  148706. assert( p->nIndex>=1 );
  148707. /* Set variable iNext to the next available segdir index at level iLevel. */
  148708. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  148709. if( rc==SQLITE_OK ){
  148710. sqlite3_bind_int64(
  148711. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  148712. );
  148713. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  148714. iNext = sqlite3_column_int(pNextIdx, 0);
  148715. }
  148716. rc = sqlite3_reset(pNextIdx);
  148717. }
  148718. if( rc==SQLITE_OK ){
  148719. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  148720. ** full, merge all segments in level iLevel into a single iLevel+1
  148721. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  148722. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  148723. */
  148724. if( iNext>=FTS3_MERGE_COUNT ){
  148725. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  148726. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  148727. *piIdx = 0;
  148728. }else{
  148729. *piIdx = iNext;
  148730. }
  148731. }
  148732. return rc;
  148733. }
  148734. /*
  148735. ** The %_segments table is declared as follows:
  148736. **
  148737. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  148738. **
  148739. ** This function reads data from a single row of the %_segments table. The
  148740. ** specific row is identified by the iBlockid parameter. If paBlob is not
  148741. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  148742. ** with the contents of the blob stored in the "block" column of the
  148743. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  148744. ** to the size of the blob in bytes before returning.
  148745. **
  148746. ** If an error occurs, or the table does not contain the specified row,
  148747. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  148748. ** paBlob is non-NULL, then it is the responsibility of the caller to
  148749. ** eventually free the returned buffer.
  148750. **
  148751. ** This function may leave an open sqlite3_blob* handle in the
  148752. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  148753. ** to this function. The handle may be closed by calling the
  148754. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  148755. ** performance improvement, but the blob handle should always be closed
  148756. ** before control is returned to the user (to prevent a lock being held
  148757. ** on the database file for longer than necessary). Thus, any virtual table
  148758. ** method (xFilter etc.) that may directly or indirectly call this function
  148759. ** must call sqlite3Fts3SegmentsClose() before returning.
  148760. */
  148761. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  148762. Fts3Table *p, /* FTS3 table handle */
  148763. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  148764. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  148765. int *pnBlob, /* OUT: Size of blob data */
  148766. int *pnLoad /* OUT: Bytes actually loaded */
  148767. ){
  148768. int rc; /* Return code */
  148769. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  148770. assert( pnBlob );
  148771. if( p->pSegments ){
  148772. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  148773. }else{
  148774. if( 0==p->zSegmentsTbl ){
  148775. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  148776. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  148777. }
  148778. rc = sqlite3_blob_open(
  148779. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  148780. );
  148781. }
  148782. if( rc==SQLITE_OK ){
  148783. int nByte = sqlite3_blob_bytes(p->pSegments);
  148784. *pnBlob = nByte;
  148785. if( paBlob ){
  148786. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  148787. if( !aByte ){
  148788. rc = SQLITE_NOMEM;
  148789. }else{
  148790. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  148791. nByte = FTS3_NODE_CHUNKSIZE;
  148792. *pnLoad = nByte;
  148793. }
  148794. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  148795. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  148796. if( rc!=SQLITE_OK ){
  148797. sqlite3_free(aByte);
  148798. aByte = 0;
  148799. }
  148800. }
  148801. *paBlob = aByte;
  148802. }
  148803. }
  148804. return rc;
  148805. }
  148806. /*
  148807. ** Close the blob handle at p->pSegments, if it is open. See comments above
  148808. ** the sqlite3Fts3ReadBlock() function for details.
  148809. */
  148810. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  148811. sqlite3_blob_close(p->pSegments);
  148812. p->pSegments = 0;
  148813. }
  148814. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  148815. int nRead; /* Number of bytes to read */
  148816. int rc; /* Return code */
  148817. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  148818. rc = sqlite3_blob_read(
  148819. pReader->pBlob,
  148820. &pReader->aNode[pReader->nPopulate],
  148821. nRead,
  148822. pReader->nPopulate
  148823. );
  148824. if( rc==SQLITE_OK ){
  148825. pReader->nPopulate += nRead;
  148826. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  148827. if( pReader->nPopulate==pReader->nNode ){
  148828. sqlite3_blob_close(pReader->pBlob);
  148829. pReader->pBlob = 0;
  148830. pReader->nPopulate = 0;
  148831. }
  148832. }
  148833. return rc;
  148834. }
  148835. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  148836. int rc = SQLITE_OK;
  148837. assert( !pReader->pBlob
  148838. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  148839. );
  148840. while( pReader->pBlob && rc==SQLITE_OK
  148841. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  148842. ){
  148843. rc = fts3SegReaderIncrRead(pReader);
  148844. }
  148845. return rc;
  148846. }
  148847. /*
  148848. ** Set an Fts3SegReader cursor to point at EOF.
  148849. */
  148850. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  148851. if( !fts3SegReaderIsRootOnly(pSeg) ){
  148852. sqlite3_free(pSeg->aNode);
  148853. sqlite3_blob_close(pSeg->pBlob);
  148854. pSeg->pBlob = 0;
  148855. }
  148856. pSeg->aNode = 0;
  148857. }
  148858. /*
  148859. ** Move the iterator passed as the first argument to the next term in the
  148860. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  148861. ** SQLITE_DONE. Otherwise, an SQLite error code.
  148862. */
  148863. static int fts3SegReaderNext(
  148864. Fts3Table *p,
  148865. Fts3SegReader *pReader,
  148866. int bIncr
  148867. ){
  148868. int rc; /* Return code of various sub-routines */
  148869. char *pNext; /* Cursor variable */
  148870. int nPrefix; /* Number of bytes in term prefix */
  148871. int nSuffix; /* Number of bytes in term suffix */
  148872. if( !pReader->aDoclist ){
  148873. pNext = pReader->aNode;
  148874. }else{
  148875. pNext = &pReader->aDoclist[pReader->nDoclist];
  148876. }
  148877. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  148878. if( fts3SegReaderIsPending(pReader) ){
  148879. Fts3HashElem *pElem = *(pReader->ppNextElem);
  148880. sqlite3_free(pReader->aNode);
  148881. pReader->aNode = 0;
  148882. if( pElem ){
  148883. char *aCopy;
  148884. PendingList *pList = (PendingList *)fts3HashData(pElem);
  148885. int nCopy = pList->nData+1;
  148886. pReader->zTerm = (char *)fts3HashKey(pElem);
  148887. pReader->nTerm = fts3HashKeysize(pElem);
  148888. aCopy = (char*)sqlite3_malloc(nCopy);
  148889. if( !aCopy ) return SQLITE_NOMEM;
  148890. memcpy(aCopy, pList->aData, nCopy);
  148891. pReader->nNode = pReader->nDoclist = nCopy;
  148892. pReader->aNode = pReader->aDoclist = aCopy;
  148893. pReader->ppNextElem++;
  148894. assert( pReader->aNode );
  148895. }
  148896. return SQLITE_OK;
  148897. }
  148898. fts3SegReaderSetEof(pReader);
  148899. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  148900. ** blocks have already been traversed. */
  148901. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  148902. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  148903. return SQLITE_OK;
  148904. }
  148905. rc = sqlite3Fts3ReadBlock(
  148906. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  148907. (bIncr ? &pReader->nPopulate : 0)
  148908. );
  148909. if( rc!=SQLITE_OK ) return rc;
  148910. assert( pReader->pBlob==0 );
  148911. if( bIncr && pReader->nPopulate<pReader->nNode ){
  148912. pReader->pBlob = p->pSegments;
  148913. p->pSegments = 0;
  148914. }
  148915. pNext = pReader->aNode;
  148916. }
  148917. assert( !fts3SegReaderIsPending(pReader) );
  148918. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  148919. if( rc!=SQLITE_OK ) return rc;
  148920. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  148921. ** safe (no risk of overread) even if the node data is corrupted. */
  148922. pNext += fts3GetVarint32(pNext, &nPrefix);
  148923. pNext += fts3GetVarint32(pNext, &nSuffix);
  148924. if( nPrefix<0 || nSuffix<=0
  148925. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  148926. ){
  148927. return FTS_CORRUPT_VTAB;
  148928. }
  148929. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  148930. int nNew = (nPrefix+nSuffix)*2;
  148931. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  148932. if( !zNew ){
  148933. return SQLITE_NOMEM;
  148934. }
  148935. pReader->zTerm = zNew;
  148936. pReader->nTermAlloc = nNew;
  148937. }
  148938. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  148939. if( rc!=SQLITE_OK ) return rc;
  148940. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  148941. pReader->nTerm = nPrefix+nSuffix;
  148942. pNext += nSuffix;
  148943. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  148944. pReader->aDoclist = pNext;
  148945. pReader->pOffsetList = 0;
  148946. /* Check that the doclist does not appear to extend past the end of the
  148947. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  148948. ** of these statements is untrue, then the data structure is corrupt.
  148949. */
  148950. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  148951. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  148952. ){
  148953. return FTS_CORRUPT_VTAB;
  148954. }
  148955. return SQLITE_OK;
  148956. }
  148957. /*
  148958. ** Set the SegReader to point to the first docid in the doclist associated
  148959. ** with the current term.
  148960. */
  148961. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  148962. int rc = SQLITE_OK;
  148963. assert( pReader->aDoclist );
  148964. assert( !pReader->pOffsetList );
  148965. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  148966. u8 bEof = 0;
  148967. pReader->iDocid = 0;
  148968. pReader->nOffsetList = 0;
  148969. sqlite3Fts3DoclistPrev(0,
  148970. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  148971. &pReader->iDocid, &pReader->nOffsetList, &bEof
  148972. );
  148973. }else{
  148974. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  148975. if( rc==SQLITE_OK ){
  148976. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  148977. pReader->pOffsetList = &pReader->aDoclist[n];
  148978. }
  148979. }
  148980. return rc;
  148981. }
  148982. /*
  148983. ** Advance the SegReader to point to the next docid in the doclist
  148984. ** associated with the current term.
  148985. **
  148986. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  148987. ** *ppOffsetList is set to point to the first column-offset list
  148988. ** in the doclist entry (i.e. immediately past the docid varint).
  148989. ** *pnOffsetList is set to the length of the set of column-offset
  148990. ** lists, not including the nul-terminator byte. For example:
  148991. */
  148992. static int fts3SegReaderNextDocid(
  148993. Fts3Table *pTab,
  148994. Fts3SegReader *pReader, /* Reader to advance to next docid */
  148995. char **ppOffsetList, /* OUT: Pointer to current position-list */
  148996. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  148997. ){
  148998. int rc = SQLITE_OK;
  148999. char *p = pReader->pOffsetList;
  149000. char c = 0;
  149001. assert( p );
  149002. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  149003. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  149004. ** Pending-terms doclists are always built up in ascending order, so
  149005. ** we have to iterate through them backwards here. */
  149006. u8 bEof = 0;
  149007. if( ppOffsetList ){
  149008. *ppOffsetList = pReader->pOffsetList;
  149009. *pnOffsetList = pReader->nOffsetList - 1;
  149010. }
  149011. sqlite3Fts3DoclistPrev(0,
  149012. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  149013. &pReader->nOffsetList, &bEof
  149014. );
  149015. if( bEof ){
  149016. pReader->pOffsetList = 0;
  149017. }else{
  149018. pReader->pOffsetList = p;
  149019. }
  149020. }else{
  149021. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  149022. /* Pointer p currently points at the first byte of an offset list. The
  149023. ** following block advances it to point one byte past the end of
  149024. ** the same offset list. */
  149025. while( 1 ){
  149026. /* The following line of code (and the "p++" below the while() loop) is
  149027. ** normally all that is required to move pointer p to the desired
  149028. ** position. The exception is if this node is being loaded from disk
  149029. ** incrementally and pointer "p" now points to the first byte past
  149030. ** the populated part of pReader->aNode[].
  149031. */
  149032. while( *p | c ) c = *p++ & 0x80;
  149033. assert( *p==0 );
  149034. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  149035. rc = fts3SegReaderIncrRead(pReader);
  149036. if( rc!=SQLITE_OK ) return rc;
  149037. }
  149038. p++;
  149039. /* If required, populate the output variables with a pointer to and the
  149040. ** size of the previous offset-list.
  149041. */
  149042. if( ppOffsetList ){
  149043. *ppOffsetList = pReader->pOffsetList;
  149044. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  149045. }
  149046. /* List may have been edited in place by fts3EvalNearTrim() */
  149047. while( p<pEnd && *p==0 ) p++;
  149048. /* If there are no more entries in the doclist, set pOffsetList to
  149049. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  149050. ** Fts3SegReader.pOffsetList to point to the next offset list before
  149051. ** returning.
  149052. */
  149053. if( p>=pEnd ){
  149054. pReader->pOffsetList = 0;
  149055. }else{
  149056. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  149057. if( rc==SQLITE_OK ){
  149058. sqlite3_int64 iDelta;
  149059. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  149060. if( pTab->bDescIdx ){
  149061. pReader->iDocid -= iDelta;
  149062. }else{
  149063. pReader->iDocid += iDelta;
  149064. }
  149065. }
  149066. }
  149067. }
  149068. return SQLITE_OK;
  149069. }
  149070. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  149071. Fts3Cursor *pCsr,
  149072. Fts3MultiSegReader *pMsr,
  149073. int *pnOvfl
  149074. ){
  149075. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  149076. int nOvfl = 0;
  149077. int ii;
  149078. int rc = SQLITE_OK;
  149079. int pgsz = p->nPgsz;
  149080. assert( p->bFts4 );
  149081. assert( pgsz>0 );
  149082. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  149083. Fts3SegReader *pReader = pMsr->apSegment[ii];
  149084. if( !fts3SegReaderIsPending(pReader)
  149085. && !fts3SegReaderIsRootOnly(pReader)
  149086. ){
  149087. sqlite3_int64 jj;
  149088. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  149089. int nBlob;
  149090. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  149091. if( rc!=SQLITE_OK ) break;
  149092. if( (nBlob+35)>pgsz ){
  149093. nOvfl += (nBlob + 34)/pgsz;
  149094. }
  149095. }
  149096. }
  149097. }
  149098. *pnOvfl = nOvfl;
  149099. return rc;
  149100. }
  149101. /*
  149102. ** Free all allocations associated with the iterator passed as the
  149103. ** second argument.
  149104. */
  149105. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  149106. if( pReader ){
  149107. if( !fts3SegReaderIsPending(pReader) ){
  149108. sqlite3_free(pReader->zTerm);
  149109. }
  149110. if( !fts3SegReaderIsRootOnly(pReader) ){
  149111. sqlite3_free(pReader->aNode);
  149112. }
  149113. sqlite3_blob_close(pReader->pBlob);
  149114. }
  149115. sqlite3_free(pReader);
  149116. }
  149117. /*
  149118. ** Allocate a new SegReader object.
  149119. */
  149120. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  149121. int iAge, /* Segment "age". */
  149122. int bLookup, /* True for a lookup only */
  149123. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  149124. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  149125. sqlite3_int64 iEndBlock, /* Final block of segment */
  149126. const char *zRoot, /* Buffer containing root node */
  149127. int nRoot, /* Size of buffer containing root node */
  149128. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  149129. ){
  149130. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  149131. int nExtra = 0; /* Bytes to allocate segment root node */
  149132. assert( iStartLeaf<=iEndLeaf );
  149133. if( iStartLeaf==0 ){
  149134. nExtra = nRoot + FTS3_NODE_PADDING;
  149135. }
  149136. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  149137. if( !pReader ){
  149138. return SQLITE_NOMEM;
  149139. }
  149140. memset(pReader, 0, sizeof(Fts3SegReader));
  149141. pReader->iIdx = iAge;
  149142. pReader->bLookup = bLookup!=0;
  149143. pReader->iStartBlock = iStartLeaf;
  149144. pReader->iLeafEndBlock = iEndLeaf;
  149145. pReader->iEndBlock = iEndBlock;
  149146. if( nExtra ){
  149147. /* The entire segment is stored in the root node. */
  149148. pReader->aNode = (char *)&pReader[1];
  149149. pReader->rootOnly = 1;
  149150. pReader->nNode = nRoot;
  149151. memcpy(pReader->aNode, zRoot, nRoot);
  149152. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  149153. }else{
  149154. pReader->iCurrentBlock = iStartLeaf-1;
  149155. }
  149156. *ppReader = pReader;
  149157. return SQLITE_OK;
  149158. }
  149159. /*
  149160. ** This is a comparison function used as a qsort() callback when sorting
  149161. ** an array of pending terms by term. This occurs as part of flushing
  149162. ** the contents of the pending-terms hash table to the database.
  149163. */
  149164. static int SQLITE_CDECL fts3CompareElemByTerm(
  149165. const void *lhs,
  149166. const void *rhs
  149167. ){
  149168. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  149169. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  149170. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  149171. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  149172. int n = (n1<n2 ? n1 : n2);
  149173. int c = memcmp(z1, z2, n);
  149174. if( c==0 ){
  149175. c = n1 - n2;
  149176. }
  149177. return c;
  149178. }
  149179. /*
  149180. ** This function is used to allocate an Fts3SegReader that iterates through
  149181. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  149182. **
  149183. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  149184. ** through each term in the pending-terms table. Or, if isPrefixIter is
  149185. ** non-zero, it iterates through each term and its prefixes. For example, if
  149186. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  149187. ** "firebird", then the iterator visits the following 'terms' (in the order
  149188. ** shown):
  149189. **
  149190. ** f fi fir fire fireb firebi firebir firebird
  149191. ** m my mys mysq mysql
  149192. ** s sq sql sqli sqlit sqlite
  149193. **
  149194. ** Whereas if isPrefixIter is zero, the terms visited are:
  149195. **
  149196. ** firebird mysql sqlite
  149197. */
  149198. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  149199. Fts3Table *p, /* Virtual table handle */
  149200. int iIndex, /* Index for p->aIndex */
  149201. const char *zTerm, /* Term to search for */
  149202. int nTerm, /* Size of buffer zTerm */
  149203. int bPrefix, /* True for a prefix iterator */
  149204. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  149205. ){
  149206. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  149207. Fts3HashElem *pE; /* Iterator variable */
  149208. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  149209. int nElem = 0; /* Size of array at aElem */
  149210. int rc = SQLITE_OK; /* Return Code */
  149211. Fts3Hash *pHash;
  149212. pHash = &p->aIndex[iIndex].hPending;
  149213. if( bPrefix ){
  149214. int nAlloc = 0; /* Size of allocated array at aElem */
  149215. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  149216. char *zKey = (char *)fts3HashKey(pE);
  149217. int nKey = fts3HashKeysize(pE);
  149218. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  149219. if( nElem==nAlloc ){
  149220. Fts3HashElem **aElem2;
  149221. nAlloc += 16;
  149222. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  149223. aElem, nAlloc*sizeof(Fts3HashElem *)
  149224. );
  149225. if( !aElem2 ){
  149226. rc = SQLITE_NOMEM;
  149227. nElem = 0;
  149228. break;
  149229. }
  149230. aElem = aElem2;
  149231. }
  149232. aElem[nElem++] = pE;
  149233. }
  149234. }
  149235. /* If more than one term matches the prefix, sort the Fts3HashElem
  149236. ** objects in term order using qsort(). This uses the same comparison
  149237. ** callback as is used when flushing terms to disk.
  149238. */
  149239. if( nElem>1 ){
  149240. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  149241. }
  149242. }else{
  149243. /* The query is a simple term lookup that matches at most one term in
  149244. ** the index. All that is required is a straight hash-lookup.
  149245. **
  149246. ** Because the stack address of pE may be accessed via the aElem pointer
  149247. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  149248. ** within this entire function, not just this "else{...}" block.
  149249. */
  149250. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  149251. if( pE ){
  149252. aElem = &pE;
  149253. nElem = 1;
  149254. }
  149255. }
  149256. if( nElem>0 ){
  149257. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  149258. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  149259. if( !pReader ){
  149260. rc = SQLITE_NOMEM;
  149261. }else{
  149262. memset(pReader, 0, nByte);
  149263. pReader->iIdx = 0x7FFFFFFF;
  149264. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  149265. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  149266. }
  149267. }
  149268. if( bPrefix ){
  149269. sqlite3_free(aElem);
  149270. }
  149271. *ppReader = pReader;
  149272. return rc;
  149273. }
  149274. /*
  149275. ** Compare the entries pointed to by two Fts3SegReader structures.
  149276. ** Comparison is as follows:
  149277. **
  149278. ** 1) EOF is greater than not EOF.
  149279. **
  149280. ** 2) The current terms (if any) are compared using memcmp(). If one
  149281. ** term is a prefix of another, the longer term is considered the
  149282. ** larger.
  149283. **
  149284. ** 3) By segment age. An older segment is considered larger.
  149285. */
  149286. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  149287. int rc;
  149288. if( pLhs->aNode && pRhs->aNode ){
  149289. int rc2 = pLhs->nTerm - pRhs->nTerm;
  149290. if( rc2<0 ){
  149291. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  149292. }else{
  149293. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  149294. }
  149295. if( rc==0 ){
  149296. rc = rc2;
  149297. }
  149298. }else{
  149299. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  149300. }
  149301. if( rc==0 ){
  149302. rc = pRhs->iIdx - pLhs->iIdx;
  149303. }
  149304. assert( rc!=0 );
  149305. return rc;
  149306. }
  149307. /*
  149308. ** A different comparison function for SegReader structures. In this
  149309. ** version, it is assumed that each SegReader points to an entry in
  149310. ** a doclist for identical terms. Comparison is made as follows:
  149311. **
  149312. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  149313. **
  149314. ** 2) By current docid.
  149315. **
  149316. ** 3) By segment age. An older segment is considered larger.
  149317. */
  149318. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  149319. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  149320. if( rc==0 ){
  149321. if( pLhs->iDocid==pRhs->iDocid ){
  149322. rc = pRhs->iIdx - pLhs->iIdx;
  149323. }else{
  149324. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  149325. }
  149326. }
  149327. assert( pLhs->aNode && pRhs->aNode );
  149328. return rc;
  149329. }
  149330. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  149331. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  149332. if( rc==0 ){
  149333. if( pLhs->iDocid==pRhs->iDocid ){
  149334. rc = pRhs->iIdx - pLhs->iIdx;
  149335. }else{
  149336. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  149337. }
  149338. }
  149339. assert( pLhs->aNode && pRhs->aNode );
  149340. return rc;
  149341. }
  149342. /*
  149343. ** Compare the term that the Fts3SegReader object passed as the first argument
  149344. ** points to with the term specified by arguments zTerm and nTerm.
  149345. **
  149346. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  149347. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  149348. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  149349. */
  149350. static int fts3SegReaderTermCmp(
  149351. Fts3SegReader *pSeg, /* Segment reader object */
  149352. const char *zTerm, /* Term to compare to */
  149353. int nTerm /* Size of term zTerm in bytes */
  149354. ){
  149355. int res = 0;
  149356. if( pSeg->aNode ){
  149357. if( pSeg->nTerm>nTerm ){
  149358. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  149359. }else{
  149360. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  149361. }
  149362. if( res==0 ){
  149363. res = pSeg->nTerm-nTerm;
  149364. }
  149365. }
  149366. return res;
  149367. }
  149368. /*
  149369. ** Argument apSegment is an array of nSegment elements. It is known that
  149370. ** the final (nSegment-nSuspect) members are already in sorted order
  149371. ** (according to the comparison function provided). This function shuffles
  149372. ** the array around until all entries are in sorted order.
  149373. */
  149374. static void fts3SegReaderSort(
  149375. Fts3SegReader **apSegment, /* Array to sort entries of */
  149376. int nSegment, /* Size of apSegment array */
  149377. int nSuspect, /* Unsorted entry count */
  149378. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  149379. ){
  149380. int i; /* Iterator variable */
  149381. assert( nSuspect<=nSegment );
  149382. if( nSuspect==nSegment ) nSuspect--;
  149383. for(i=nSuspect-1; i>=0; i--){
  149384. int j;
  149385. for(j=i; j<(nSegment-1); j++){
  149386. Fts3SegReader *pTmp;
  149387. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  149388. pTmp = apSegment[j+1];
  149389. apSegment[j+1] = apSegment[j];
  149390. apSegment[j] = pTmp;
  149391. }
  149392. }
  149393. #ifndef NDEBUG
  149394. /* Check that the list really is sorted now. */
  149395. for(i=0; i<(nSuspect-1); i++){
  149396. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  149397. }
  149398. #endif
  149399. }
  149400. /*
  149401. ** Insert a record into the %_segments table.
  149402. */
  149403. static int fts3WriteSegment(
  149404. Fts3Table *p, /* Virtual table handle */
  149405. sqlite3_int64 iBlock, /* Block id for new block */
  149406. char *z, /* Pointer to buffer containing block data */
  149407. int n /* Size of buffer z in bytes */
  149408. ){
  149409. sqlite3_stmt *pStmt;
  149410. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  149411. if( rc==SQLITE_OK ){
  149412. sqlite3_bind_int64(pStmt, 1, iBlock);
  149413. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  149414. sqlite3_step(pStmt);
  149415. rc = sqlite3_reset(pStmt);
  149416. }
  149417. return rc;
  149418. }
  149419. /*
  149420. ** Find the largest relative level number in the table. If successful, set
  149421. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  149422. ** set *pnMax to zero and return an SQLite error code.
  149423. */
  149424. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  149425. int rc;
  149426. int mxLevel = 0;
  149427. sqlite3_stmt *pStmt = 0;
  149428. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  149429. if( rc==SQLITE_OK ){
  149430. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149431. mxLevel = sqlite3_column_int(pStmt, 0);
  149432. }
  149433. rc = sqlite3_reset(pStmt);
  149434. }
  149435. *pnMax = mxLevel;
  149436. return rc;
  149437. }
  149438. /*
  149439. ** Insert a record into the %_segdir table.
  149440. */
  149441. static int fts3WriteSegdir(
  149442. Fts3Table *p, /* Virtual table handle */
  149443. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  149444. int iIdx, /* Value for "idx" field */
  149445. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  149446. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  149447. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  149448. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  149449. char *zRoot, /* Blob value for "root" field */
  149450. int nRoot /* Number of bytes in buffer zRoot */
  149451. ){
  149452. sqlite3_stmt *pStmt;
  149453. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  149454. if( rc==SQLITE_OK ){
  149455. sqlite3_bind_int64(pStmt, 1, iLevel);
  149456. sqlite3_bind_int(pStmt, 2, iIdx);
  149457. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  149458. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  149459. if( nLeafData==0 ){
  149460. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  149461. }else{
  149462. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  149463. if( !zEnd ) return SQLITE_NOMEM;
  149464. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  149465. }
  149466. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  149467. sqlite3_step(pStmt);
  149468. rc = sqlite3_reset(pStmt);
  149469. }
  149470. return rc;
  149471. }
  149472. /*
  149473. ** Return the size of the common prefix (if any) shared by zPrev and
  149474. ** zNext, in bytes. For example,
  149475. **
  149476. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  149477. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  149478. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  149479. */
  149480. static int fts3PrefixCompress(
  149481. const char *zPrev, /* Buffer containing previous term */
  149482. int nPrev, /* Size of buffer zPrev in bytes */
  149483. const char *zNext, /* Buffer containing next term */
  149484. int nNext /* Size of buffer zNext in bytes */
  149485. ){
  149486. int n;
  149487. UNUSED_PARAMETER(nNext);
  149488. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  149489. return n;
  149490. }
  149491. /*
  149492. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  149493. ** (according to memcmp) than the previous term.
  149494. */
  149495. static int fts3NodeAddTerm(
  149496. Fts3Table *p, /* Virtual table handle */
  149497. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  149498. int isCopyTerm, /* True if zTerm/nTerm is transient */
  149499. const char *zTerm, /* Pointer to buffer containing term */
  149500. int nTerm /* Size of term in bytes */
  149501. ){
  149502. SegmentNode *pTree = *ppTree;
  149503. int rc;
  149504. SegmentNode *pNew;
  149505. /* First try to append the term to the current node. Return early if
  149506. ** this is possible.
  149507. */
  149508. if( pTree ){
  149509. int nData = pTree->nData; /* Current size of node in bytes */
  149510. int nReq = nData; /* Required space after adding zTerm */
  149511. int nPrefix; /* Number of bytes of prefix compression */
  149512. int nSuffix; /* Suffix length */
  149513. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  149514. nSuffix = nTerm-nPrefix;
  149515. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  149516. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  149517. if( nReq>p->nNodeSize ){
  149518. /* An unusual case: this is the first term to be added to the node
  149519. ** and the static node buffer (p->nNodeSize bytes) is not large
  149520. ** enough. Use a separately malloced buffer instead This wastes
  149521. ** p->nNodeSize bytes, but since this scenario only comes about when
  149522. ** the database contain two terms that share a prefix of almost 2KB,
  149523. ** this is not expected to be a serious problem.
  149524. */
  149525. assert( pTree->aData==(char *)&pTree[1] );
  149526. pTree->aData = (char *)sqlite3_malloc(nReq);
  149527. if( !pTree->aData ){
  149528. return SQLITE_NOMEM;
  149529. }
  149530. }
  149531. if( pTree->zTerm ){
  149532. /* There is no prefix-length field for first term in a node */
  149533. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  149534. }
  149535. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  149536. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  149537. pTree->nData = nData + nSuffix;
  149538. pTree->nEntry++;
  149539. if( isCopyTerm ){
  149540. if( pTree->nMalloc<nTerm ){
  149541. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  149542. if( !zNew ){
  149543. return SQLITE_NOMEM;
  149544. }
  149545. pTree->nMalloc = nTerm*2;
  149546. pTree->zMalloc = zNew;
  149547. }
  149548. pTree->zTerm = pTree->zMalloc;
  149549. memcpy(pTree->zTerm, zTerm, nTerm);
  149550. pTree->nTerm = nTerm;
  149551. }else{
  149552. pTree->zTerm = (char *)zTerm;
  149553. pTree->nTerm = nTerm;
  149554. }
  149555. return SQLITE_OK;
  149556. }
  149557. }
  149558. /* If control flows to here, it was not possible to append zTerm to the
  149559. ** current node. Create a new node (a right-sibling of the current node).
  149560. ** If this is the first node in the tree, the term is added to it.
  149561. **
  149562. ** Otherwise, the term is not added to the new node, it is left empty for
  149563. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  149564. ** has no parent, one is created here.
  149565. */
  149566. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  149567. if( !pNew ){
  149568. return SQLITE_NOMEM;
  149569. }
  149570. memset(pNew, 0, sizeof(SegmentNode));
  149571. pNew->nData = 1 + FTS3_VARINT_MAX;
  149572. pNew->aData = (char *)&pNew[1];
  149573. if( pTree ){
  149574. SegmentNode *pParent = pTree->pParent;
  149575. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  149576. if( pTree->pParent==0 ){
  149577. pTree->pParent = pParent;
  149578. }
  149579. pTree->pRight = pNew;
  149580. pNew->pLeftmost = pTree->pLeftmost;
  149581. pNew->pParent = pParent;
  149582. pNew->zMalloc = pTree->zMalloc;
  149583. pNew->nMalloc = pTree->nMalloc;
  149584. pTree->zMalloc = 0;
  149585. }else{
  149586. pNew->pLeftmost = pNew;
  149587. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  149588. }
  149589. *ppTree = pNew;
  149590. return rc;
  149591. }
  149592. /*
  149593. ** Helper function for fts3NodeWrite().
  149594. */
  149595. static int fts3TreeFinishNode(
  149596. SegmentNode *pTree,
  149597. int iHeight,
  149598. sqlite3_int64 iLeftChild
  149599. ){
  149600. int nStart;
  149601. assert( iHeight>=1 && iHeight<128 );
  149602. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  149603. pTree->aData[nStart] = (char)iHeight;
  149604. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  149605. return nStart;
  149606. }
  149607. /*
  149608. ** Write the buffer for the segment node pTree and all of its peers to the
  149609. ** database. Then call this function recursively to write the parent of
  149610. ** pTree and its peers to the database.
  149611. **
  149612. ** Except, if pTree is a root node, do not write it to the database. Instead,
  149613. ** set output variables *paRoot and *pnRoot to contain the root node.
  149614. **
  149615. ** If successful, SQLITE_OK is returned and output variable *piLast is
  149616. ** set to the largest blockid written to the database (or zero if no
  149617. ** blocks were written to the db). Otherwise, an SQLite error code is
  149618. ** returned.
  149619. */
  149620. static int fts3NodeWrite(
  149621. Fts3Table *p, /* Virtual table handle */
  149622. SegmentNode *pTree, /* SegmentNode handle */
  149623. int iHeight, /* Height of this node in tree */
  149624. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  149625. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  149626. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  149627. char **paRoot, /* OUT: Data for root node */
  149628. int *pnRoot /* OUT: Size of root node in bytes */
  149629. ){
  149630. int rc = SQLITE_OK;
  149631. if( !pTree->pParent ){
  149632. /* Root node of the tree. */
  149633. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  149634. *piLast = iFree-1;
  149635. *pnRoot = pTree->nData - nStart;
  149636. *paRoot = &pTree->aData[nStart];
  149637. }else{
  149638. SegmentNode *pIter;
  149639. sqlite3_int64 iNextFree = iFree;
  149640. sqlite3_int64 iNextLeaf = iLeaf;
  149641. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  149642. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  149643. int nWrite = pIter->nData - nStart;
  149644. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  149645. iNextFree++;
  149646. iNextLeaf += (pIter->nEntry+1);
  149647. }
  149648. if( rc==SQLITE_OK ){
  149649. assert( iNextLeaf==iFree );
  149650. rc = fts3NodeWrite(
  149651. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  149652. );
  149653. }
  149654. }
  149655. return rc;
  149656. }
  149657. /*
  149658. ** Free all memory allocations associated with the tree pTree.
  149659. */
  149660. static void fts3NodeFree(SegmentNode *pTree){
  149661. if( pTree ){
  149662. SegmentNode *p = pTree->pLeftmost;
  149663. fts3NodeFree(p->pParent);
  149664. while( p ){
  149665. SegmentNode *pRight = p->pRight;
  149666. if( p->aData!=(char *)&p[1] ){
  149667. sqlite3_free(p->aData);
  149668. }
  149669. assert( pRight==0 || p->zMalloc==0 );
  149670. sqlite3_free(p->zMalloc);
  149671. sqlite3_free(p);
  149672. p = pRight;
  149673. }
  149674. }
  149675. }
  149676. /*
  149677. ** Add a term to the segment being constructed by the SegmentWriter object
  149678. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  149679. ** be passed NULL. This function will allocate a new SegmentWriter object
  149680. ** and return it via the input/output variable *ppWriter in this case.
  149681. **
  149682. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  149683. */
  149684. static int fts3SegWriterAdd(
  149685. Fts3Table *p, /* Virtual table handle */
  149686. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  149687. int isCopyTerm, /* True if buffer zTerm must be copied */
  149688. const char *zTerm, /* Pointer to buffer containing term */
  149689. int nTerm, /* Size of term in bytes */
  149690. const char *aDoclist, /* Pointer to buffer containing doclist */
  149691. int nDoclist /* Size of doclist in bytes */
  149692. ){
  149693. int nPrefix; /* Size of term prefix in bytes */
  149694. int nSuffix; /* Size of term suffix in bytes */
  149695. int nReq; /* Number of bytes required on leaf page */
  149696. int nData;
  149697. SegmentWriter *pWriter = *ppWriter;
  149698. if( !pWriter ){
  149699. int rc;
  149700. sqlite3_stmt *pStmt;
  149701. /* Allocate the SegmentWriter structure */
  149702. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  149703. if( !pWriter ) return SQLITE_NOMEM;
  149704. memset(pWriter, 0, sizeof(SegmentWriter));
  149705. *ppWriter = pWriter;
  149706. /* Allocate a buffer in which to accumulate data */
  149707. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  149708. if( !pWriter->aData ) return SQLITE_NOMEM;
  149709. pWriter->nSize = p->nNodeSize;
  149710. /* Find the next free blockid in the %_segments table */
  149711. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  149712. if( rc!=SQLITE_OK ) return rc;
  149713. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149714. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  149715. pWriter->iFirst = pWriter->iFree;
  149716. }
  149717. rc = sqlite3_reset(pStmt);
  149718. if( rc!=SQLITE_OK ) return rc;
  149719. }
  149720. nData = pWriter->nData;
  149721. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  149722. nSuffix = nTerm-nPrefix;
  149723. /* Figure out how many bytes are required by this new entry */
  149724. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  149725. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  149726. nSuffix + /* Term suffix */
  149727. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  149728. nDoclist; /* Doclist data */
  149729. if( nData>0 && nData+nReq>p->nNodeSize ){
  149730. int rc;
  149731. /* The current leaf node is full. Write it out to the database. */
  149732. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  149733. if( rc!=SQLITE_OK ) return rc;
  149734. p->nLeafAdd++;
  149735. /* Add the current term to the interior node tree. The term added to
  149736. ** the interior tree must:
  149737. **
  149738. ** a) be greater than the largest term on the leaf node just written
  149739. ** to the database (still available in pWriter->zTerm), and
  149740. **
  149741. ** b) be less than or equal to the term about to be added to the new
  149742. ** leaf node (zTerm/nTerm).
  149743. **
  149744. ** In other words, it must be the prefix of zTerm 1 byte longer than
  149745. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  149746. */
  149747. assert( nPrefix<nTerm );
  149748. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  149749. if( rc!=SQLITE_OK ) return rc;
  149750. nData = 0;
  149751. pWriter->nTerm = 0;
  149752. nPrefix = 0;
  149753. nSuffix = nTerm;
  149754. nReq = 1 + /* varint containing prefix size */
  149755. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  149756. nTerm + /* Term suffix */
  149757. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  149758. nDoclist; /* Doclist data */
  149759. }
  149760. /* Increase the total number of bytes written to account for the new entry. */
  149761. pWriter->nLeafData += nReq;
  149762. /* If the buffer currently allocated is too small for this entry, realloc
  149763. ** the buffer to make it large enough.
  149764. */
  149765. if( nReq>pWriter->nSize ){
  149766. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  149767. if( !aNew ) return SQLITE_NOMEM;
  149768. pWriter->aData = aNew;
  149769. pWriter->nSize = nReq;
  149770. }
  149771. assert( nData+nReq<=pWriter->nSize );
  149772. /* Append the prefix-compressed term and doclist to the buffer. */
  149773. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  149774. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  149775. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  149776. nData += nSuffix;
  149777. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  149778. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  149779. pWriter->nData = nData + nDoclist;
  149780. /* Save the current term so that it can be used to prefix-compress the next.
  149781. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  149782. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  149783. ** store a copy of the pointer.
  149784. */
  149785. if( isCopyTerm ){
  149786. if( nTerm>pWriter->nMalloc ){
  149787. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  149788. if( !zNew ){
  149789. return SQLITE_NOMEM;
  149790. }
  149791. pWriter->nMalloc = nTerm*2;
  149792. pWriter->zMalloc = zNew;
  149793. pWriter->zTerm = zNew;
  149794. }
  149795. assert( pWriter->zTerm==pWriter->zMalloc );
  149796. memcpy(pWriter->zTerm, zTerm, nTerm);
  149797. }else{
  149798. pWriter->zTerm = (char *)zTerm;
  149799. }
  149800. pWriter->nTerm = nTerm;
  149801. return SQLITE_OK;
  149802. }
  149803. /*
  149804. ** Flush all data associated with the SegmentWriter object pWriter to the
  149805. ** database. This function must be called after all terms have been added
  149806. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  149807. ** returned. Otherwise, an SQLite error code.
  149808. */
  149809. static int fts3SegWriterFlush(
  149810. Fts3Table *p, /* Virtual table handle */
  149811. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  149812. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  149813. int iIdx /* Value for 'idx' column of %_segdir */
  149814. ){
  149815. int rc; /* Return code */
  149816. if( pWriter->pTree ){
  149817. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  149818. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  149819. char *zRoot = NULL; /* Pointer to buffer containing root node */
  149820. int nRoot = 0; /* Size of buffer zRoot */
  149821. iLastLeaf = pWriter->iFree;
  149822. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  149823. if( rc==SQLITE_OK ){
  149824. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  149825. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  149826. }
  149827. if( rc==SQLITE_OK ){
  149828. rc = fts3WriteSegdir(p, iLevel, iIdx,
  149829. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  149830. }
  149831. }else{
  149832. /* The entire tree fits on the root node. Write it to the segdir table. */
  149833. rc = fts3WriteSegdir(p, iLevel, iIdx,
  149834. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  149835. }
  149836. p->nLeafAdd++;
  149837. return rc;
  149838. }
  149839. /*
  149840. ** Release all memory held by the SegmentWriter object passed as the
  149841. ** first argument.
  149842. */
  149843. static void fts3SegWriterFree(SegmentWriter *pWriter){
  149844. if( pWriter ){
  149845. sqlite3_free(pWriter->aData);
  149846. sqlite3_free(pWriter->zMalloc);
  149847. fts3NodeFree(pWriter->pTree);
  149848. sqlite3_free(pWriter);
  149849. }
  149850. }
  149851. /*
  149852. ** The first value in the apVal[] array is assumed to contain an integer.
  149853. ** This function tests if there exist any documents with docid values that
  149854. ** are different from that integer. i.e. if deleting the document with docid
  149855. ** pRowid would mean the FTS3 table were empty.
  149856. **
  149857. ** If successful, *pisEmpty is set to true if the table is empty except for
  149858. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  149859. ** error occurs, an SQLite error code is returned.
  149860. */
  149861. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  149862. sqlite3_stmt *pStmt;
  149863. int rc;
  149864. if( p->zContentTbl ){
  149865. /* If using the content=xxx option, assume the table is never empty */
  149866. *pisEmpty = 0;
  149867. rc = SQLITE_OK;
  149868. }else{
  149869. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  149870. if( rc==SQLITE_OK ){
  149871. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149872. *pisEmpty = sqlite3_column_int(pStmt, 0);
  149873. }
  149874. rc = sqlite3_reset(pStmt);
  149875. }
  149876. }
  149877. return rc;
  149878. }
  149879. /*
  149880. ** Set *pnMax to the largest segment level in the database for the index
  149881. ** iIndex.
  149882. **
  149883. ** Segment levels are stored in the 'level' column of the %_segdir table.
  149884. **
  149885. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  149886. */
  149887. static int fts3SegmentMaxLevel(
  149888. Fts3Table *p,
  149889. int iLangid,
  149890. int iIndex,
  149891. sqlite3_int64 *pnMax
  149892. ){
  149893. sqlite3_stmt *pStmt;
  149894. int rc;
  149895. assert( iIndex>=0 && iIndex<p->nIndex );
  149896. /* Set pStmt to the compiled version of:
  149897. **
  149898. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  149899. **
  149900. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  149901. */
  149902. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  149903. if( rc!=SQLITE_OK ) return rc;
  149904. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  149905. sqlite3_bind_int64(pStmt, 2,
  149906. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  149907. );
  149908. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149909. *pnMax = sqlite3_column_int64(pStmt, 0);
  149910. }
  149911. return sqlite3_reset(pStmt);
  149912. }
  149913. /*
  149914. ** iAbsLevel is an absolute level that may be assumed to exist within
  149915. ** the database. This function checks if it is the largest level number
  149916. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  149917. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  149918. ** is returned. If an error occurs, an error code is returned and the
  149919. ** final value of *pbMax is undefined.
  149920. */
  149921. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  149922. /* Set pStmt to the compiled version of:
  149923. **
  149924. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  149925. **
  149926. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  149927. */
  149928. sqlite3_stmt *pStmt;
  149929. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  149930. if( rc!=SQLITE_OK ) return rc;
  149931. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  149932. sqlite3_bind_int64(pStmt, 2,
  149933. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  149934. );
  149935. *pbMax = 0;
  149936. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149937. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  149938. }
  149939. return sqlite3_reset(pStmt);
  149940. }
  149941. /*
  149942. ** Delete all entries in the %_segments table associated with the segment
  149943. ** opened with seg-reader pSeg. This function does not affect the contents
  149944. ** of the %_segdir table.
  149945. */
  149946. static int fts3DeleteSegment(
  149947. Fts3Table *p, /* FTS table handle */
  149948. Fts3SegReader *pSeg /* Segment to delete */
  149949. ){
  149950. int rc = SQLITE_OK; /* Return code */
  149951. if( pSeg->iStartBlock ){
  149952. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  149953. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  149954. if( rc==SQLITE_OK ){
  149955. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  149956. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  149957. sqlite3_step(pDelete);
  149958. rc = sqlite3_reset(pDelete);
  149959. }
  149960. }
  149961. return rc;
  149962. }
  149963. /*
  149964. ** This function is used after merging multiple segments into a single large
  149965. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  149966. ** it:
  149967. **
  149968. ** 1) Deletes all %_segments entries for the segments associated with
  149969. ** each of the SegReader objects in the array passed as the third
  149970. ** argument, and
  149971. **
  149972. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  149973. ** entries regardless of level if (iLevel<0).
  149974. **
  149975. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  149976. */
  149977. static int fts3DeleteSegdir(
  149978. Fts3Table *p, /* Virtual table handle */
  149979. int iLangid, /* Language id */
  149980. int iIndex, /* Index for p->aIndex */
  149981. int iLevel, /* Level of %_segdir entries to delete */
  149982. Fts3SegReader **apSegment, /* Array of SegReader objects */
  149983. int nReader /* Size of array apSegment */
  149984. ){
  149985. int rc = SQLITE_OK; /* Return Code */
  149986. int i; /* Iterator variable */
  149987. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  149988. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  149989. rc = fts3DeleteSegment(p, apSegment[i]);
  149990. }
  149991. if( rc!=SQLITE_OK ){
  149992. return rc;
  149993. }
  149994. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  149995. if( iLevel==FTS3_SEGCURSOR_ALL ){
  149996. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  149997. if( rc==SQLITE_OK ){
  149998. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  149999. sqlite3_bind_int64(pDelete, 2,
  150000. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  150001. );
  150002. }
  150003. }else{
  150004. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  150005. if( rc==SQLITE_OK ){
  150006. sqlite3_bind_int64(
  150007. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  150008. );
  150009. }
  150010. }
  150011. if( rc==SQLITE_OK ){
  150012. sqlite3_step(pDelete);
  150013. rc = sqlite3_reset(pDelete);
  150014. }
  150015. return rc;
  150016. }
  150017. /*
  150018. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  150019. ** a position list that may (or may not) feature multiple columns. This
  150020. ** function adjusts the pointer *ppList and the length *pnList so that they
  150021. ** identify the subset of the position list that corresponds to column iCol.
  150022. **
  150023. ** If there are no entries in the input position list for column iCol, then
  150024. ** *pnList is set to zero before returning.
  150025. **
  150026. ** If parameter bZero is non-zero, then any part of the input list following
  150027. ** the end of the output list is zeroed before returning.
  150028. */
  150029. static void fts3ColumnFilter(
  150030. int iCol, /* Column to filter on */
  150031. int bZero, /* Zero out anything following *ppList */
  150032. char **ppList, /* IN/OUT: Pointer to position list */
  150033. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  150034. ){
  150035. char *pList = *ppList;
  150036. int nList = *pnList;
  150037. char *pEnd = &pList[nList];
  150038. int iCurrent = 0;
  150039. char *p = pList;
  150040. assert( iCol>=0 );
  150041. while( 1 ){
  150042. char c = 0;
  150043. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  150044. if( iCol==iCurrent ){
  150045. nList = (int)(p - pList);
  150046. break;
  150047. }
  150048. nList -= (int)(p - pList);
  150049. pList = p;
  150050. if( nList==0 ){
  150051. break;
  150052. }
  150053. p = &pList[1];
  150054. p += fts3GetVarint32(p, &iCurrent);
  150055. }
  150056. if( bZero && &pList[nList]!=pEnd ){
  150057. memset(&pList[nList], 0, pEnd - &pList[nList]);
  150058. }
  150059. *ppList = pList;
  150060. *pnList = nList;
  150061. }
  150062. /*
  150063. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  150064. ** existing data). Grow the buffer if required.
  150065. **
  150066. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  150067. ** trying to resize the buffer, return SQLITE_NOMEM.
  150068. */
  150069. static int fts3MsrBufferData(
  150070. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  150071. char *pList,
  150072. int nList
  150073. ){
  150074. if( nList>pMsr->nBuffer ){
  150075. char *pNew;
  150076. pMsr->nBuffer = nList*2;
  150077. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  150078. if( !pNew ) return SQLITE_NOMEM;
  150079. pMsr->aBuffer = pNew;
  150080. }
  150081. memcpy(pMsr->aBuffer, pList, nList);
  150082. return SQLITE_OK;
  150083. }
  150084. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  150085. Fts3Table *p, /* Virtual table handle */
  150086. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  150087. sqlite3_int64 *piDocid, /* OUT: Docid value */
  150088. char **paPoslist, /* OUT: Pointer to position list */
  150089. int *pnPoslist /* OUT: Size of position list in bytes */
  150090. ){
  150091. int nMerge = pMsr->nAdvance;
  150092. Fts3SegReader **apSegment = pMsr->apSegment;
  150093. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  150094. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  150095. );
  150096. if( nMerge==0 ){
  150097. *paPoslist = 0;
  150098. return SQLITE_OK;
  150099. }
  150100. while( 1 ){
  150101. Fts3SegReader *pSeg;
  150102. pSeg = pMsr->apSegment[0];
  150103. if( pSeg->pOffsetList==0 ){
  150104. *paPoslist = 0;
  150105. break;
  150106. }else{
  150107. int rc;
  150108. char *pList;
  150109. int nList;
  150110. int j;
  150111. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  150112. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  150113. j = 1;
  150114. while( rc==SQLITE_OK
  150115. && j<nMerge
  150116. && apSegment[j]->pOffsetList
  150117. && apSegment[j]->iDocid==iDocid
  150118. ){
  150119. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  150120. j++;
  150121. }
  150122. if( rc!=SQLITE_OK ) return rc;
  150123. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  150124. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  150125. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  150126. if( rc!=SQLITE_OK ) return rc;
  150127. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  150128. pList = pMsr->aBuffer;
  150129. }
  150130. if( pMsr->iColFilter>=0 ){
  150131. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  150132. }
  150133. if( nList>0 ){
  150134. *paPoslist = pList;
  150135. *piDocid = iDocid;
  150136. *pnPoslist = nList;
  150137. break;
  150138. }
  150139. }
  150140. }
  150141. return SQLITE_OK;
  150142. }
  150143. static int fts3SegReaderStart(
  150144. Fts3Table *p, /* Virtual table handle */
  150145. Fts3MultiSegReader *pCsr, /* Cursor object */
  150146. const char *zTerm, /* Term searched for (or NULL) */
  150147. int nTerm /* Length of zTerm in bytes */
  150148. ){
  150149. int i;
  150150. int nSeg = pCsr->nSegment;
  150151. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  150152. ** for, then advance each segment iterator until it points to a term of
  150153. ** equal or greater value than the specified term. This prevents many
  150154. ** unnecessary merge/sort operations for the case where single segment
  150155. ** b-tree leaf nodes contain more than one term.
  150156. */
  150157. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  150158. int res = 0;
  150159. Fts3SegReader *pSeg = pCsr->apSegment[i];
  150160. do {
  150161. int rc = fts3SegReaderNext(p, pSeg, 0);
  150162. if( rc!=SQLITE_OK ) return rc;
  150163. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  150164. if( pSeg->bLookup && res!=0 ){
  150165. fts3SegReaderSetEof(pSeg);
  150166. }
  150167. }
  150168. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  150169. return SQLITE_OK;
  150170. }
  150171. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  150172. Fts3Table *p, /* Virtual table handle */
  150173. Fts3MultiSegReader *pCsr, /* Cursor object */
  150174. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  150175. ){
  150176. pCsr->pFilter = pFilter;
  150177. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  150178. }
  150179. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  150180. Fts3Table *p, /* Virtual table handle */
  150181. Fts3MultiSegReader *pCsr, /* Cursor object */
  150182. int iCol, /* Column to match on. */
  150183. const char *zTerm, /* Term to iterate through a doclist for */
  150184. int nTerm /* Number of bytes in zTerm */
  150185. ){
  150186. int i;
  150187. int rc;
  150188. int nSegment = pCsr->nSegment;
  150189. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  150190. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  150191. );
  150192. assert( pCsr->pFilter==0 );
  150193. assert( zTerm && nTerm>0 );
  150194. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  150195. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  150196. if( rc!=SQLITE_OK ) return rc;
  150197. /* Determine how many of the segments actually point to zTerm/nTerm. */
  150198. for(i=0; i<nSegment; i++){
  150199. Fts3SegReader *pSeg = pCsr->apSegment[i];
  150200. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  150201. break;
  150202. }
  150203. }
  150204. pCsr->nAdvance = i;
  150205. /* Advance each of the segments to point to the first docid. */
  150206. for(i=0; i<pCsr->nAdvance; i++){
  150207. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  150208. if( rc!=SQLITE_OK ) return rc;
  150209. }
  150210. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  150211. assert( iCol<0 || iCol<p->nColumn );
  150212. pCsr->iColFilter = iCol;
  150213. return SQLITE_OK;
  150214. }
  150215. /*
  150216. ** This function is called on a MultiSegReader that has been started using
  150217. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  150218. ** have been made. Calling this function puts the MultiSegReader in such
  150219. ** a state that if the next two calls are:
  150220. **
  150221. ** sqlite3Fts3SegReaderStart()
  150222. ** sqlite3Fts3SegReaderStep()
  150223. **
  150224. ** then the entire doclist for the term is available in
  150225. ** MultiSegReader.aDoclist/nDoclist.
  150226. */
  150227. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  150228. int i; /* Used to iterate through segment-readers */
  150229. assert( pCsr->zTerm==0 );
  150230. assert( pCsr->nTerm==0 );
  150231. assert( pCsr->aDoclist==0 );
  150232. assert( pCsr->nDoclist==0 );
  150233. pCsr->nAdvance = 0;
  150234. pCsr->bRestart = 1;
  150235. for(i=0; i<pCsr->nSegment; i++){
  150236. pCsr->apSegment[i]->pOffsetList = 0;
  150237. pCsr->apSegment[i]->nOffsetList = 0;
  150238. pCsr->apSegment[i]->iDocid = 0;
  150239. }
  150240. return SQLITE_OK;
  150241. }
  150242. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  150243. Fts3Table *p, /* Virtual table handle */
  150244. Fts3MultiSegReader *pCsr /* Cursor object */
  150245. ){
  150246. int rc = SQLITE_OK;
  150247. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  150248. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  150249. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  150250. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  150251. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  150252. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  150253. Fts3SegReader **apSegment = pCsr->apSegment;
  150254. int nSegment = pCsr->nSegment;
  150255. Fts3SegFilter *pFilter = pCsr->pFilter;
  150256. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  150257. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  150258. );
  150259. if( pCsr->nSegment==0 ) return SQLITE_OK;
  150260. do {
  150261. int nMerge;
  150262. int i;
  150263. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  150264. ** forward. Then sort the list in order of current term again.
  150265. */
  150266. for(i=0; i<pCsr->nAdvance; i++){
  150267. Fts3SegReader *pSeg = apSegment[i];
  150268. if( pSeg->bLookup ){
  150269. fts3SegReaderSetEof(pSeg);
  150270. }else{
  150271. rc = fts3SegReaderNext(p, pSeg, 0);
  150272. }
  150273. if( rc!=SQLITE_OK ) return rc;
  150274. }
  150275. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  150276. pCsr->nAdvance = 0;
  150277. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  150278. assert( rc==SQLITE_OK );
  150279. if( apSegment[0]->aNode==0 ) break;
  150280. pCsr->nTerm = apSegment[0]->nTerm;
  150281. pCsr->zTerm = apSegment[0]->zTerm;
  150282. /* If this is a prefix-search, and if the term that apSegment[0] points
  150283. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  150284. ** required callbacks have been made. In this case exit early.
  150285. **
  150286. ** Similarly, if this is a search for an exact match, and the first term
  150287. ** of segment apSegment[0] is not a match, exit early.
  150288. */
  150289. if( pFilter->zTerm && !isScan ){
  150290. if( pCsr->nTerm<pFilter->nTerm
  150291. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  150292. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  150293. ){
  150294. break;
  150295. }
  150296. }
  150297. nMerge = 1;
  150298. while( nMerge<nSegment
  150299. && apSegment[nMerge]->aNode
  150300. && apSegment[nMerge]->nTerm==pCsr->nTerm
  150301. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  150302. ){
  150303. nMerge++;
  150304. }
  150305. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  150306. if( nMerge==1
  150307. && !isIgnoreEmpty
  150308. && !isFirst
  150309. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  150310. ){
  150311. pCsr->nDoclist = apSegment[0]->nDoclist;
  150312. if( fts3SegReaderIsPending(apSegment[0]) ){
  150313. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  150314. pCsr->aDoclist = pCsr->aBuffer;
  150315. }else{
  150316. pCsr->aDoclist = apSegment[0]->aDoclist;
  150317. }
  150318. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  150319. }else{
  150320. int nDoclist = 0; /* Size of doclist */
  150321. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  150322. /* The current term of the first nMerge entries in the array
  150323. ** of Fts3SegReader objects is the same. The doclists must be merged
  150324. ** and a single term returned with the merged doclist.
  150325. */
  150326. for(i=0; i<nMerge; i++){
  150327. fts3SegReaderFirstDocid(p, apSegment[i]);
  150328. }
  150329. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  150330. while( apSegment[0]->pOffsetList ){
  150331. int j; /* Number of segments that share a docid */
  150332. char *pList = 0;
  150333. int nList = 0;
  150334. int nByte;
  150335. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  150336. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  150337. j = 1;
  150338. while( j<nMerge
  150339. && apSegment[j]->pOffsetList
  150340. && apSegment[j]->iDocid==iDocid
  150341. ){
  150342. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  150343. j++;
  150344. }
  150345. if( isColFilter ){
  150346. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  150347. }
  150348. if( !isIgnoreEmpty || nList>0 ){
  150349. /* Calculate the 'docid' delta value to write into the merged
  150350. ** doclist. */
  150351. sqlite3_int64 iDelta;
  150352. if( p->bDescIdx && nDoclist>0 ){
  150353. iDelta = iPrev - iDocid;
  150354. }else{
  150355. iDelta = iDocid - iPrev;
  150356. }
  150357. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  150358. assert( nDoclist>0 || iDelta==iDocid );
  150359. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  150360. if( nDoclist+nByte>pCsr->nBuffer ){
  150361. char *aNew;
  150362. pCsr->nBuffer = (nDoclist+nByte)*2;
  150363. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  150364. if( !aNew ){
  150365. return SQLITE_NOMEM;
  150366. }
  150367. pCsr->aBuffer = aNew;
  150368. }
  150369. if( isFirst ){
  150370. char *a = &pCsr->aBuffer[nDoclist];
  150371. int nWrite;
  150372. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  150373. if( nWrite ){
  150374. iPrev = iDocid;
  150375. nDoclist += nWrite;
  150376. }
  150377. }else{
  150378. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  150379. iPrev = iDocid;
  150380. if( isRequirePos ){
  150381. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  150382. nDoclist += nList;
  150383. pCsr->aBuffer[nDoclist++] = '\0';
  150384. }
  150385. }
  150386. }
  150387. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  150388. }
  150389. if( nDoclist>0 ){
  150390. pCsr->aDoclist = pCsr->aBuffer;
  150391. pCsr->nDoclist = nDoclist;
  150392. rc = SQLITE_ROW;
  150393. }
  150394. }
  150395. pCsr->nAdvance = nMerge;
  150396. }while( rc==SQLITE_OK );
  150397. return rc;
  150398. }
  150399. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  150400. Fts3MultiSegReader *pCsr /* Cursor object */
  150401. ){
  150402. if( pCsr ){
  150403. int i;
  150404. for(i=0; i<pCsr->nSegment; i++){
  150405. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  150406. }
  150407. sqlite3_free(pCsr->apSegment);
  150408. sqlite3_free(pCsr->aBuffer);
  150409. pCsr->nSegment = 0;
  150410. pCsr->apSegment = 0;
  150411. pCsr->aBuffer = 0;
  150412. }
  150413. }
  150414. /*
  150415. ** Decode the "end_block" field, selected by column iCol of the SELECT
  150416. ** statement passed as the first argument.
  150417. **
  150418. ** The "end_block" field may contain either an integer, or a text field
  150419. ** containing the text representation of two non-negative integers separated
  150420. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  150421. ** to the integer value and *pnByte to zero before returning. In the second,
  150422. ** set *piEndBlock to the first value and *pnByte to the second.
  150423. */
  150424. static void fts3ReadEndBlockField(
  150425. sqlite3_stmt *pStmt,
  150426. int iCol,
  150427. i64 *piEndBlock,
  150428. i64 *pnByte
  150429. ){
  150430. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  150431. if( zText ){
  150432. int i;
  150433. int iMul = 1;
  150434. i64 iVal = 0;
  150435. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  150436. iVal = iVal*10 + (zText[i] - '0');
  150437. }
  150438. *piEndBlock = iVal;
  150439. while( zText[i]==' ' ) i++;
  150440. iVal = 0;
  150441. if( zText[i]=='-' ){
  150442. i++;
  150443. iMul = -1;
  150444. }
  150445. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  150446. iVal = iVal*10 + (zText[i] - '0');
  150447. }
  150448. *pnByte = (iVal * (i64)iMul);
  150449. }
  150450. }
  150451. /*
  150452. ** A segment of size nByte bytes has just been written to absolute level
  150453. ** iAbsLevel. Promote any segments that should be promoted as a result.
  150454. */
  150455. static int fts3PromoteSegments(
  150456. Fts3Table *p, /* FTS table handle */
  150457. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  150458. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  150459. ){
  150460. int rc = SQLITE_OK;
  150461. sqlite3_stmt *pRange;
  150462. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  150463. if( rc==SQLITE_OK ){
  150464. int bOk = 0;
  150465. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  150466. i64 nLimit = (nByte*3)/2;
  150467. /* Loop through all entries in the %_segdir table corresponding to
  150468. ** segments in this index on levels greater than iAbsLevel. If there is
  150469. ** at least one such segment, and it is possible to determine that all
  150470. ** such segments are smaller than nLimit bytes in size, they will be
  150471. ** promoted to level iAbsLevel. */
  150472. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  150473. sqlite3_bind_int64(pRange, 2, iLast);
  150474. while( SQLITE_ROW==sqlite3_step(pRange) ){
  150475. i64 nSize = 0, dummy;
  150476. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  150477. if( nSize<=0 || nSize>nLimit ){
  150478. /* If nSize==0, then the %_segdir.end_block field does not not
  150479. ** contain a size value. This happens if it was written by an
  150480. ** old version of FTS. In this case it is not possible to determine
  150481. ** the size of the segment, and so segment promotion does not
  150482. ** take place. */
  150483. bOk = 0;
  150484. break;
  150485. }
  150486. bOk = 1;
  150487. }
  150488. rc = sqlite3_reset(pRange);
  150489. if( bOk ){
  150490. int iIdx = 0;
  150491. sqlite3_stmt *pUpdate1 = 0;
  150492. sqlite3_stmt *pUpdate2 = 0;
  150493. if( rc==SQLITE_OK ){
  150494. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  150495. }
  150496. if( rc==SQLITE_OK ){
  150497. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  150498. }
  150499. if( rc==SQLITE_OK ){
  150500. /* Loop through all %_segdir entries for segments in this index with
  150501. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  150502. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  150503. ** oldest segment in the range, 1 for the next oldest, and so on.
  150504. **
  150505. ** In other words, move all segments being promoted to level -1,
  150506. ** setting the "idx" fields as appropriate to keep them in the same
  150507. ** order. The contents of level -1 (which is never used, except
  150508. ** transiently here), will be moved back to level iAbsLevel below. */
  150509. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  150510. while( SQLITE_ROW==sqlite3_step(pRange) ){
  150511. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  150512. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  150513. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  150514. sqlite3_step(pUpdate1);
  150515. rc = sqlite3_reset(pUpdate1);
  150516. if( rc!=SQLITE_OK ){
  150517. sqlite3_reset(pRange);
  150518. break;
  150519. }
  150520. }
  150521. }
  150522. if( rc==SQLITE_OK ){
  150523. rc = sqlite3_reset(pRange);
  150524. }
  150525. /* Move level -1 to level iAbsLevel */
  150526. if( rc==SQLITE_OK ){
  150527. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  150528. sqlite3_step(pUpdate2);
  150529. rc = sqlite3_reset(pUpdate2);
  150530. }
  150531. }
  150532. }
  150533. return rc;
  150534. }
  150535. /*
  150536. ** Merge all level iLevel segments in the database into a single
  150537. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  150538. ** single segment with a level equal to the numerically largest level
  150539. ** currently present in the database.
  150540. **
  150541. ** If this function is called with iLevel<0, but there is only one
  150542. ** segment in the database, SQLITE_DONE is returned immediately.
  150543. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  150544. ** an SQLite error code is returned.
  150545. */
  150546. static int fts3SegmentMerge(
  150547. Fts3Table *p,
  150548. int iLangid, /* Language id to merge */
  150549. int iIndex, /* Index in p->aIndex[] to merge */
  150550. int iLevel /* Level to merge */
  150551. ){
  150552. int rc; /* Return code */
  150553. int iIdx = 0; /* Index of new segment */
  150554. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  150555. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  150556. Fts3SegFilter filter; /* Segment term filter condition */
  150557. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  150558. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  150559. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  150560. assert( iLevel==FTS3_SEGCURSOR_ALL
  150561. || iLevel==FTS3_SEGCURSOR_PENDING
  150562. || iLevel>=0
  150563. );
  150564. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  150565. assert( iIndex>=0 && iIndex<p->nIndex );
  150566. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  150567. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  150568. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  150569. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  150570. if( rc!=SQLITE_OK ) goto finished;
  150571. }
  150572. if( iLevel==FTS3_SEGCURSOR_ALL ){
  150573. /* This call is to merge all segments in the database to a single
  150574. ** segment. The level of the new segment is equal to the numerically
  150575. ** greatest segment level currently present in the database for this
  150576. ** index. The idx of the new segment is always 0. */
  150577. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  150578. rc = SQLITE_DONE;
  150579. goto finished;
  150580. }
  150581. iNewLevel = iMaxLevel;
  150582. bIgnoreEmpty = 1;
  150583. }else{
  150584. /* This call is to merge all segments at level iLevel. find the next
  150585. ** available segment index at level iLevel+1. The call to
  150586. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  150587. ** a single iLevel+2 segment if necessary. */
  150588. assert( FTS3_SEGCURSOR_PENDING==-1 );
  150589. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  150590. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  150591. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  150592. }
  150593. if( rc!=SQLITE_OK ) goto finished;
  150594. assert( csr.nSegment>0 );
  150595. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  150596. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  150597. memset(&filter, 0, sizeof(Fts3SegFilter));
  150598. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  150599. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  150600. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  150601. while( SQLITE_OK==rc ){
  150602. rc = sqlite3Fts3SegReaderStep(p, &csr);
  150603. if( rc!=SQLITE_ROW ) break;
  150604. rc = fts3SegWriterAdd(p, &pWriter, 1,
  150605. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  150606. }
  150607. if( rc!=SQLITE_OK ) goto finished;
  150608. assert( pWriter || bIgnoreEmpty );
  150609. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  150610. rc = fts3DeleteSegdir(
  150611. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  150612. );
  150613. if( rc!=SQLITE_OK ) goto finished;
  150614. }
  150615. if( pWriter ){
  150616. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  150617. if( rc==SQLITE_OK ){
  150618. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  150619. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  150620. }
  150621. }
  150622. }
  150623. finished:
  150624. fts3SegWriterFree(pWriter);
  150625. sqlite3Fts3SegReaderFinish(&csr);
  150626. return rc;
  150627. }
  150628. /*
  150629. ** Flush the contents of pendingTerms to level 0 segments.
  150630. */
  150631. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  150632. int rc = SQLITE_OK;
  150633. int i;
  150634. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  150635. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  150636. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  150637. }
  150638. sqlite3Fts3PendingTermsClear(p);
  150639. /* Determine the auto-incr-merge setting if unknown. If enabled,
  150640. ** estimate the number of leaf blocks of content to be written
  150641. */
  150642. if( rc==SQLITE_OK && p->bHasStat
  150643. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  150644. ){
  150645. sqlite3_stmt *pStmt = 0;
  150646. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  150647. if( rc==SQLITE_OK ){
  150648. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  150649. rc = sqlite3_step(pStmt);
  150650. if( rc==SQLITE_ROW ){
  150651. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  150652. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  150653. }else if( rc==SQLITE_DONE ){
  150654. p->nAutoincrmerge = 0;
  150655. }
  150656. rc = sqlite3_reset(pStmt);
  150657. }
  150658. }
  150659. return rc;
  150660. }
  150661. /*
  150662. ** Encode N integers as varints into a blob.
  150663. */
  150664. static void fts3EncodeIntArray(
  150665. int N, /* The number of integers to encode */
  150666. u32 *a, /* The integer values */
  150667. char *zBuf, /* Write the BLOB here */
  150668. int *pNBuf /* Write number of bytes if zBuf[] used here */
  150669. ){
  150670. int i, j;
  150671. for(i=j=0; i<N; i++){
  150672. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  150673. }
  150674. *pNBuf = j;
  150675. }
  150676. /*
  150677. ** Decode a blob of varints into N integers
  150678. */
  150679. static void fts3DecodeIntArray(
  150680. int N, /* The number of integers to decode */
  150681. u32 *a, /* Write the integer values */
  150682. const char *zBuf, /* The BLOB containing the varints */
  150683. int nBuf /* size of the BLOB */
  150684. ){
  150685. int i, j;
  150686. UNUSED_PARAMETER(nBuf);
  150687. for(i=j=0; i<N; i++){
  150688. sqlite3_int64 x;
  150689. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  150690. assert(j<=nBuf);
  150691. a[i] = (u32)(x & 0xffffffff);
  150692. }
  150693. }
  150694. /*
  150695. ** Insert the sizes (in tokens) for each column of the document
  150696. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  150697. ** a blob of varints.
  150698. */
  150699. static void fts3InsertDocsize(
  150700. int *pRC, /* Result code */
  150701. Fts3Table *p, /* Table into which to insert */
  150702. u32 *aSz /* Sizes of each column, in tokens */
  150703. ){
  150704. char *pBlob; /* The BLOB encoding of the document size */
  150705. int nBlob; /* Number of bytes in the BLOB */
  150706. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  150707. int rc; /* Result code from subfunctions */
  150708. if( *pRC ) return;
  150709. pBlob = sqlite3_malloc( 10*p->nColumn );
  150710. if( pBlob==0 ){
  150711. *pRC = SQLITE_NOMEM;
  150712. return;
  150713. }
  150714. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  150715. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  150716. if( rc ){
  150717. sqlite3_free(pBlob);
  150718. *pRC = rc;
  150719. return;
  150720. }
  150721. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  150722. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  150723. sqlite3_step(pStmt);
  150724. *pRC = sqlite3_reset(pStmt);
  150725. }
  150726. /*
  150727. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  150728. ** where N is the number of user defined columns in the fts3 table plus
  150729. ** two. If nCol is the number of user defined columns, then values of the
  150730. ** varints are set as follows:
  150731. **
  150732. ** Varint 0: Total number of rows in the table.
  150733. **
  150734. ** Varint 1..nCol: For each column, the total number of tokens stored in
  150735. ** the column for all rows of the table.
  150736. **
  150737. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  150738. ** columns of all rows of the table.
  150739. **
  150740. */
  150741. static void fts3UpdateDocTotals(
  150742. int *pRC, /* The result code */
  150743. Fts3Table *p, /* Table being updated */
  150744. u32 *aSzIns, /* Size increases */
  150745. u32 *aSzDel, /* Size decreases */
  150746. int nChng /* Change in the number of documents */
  150747. ){
  150748. char *pBlob; /* Storage for BLOB written into %_stat */
  150749. int nBlob; /* Size of BLOB written into %_stat */
  150750. u32 *a; /* Array of integers that becomes the BLOB */
  150751. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  150752. int i; /* Loop counter */
  150753. int rc; /* Result code from subfunctions */
  150754. const int nStat = p->nColumn+2;
  150755. if( *pRC ) return;
  150756. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  150757. if( a==0 ){
  150758. *pRC = SQLITE_NOMEM;
  150759. return;
  150760. }
  150761. pBlob = (char*)&a[nStat];
  150762. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  150763. if( rc ){
  150764. sqlite3_free(a);
  150765. *pRC = rc;
  150766. return;
  150767. }
  150768. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  150769. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  150770. fts3DecodeIntArray(nStat, a,
  150771. sqlite3_column_blob(pStmt, 0),
  150772. sqlite3_column_bytes(pStmt, 0));
  150773. }else{
  150774. memset(a, 0, sizeof(u32)*(nStat) );
  150775. }
  150776. rc = sqlite3_reset(pStmt);
  150777. if( rc!=SQLITE_OK ){
  150778. sqlite3_free(a);
  150779. *pRC = rc;
  150780. return;
  150781. }
  150782. if( nChng<0 && a[0]<(u32)(-nChng) ){
  150783. a[0] = 0;
  150784. }else{
  150785. a[0] += nChng;
  150786. }
  150787. for(i=0; i<p->nColumn+1; i++){
  150788. u32 x = a[i+1];
  150789. if( x+aSzIns[i] < aSzDel[i] ){
  150790. x = 0;
  150791. }else{
  150792. x = x + aSzIns[i] - aSzDel[i];
  150793. }
  150794. a[i+1] = x;
  150795. }
  150796. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  150797. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  150798. if( rc ){
  150799. sqlite3_free(a);
  150800. *pRC = rc;
  150801. return;
  150802. }
  150803. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  150804. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  150805. sqlite3_step(pStmt);
  150806. *pRC = sqlite3_reset(pStmt);
  150807. sqlite3_free(a);
  150808. }
  150809. /*
  150810. ** Merge the entire database so that there is one segment for each
  150811. ** iIndex/iLangid combination.
  150812. */
  150813. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  150814. int bSeenDone = 0;
  150815. int rc;
  150816. sqlite3_stmt *pAllLangid = 0;
  150817. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  150818. if( rc==SQLITE_OK ){
  150819. int rc2;
  150820. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  150821. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  150822. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  150823. int i;
  150824. int iLangid = sqlite3_column_int(pAllLangid, 0);
  150825. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  150826. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  150827. if( rc==SQLITE_DONE ){
  150828. bSeenDone = 1;
  150829. rc = SQLITE_OK;
  150830. }
  150831. }
  150832. }
  150833. rc2 = sqlite3_reset(pAllLangid);
  150834. if( rc==SQLITE_OK ) rc = rc2;
  150835. }
  150836. sqlite3Fts3SegmentsClose(p);
  150837. sqlite3Fts3PendingTermsClear(p);
  150838. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  150839. }
  150840. /*
  150841. ** This function is called when the user executes the following statement:
  150842. **
  150843. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  150844. **
  150845. ** The entire FTS index is discarded and rebuilt. If the table is one
  150846. ** created using the content=xxx option, then the new index is based on
  150847. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  150848. ** on the contents of the %_content table.
  150849. */
  150850. static int fts3DoRebuild(Fts3Table *p){
  150851. int rc; /* Return Code */
  150852. rc = fts3DeleteAll(p, 0);
  150853. if( rc==SQLITE_OK ){
  150854. u32 *aSz = 0;
  150855. u32 *aSzIns = 0;
  150856. u32 *aSzDel = 0;
  150857. sqlite3_stmt *pStmt = 0;
  150858. int nEntry = 0;
  150859. /* Compose and prepare an SQL statement to loop through the content table */
  150860. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  150861. if( !zSql ){
  150862. rc = SQLITE_NOMEM;
  150863. }else{
  150864. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  150865. sqlite3_free(zSql);
  150866. }
  150867. if( rc==SQLITE_OK ){
  150868. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  150869. aSz = (u32 *)sqlite3_malloc(nByte);
  150870. if( aSz==0 ){
  150871. rc = SQLITE_NOMEM;
  150872. }else{
  150873. memset(aSz, 0, nByte);
  150874. aSzIns = &aSz[p->nColumn+1];
  150875. aSzDel = &aSzIns[p->nColumn+1];
  150876. }
  150877. }
  150878. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  150879. int iCol;
  150880. int iLangid = langidFromSelect(p, pStmt);
  150881. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  150882. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  150883. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  150884. if( p->abNotindexed[iCol]==0 ){
  150885. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  150886. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  150887. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  150888. }
  150889. }
  150890. if( p->bHasDocsize ){
  150891. fts3InsertDocsize(&rc, p, aSz);
  150892. }
  150893. if( rc!=SQLITE_OK ){
  150894. sqlite3_finalize(pStmt);
  150895. pStmt = 0;
  150896. }else{
  150897. nEntry++;
  150898. for(iCol=0; iCol<=p->nColumn; iCol++){
  150899. aSzIns[iCol] += aSz[iCol];
  150900. }
  150901. }
  150902. }
  150903. if( p->bFts4 ){
  150904. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  150905. }
  150906. sqlite3_free(aSz);
  150907. if( pStmt ){
  150908. int rc2 = sqlite3_finalize(pStmt);
  150909. if( rc==SQLITE_OK ){
  150910. rc = rc2;
  150911. }
  150912. }
  150913. }
  150914. return rc;
  150915. }
  150916. /*
  150917. ** This function opens a cursor used to read the input data for an
  150918. ** incremental merge operation. Specifically, it opens a cursor to scan
  150919. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  150920. ** level iAbsLevel.
  150921. */
  150922. static int fts3IncrmergeCsr(
  150923. Fts3Table *p, /* FTS3 table handle */
  150924. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  150925. int nSeg, /* Number of segments to merge */
  150926. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  150927. ){
  150928. int rc; /* Return Code */
  150929. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  150930. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  150931. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  150932. memset(pCsr, 0, sizeof(*pCsr));
  150933. nByte = sizeof(Fts3SegReader *) * nSeg;
  150934. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  150935. if( pCsr->apSegment==0 ){
  150936. rc = SQLITE_NOMEM;
  150937. }else{
  150938. memset(pCsr->apSegment, 0, nByte);
  150939. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  150940. }
  150941. if( rc==SQLITE_OK ){
  150942. int i;
  150943. int rc2;
  150944. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  150945. assert( pCsr->nSegment==0 );
  150946. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  150947. rc = sqlite3Fts3SegReaderNew(i, 0,
  150948. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  150949. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  150950. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  150951. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  150952. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  150953. &pCsr->apSegment[i]
  150954. );
  150955. pCsr->nSegment++;
  150956. }
  150957. rc2 = sqlite3_reset(pStmt);
  150958. if( rc==SQLITE_OK ) rc = rc2;
  150959. }
  150960. return rc;
  150961. }
  150962. typedef struct IncrmergeWriter IncrmergeWriter;
  150963. typedef struct NodeWriter NodeWriter;
  150964. typedef struct Blob Blob;
  150965. typedef struct NodeReader NodeReader;
  150966. /*
  150967. ** An instance of the following structure is used as a dynamic buffer
  150968. ** to build up nodes or other blobs of data in.
  150969. **
  150970. ** The function blobGrowBuffer() is used to extend the allocation.
  150971. */
  150972. struct Blob {
  150973. char *a; /* Pointer to allocation */
  150974. int n; /* Number of valid bytes of data in a[] */
  150975. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  150976. };
  150977. /*
  150978. ** This structure is used to build up buffers containing segment b-tree
  150979. ** nodes (blocks).
  150980. */
  150981. struct NodeWriter {
  150982. sqlite3_int64 iBlock; /* Current block id */
  150983. Blob key; /* Last key written to the current block */
  150984. Blob block; /* Current block image */
  150985. };
  150986. /*
  150987. ** An object of this type contains the state required to create or append
  150988. ** to an appendable b-tree segment.
  150989. */
  150990. struct IncrmergeWriter {
  150991. int nLeafEst; /* Space allocated for leaf blocks */
  150992. int nWork; /* Number of leaf pages flushed */
  150993. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  150994. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  150995. sqlite3_int64 iStart; /* Block number of first allocated block */
  150996. sqlite3_int64 iEnd; /* Block number of last allocated block */
  150997. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  150998. u8 bNoLeafData; /* If true, store 0 for segment size */
  150999. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  151000. };
  151001. /*
  151002. ** An object of the following type is used to read data from a single
  151003. ** FTS segment node. See the following functions:
  151004. **
  151005. ** nodeReaderInit()
  151006. ** nodeReaderNext()
  151007. ** nodeReaderRelease()
  151008. */
  151009. struct NodeReader {
  151010. const char *aNode;
  151011. int nNode;
  151012. int iOff; /* Current offset within aNode[] */
  151013. /* Output variables. Containing the current node entry. */
  151014. sqlite3_int64 iChild; /* Pointer to child node */
  151015. Blob term; /* Current term */
  151016. const char *aDoclist; /* Pointer to doclist */
  151017. int nDoclist; /* Size of doclist in bytes */
  151018. };
  151019. /*
  151020. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  151021. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  151022. ** bytes in size, extend (realloc) it to be so.
  151023. **
  151024. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  151025. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  151026. ** to reflect the new size of the pBlob->a[] buffer.
  151027. */
  151028. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  151029. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  151030. int nAlloc = nMin;
  151031. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  151032. if( a ){
  151033. pBlob->nAlloc = nAlloc;
  151034. pBlob->a = a;
  151035. }else{
  151036. *pRc = SQLITE_NOMEM;
  151037. }
  151038. }
  151039. }
  151040. /*
  151041. ** Attempt to advance the node-reader object passed as the first argument to
  151042. ** the next entry on the node.
  151043. **
  151044. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  151045. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  151046. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  151047. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  151048. ** variables for the new entry.
  151049. */
  151050. static int nodeReaderNext(NodeReader *p){
  151051. int bFirst = (p->term.n==0); /* True for first term on the node */
  151052. int nPrefix = 0; /* Bytes to copy from previous term */
  151053. int nSuffix = 0; /* Bytes to append to the prefix */
  151054. int rc = SQLITE_OK; /* Return code */
  151055. assert( p->aNode );
  151056. if( p->iChild && bFirst==0 ) p->iChild++;
  151057. if( p->iOff>=p->nNode ){
  151058. /* EOF */
  151059. p->aNode = 0;
  151060. }else{
  151061. if( bFirst==0 ){
  151062. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  151063. }
  151064. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  151065. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  151066. if( rc==SQLITE_OK ){
  151067. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  151068. p->term.n = nPrefix+nSuffix;
  151069. p->iOff += nSuffix;
  151070. if( p->iChild==0 ){
  151071. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  151072. p->aDoclist = &p->aNode[p->iOff];
  151073. p->iOff += p->nDoclist;
  151074. }
  151075. }
  151076. }
  151077. assert( p->iOff<=p->nNode );
  151078. return rc;
  151079. }
  151080. /*
  151081. ** Release all dynamic resources held by node-reader object *p.
  151082. */
  151083. static void nodeReaderRelease(NodeReader *p){
  151084. sqlite3_free(p->term.a);
  151085. }
  151086. /*
  151087. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  151088. **
  151089. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  151090. ** point to the first entry on the node (if any). Otherwise, an SQLite
  151091. ** error code is returned.
  151092. */
  151093. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  151094. memset(p, 0, sizeof(NodeReader));
  151095. p->aNode = aNode;
  151096. p->nNode = nNode;
  151097. /* Figure out if this is a leaf or an internal node. */
  151098. if( p->aNode[0] ){
  151099. /* An internal node. */
  151100. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  151101. }else{
  151102. p->iOff = 1;
  151103. }
  151104. return nodeReaderNext(p);
  151105. }
  151106. /*
  151107. ** This function is called while writing an FTS segment each time a leaf o
  151108. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  151109. ** to be greater than the largest key on the node just written, but smaller
  151110. ** than or equal to the first key that will be written to the next leaf
  151111. ** node.
  151112. **
  151113. ** The block id of the leaf node just written to disk may be found in
  151114. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  151115. */
  151116. static int fts3IncrmergePush(
  151117. Fts3Table *p, /* Fts3 table handle */
  151118. IncrmergeWriter *pWriter, /* Writer object */
  151119. const char *zTerm, /* Term to write to internal node */
  151120. int nTerm /* Bytes at zTerm */
  151121. ){
  151122. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  151123. int iLayer;
  151124. assert( nTerm>0 );
  151125. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  151126. sqlite3_int64 iNextPtr = 0;
  151127. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  151128. int rc = SQLITE_OK;
  151129. int nPrefix;
  151130. int nSuffix;
  151131. int nSpace;
  151132. /* Figure out how much space the key will consume if it is written to
  151133. ** the current node of layer iLayer. Due to the prefix compression,
  151134. ** the space required changes depending on which node the key is to
  151135. ** be added to. */
  151136. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  151137. nSuffix = nTerm - nPrefix;
  151138. nSpace = sqlite3Fts3VarintLen(nPrefix);
  151139. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  151140. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  151141. /* If the current node of layer iLayer contains zero keys, or if adding
  151142. ** the key to it will not cause it to grow to larger than nNodeSize
  151143. ** bytes in size, write the key here. */
  151144. Blob *pBlk = &pNode->block;
  151145. if( pBlk->n==0 ){
  151146. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  151147. if( rc==SQLITE_OK ){
  151148. pBlk->a[0] = (char)iLayer;
  151149. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  151150. }
  151151. }
  151152. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  151153. blobGrowBuffer(&pNode->key, nTerm, &rc);
  151154. if( rc==SQLITE_OK ){
  151155. if( pNode->key.n ){
  151156. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  151157. }
  151158. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  151159. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  151160. pBlk->n += nSuffix;
  151161. memcpy(pNode->key.a, zTerm, nTerm);
  151162. pNode->key.n = nTerm;
  151163. }
  151164. }else{
  151165. /* Otherwise, flush the current node of layer iLayer to disk.
  151166. ** Then allocate a new, empty sibling node. The key will be written
  151167. ** into the parent of this node. */
  151168. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  151169. assert( pNode->block.nAlloc>=p->nNodeSize );
  151170. pNode->block.a[0] = (char)iLayer;
  151171. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  151172. iNextPtr = pNode->iBlock;
  151173. pNode->iBlock++;
  151174. pNode->key.n = 0;
  151175. }
  151176. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  151177. iPtr = iNextPtr;
  151178. }
  151179. assert( 0 );
  151180. return 0;
  151181. }
  151182. /*
  151183. ** Append a term and (optionally) doclist to the FTS segment node currently
  151184. ** stored in blob *pNode. The node need not contain any terms, but the
  151185. ** header must be written before this function is called.
  151186. **
  151187. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  151188. ** followed by the left-hand-child varint for an internal node.
  151189. **
  151190. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  151191. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  151192. ** node, both aDoclist and nDoclist must be passed 0.
  151193. **
  151194. ** If the size of the value in blob pPrev is zero, then this is the first
  151195. ** term written to the node. Otherwise, pPrev contains a copy of the
  151196. ** previous term. Before this function returns, it is updated to contain a
  151197. ** copy of zTerm/nTerm.
  151198. **
  151199. ** It is assumed that the buffer associated with pNode is already large
  151200. ** enough to accommodate the new entry. The buffer associated with pPrev
  151201. ** is extended by this function if requrired.
  151202. **
  151203. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  151204. ** returned. Otherwise, SQLITE_OK.
  151205. */
  151206. static int fts3AppendToNode(
  151207. Blob *pNode, /* Current node image to append to */
  151208. Blob *pPrev, /* Buffer containing previous term written */
  151209. const char *zTerm, /* New term to write */
  151210. int nTerm, /* Size of zTerm in bytes */
  151211. const char *aDoclist, /* Doclist (or NULL) to write */
  151212. int nDoclist /* Size of aDoclist in bytes */
  151213. ){
  151214. int rc = SQLITE_OK; /* Return code */
  151215. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  151216. int nPrefix; /* Size of term prefix in bytes */
  151217. int nSuffix; /* Size of term suffix in bytes */
  151218. /* Node must have already been started. There must be a doclist for a
  151219. ** leaf node, and there must not be a doclist for an internal node. */
  151220. assert( pNode->n>0 );
  151221. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  151222. blobGrowBuffer(pPrev, nTerm, &rc);
  151223. if( rc!=SQLITE_OK ) return rc;
  151224. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  151225. nSuffix = nTerm - nPrefix;
  151226. memcpy(pPrev->a, zTerm, nTerm);
  151227. pPrev->n = nTerm;
  151228. if( bFirst==0 ){
  151229. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  151230. }
  151231. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  151232. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  151233. pNode->n += nSuffix;
  151234. if( aDoclist ){
  151235. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  151236. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  151237. pNode->n += nDoclist;
  151238. }
  151239. assert( pNode->n<=pNode->nAlloc );
  151240. return SQLITE_OK;
  151241. }
  151242. /*
  151243. ** Append the current term and doclist pointed to by cursor pCsr to the
  151244. ** appendable b-tree segment opened for writing by pWriter.
  151245. **
  151246. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  151247. */
  151248. static int fts3IncrmergeAppend(
  151249. Fts3Table *p, /* Fts3 table handle */
  151250. IncrmergeWriter *pWriter, /* Writer object */
  151251. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  151252. ){
  151253. const char *zTerm = pCsr->zTerm;
  151254. int nTerm = pCsr->nTerm;
  151255. const char *aDoclist = pCsr->aDoclist;
  151256. int nDoclist = pCsr->nDoclist;
  151257. int rc = SQLITE_OK; /* Return code */
  151258. int nSpace; /* Total space in bytes required on leaf */
  151259. int nPrefix; /* Size of prefix shared with previous term */
  151260. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  151261. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  151262. pLeaf = &pWriter->aNodeWriter[0];
  151263. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  151264. nSuffix = nTerm - nPrefix;
  151265. nSpace = sqlite3Fts3VarintLen(nPrefix);
  151266. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  151267. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  151268. /* If the current block is not empty, and if adding this term/doclist
  151269. ** to the current block would make it larger than Fts3Table.nNodeSize
  151270. ** bytes, write this block out to the database. */
  151271. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  151272. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  151273. pWriter->nWork++;
  151274. /* Add the current term to the parent node. The term added to the
  151275. ** parent must:
  151276. **
  151277. ** a) be greater than the largest term on the leaf node just written
  151278. ** to the database (still available in pLeaf->key), and
  151279. **
  151280. ** b) be less than or equal to the term about to be added to the new
  151281. ** leaf node (zTerm/nTerm).
  151282. **
  151283. ** In other words, it must be the prefix of zTerm 1 byte longer than
  151284. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  151285. */
  151286. if( rc==SQLITE_OK ){
  151287. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  151288. }
  151289. /* Advance to the next output block */
  151290. pLeaf->iBlock++;
  151291. pLeaf->key.n = 0;
  151292. pLeaf->block.n = 0;
  151293. nSuffix = nTerm;
  151294. nSpace = 1;
  151295. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  151296. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  151297. }
  151298. pWriter->nLeafData += nSpace;
  151299. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  151300. if( rc==SQLITE_OK ){
  151301. if( pLeaf->block.n==0 ){
  151302. pLeaf->block.n = 1;
  151303. pLeaf->block.a[0] = '\0';
  151304. }
  151305. rc = fts3AppendToNode(
  151306. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  151307. );
  151308. }
  151309. return rc;
  151310. }
  151311. /*
  151312. ** This function is called to release all dynamic resources held by the
  151313. ** merge-writer object pWriter, and if no error has occurred, to flush
  151314. ** all outstanding node buffers held by pWriter to disk.
  151315. **
  151316. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  151317. ** is made to write any data to disk. Instead, this function serves only
  151318. ** to release outstanding resources.
  151319. **
  151320. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  151321. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  151322. ** returning.
  151323. */
  151324. static void fts3IncrmergeRelease(
  151325. Fts3Table *p, /* FTS3 table handle */
  151326. IncrmergeWriter *pWriter, /* Merge-writer object */
  151327. int *pRc /* IN/OUT: Error code */
  151328. ){
  151329. int i; /* Used to iterate through non-root layers */
  151330. int iRoot; /* Index of root in pWriter->aNodeWriter */
  151331. NodeWriter *pRoot; /* NodeWriter for root node */
  151332. int rc = *pRc; /* Error code */
  151333. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  151334. ** root node. If the segment fits entirely on a single leaf node, iRoot
  151335. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  151336. ** will be 1. And so on. */
  151337. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  151338. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  151339. if( pNode->block.n>0 ) break;
  151340. assert( *pRc || pNode->block.nAlloc==0 );
  151341. assert( *pRc || pNode->key.nAlloc==0 );
  151342. sqlite3_free(pNode->block.a);
  151343. sqlite3_free(pNode->key.a);
  151344. }
  151345. /* Empty output segment. This is a no-op. */
  151346. if( iRoot<0 ) return;
  151347. /* The entire output segment fits on a single node. Normally, this means
  151348. ** the node would be stored as a blob in the "root" column of the %_segdir
  151349. ** table. However, this is not permitted in this case. The problem is that
  151350. ** space has already been reserved in the %_segments table, and so the
  151351. ** start_block and end_block fields of the %_segdir table must be populated.
  151352. ** And, by design or by accident, released versions of FTS cannot handle
  151353. ** segments that fit entirely on the root node with start_block!=0.
  151354. **
  151355. ** Instead, create a synthetic root node that contains nothing but a
  151356. ** pointer to the single content node. So that the segment consists of a
  151357. ** single leaf and a single interior (root) node.
  151358. **
  151359. ** Todo: Better might be to defer allocating space in the %_segments
  151360. ** table until we are sure it is needed.
  151361. */
  151362. if( iRoot==0 ){
  151363. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  151364. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  151365. if( rc==SQLITE_OK ){
  151366. pBlock->a[0] = 0x01;
  151367. pBlock->n = 1 + sqlite3Fts3PutVarint(
  151368. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  151369. );
  151370. }
  151371. iRoot = 1;
  151372. }
  151373. pRoot = &pWriter->aNodeWriter[iRoot];
  151374. /* Flush all currently outstanding nodes to disk. */
  151375. for(i=0; i<iRoot; i++){
  151376. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  151377. if( pNode->block.n>0 && rc==SQLITE_OK ){
  151378. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  151379. }
  151380. sqlite3_free(pNode->block.a);
  151381. sqlite3_free(pNode->key.a);
  151382. }
  151383. /* Write the %_segdir record. */
  151384. if( rc==SQLITE_OK ){
  151385. rc = fts3WriteSegdir(p,
  151386. pWriter->iAbsLevel+1, /* level */
  151387. pWriter->iIdx, /* idx */
  151388. pWriter->iStart, /* start_block */
  151389. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  151390. pWriter->iEnd, /* end_block */
  151391. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  151392. pRoot->block.a, pRoot->block.n /* root */
  151393. );
  151394. }
  151395. sqlite3_free(pRoot->block.a);
  151396. sqlite3_free(pRoot->key.a);
  151397. *pRc = rc;
  151398. }
  151399. /*
  151400. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  151401. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  151402. ** the other, it is considered to be smaller than the other.
  151403. **
  151404. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  151405. ** if it is greater.
  151406. */
  151407. static int fts3TermCmp(
  151408. const char *zLhs, int nLhs, /* LHS of comparison */
  151409. const char *zRhs, int nRhs /* RHS of comparison */
  151410. ){
  151411. int nCmp = MIN(nLhs, nRhs);
  151412. int res;
  151413. res = memcmp(zLhs, zRhs, nCmp);
  151414. if( res==0 ) res = nLhs - nRhs;
  151415. return res;
  151416. }
  151417. /*
  151418. ** Query to see if the entry in the %_segments table with blockid iEnd is
  151419. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  151420. ** returning. Otherwise, set *pbRes to 0.
  151421. **
  151422. ** Or, if an error occurs while querying the database, return an SQLite
  151423. ** error code. The final value of *pbRes is undefined in this case.
  151424. **
  151425. ** This is used to test if a segment is an "appendable" segment. If it
  151426. ** is, then a NULL entry has been inserted into the %_segments table
  151427. ** with blockid %_segdir.end_block.
  151428. */
  151429. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  151430. int bRes = 0; /* Result to set *pbRes to */
  151431. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  151432. int rc; /* Return code */
  151433. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  151434. if( rc==SQLITE_OK ){
  151435. sqlite3_bind_int64(pCheck, 1, iEnd);
  151436. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  151437. rc = sqlite3_reset(pCheck);
  151438. }
  151439. *pbRes = bRes;
  151440. return rc;
  151441. }
  151442. /*
  151443. ** This function is called when initializing an incremental-merge operation.
  151444. ** It checks if the existing segment with index value iIdx at absolute level
  151445. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  151446. ** merge-writer object *pWriter is initialized to write to it.
  151447. **
  151448. ** An existing segment can be appended to by an incremental merge if:
  151449. **
  151450. ** * It was initially created as an appendable segment (with all required
  151451. ** space pre-allocated), and
  151452. **
  151453. ** * The first key read from the input (arguments zKey and nKey) is
  151454. ** greater than the largest key currently stored in the potential
  151455. ** output segment.
  151456. */
  151457. static int fts3IncrmergeLoad(
  151458. Fts3Table *p, /* Fts3 table handle */
  151459. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  151460. int iIdx, /* Index of candidate output segment */
  151461. const char *zKey, /* First key to write */
  151462. int nKey, /* Number of bytes in nKey */
  151463. IncrmergeWriter *pWriter /* Populate this object */
  151464. ){
  151465. int rc; /* Return code */
  151466. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  151467. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  151468. if( rc==SQLITE_OK ){
  151469. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  151470. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  151471. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  151472. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  151473. int nRoot = 0; /* Size of aRoot[] in bytes */
  151474. int rc2; /* Return code from sqlite3_reset() */
  151475. int bAppendable = 0; /* Set to true if segment is appendable */
  151476. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  151477. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  151478. sqlite3_bind_int(pSelect, 2, iIdx);
  151479. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  151480. iStart = sqlite3_column_int64(pSelect, 1);
  151481. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  151482. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  151483. if( pWriter->nLeafData<0 ){
  151484. pWriter->nLeafData = pWriter->nLeafData * -1;
  151485. }
  151486. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  151487. nRoot = sqlite3_column_bytes(pSelect, 4);
  151488. aRoot = sqlite3_column_blob(pSelect, 4);
  151489. }else{
  151490. return sqlite3_reset(pSelect);
  151491. }
  151492. /* Check for the zero-length marker in the %_segments table */
  151493. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  151494. /* Check that zKey/nKey is larger than the largest key the candidate */
  151495. if( rc==SQLITE_OK && bAppendable ){
  151496. char *aLeaf = 0;
  151497. int nLeaf = 0;
  151498. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  151499. if( rc==SQLITE_OK ){
  151500. NodeReader reader;
  151501. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  151502. rc==SQLITE_OK && reader.aNode;
  151503. rc = nodeReaderNext(&reader)
  151504. ){
  151505. assert( reader.aNode );
  151506. }
  151507. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  151508. bAppendable = 0;
  151509. }
  151510. nodeReaderRelease(&reader);
  151511. }
  151512. sqlite3_free(aLeaf);
  151513. }
  151514. if( rc==SQLITE_OK && bAppendable ){
  151515. /* It is possible to append to this segment. Set up the IncrmergeWriter
  151516. ** object to do so. */
  151517. int i;
  151518. int nHeight = (int)aRoot[0];
  151519. NodeWriter *pNode;
  151520. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  151521. pWriter->iStart = iStart;
  151522. pWriter->iEnd = iEnd;
  151523. pWriter->iAbsLevel = iAbsLevel;
  151524. pWriter->iIdx = iIdx;
  151525. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  151526. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  151527. }
  151528. pNode = &pWriter->aNodeWriter[nHeight];
  151529. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  151530. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  151531. if( rc==SQLITE_OK ){
  151532. memcpy(pNode->block.a, aRoot, nRoot);
  151533. pNode->block.n = nRoot;
  151534. }
  151535. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  151536. NodeReader reader;
  151537. pNode = &pWriter->aNodeWriter[i];
  151538. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  151539. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  151540. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  151541. if( rc==SQLITE_OK ){
  151542. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  151543. pNode->key.n = reader.term.n;
  151544. if( i>0 ){
  151545. char *aBlock = 0;
  151546. int nBlock = 0;
  151547. pNode = &pWriter->aNodeWriter[i-1];
  151548. pNode->iBlock = reader.iChild;
  151549. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  151550. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  151551. if( rc==SQLITE_OK ){
  151552. memcpy(pNode->block.a, aBlock, nBlock);
  151553. pNode->block.n = nBlock;
  151554. }
  151555. sqlite3_free(aBlock);
  151556. }
  151557. }
  151558. nodeReaderRelease(&reader);
  151559. }
  151560. }
  151561. rc2 = sqlite3_reset(pSelect);
  151562. if( rc==SQLITE_OK ) rc = rc2;
  151563. }
  151564. return rc;
  151565. }
  151566. /*
  151567. ** Determine the largest segment index value that exists within absolute
  151568. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  151569. ** one before returning SQLITE_OK. Or, if there are no segments at all
  151570. ** within level iAbsLevel, set *piIdx to zero.
  151571. **
  151572. ** If an error occurs, return an SQLite error code. The final value of
  151573. ** *piIdx is undefined in this case.
  151574. */
  151575. static int fts3IncrmergeOutputIdx(
  151576. Fts3Table *p, /* FTS Table handle */
  151577. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  151578. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  151579. ){
  151580. int rc;
  151581. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  151582. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  151583. if( rc==SQLITE_OK ){
  151584. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  151585. sqlite3_step(pOutputIdx);
  151586. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  151587. rc = sqlite3_reset(pOutputIdx);
  151588. }
  151589. return rc;
  151590. }
  151591. /*
  151592. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  151593. ** with idx value iIdx.
  151594. **
  151595. ** In the %_segdir table, a segment is defined by the values in three
  151596. ** columns:
  151597. **
  151598. ** start_block
  151599. ** leaves_end_block
  151600. ** end_block
  151601. **
  151602. ** When an appendable segment is allocated, it is estimated that the
  151603. ** maximum number of leaf blocks that may be required is the sum of the
  151604. ** number of leaf blocks consumed by the input segments, plus the number
  151605. ** of input segments, multiplied by two. This value is stored in stack
  151606. ** variable nLeafEst.
  151607. **
  151608. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  151609. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  151610. ** array of leaf nodes starts at the first block allocated. The array
  151611. ** of interior nodes that are parents of the leaf nodes start at block
  151612. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  151613. **
  151614. ** In the actual code below, the value "16" is replaced with the
  151615. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  151616. */
  151617. static int fts3IncrmergeWriter(
  151618. Fts3Table *p, /* Fts3 table handle */
  151619. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  151620. int iIdx, /* Index of new output segment */
  151621. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  151622. IncrmergeWriter *pWriter /* Populate this object */
  151623. ){
  151624. int rc; /* Return Code */
  151625. int i; /* Iterator variable */
  151626. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  151627. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  151628. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  151629. /* Calculate nLeafEst. */
  151630. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  151631. if( rc==SQLITE_OK ){
  151632. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  151633. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  151634. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  151635. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  151636. }
  151637. rc = sqlite3_reset(pLeafEst);
  151638. }
  151639. if( rc!=SQLITE_OK ) return rc;
  151640. /* Calculate the first block to use in the output segment */
  151641. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  151642. if( rc==SQLITE_OK ){
  151643. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  151644. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  151645. pWriter->iEnd = pWriter->iStart - 1;
  151646. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  151647. }
  151648. rc = sqlite3_reset(pFirstBlock);
  151649. }
  151650. if( rc!=SQLITE_OK ) return rc;
  151651. /* Insert the marker in the %_segments table to make sure nobody tries
  151652. ** to steal the space just allocated. This is also used to identify
  151653. ** appendable segments. */
  151654. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  151655. if( rc!=SQLITE_OK ) return rc;
  151656. pWriter->iAbsLevel = iAbsLevel;
  151657. pWriter->nLeafEst = nLeafEst;
  151658. pWriter->iIdx = iIdx;
  151659. /* Set up the array of NodeWriter objects */
  151660. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  151661. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  151662. }
  151663. return SQLITE_OK;
  151664. }
  151665. /*
  151666. ** Remove an entry from the %_segdir table. This involves running the
  151667. ** following two statements:
  151668. **
  151669. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  151670. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  151671. **
  151672. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  151673. ** statement ensures that the remaining segments have contiguously allocated
  151674. ** idx values.
  151675. */
  151676. static int fts3RemoveSegdirEntry(
  151677. Fts3Table *p, /* FTS3 table handle */
  151678. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  151679. int iIdx /* Index of %_segdir entry to delete */
  151680. ){
  151681. int rc; /* Return code */
  151682. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  151683. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  151684. if( rc==SQLITE_OK ){
  151685. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  151686. sqlite3_bind_int(pDelete, 2, iIdx);
  151687. sqlite3_step(pDelete);
  151688. rc = sqlite3_reset(pDelete);
  151689. }
  151690. return rc;
  151691. }
  151692. /*
  151693. ** One or more segments have just been removed from absolute level iAbsLevel.
  151694. ** Update the 'idx' values of the remaining segments in the level so that
  151695. ** the idx values are a contiguous sequence starting from 0.
  151696. */
  151697. static int fts3RepackSegdirLevel(
  151698. Fts3Table *p, /* FTS3 table handle */
  151699. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  151700. ){
  151701. int rc; /* Return code */
  151702. int *aIdx = 0; /* Array of remaining idx values */
  151703. int nIdx = 0; /* Valid entries in aIdx[] */
  151704. int nAlloc = 0; /* Allocated size of aIdx[] */
  151705. int i; /* Iterator variable */
  151706. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  151707. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  151708. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  151709. if( rc==SQLITE_OK ){
  151710. int rc2;
  151711. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  151712. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  151713. if( nIdx>=nAlloc ){
  151714. int *aNew;
  151715. nAlloc += 16;
  151716. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  151717. if( !aNew ){
  151718. rc = SQLITE_NOMEM;
  151719. break;
  151720. }
  151721. aIdx = aNew;
  151722. }
  151723. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  151724. }
  151725. rc2 = sqlite3_reset(pSelect);
  151726. if( rc==SQLITE_OK ) rc = rc2;
  151727. }
  151728. if( rc==SQLITE_OK ){
  151729. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  151730. }
  151731. if( rc==SQLITE_OK ){
  151732. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  151733. }
  151734. assert( p->bIgnoreSavepoint==0 );
  151735. p->bIgnoreSavepoint = 1;
  151736. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  151737. if( aIdx[i]!=i ){
  151738. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  151739. sqlite3_bind_int(pUpdate, 1, i);
  151740. sqlite3_step(pUpdate);
  151741. rc = sqlite3_reset(pUpdate);
  151742. }
  151743. }
  151744. p->bIgnoreSavepoint = 0;
  151745. sqlite3_free(aIdx);
  151746. return rc;
  151747. }
  151748. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  151749. pNode->a[0] = (char)iHeight;
  151750. if( iChild ){
  151751. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  151752. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  151753. }else{
  151754. assert( pNode->nAlloc>=1 );
  151755. pNode->n = 1;
  151756. }
  151757. }
  151758. /*
  151759. ** The first two arguments are a pointer to and the size of a segment b-tree
  151760. ** node. The node may be a leaf or an internal node.
  151761. **
  151762. ** This function creates a new node image in blob object *pNew by copying
  151763. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  151764. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  151765. */
  151766. static int fts3TruncateNode(
  151767. const char *aNode, /* Current node image */
  151768. int nNode, /* Size of aNode in bytes */
  151769. Blob *pNew, /* OUT: Write new node image here */
  151770. const char *zTerm, /* Omit all terms smaller than this */
  151771. int nTerm, /* Size of zTerm in bytes */
  151772. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  151773. ){
  151774. NodeReader reader; /* Reader object */
  151775. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  151776. int rc = SQLITE_OK; /* Return code */
  151777. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  151778. /* Allocate required output space */
  151779. blobGrowBuffer(pNew, nNode, &rc);
  151780. if( rc!=SQLITE_OK ) return rc;
  151781. pNew->n = 0;
  151782. /* Populate new node buffer */
  151783. for(rc = nodeReaderInit(&reader, aNode, nNode);
  151784. rc==SQLITE_OK && reader.aNode;
  151785. rc = nodeReaderNext(&reader)
  151786. ){
  151787. if( pNew->n==0 ){
  151788. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  151789. if( res<0 || (bLeaf==0 && res==0) ) continue;
  151790. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  151791. *piBlock = reader.iChild;
  151792. }
  151793. rc = fts3AppendToNode(
  151794. pNew, &prev, reader.term.a, reader.term.n,
  151795. reader.aDoclist, reader.nDoclist
  151796. );
  151797. if( rc!=SQLITE_OK ) break;
  151798. }
  151799. if( pNew->n==0 ){
  151800. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  151801. *piBlock = reader.iChild;
  151802. }
  151803. assert( pNew->n<=pNew->nAlloc );
  151804. nodeReaderRelease(&reader);
  151805. sqlite3_free(prev.a);
  151806. return rc;
  151807. }
  151808. /*
  151809. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  151810. ** level iAbsLevel. This may involve deleting entries from the %_segments
  151811. ** table, and modifying existing entries in both the %_segments and %_segdir
  151812. ** tables.
  151813. **
  151814. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  151815. ** SQLite error code otherwise.
  151816. */
  151817. static int fts3TruncateSegment(
  151818. Fts3Table *p, /* FTS3 table handle */
  151819. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  151820. int iIdx, /* Index within level of segment to modify */
  151821. const char *zTerm, /* Remove terms smaller than this */
  151822. int nTerm /* Number of bytes in buffer zTerm */
  151823. ){
  151824. int rc = SQLITE_OK; /* Return code */
  151825. Blob root = {0,0,0}; /* New root page image */
  151826. Blob block = {0,0,0}; /* Buffer used for any other block */
  151827. sqlite3_int64 iBlock = 0; /* Block id */
  151828. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  151829. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  151830. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  151831. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  151832. if( rc==SQLITE_OK ){
  151833. int rc2; /* sqlite3_reset() return code */
  151834. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  151835. sqlite3_bind_int(pFetch, 2, iIdx);
  151836. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  151837. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  151838. int nRoot = sqlite3_column_bytes(pFetch, 4);
  151839. iOldStart = sqlite3_column_int64(pFetch, 1);
  151840. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  151841. }
  151842. rc2 = sqlite3_reset(pFetch);
  151843. if( rc==SQLITE_OK ) rc = rc2;
  151844. }
  151845. while( rc==SQLITE_OK && iBlock ){
  151846. char *aBlock = 0;
  151847. int nBlock = 0;
  151848. iNewStart = iBlock;
  151849. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  151850. if( rc==SQLITE_OK ){
  151851. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  151852. }
  151853. if( rc==SQLITE_OK ){
  151854. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  151855. }
  151856. sqlite3_free(aBlock);
  151857. }
  151858. /* Variable iNewStart now contains the first valid leaf node. */
  151859. if( rc==SQLITE_OK && iNewStart ){
  151860. sqlite3_stmt *pDel = 0;
  151861. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  151862. if( rc==SQLITE_OK ){
  151863. sqlite3_bind_int64(pDel, 1, iOldStart);
  151864. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  151865. sqlite3_step(pDel);
  151866. rc = sqlite3_reset(pDel);
  151867. }
  151868. }
  151869. if( rc==SQLITE_OK ){
  151870. sqlite3_stmt *pChomp = 0;
  151871. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  151872. if( rc==SQLITE_OK ){
  151873. sqlite3_bind_int64(pChomp, 1, iNewStart);
  151874. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  151875. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  151876. sqlite3_bind_int(pChomp, 4, iIdx);
  151877. sqlite3_step(pChomp);
  151878. rc = sqlite3_reset(pChomp);
  151879. }
  151880. }
  151881. sqlite3_free(root.a);
  151882. sqlite3_free(block.a);
  151883. return rc;
  151884. }
  151885. /*
  151886. ** This function is called after an incrmental-merge operation has run to
  151887. ** merge (or partially merge) two or more segments from absolute level
  151888. ** iAbsLevel.
  151889. **
  151890. ** Each input segment is either removed from the db completely (if all of
  151891. ** its data was copied to the output segment by the incrmerge operation)
  151892. ** or modified in place so that it no longer contains those entries that
  151893. ** have been duplicated in the output segment.
  151894. */
  151895. static int fts3IncrmergeChomp(
  151896. Fts3Table *p, /* FTS table handle */
  151897. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  151898. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  151899. int *pnRem /* Number of segments not deleted */
  151900. ){
  151901. int i;
  151902. int nRem = 0;
  151903. int rc = SQLITE_OK;
  151904. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  151905. Fts3SegReader *pSeg = 0;
  151906. int j;
  151907. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  151908. ** somewhere in the pCsr->apSegment[] array. */
  151909. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  151910. pSeg = pCsr->apSegment[j];
  151911. if( pSeg->iIdx==i ) break;
  151912. }
  151913. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  151914. if( pSeg->aNode==0 ){
  151915. /* Seg-reader is at EOF. Remove the entire input segment. */
  151916. rc = fts3DeleteSegment(p, pSeg);
  151917. if( rc==SQLITE_OK ){
  151918. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  151919. }
  151920. *pnRem = 0;
  151921. }else{
  151922. /* The incremental merge did not copy all the data from this
  151923. ** segment to the upper level. The segment is modified in place
  151924. ** so that it contains no keys smaller than zTerm/nTerm. */
  151925. const char *zTerm = pSeg->zTerm;
  151926. int nTerm = pSeg->nTerm;
  151927. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  151928. nRem++;
  151929. }
  151930. }
  151931. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  151932. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  151933. }
  151934. *pnRem = nRem;
  151935. return rc;
  151936. }
  151937. /*
  151938. ** Store an incr-merge hint in the database.
  151939. */
  151940. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  151941. sqlite3_stmt *pReplace = 0;
  151942. int rc; /* Return code */
  151943. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  151944. if( rc==SQLITE_OK ){
  151945. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  151946. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  151947. sqlite3_step(pReplace);
  151948. rc = sqlite3_reset(pReplace);
  151949. }
  151950. return rc;
  151951. }
  151952. /*
  151953. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  151954. ** exists, is stored in the rowid==1 row of the %_stat table.
  151955. **
  151956. ** If successful, populate blob *pHint with the value read from the %_stat
  151957. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  151958. ** SQLite error code.
  151959. */
  151960. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  151961. sqlite3_stmt *pSelect = 0;
  151962. int rc;
  151963. pHint->n = 0;
  151964. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  151965. if( rc==SQLITE_OK ){
  151966. int rc2;
  151967. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  151968. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  151969. const char *aHint = sqlite3_column_blob(pSelect, 0);
  151970. int nHint = sqlite3_column_bytes(pSelect, 0);
  151971. if( aHint ){
  151972. blobGrowBuffer(pHint, nHint, &rc);
  151973. if( rc==SQLITE_OK ){
  151974. memcpy(pHint->a, aHint, nHint);
  151975. pHint->n = nHint;
  151976. }
  151977. }
  151978. }
  151979. rc2 = sqlite3_reset(pSelect);
  151980. if( rc==SQLITE_OK ) rc = rc2;
  151981. }
  151982. return rc;
  151983. }
  151984. /*
  151985. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  151986. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  151987. ** consists of two varints, the absolute level number of the input segments
  151988. ** and the number of input segments.
  151989. **
  151990. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  151991. ** set *pRc to an SQLite error code before returning.
  151992. */
  151993. static void fts3IncrmergeHintPush(
  151994. Blob *pHint, /* Hint blob to append to */
  151995. i64 iAbsLevel, /* First varint to store in hint */
  151996. int nInput, /* Second varint to store in hint */
  151997. int *pRc /* IN/OUT: Error code */
  151998. ){
  151999. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  152000. if( *pRc==SQLITE_OK ){
  152001. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  152002. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  152003. }
  152004. }
  152005. /*
  152006. ** Read the last entry (most recently pushed) from the hint blob *pHint
  152007. ** and then remove the entry. Write the two values read to *piAbsLevel and
  152008. ** *pnInput before returning.
  152009. **
  152010. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  152011. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  152012. */
  152013. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  152014. const int nHint = pHint->n;
  152015. int i;
  152016. i = pHint->n-2;
  152017. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  152018. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  152019. pHint->n = i;
  152020. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  152021. i += fts3GetVarint32(&pHint->a[i], pnInput);
  152022. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  152023. return SQLITE_OK;
  152024. }
  152025. /*
  152026. ** Attempt an incremental merge that writes nMerge leaf blocks.
  152027. **
  152028. ** Incremental merges happen nMin segments at a time. The segments
  152029. ** to be merged are the nMin oldest segments (the ones with the smallest
  152030. ** values for the _segdir.idx field) in the highest level that contains
  152031. ** at least nMin segments. Multiple merges might occur in an attempt to
  152032. ** write the quota of nMerge leaf blocks.
  152033. */
  152034. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  152035. int rc; /* Return code */
  152036. int nRem = nMerge; /* Number of leaf pages yet to be written */
  152037. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  152038. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  152039. IncrmergeWriter *pWriter; /* Writer object */
  152040. int nSeg = 0; /* Number of input segments */
  152041. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  152042. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  152043. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  152044. /* Allocate space for the cursor, filter and writer objects */
  152045. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  152046. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  152047. if( !pWriter ) return SQLITE_NOMEM;
  152048. pFilter = (Fts3SegFilter *)&pWriter[1];
  152049. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  152050. rc = fts3IncrmergeHintLoad(p, &hint);
  152051. while( rc==SQLITE_OK && nRem>0 ){
  152052. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  152053. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  152054. int bUseHint = 0; /* True if attempting to append */
  152055. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  152056. /* Search the %_segdir table for the absolute level with the smallest
  152057. ** relative level number that contains at least nMin segments, if any.
  152058. ** If one is found, set iAbsLevel to the absolute level number and
  152059. ** nSeg to nMin. If no level with at least nMin segments can be found,
  152060. ** set nSeg to -1.
  152061. */
  152062. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  152063. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  152064. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  152065. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  152066. nSeg = sqlite3_column_int(pFindLevel, 1);
  152067. assert( nSeg>=2 );
  152068. }else{
  152069. nSeg = -1;
  152070. }
  152071. rc = sqlite3_reset(pFindLevel);
  152072. /* If the hint read from the %_stat table is not empty, check if the
  152073. ** last entry in it specifies a relative level smaller than or equal
  152074. ** to the level identified by the block above (if any). If so, this
  152075. ** iteration of the loop will work on merging at the hinted level.
  152076. */
  152077. if( rc==SQLITE_OK && hint.n ){
  152078. int nHint = hint.n;
  152079. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  152080. int nHintSeg = 0; /* Hint number of segments */
  152081. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  152082. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  152083. iAbsLevel = iHintAbsLevel;
  152084. nSeg = nHintSeg;
  152085. bUseHint = 1;
  152086. bDirtyHint = 1;
  152087. }else{
  152088. /* This undoes the effect of the HintPop() above - so that no entry
  152089. ** is removed from the hint blob. */
  152090. hint.n = nHint;
  152091. }
  152092. }
  152093. /* If nSeg is less that zero, then there is no level with at least
  152094. ** nMin segments and no hint in the %_stat table. No work to do.
  152095. ** Exit early in this case. */
  152096. if( nSeg<0 ) break;
  152097. /* Open a cursor to iterate through the contents of the oldest nSeg
  152098. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  152099. ** the 'hint' parameters, it is possible that there are less than nSeg
  152100. ** segments available in level iAbsLevel. In this case, no work is
  152101. ** done on iAbsLevel - fall through to the next iteration of the loop
  152102. ** to start work on some other level. */
  152103. memset(pWriter, 0, nAlloc);
  152104. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  152105. if( rc==SQLITE_OK ){
  152106. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  152107. assert( bUseHint==1 || bUseHint==0 );
  152108. if( iIdx==0 || (bUseHint && iIdx==1) ){
  152109. int bIgnore = 0;
  152110. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  152111. if( bIgnore ){
  152112. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  152113. }
  152114. }
  152115. }
  152116. if( rc==SQLITE_OK ){
  152117. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  152118. }
  152119. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  152120. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  152121. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  152122. ){
  152123. if( bUseHint && iIdx>0 ){
  152124. const char *zKey = pCsr->zTerm;
  152125. int nKey = pCsr->nTerm;
  152126. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  152127. }else{
  152128. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  152129. }
  152130. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  152131. fts3LogMerge(nSeg, iAbsLevel);
  152132. do {
  152133. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  152134. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  152135. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  152136. }while( rc==SQLITE_ROW );
  152137. /* Update or delete the input segments */
  152138. if( rc==SQLITE_OK ){
  152139. nRem -= (1 + pWriter->nWork);
  152140. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  152141. if( nSeg!=0 ){
  152142. bDirtyHint = 1;
  152143. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  152144. }
  152145. }
  152146. }
  152147. if( nSeg!=0 ){
  152148. pWriter->nLeafData = pWriter->nLeafData * -1;
  152149. }
  152150. fts3IncrmergeRelease(p, pWriter, &rc);
  152151. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  152152. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  152153. }
  152154. }
  152155. sqlite3Fts3SegReaderFinish(pCsr);
  152156. }
  152157. /* Write the hint values into the %_stat table for the next incr-merger */
  152158. if( bDirtyHint && rc==SQLITE_OK ){
  152159. rc = fts3IncrmergeHintStore(p, &hint);
  152160. }
  152161. sqlite3_free(pWriter);
  152162. sqlite3_free(hint.a);
  152163. return rc;
  152164. }
  152165. /*
  152166. ** Convert the text beginning at *pz into an integer and return
  152167. ** its value. Advance *pz to point to the first character past
  152168. ** the integer.
  152169. **
  152170. ** This function used for parameters to merge= and incrmerge=
  152171. ** commands.
  152172. */
  152173. static int fts3Getint(const char **pz){
  152174. const char *z = *pz;
  152175. int i = 0;
  152176. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  152177. *pz = z;
  152178. return i;
  152179. }
  152180. /*
  152181. ** Process statements of the form:
  152182. **
  152183. ** INSERT INTO table(table) VALUES('merge=A,B');
  152184. **
  152185. ** A and B are integers that decode to be the number of leaf pages
  152186. ** written for the merge, and the minimum number of segments on a level
  152187. ** before it will be selected for a merge, respectively.
  152188. */
  152189. static int fts3DoIncrmerge(
  152190. Fts3Table *p, /* FTS3 table handle */
  152191. const char *zParam /* Nul-terminated string containing "A,B" */
  152192. ){
  152193. int rc;
  152194. int nMin = (FTS3_MERGE_COUNT / 2);
  152195. int nMerge = 0;
  152196. const char *z = zParam;
  152197. /* Read the first integer value */
  152198. nMerge = fts3Getint(&z);
  152199. /* If the first integer value is followed by a ',', read the second
  152200. ** integer value. */
  152201. if( z[0]==',' && z[1]!='\0' ){
  152202. z++;
  152203. nMin = fts3Getint(&z);
  152204. }
  152205. if( z[0]!='\0' || nMin<2 ){
  152206. rc = SQLITE_ERROR;
  152207. }else{
  152208. rc = SQLITE_OK;
  152209. if( !p->bHasStat ){
  152210. assert( p->bFts4==0 );
  152211. sqlite3Fts3CreateStatTable(&rc, p);
  152212. }
  152213. if( rc==SQLITE_OK ){
  152214. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  152215. }
  152216. sqlite3Fts3SegmentsClose(p);
  152217. }
  152218. return rc;
  152219. }
  152220. /*
  152221. ** Process statements of the form:
  152222. **
  152223. ** INSERT INTO table(table) VALUES('automerge=X');
  152224. **
  152225. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  152226. ** turn it on. The setting is persistent.
  152227. */
  152228. static int fts3DoAutoincrmerge(
  152229. Fts3Table *p, /* FTS3 table handle */
  152230. const char *zParam /* Nul-terminated string containing boolean */
  152231. ){
  152232. int rc = SQLITE_OK;
  152233. sqlite3_stmt *pStmt = 0;
  152234. p->nAutoincrmerge = fts3Getint(&zParam);
  152235. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  152236. p->nAutoincrmerge = 8;
  152237. }
  152238. if( !p->bHasStat ){
  152239. assert( p->bFts4==0 );
  152240. sqlite3Fts3CreateStatTable(&rc, p);
  152241. if( rc ) return rc;
  152242. }
  152243. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  152244. if( rc ) return rc;
  152245. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  152246. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  152247. sqlite3_step(pStmt);
  152248. rc = sqlite3_reset(pStmt);
  152249. return rc;
  152250. }
  152251. /*
  152252. ** Return a 64-bit checksum for the FTS index entry specified by the
  152253. ** arguments to this function.
  152254. */
  152255. static u64 fts3ChecksumEntry(
  152256. const char *zTerm, /* Pointer to buffer containing term */
  152257. int nTerm, /* Size of zTerm in bytes */
  152258. int iLangid, /* Language id for current row */
  152259. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  152260. i64 iDocid, /* Docid for current row. */
  152261. int iCol, /* Column number */
  152262. int iPos /* Position */
  152263. ){
  152264. int i;
  152265. u64 ret = (u64)iDocid;
  152266. ret += (ret<<3) + iLangid;
  152267. ret += (ret<<3) + iIndex;
  152268. ret += (ret<<3) + iCol;
  152269. ret += (ret<<3) + iPos;
  152270. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  152271. return ret;
  152272. }
  152273. /*
  152274. ** Return a checksum of all entries in the FTS index that correspond to
  152275. ** language id iLangid. The checksum is calculated by XORing the checksums
  152276. ** of each individual entry (see fts3ChecksumEntry()) together.
  152277. **
  152278. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  152279. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  152280. ** return value is undefined in this case.
  152281. */
  152282. static u64 fts3ChecksumIndex(
  152283. Fts3Table *p, /* FTS3 table handle */
  152284. int iLangid, /* Language id to return cksum for */
  152285. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  152286. int *pRc /* OUT: Return code */
  152287. ){
  152288. Fts3SegFilter filter;
  152289. Fts3MultiSegReader csr;
  152290. int rc;
  152291. u64 cksum = 0;
  152292. assert( *pRc==SQLITE_OK );
  152293. memset(&filter, 0, sizeof(filter));
  152294. memset(&csr, 0, sizeof(csr));
  152295. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  152296. filter.flags |= FTS3_SEGMENT_SCAN;
  152297. rc = sqlite3Fts3SegReaderCursor(
  152298. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  152299. );
  152300. if( rc==SQLITE_OK ){
  152301. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  152302. }
  152303. if( rc==SQLITE_OK ){
  152304. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  152305. char *pCsr = csr.aDoclist;
  152306. char *pEnd = &pCsr[csr.nDoclist];
  152307. i64 iDocid = 0;
  152308. i64 iCol = 0;
  152309. i64 iPos = 0;
  152310. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  152311. while( pCsr<pEnd ){
  152312. i64 iVal = 0;
  152313. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  152314. if( pCsr<pEnd ){
  152315. if( iVal==0 || iVal==1 ){
  152316. iCol = 0;
  152317. iPos = 0;
  152318. if( iVal ){
  152319. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  152320. }else{
  152321. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  152322. iDocid += iVal;
  152323. }
  152324. }else{
  152325. iPos += (iVal - 2);
  152326. cksum = cksum ^ fts3ChecksumEntry(
  152327. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  152328. (int)iCol, (int)iPos
  152329. );
  152330. }
  152331. }
  152332. }
  152333. }
  152334. }
  152335. sqlite3Fts3SegReaderFinish(&csr);
  152336. *pRc = rc;
  152337. return cksum;
  152338. }
  152339. /*
  152340. ** Check if the contents of the FTS index match the current contents of the
  152341. ** content table. If no error occurs and the contents do match, set *pbOk
  152342. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  152343. ** to false before returning.
  152344. **
  152345. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  152346. ** code. The final value of *pbOk is undefined in this case.
  152347. */
  152348. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  152349. int rc = SQLITE_OK; /* Return code */
  152350. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  152351. u64 cksum2 = 0; /* Checksum based on %_content contents */
  152352. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  152353. /* This block calculates the checksum according to the FTS index. */
  152354. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  152355. if( rc==SQLITE_OK ){
  152356. int rc2;
  152357. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  152358. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  152359. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  152360. int iLangid = sqlite3_column_int(pAllLangid, 0);
  152361. int i;
  152362. for(i=0; i<p->nIndex; i++){
  152363. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  152364. }
  152365. }
  152366. rc2 = sqlite3_reset(pAllLangid);
  152367. if( rc==SQLITE_OK ) rc = rc2;
  152368. }
  152369. /* This block calculates the checksum according to the %_content table */
  152370. if( rc==SQLITE_OK ){
  152371. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  152372. sqlite3_stmt *pStmt = 0;
  152373. char *zSql;
  152374. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  152375. if( !zSql ){
  152376. rc = SQLITE_NOMEM;
  152377. }else{
  152378. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  152379. sqlite3_free(zSql);
  152380. }
  152381. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  152382. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  152383. int iLang = langidFromSelect(p, pStmt);
  152384. int iCol;
  152385. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  152386. if( p->abNotindexed[iCol]==0 ){
  152387. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  152388. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  152389. sqlite3_tokenizer_cursor *pT = 0;
  152390. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  152391. while( rc==SQLITE_OK ){
  152392. char const *zToken; /* Buffer containing token */
  152393. int nToken = 0; /* Number of bytes in token */
  152394. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  152395. int iPos = 0; /* Position of token in zText */
  152396. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  152397. if( rc==SQLITE_OK ){
  152398. int i;
  152399. cksum2 = cksum2 ^ fts3ChecksumEntry(
  152400. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  152401. );
  152402. for(i=1; i<p->nIndex; i++){
  152403. if( p->aIndex[i].nPrefix<=nToken ){
  152404. cksum2 = cksum2 ^ fts3ChecksumEntry(
  152405. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  152406. );
  152407. }
  152408. }
  152409. }
  152410. }
  152411. if( pT ) pModule->xClose(pT);
  152412. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  152413. }
  152414. }
  152415. }
  152416. sqlite3_finalize(pStmt);
  152417. }
  152418. *pbOk = (cksum1==cksum2);
  152419. return rc;
  152420. }
  152421. /*
  152422. ** Run the integrity-check. If no error occurs and the current contents of
  152423. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  152424. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  152425. **
  152426. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  152427. ** error code.
  152428. **
  152429. ** The integrity-check works as follows. For each token and indexed token
  152430. ** prefix in the document set, a 64-bit checksum is calculated (by code
  152431. ** in fts3ChecksumEntry()) based on the following:
  152432. **
  152433. ** + The index number (0 for the main index, 1 for the first prefix
  152434. ** index etc.),
  152435. ** + The token (or token prefix) text itself,
  152436. ** + The language-id of the row it appears in,
  152437. ** + The docid of the row it appears in,
  152438. ** + The column it appears in, and
  152439. ** + The tokens position within that column.
  152440. **
  152441. ** The checksums for all entries in the index are XORed together to create
  152442. ** a single checksum for the entire index.
  152443. **
  152444. ** The integrity-check code calculates the same checksum in two ways:
  152445. **
  152446. ** 1. By scanning the contents of the FTS index, and
  152447. ** 2. By scanning and tokenizing the content table.
  152448. **
  152449. ** If the two checksums are identical, the integrity-check is deemed to have
  152450. ** passed.
  152451. */
  152452. static int fts3DoIntegrityCheck(
  152453. Fts3Table *p /* FTS3 table handle */
  152454. ){
  152455. int rc;
  152456. int bOk = 0;
  152457. rc = fts3IntegrityCheck(p, &bOk);
  152458. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  152459. return rc;
  152460. }
  152461. /*
  152462. ** Handle a 'special' INSERT of the form:
  152463. **
  152464. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  152465. **
  152466. ** Argument pVal contains the result of <expr>. Currently the only
  152467. ** meaningful value to insert is the text 'optimize'.
  152468. */
  152469. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  152470. int rc; /* Return Code */
  152471. const char *zVal = (const char *)sqlite3_value_text(pVal);
  152472. int nVal = sqlite3_value_bytes(pVal);
  152473. if( !zVal ){
  152474. return SQLITE_NOMEM;
  152475. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  152476. rc = fts3DoOptimize(p, 0);
  152477. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  152478. rc = fts3DoRebuild(p);
  152479. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  152480. rc = fts3DoIntegrityCheck(p);
  152481. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  152482. rc = fts3DoIncrmerge(p, &zVal[6]);
  152483. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  152484. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  152485. #ifdef SQLITE_TEST
  152486. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  152487. p->nNodeSize = atoi(&zVal[9]);
  152488. rc = SQLITE_OK;
  152489. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  152490. p->nMaxPendingData = atoi(&zVal[11]);
  152491. rc = SQLITE_OK;
  152492. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  152493. p->bNoIncrDoclist = atoi(&zVal[21]);
  152494. rc = SQLITE_OK;
  152495. #endif
  152496. }else{
  152497. rc = SQLITE_ERROR;
  152498. }
  152499. return rc;
  152500. }
  152501. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  152502. /*
  152503. ** Delete all cached deferred doclists. Deferred doclists are cached
  152504. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  152505. */
  152506. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  152507. Fts3DeferredToken *pDef;
  152508. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  152509. fts3PendingListDelete(pDef->pList);
  152510. pDef->pList = 0;
  152511. }
  152512. }
  152513. /*
  152514. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  152515. ** this list using sqlite3Fts3DeferToken().
  152516. */
  152517. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  152518. Fts3DeferredToken *pDef;
  152519. Fts3DeferredToken *pNext;
  152520. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  152521. pNext = pDef->pNext;
  152522. fts3PendingListDelete(pDef->pList);
  152523. sqlite3_free(pDef);
  152524. }
  152525. pCsr->pDeferred = 0;
  152526. }
  152527. /*
  152528. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  152529. ** based on the row that pCsr currently points to.
  152530. **
  152531. ** A deferred-doclist is like any other doclist with position information
  152532. ** included, except that it only contains entries for a single row of the
  152533. ** table, not for all rows.
  152534. */
  152535. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  152536. int rc = SQLITE_OK; /* Return code */
  152537. if( pCsr->pDeferred ){
  152538. int i; /* Used to iterate through table columns */
  152539. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  152540. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  152541. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  152542. sqlite3_tokenizer *pT = p->pTokenizer;
  152543. sqlite3_tokenizer_module const *pModule = pT->pModule;
  152544. assert( pCsr->isRequireSeek==0 );
  152545. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  152546. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  152547. if( p->abNotindexed[i]==0 ){
  152548. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  152549. sqlite3_tokenizer_cursor *pTC = 0;
  152550. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  152551. while( rc==SQLITE_OK ){
  152552. char const *zToken; /* Buffer containing token */
  152553. int nToken = 0; /* Number of bytes in token */
  152554. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  152555. int iPos = 0; /* Position of token in zText */
  152556. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  152557. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  152558. Fts3PhraseToken *pPT = pDef->pToken;
  152559. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  152560. && (pPT->bFirst==0 || iPos==0)
  152561. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  152562. && (0==memcmp(zToken, pPT->z, pPT->n))
  152563. ){
  152564. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  152565. }
  152566. }
  152567. }
  152568. if( pTC ) pModule->xClose(pTC);
  152569. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  152570. }
  152571. }
  152572. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  152573. if( pDef->pList ){
  152574. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  152575. }
  152576. }
  152577. }
  152578. return rc;
  152579. }
  152580. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  152581. Fts3DeferredToken *p,
  152582. char **ppData,
  152583. int *pnData
  152584. ){
  152585. char *pRet;
  152586. int nSkip;
  152587. sqlite3_int64 dummy;
  152588. *ppData = 0;
  152589. *pnData = 0;
  152590. if( p->pList==0 ){
  152591. return SQLITE_OK;
  152592. }
  152593. pRet = (char *)sqlite3_malloc(p->pList->nData);
  152594. if( !pRet ) return SQLITE_NOMEM;
  152595. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  152596. *pnData = p->pList->nData - nSkip;
  152597. *ppData = pRet;
  152598. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  152599. return SQLITE_OK;
  152600. }
  152601. /*
  152602. ** Add an entry for token pToken to the pCsr->pDeferred list.
  152603. */
  152604. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  152605. Fts3Cursor *pCsr, /* Fts3 table cursor */
  152606. Fts3PhraseToken *pToken, /* Token to defer */
  152607. int iCol /* Column that token must appear in (or -1) */
  152608. ){
  152609. Fts3DeferredToken *pDeferred;
  152610. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  152611. if( !pDeferred ){
  152612. return SQLITE_NOMEM;
  152613. }
  152614. memset(pDeferred, 0, sizeof(*pDeferred));
  152615. pDeferred->pToken = pToken;
  152616. pDeferred->pNext = pCsr->pDeferred;
  152617. pDeferred->iCol = iCol;
  152618. pCsr->pDeferred = pDeferred;
  152619. assert( pToken->pDeferred==0 );
  152620. pToken->pDeferred = pDeferred;
  152621. return SQLITE_OK;
  152622. }
  152623. #endif
  152624. /*
  152625. ** SQLite value pRowid contains the rowid of a row that may or may not be
  152626. ** present in the FTS3 table. If it is, delete it and adjust the contents
  152627. ** of subsiduary data structures accordingly.
  152628. */
  152629. static int fts3DeleteByRowid(
  152630. Fts3Table *p,
  152631. sqlite3_value *pRowid,
  152632. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  152633. u32 *aSzDel
  152634. ){
  152635. int rc = SQLITE_OK; /* Return code */
  152636. int bFound = 0; /* True if *pRowid really is in the table */
  152637. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  152638. if( bFound && rc==SQLITE_OK ){
  152639. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  152640. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  152641. if( rc==SQLITE_OK ){
  152642. if( isEmpty ){
  152643. /* Deleting this row means the whole table is empty. In this case
  152644. ** delete the contents of all three tables and throw away any
  152645. ** data in the pendingTerms hash table. */
  152646. rc = fts3DeleteAll(p, 1);
  152647. *pnChng = 0;
  152648. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  152649. }else{
  152650. *pnChng = *pnChng - 1;
  152651. if( p->zContentTbl==0 ){
  152652. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  152653. }
  152654. if( p->bHasDocsize ){
  152655. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  152656. }
  152657. }
  152658. }
  152659. }
  152660. return rc;
  152661. }
  152662. /*
  152663. ** This function does the work for the xUpdate method of FTS3 virtual
  152664. ** tables. The schema of the virtual table being:
  152665. **
  152666. ** CREATE TABLE <table name>(
  152667. ** <user columns>,
  152668. ** <table name> HIDDEN,
  152669. ** docid HIDDEN,
  152670. ** <langid> HIDDEN
  152671. ** );
  152672. **
  152673. **
  152674. */
  152675. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  152676. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  152677. int nArg, /* Size of argument array */
  152678. sqlite3_value **apVal, /* Array of arguments */
  152679. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  152680. ){
  152681. Fts3Table *p = (Fts3Table *)pVtab;
  152682. int rc = SQLITE_OK; /* Return Code */
  152683. int isRemove = 0; /* True for an UPDATE or DELETE */
  152684. u32 *aSzIns = 0; /* Sizes of inserted documents */
  152685. u32 *aSzDel = 0; /* Sizes of deleted documents */
  152686. int nChng = 0; /* Net change in number of documents */
  152687. int bInsertDone = 0;
  152688. /* At this point it must be known if the %_stat table exists or not.
  152689. ** So bHasStat may not be 2. */
  152690. assert( p->bHasStat==0 || p->bHasStat==1 );
  152691. assert( p->pSegments==0 );
  152692. assert(
  152693. nArg==1 /* DELETE operations */
  152694. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  152695. );
  152696. /* Check for a "special" INSERT operation. One of the form:
  152697. **
  152698. ** INSERT INTO xyz(xyz) VALUES('command');
  152699. */
  152700. if( nArg>1
  152701. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  152702. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  152703. ){
  152704. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  152705. goto update_out;
  152706. }
  152707. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  152708. rc = SQLITE_CONSTRAINT;
  152709. goto update_out;
  152710. }
  152711. /* Allocate space to hold the change in document sizes */
  152712. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  152713. if( aSzDel==0 ){
  152714. rc = SQLITE_NOMEM;
  152715. goto update_out;
  152716. }
  152717. aSzIns = &aSzDel[p->nColumn+1];
  152718. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  152719. rc = fts3Writelock(p);
  152720. if( rc!=SQLITE_OK ) goto update_out;
  152721. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  152722. ** value, then this operation requires constraint handling.
  152723. **
  152724. ** If the on-conflict mode is REPLACE, this means that the existing row
  152725. ** should be deleted from the database before inserting the new row. Or,
  152726. ** if the on-conflict mode is other than REPLACE, then this method must
  152727. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  152728. ** modify the database file.
  152729. */
  152730. if( nArg>1 && p->zContentTbl==0 ){
  152731. /* Find the value object that holds the new rowid value. */
  152732. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  152733. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  152734. pNewRowid = apVal[1];
  152735. }
  152736. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  152737. sqlite3_value_type(apVal[0])==SQLITE_NULL
  152738. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  152739. )){
  152740. /* The new rowid is not NULL (in this case the rowid will be
  152741. ** automatically assigned and there is no chance of a conflict), and
  152742. ** the statement is either an INSERT or an UPDATE that modifies the
  152743. ** rowid column. So if the conflict mode is REPLACE, then delete any
  152744. ** existing row with rowid=pNewRowid.
  152745. **
  152746. ** Or, if the conflict mode is not REPLACE, insert the new record into
  152747. ** the %_content table. If we hit the duplicate rowid constraint (or any
  152748. ** other error) while doing so, return immediately.
  152749. **
  152750. ** This branch may also run if pNewRowid contains a value that cannot
  152751. ** be losslessly converted to an integer. In this case, the eventual
  152752. ** call to fts3InsertData() (either just below or further on in this
  152753. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  152754. ** invoked, it will delete zero rows (since no row will have
  152755. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  152756. */
  152757. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  152758. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  152759. }else{
  152760. rc = fts3InsertData(p, apVal, pRowid);
  152761. bInsertDone = 1;
  152762. }
  152763. }
  152764. }
  152765. if( rc!=SQLITE_OK ){
  152766. goto update_out;
  152767. }
  152768. /* If this is a DELETE or UPDATE operation, remove the old record. */
  152769. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  152770. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  152771. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  152772. isRemove = 1;
  152773. }
  152774. /* If this is an INSERT or UPDATE operation, insert the new record. */
  152775. if( nArg>1 && rc==SQLITE_OK ){
  152776. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  152777. if( bInsertDone==0 ){
  152778. rc = fts3InsertData(p, apVal, pRowid);
  152779. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  152780. rc = FTS_CORRUPT_VTAB;
  152781. }
  152782. }
  152783. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  152784. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  152785. }
  152786. if( rc==SQLITE_OK ){
  152787. assert( p->iPrevDocid==*pRowid );
  152788. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  152789. }
  152790. if( p->bHasDocsize ){
  152791. fts3InsertDocsize(&rc, p, aSzIns);
  152792. }
  152793. nChng++;
  152794. }
  152795. if( p->bFts4 ){
  152796. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  152797. }
  152798. update_out:
  152799. sqlite3_free(aSzDel);
  152800. sqlite3Fts3SegmentsClose(p);
  152801. return rc;
  152802. }
  152803. /*
  152804. ** Flush any data in the pending-terms hash table to disk. If successful,
  152805. ** merge all segments in the database (including the new segment, if
  152806. ** there was any data to flush) into a single segment.
  152807. */
  152808. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  152809. int rc;
  152810. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  152811. if( rc==SQLITE_OK ){
  152812. rc = fts3DoOptimize(p, 1);
  152813. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  152814. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  152815. if( rc2!=SQLITE_OK ) rc = rc2;
  152816. }else{
  152817. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  152818. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  152819. }
  152820. }
  152821. sqlite3Fts3SegmentsClose(p);
  152822. return rc;
  152823. }
  152824. #endif
  152825. /************** End of fts3_write.c ******************************************/
  152826. /************** Begin file fts3_snippet.c ************************************/
  152827. /*
  152828. ** 2009 Oct 23
  152829. **
  152830. ** The author disclaims copyright to this source code. In place of
  152831. ** a legal notice, here is a blessing:
  152832. **
  152833. ** May you do good and not evil.
  152834. ** May you find forgiveness for yourself and forgive others.
  152835. ** May you share freely, never taking more than you give.
  152836. **
  152837. ******************************************************************************
  152838. */
  152839. /* #include "fts3Int.h" */
  152840. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  152841. /* #include <string.h> */
  152842. /* #include <assert.h> */
  152843. /*
  152844. ** Characters that may appear in the second argument to matchinfo().
  152845. */
  152846. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  152847. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  152848. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  152849. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  152850. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  152851. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  152852. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  152853. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  152854. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  152855. /*
  152856. ** The default value for the second argument to matchinfo().
  152857. */
  152858. #define FTS3_MATCHINFO_DEFAULT "pcx"
  152859. /*
  152860. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  152861. ** Fts3Expr.aDoclist[]/nDoclist.
  152862. */
  152863. typedef struct LoadDoclistCtx LoadDoclistCtx;
  152864. struct LoadDoclistCtx {
  152865. Fts3Cursor *pCsr; /* FTS3 Cursor */
  152866. int nPhrase; /* Number of phrases seen so far */
  152867. int nToken; /* Number of tokens seen so far */
  152868. };
  152869. /*
  152870. ** The following types are used as part of the implementation of the
  152871. ** fts3BestSnippet() routine.
  152872. */
  152873. typedef struct SnippetIter SnippetIter;
  152874. typedef struct SnippetPhrase SnippetPhrase;
  152875. typedef struct SnippetFragment SnippetFragment;
  152876. struct SnippetIter {
  152877. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  152878. int iCol; /* Extract snippet from this column */
  152879. int nSnippet; /* Requested snippet length (in tokens) */
  152880. int nPhrase; /* Number of phrases in query */
  152881. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  152882. int iCurrent; /* First token of current snippet */
  152883. };
  152884. struct SnippetPhrase {
  152885. int nToken; /* Number of tokens in phrase */
  152886. char *pList; /* Pointer to start of phrase position list */
  152887. int iHead; /* Next value in position list */
  152888. char *pHead; /* Position list data following iHead */
  152889. int iTail; /* Next value in trailing position list */
  152890. char *pTail; /* Position list data following iTail */
  152891. };
  152892. struct SnippetFragment {
  152893. int iCol; /* Column snippet is extracted from */
  152894. int iPos; /* Index of first token in snippet */
  152895. u64 covered; /* Mask of query phrases covered */
  152896. u64 hlmask; /* Mask of snippet terms to highlight */
  152897. };
  152898. /*
  152899. ** This type is used as an fts3ExprIterate() context object while
  152900. ** accumulating the data returned by the matchinfo() function.
  152901. */
  152902. typedef struct MatchInfo MatchInfo;
  152903. struct MatchInfo {
  152904. Fts3Cursor *pCursor; /* FTS3 Cursor */
  152905. int nCol; /* Number of columns in table */
  152906. int nPhrase; /* Number of matchable phrases in query */
  152907. sqlite3_int64 nDoc; /* Number of docs in database */
  152908. char flag;
  152909. u32 *aMatchinfo; /* Pre-allocated buffer */
  152910. };
  152911. /*
  152912. ** An instance of this structure is used to manage a pair of buffers, each
  152913. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  152914. ** for details.
  152915. */
  152916. struct MatchinfoBuffer {
  152917. u8 aRef[3];
  152918. int nElem;
  152919. int bGlobal; /* Set if global data is loaded */
  152920. char *zMatchinfo;
  152921. u32 aMatchinfo[1];
  152922. };
  152923. /*
  152924. ** The snippet() and offsets() functions both return text values. An instance
  152925. ** of the following structure is used to accumulate those values while the
  152926. ** functions are running. See fts3StringAppend() for details.
  152927. */
  152928. typedef struct StrBuffer StrBuffer;
  152929. struct StrBuffer {
  152930. char *z; /* Pointer to buffer containing string */
  152931. int n; /* Length of z in bytes (excl. nul-term) */
  152932. int nAlloc; /* Allocated size of buffer z in bytes */
  152933. };
  152934. /*************************************************************************
  152935. ** Start of MatchinfoBuffer code.
  152936. */
  152937. /*
  152938. ** Allocate a two-slot MatchinfoBuffer object.
  152939. */
  152940. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  152941. MatchinfoBuffer *pRet;
  152942. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  152943. int nStr = (int)strlen(zMatchinfo);
  152944. pRet = sqlite3_malloc(nByte + nStr+1);
  152945. if( pRet ){
  152946. memset(pRet, 0, nByte);
  152947. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  152948. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  152949. pRet->nElem = nElem;
  152950. pRet->zMatchinfo = ((char*)pRet) + nByte;
  152951. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  152952. pRet->aRef[0] = 1;
  152953. }
  152954. return pRet;
  152955. }
  152956. static void fts3MIBufferFree(void *p){
  152957. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  152958. assert( (u32*)p==&pBuf->aMatchinfo[1]
  152959. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  152960. );
  152961. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  152962. pBuf->aRef[1] = 0;
  152963. }else{
  152964. pBuf->aRef[2] = 0;
  152965. }
  152966. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  152967. sqlite3_free(pBuf);
  152968. }
  152969. }
  152970. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  152971. void (*xRet)(void*) = 0;
  152972. u32 *aOut = 0;
  152973. if( p->aRef[1]==0 ){
  152974. p->aRef[1] = 1;
  152975. aOut = &p->aMatchinfo[1];
  152976. xRet = fts3MIBufferFree;
  152977. }
  152978. else if( p->aRef[2]==0 ){
  152979. p->aRef[2] = 1;
  152980. aOut = &p->aMatchinfo[p->nElem+2];
  152981. xRet = fts3MIBufferFree;
  152982. }else{
  152983. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  152984. if( aOut ){
  152985. xRet = sqlite3_free;
  152986. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  152987. }
  152988. }
  152989. *paOut = aOut;
  152990. return xRet;
  152991. }
  152992. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  152993. p->bGlobal = 1;
  152994. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  152995. }
  152996. /*
  152997. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  152998. */
  152999. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  153000. if( p ){
  153001. assert( p->aRef[0]==1 );
  153002. p->aRef[0] = 0;
  153003. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  153004. sqlite3_free(p);
  153005. }
  153006. }
  153007. }
  153008. /*
  153009. ** End of MatchinfoBuffer code.
  153010. *************************************************************************/
  153011. /*
  153012. ** This function is used to help iterate through a position-list. A position
  153013. ** list is a list of unique integers, sorted from smallest to largest. Each
  153014. ** element of the list is represented by an FTS3 varint that takes the value
  153015. ** of the difference between the current element and the previous one plus
  153016. ** two. For example, to store the position-list:
  153017. **
  153018. ** 4 9 113
  153019. **
  153020. ** the three varints:
  153021. **
  153022. ** 6 7 106
  153023. **
  153024. ** are encoded.
  153025. **
  153026. ** When this function is called, *pp points to the start of an element of
  153027. ** the list. *piPos contains the value of the previous entry in the list.
  153028. ** After it returns, *piPos contains the value of the next element of the
  153029. ** list and *pp is advanced to the following varint.
  153030. */
  153031. static void fts3GetDeltaPosition(char **pp, int *piPos){
  153032. int iVal;
  153033. *pp += fts3GetVarint32(*pp, &iVal);
  153034. *piPos += (iVal-2);
  153035. }
  153036. /*
  153037. ** Helper function for fts3ExprIterate() (see below).
  153038. */
  153039. static int fts3ExprIterate2(
  153040. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  153041. int *piPhrase, /* Pointer to phrase counter */
  153042. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  153043. void *pCtx /* Second argument to pass to callback */
  153044. ){
  153045. int rc; /* Return code */
  153046. int eType = pExpr->eType; /* Type of expression node pExpr */
  153047. if( eType!=FTSQUERY_PHRASE ){
  153048. assert( pExpr->pLeft && pExpr->pRight );
  153049. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  153050. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  153051. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  153052. }
  153053. }else{
  153054. rc = x(pExpr, *piPhrase, pCtx);
  153055. (*piPhrase)++;
  153056. }
  153057. return rc;
  153058. }
  153059. /*
  153060. ** Iterate through all phrase nodes in an FTS3 query, except those that
  153061. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  153062. ** For each phrase node found, the supplied callback function is invoked.
  153063. **
  153064. ** If the callback function returns anything other than SQLITE_OK,
  153065. ** the iteration is abandoned and the error code returned immediately.
  153066. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  153067. ** all eligible phrase nodes.
  153068. */
  153069. static int fts3ExprIterate(
  153070. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  153071. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  153072. void *pCtx /* Second argument to pass to callback */
  153073. ){
  153074. int iPhrase = 0; /* Variable used as the phrase counter */
  153075. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  153076. }
  153077. /*
  153078. ** This is an fts3ExprIterate() callback used while loading the doclists
  153079. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  153080. ** fts3ExprLoadDoclists().
  153081. */
  153082. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  153083. int rc = SQLITE_OK;
  153084. Fts3Phrase *pPhrase = pExpr->pPhrase;
  153085. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  153086. UNUSED_PARAMETER(iPhrase);
  153087. p->nPhrase++;
  153088. p->nToken += pPhrase->nToken;
  153089. return rc;
  153090. }
  153091. /*
  153092. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  153093. ** pCsr.
  153094. **
  153095. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  153096. ** phrases in the expression (all phrases except those directly or
  153097. ** indirectly descended from the right-hand-side of a NOT operator). If
  153098. ** pnToken is not NULL, then it is set to the number of tokens in all
  153099. ** matchable phrases of the expression.
  153100. */
  153101. static int fts3ExprLoadDoclists(
  153102. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  153103. int *pnPhrase, /* OUT: Number of phrases in query */
  153104. int *pnToken /* OUT: Number of tokens in query */
  153105. ){
  153106. int rc; /* Return Code */
  153107. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  153108. sCtx.pCsr = pCsr;
  153109. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  153110. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  153111. if( pnToken ) *pnToken = sCtx.nToken;
  153112. return rc;
  153113. }
  153114. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  153115. (*(int *)ctx)++;
  153116. pExpr->iPhrase = iPhrase;
  153117. return SQLITE_OK;
  153118. }
  153119. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  153120. int nPhrase = 0;
  153121. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  153122. return nPhrase;
  153123. }
  153124. /*
  153125. ** Advance the position list iterator specified by the first two
  153126. ** arguments so that it points to the first element with a value greater
  153127. ** than or equal to parameter iNext.
  153128. */
  153129. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  153130. char *pIter = *ppIter;
  153131. if( pIter ){
  153132. int iIter = *piIter;
  153133. while( iIter<iNext ){
  153134. if( 0==(*pIter & 0xFE) ){
  153135. iIter = -1;
  153136. pIter = 0;
  153137. break;
  153138. }
  153139. fts3GetDeltaPosition(&pIter, &iIter);
  153140. }
  153141. *piIter = iIter;
  153142. *ppIter = pIter;
  153143. }
  153144. }
  153145. /*
  153146. ** Advance the snippet iterator to the next candidate snippet.
  153147. */
  153148. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  153149. int i; /* Loop counter */
  153150. if( pIter->iCurrent<0 ){
  153151. /* The SnippetIter object has just been initialized. The first snippet
  153152. ** candidate always starts at offset 0 (even if this candidate has a
  153153. ** score of 0.0).
  153154. */
  153155. pIter->iCurrent = 0;
  153156. /* Advance the 'head' iterator of each phrase to the first offset that
  153157. ** is greater than or equal to (iNext+nSnippet).
  153158. */
  153159. for(i=0; i<pIter->nPhrase; i++){
  153160. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  153161. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  153162. }
  153163. }else{
  153164. int iStart;
  153165. int iEnd = 0x7FFFFFFF;
  153166. for(i=0; i<pIter->nPhrase; i++){
  153167. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  153168. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  153169. iEnd = pPhrase->iHead;
  153170. }
  153171. }
  153172. if( iEnd==0x7FFFFFFF ){
  153173. return 1;
  153174. }
  153175. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  153176. for(i=0; i<pIter->nPhrase; i++){
  153177. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  153178. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  153179. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  153180. }
  153181. }
  153182. return 0;
  153183. }
  153184. /*
  153185. ** Retrieve information about the current candidate snippet of snippet
  153186. ** iterator pIter.
  153187. */
  153188. static void fts3SnippetDetails(
  153189. SnippetIter *pIter, /* Snippet iterator */
  153190. u64 mCovered, /* Bitmask of phrases already covered */
  153191. int *piToken, /* OUT: First token of proposed snippet */
  153192. int *piScore, /* OUT: "Score" for this snippet */
  153193. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  153194. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  153195. ){
  153196. int iStart = pIter->iCurrent; /* First token of snippet */
  153197. int iScore = 0; /* Score of this snippet */
  153198. int i; /* Loop counter */
  153199. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  153200. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  153201. for(i=0; i<pIter->nPhrase; i++){
  153202. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  153203. if( pPhrase->pTail ){
  153204. char *pCsr = pPhrase->pTail;
  153205. int iCsr = pPhrase->iTail;
  153206. while( iCsr<(iStart+pIter->nSnippet) ){
  153207. int j;
  153208. u64 mPhrase = (u64)1 << i;
  153209. u64 mPos = (u64)1 << (iCsr - iStart);
  153210. assert( iCsr>=iStart );
  153211. if( (mCover|mCovered)&mPhrase ){
  153212. iScore++;
  153213. }else{
  153214. iScore += 1000;
  153215. }
  153216. mCover |= mPhrase;
  153217. for(j=0; j<pPhrase->nToken; j++){
  153218. mHighlight |= (mPos>>j);
  153219. }
  153220. if( 0==(*pCsr & 0x0FE) ) break;
  153221. fts3GetDeltaPosition(&pCsr, &iCsr);
  153222. }
  153223. }
  153224. }
  153225. /* Set the output variables before returning. */
  153226. *piToken = iStart;
  153227. *piScore = iScore;
  153228. *pmCover = mCover;
  153229. *pmHighlight = mHighlight;
  153230. }
  153231. /*
  153232. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  153233. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  153234. */
  153235. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  153236. SnippetIter *p = (SnippetIter *)ctx;
  153237. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  153238. char *pCsr;
  153239. int rc;
  153240. pPhrase->nToken = pExpr->pPhrase->nToken;
  153241. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  153242. assert( rc==SQLITE_OK || pCsr==0 );
  153243. if( pCsr ){
  153244. int iFirst = 0;
  153245. pPhrase->pList = pCsr;
  153246. fts3GetDeltaPosition(&pCsr, &iFirst);
  153247. assert( iFirst>=0 );
  153248. pPhrase->pHead = pCsr;
  153249. pPhrase->pTail = pCsr;
  153250. pPhrase->iHead = iFirst;
  153251. pPhrase->iTail = iFirst;
  153252. }else{
  153253. assert( rc!=SQLITE_OK || (
  153254. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  153255. ));
  153256. }
  153257. return rc;
  153258. }
  153259. /*
  153260. ** Select the fragment of text consisting of nFragment contiguous tokens
  153261. ** from column iCol that represent the "best" snippet. The best snippet
  153262. ** is the snippet with the highest score, where scores are calculated
  153263. ** by adding:
  153264. **
  153265. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  153266. **
  153267. ** (b) +1000 points for the first occurrence of each matchable phrase in
  153268. ** the snippet for which the corresponding mCovered bit is not set.
  153269. **
  153270. ** The selected snippet parameters are stored in structure *pFragment before
  153271. ** returning. The score of the selected snippet is stored in *piScore
  153272. ** before returning.
  153273. */
  153274. static int fts3BestSnippet(
  153275. int nSnippet, /* Desired snippet length */
  153276. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  153277. int iCol, /* Index of column to create snippet from */
  153278. u64 mCovered, /* Mask of phrases already covered */
  153279. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  153280. SnippetFragment *pFragment, /* OUT: Best snippet found */
  153281. int *piScore /* OUT: Score of snippet pFragment */
  153282. ){
  153283. int rc; /* Return Code */
  153284. int nList; /* Number of phrases in expression */
  153285. SnippetIter sIter; /* Iterates through snippet candidates */
  153286. int nByte; /* Number of bytes of space to allocate */
  153287. int iBestScore = -1; /* Best snippet score found so far */
  153288. int i; /* Loop counter */
  153289. memset(&sIter, 0, sizeof(sIter));
  153290. /* Iterate through the phrases in the expression to count them. The same
  153291. ** callback makes sure the doclists are loaded for each phrase.
  153292. */
  153293. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  153294. if( rc!=SQLITE_OK ){
  153295. return rc;
  153296. }
  153297. /* Now that it is known how many phrases there are, allocate and zero
  153298. ** the required space using malloc().
  153299. */
  153300. nByte = sizeof(SnippetPhrase) * nList;
  153301. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  153302. if( !sIter.aPhrase ){
  153303. return SQLITE_NOMEM;
  153304. }
  153305. memset(sIter.aPhrase, 0, nByte);
  153306. /* Initialize the contents of the SnippetIter object. Then iterate through
  153307. ** the set of phrases in the expression to populate the aPhrase[] array.
  153308. */
  153309. sIter.pCsr = pCsr;
  153310. sIter.iCol = iCol;
  153311. sIter.nSnippet = nSnippet;
  153312. sIter.nPhrase = nList;
  153313. sIter.iCurrent = -1;
  153314. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  153315. if( rc==SQLITE_OK ){
  153316. /* Set the *pmSeen output variable. */
  153317. for(i=0; i<nList; i++){
  153318. if( sIter.aPhrase[i].pHead ){
  153319. *pmSeen |= (u64)1 << i;
  153320. }
  153321. }
  153322. /* Loop through all candidate snippets. Store the best snippet in
  153323. ** *pFragment. Store its associated 'score' in iBestScore.
  153324. */
  153325. pFragment->iCol = iCol;
  153326. while( !fts3SnippetNextCandidate(&sIter) ){
  153327. int iPos;
  153328. int iScore;
  153329. u64 mCover;
  153330. u64 mHighlite;
  153331. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  153332. assert( iScore>=0 );
  153333. if( iScore>iBestScore ){
  153334. pFragment->iPos = iPos;
  153335. pFragment->hlmask = mHighlite;
  153336. pFragment->covered = mCover;
  153337. iBestScore = iScore;
  153338. }
  153339. }
  153340. *piScore = iBestScore;
  153341. }
  153342. sqlite3_free(sIter.aPhrase);
  153343. return rc;
  153344. }
  153345. /*
  153346. ** Append a string to the string-buffer passed as the first argument.
  153347. **
  153348. ** If nAppend is negative, then the length of the string zAppend is
  153349. ** determined using strlen().
  153350. */
  153351. static int fts3StringAppend(
  153352. StrBuffer *pStr, /* Buffer to append to */
  153353. const char *zAppend, /* Pointer to data to append to buffer */
  153354. int nAppend /* Size of zAppend in bytes (or -1) */
  153355. ){
  153356. if( nAppend<0 ){
  153357. nAppend = (int)strlen(zAppend);
  153358. }
  153359. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  153360. ** to grow the buffer until so that it is big enough to accomadate the
  153361. ** appended data.
  153362. */
  153363. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  153364. int nAlloc = pStr->nAlloc+nAppend+100;
  153365. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  153366. if( !zNew ){
  153367. return SQLITE_NOMEM;
  153368. }
  153369. pStr->z = zNew;
  153370. pStr->nAlloc = nAlloc;
  153371. }
  153372. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  153373. /* Append the data to the string buffer. */
  153374. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  153375. pStr->n += nAppend;
  153376. pStr->z[pStr->n] = '\0';
  153377. return SQLITE_OK;
  153378. }
  153379. /*
  153380. ** The fts3BestSnippet() function often selects snippets that end with a
  153381. ** query term. That is, the final term of the snippet is always a term
  153382. ** that requires highlighting. For example, if 'X' is a highlighted term
  153383. ** and '.' is a non-highlighted term, BestSnippet() may select:
  153384. **
  153385. ** ........X.....X
  153386. **
  153387. ** This function "shifts" the beginning of the snippet forward in the
  153388. ** document so that there are approximately the same number of
  153389. ** non-highlighted terms to the right of the final highlighted term as there
  153390. ** are to the left of the first highlighted term. For example, to this:
  153391. **
  153392. ** ....X.....X....
  153393. **
  153394. ** This is done as part of extracting the snippet text, not when selecting
  153395. ** the snippet. Snippet selection is done based on doclists only, so there
  153396. ** is no way for fts3BestSnippet() to know whether or not the document
  153397. ** actually contains terms that follow the final highlighted term.
  153398. */
  153399. static int fts3SnippetShift(
  153400. Fts3Table *pTab, /* FTS3 table snippet comes from */
  153401. int iLangid, /* Language id to use in tokenizing */
  153402. int nSnippet, /* Number of tokens desired for snippet */
  153403. const char *zDoc, /* Document text to extract snippet from */
  153404. int nDoc, /* Size of buffer zDoc in bytes */
  153405. int *piPos, /* IN/OUT: First token of snippet */
  153406. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  153407. ){
  153408. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  153409. if( hlmask ){
  153410. int nLeft; /* Tokens to the left of first highlight */
  153411. int nRight; /* Tokens to the right of last highlight */
  153412. int nDesired; /* Ideal number of tokens to shift forward */
  153413. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  153414. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  153415. nDesired = (nLeft-nRight)/2;
  153416. /* Ideally, the start of the snippet should be pushed forward in the
  153417. ** document nDesired tokens. This block checks if there are actually
  153418. ** nDesired tokens to the right of the snippet. If so, *piPos and
  153419. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  153420. ** right. Otherwise, the snippet is shifted by the number of tokens
  153421. ** available.
  153422. */
  153423. if( nDesired>0 ){
  153424. int nShift; /* Number of tokens to shift snippet by */
  153425. int iCurrent = 0; /* Token counter */
  153426. int rc; /* Return Code */
  153427. sqlite3_tokenizer_module *pMod;
  153428. sqlite3_tokenizer_cursor *pC;
  153429. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  153430. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  153431. ** or more tokens in zDoc/nDoc.
  153432. */
  153433. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  153434. if( rc!=SQLITE_OK ){
  153435. return rc;
  153436. }
  153437. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  153438. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  153439. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  153440. }
  153441. pMod->xClose(pC);
  153442. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  153443. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  153444. assert( nShift<=nDesired );
  153445. if( nShift>0 ){
  153446. *piPos += nShift;
  153447. *pHlmask = hlmask >> nShift;
  153448. }
  153449. }
  153450. }
  153451. return SQLITE_OK;
  153452. }
  153453. /*
  153454. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  153455. ** append it to string buffer pOut.
  153456. */
  153457. static int fts3SnippetText(
  153458. Fts3Cursor *pCsr, /* FTS3 Cursor */
  153459. SnippetFragment *pFragment, /* Snippet to extract */
  153460. int iFragment, /* Fragment number */
  153461. int isLast, /* True for final fragment in snippet */
  153462. int nSnippet, /* Number of tokens in extracted snippet */
  153463. const char *zOpen, /* String inserted before highlighted term */
  153464. const char *zClose, /* String inserted after highlighted term */
  153465. const char *zEllipsis, /* String inserted between snippets */
  153466. StrBuffer *pOut /* Write output here */
  153467. ){
  153468. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153469. int rc; /* Return code */
  153470. const char *zDoc; /* Document text to extract snippet from */
  153471. int nDoc; /* Size of zDoc in bytes */
  153472. int iCurrent = 0; /* Current token number of document */
  153473. int iEnd = 0; /* Byte offset of end of current token */
  153474. int isShiftDone = 0; /* True after snippet is shifted */
  153475. int iPos = pFragment->iPos; /* First token of snippet */
  153476. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  153477. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  153478. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  153479. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  153480. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  153481. if( zDoc==0 ){
  153482. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  153483. return SQLITE_NOMEM;
  153484. }
  153485. return SQLITE_OK;
  153486. }
  153487. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  153488. /* Open a token cursor on the document. */
  153489. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  153490. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  153491. if( rc!=SQLITE_OK ){
  153492. return rc;
  153493. }
  153494. while( rc==SQLITE_OK ){
  153495. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  153496. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  153497. int iBegin = 0; /* Offset in zDoc of start of token */
  153498. int iFin = 0; /* Offset in zDoc of end of token */
  153499. int isHighlight = 0; /* True for highlighted terms */
  153500. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  153501. ** in the FTS code the variable that the third argument to xNext points to
  153502. ** is initialized to zero before the first (*but not necessarily
  153503. ** subsequent*) call to xNext(). This is done for a particular application
  153504. ** that needs to know whether or not the tokenizer is being used for
  153505. ** snippet generation or for some other purpose.
  153506. **
  153507. ** Extreme care is required when writing code to depend on this
  153508. ** initialization. It is not a documented part of the tokenizer interface.
  153509. ** If a tokenizer is used directly by any code outside of FTS, this
  153510. ** convention might not be respected. */
  153511. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  153512. if( rc!=SQLITE_OK ){
  153513. if( rc==SQLITE_DONE ){
  153514. /* Special case - the last token of the snippet is also the last token
  153515. ** of the column. Append any punctuation that occurred between the end
  153516. ** of the previous token and the end of the document to the output.
  153517. ** Then break out of the loop. */
  153518. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  153519. }
  153520. break;
  153521. }
  153522. if( iCurrent<iPos ){ continue; }
  153523. if( !isShiftDone ){
  153524. int n = nDoc - iBegin;
  153525. rc = fts3SnippetShift(
  153526. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  153527. );
  153528. isShiftDone = 1;
  153529. /* Now that the shift has been done, check if the initial "..." are
  153530. ** required. They are required if (a) this is not the first fragment,
  153531. ** or (b) this fragment does not begin at position 0 of its column.
  153532. */
  153533. if( rc==SQLITE_OK ){
  153534. if( iPos>0 || iFragment>0 ){
  153535. rc = fts3StringAppend(pOut, zEllipsis, -1);
  153536. }else if( iBegin ){
  153537. rc = fts3StringAppend(pOut, zDoc, iBegin);
  153538. }
  153539. }
  153540. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  153541. }
  153542. if( iCurrent>=(iPos+nSnippet) ){
  153543. if( isLast ){
  153544. rc = fts3StringAppend(pOut, zEllipsis, -1);
  153545. }
  153546. break;
  153547. }
  153548. /* Set isHighlight to true if this term should be highlighted. */
  153549. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  153550. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  153551. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  153552. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  153553. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  153554. iEnd = iFin;
  153555. }
  153556. pMod->xClose(pC);
  153557. return rc;
  153558. }
  153559. /*
  153560. ** This function is used to count the entries in a column-list (a
  153561. ** delta-encoded list of term offsets within a single column of a single
  153562. ** row). When this function is called, *ppCollist should point to the
  153563. ** beginning of the first varint in the column-list (the varint that
  153564. ** contains the position of the first matching term in the column data).
  153565. ** Before returning, *ppCollist is set to point to the first byte after
  153566. ** the last varint in the column-list (either the 0x00 signifying the end
  153567. ** of the position-list, or the 0x01 that precedes the column number of
  153568. ** the next column in the position-list).
  153569. **
  153570. ** The number of elements in the column-list is returned.
  153571. */
  153572. static int fts3ColumnlistCount(char **ppCollist){
  153573. char *pEnd = *ppCollist;
  153574. char c = 0;
  153575. int nEntry = 0;
  153576. /* A column-list is terminated by either a 0x01 or 0x00. */
  153577. while( 0xFE & (*pEnd | c) ){
  153578. c = *pEnd++ & 0x80;
  153579. if( !c ) nEntry++;
  153580. }
  153581. *ppCollist = pEnd;
  153582. return nEntry;
  153583. }
  153584. /*
  153585. ** This function gathers 'y' or 'b' data for a single phrase.
  153586. */
  153587. static void fts3ExprLHits(
  153588. Fts3Expr *pExpr, /* Phrase expression node */
  153589. MatchInfo *p /* Matchinfo context */
  153590. ){
  153591. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  153592. int iStart;
  153593. Fts3Phrase *pPhrase = pExpr->pPhrase;
  153594. char *pIter = pPhrase->doclist.pList;
  153595. int iCol = 0;
  153596. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  153597. if( p->flag==FTS3_MATCHINFO_LHITS ){
  153598. iStart = pExpr->iPhrase * p->nCol;
  153599. }else{
  153600. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  153601. }
  153602. while( 1 ){
  153603. int nHit = fts3ColumnlistCount(&pIter);
  153604. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  153605. if( p->flag==FTS3_MATCHINFO_LHITS ){
  153606. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  153607. }else if( nHit ){
  153608. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  153609. }
  153610. }
  153611. assert( *pIter==0x00 || *pIter==0x01 );
  153612. if( *pIter!=0x01 ) break;
  153613. pIter++;
  153614. pIter += fts3GetVarint32(pIter, &iCol);
  153615. }
  153616. }
  153617. /*
  153618. ** Gather the results for matchinfo directives 'y' and 'b'.
  153619. */
  153620. static void fts3ExprLHitGather(
  153621. Fts3Expr *pExpr,
  153622. MatchInfo *p
  153623. ){
  153624. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  153625. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  153626. if( pExpr->pLeft ){
  153627. fts3ExprLHitGather(pExpr->pLeft, p);
  153628. fts3ExprLHitGather(pExpr->pRight, p);
  153629. }else{
  153630. fts3ExprLHits(pExpr, p);
  153631. }
  153632. }
  153633. }
  153634. /*
  153635. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  153636. ** for a single query.
  153637. **
  153638. ** fts3ExprIterate() callback to load the 'global' elements of a
  153639. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  153640. ** of the matchinfo array that are constant for all rows returned by the
  153641. ** current query.
  153642. **
  153643. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  153644. ** function populates Matchinfo.aMatchinfo[] as follows:
  153645. **
  153646. ** for(iCol=0; iCol<nCol; iCol++){
  153647. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  153648. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  153649. ** }
  153650. **
  153651. ** where X is the number of matches for phrase iPhrase is column iCol of all
  153652. ** rows of the table. Y is the number of rows for which column iCol contains
  153653. ** at least one instance of phrase iPhrase.
  153654. **
  153655. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  153656. ** Y values are set to nDoc, where nDoc is the number of documents in the
  153657. ** file system. This is done because the full-text index doclist is required
  153658. ** to calculate these values properly, and the full-text index doclist is
  153659. ** not available for deferred tokens.
  153660. */
  153661. static int fts3ExprGlobalHitsCb(
  153662. Fts3Expr *pExpr, /* Phrase expression node */
  153663. int iPhrase, /* Phrase number (numbered from zero) */
  153664. void *pCtx /* Pointer to MatchInfo structure */
  153665. ){
  153666. MatchInfo *p = (MatchInfo *)pCtx;
  153667. return sqlite3Fts3EvalPhraseStats(
  153668. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  153669. );
  153670. }
  153671. /*
  153672. ** fts3ExprIterate() callback used to collect the "local" part of the
  153673. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  153674. ** array that are different for each row returned by the query.
  153675. */
  153676. static int fts3ExprLocalHitsCb(
  153677. Fts3Expr *pExpr, /* Phrase expression node */
  153678. int iPhrase, /* Phrase number */
  153679. void *pCtx /* Pointer to MatchInfo structure */
  153680. ){
  153681. int rc = SQLITE_OK;
  153682. MatchInfo *p = (MatchInfo *)pCtx;
  153683. int iStart = iPhrase * p->nCol * 3;
  153684. int i;
  153685. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  153686. char *pCsr;
  153687. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  153688. if( pCsr ){
  153689. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  153690. }else{
  153691. p->aMatchinfo[iStart+i*3] = 0;
  153692. }
  153693. }
  153694. return rc;
  153695. }
  153696. static int fts3MatchinfoCheck(
  153697. Fts3Table *pTab,
  153698. char cArg,
  153699. char **pzErr
  153700. ){
  153701. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  153702. || (cArg==FTS3_MATCHINFO_NCOL)
  153703. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  153704. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  153705. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  153706. || (cArg==FTS3_MATCHINFO_LCS)
  153707. || (cArg==FTS3_MATCHINFO_HITS)
  153708. || (cArg==FTS3_MATCHINFO_LHITS)
  153709. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  153710. ){
  153711. return SQLITE_OK;
  153712. }
  153713. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  153714. return SQLITE_ERROR;
  153715. }
  153716. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  153717. int nVal; /* Number of integers output by cArg */
  153718. switch( cArg ){
  153719. case FTS3_MATCHINFO_NDOC:
  153720. case FTS3_MATCHINFO_NPHRASE:
  153721. case FTS3_MATCHINFO_NCOL:
  153722. nVal = 1;
  153723. break;
  153724. case FTS3_MATCHINFO_AVGLENGTH:
  153725. case FTS3_MATCHINFO_LENGTH:
  153726. case FTS3_MATCHINFO_LCS:
  153727. nVal = pInfo->nCol;
  153728. break;
  153729. case FTS3_MATCHINFO_LHITS:
  153730. nVal = pInfo->nCol * pInfo->nPhrase;
  153731. break;
  153732. case FTS3_MATCHINFO_LHITS_BM:
  153733. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  153734. break;
  153735. default:
  153736. assert( cArg==FTS3_MATCHINFO_HITS );
  153737. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  153738. break;
  153739. }
  153740. return nVal;
  153741. }
  153742. static int fts3MatchinfoSelectDoctotal(
  153743. Fts3Table *pTab,
  153744. sqlite3_stmt **ppStmt,
  153745. sqlite3_int64 *pnDoc,
  153746. const char **paLen
  153747. ){
  153748. sqlite3_stmt *pStmt;
  153749. const char *a;
  153750. sqlite3_int64 nDoc;
  153751. if( !*ppStmt ){
  153752. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  153753. if( rc!=SQLITE_OK ) return rc;
  153754. }
  153755. pStmt = *ppStmt;
  153756. assert( sqlite3_data_count(pStmt)==1 );
  153757. a = sqlite3_column_blob(pStmt, 0);
  153758. a += sqlite3Fts3GetVarint(a, &nDoc);
  153759. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  153760. *pnDoc = (u32)nDoc;
  153761. if( paLen ) *paLen = a;
  153762. return SQLITE_OK;
  153763. }
  153764. /*
  153765. ** An instance of the following structure is used to store state while
  153766. ** iterating through a multi-column position-list corresponding to the
  153767. ** hits for a single phrase on a single row in order to calculate the
  153768. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  153769. */
  153770. typedef struct LcsIterator LcsIterator;
  153771. struct LcsIterator {
  153772. Fts3Expr *pExpr; /* Pointer to phrase expression */
  153773. int iPosOffset; /* Tokens count up to end of this phrase */
  153774. char *pRead; /* Cursor used to iterate through aDoclist */
  153775. int iPos; /* Current position */
  153776. };
  153777. /*
  153778. ** If LcsIterator.iCol is set to the following value, the iterator has
  153779. ** finished iterating through all offsets for all columns.
  153780. */
  153781. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  153782. static int fts3MatchinfoLcsCb(
  153783. Fts3Expr *pExpr, /* Phrase expression node */
  153784. int iPhrase, /* Phrase number (numbered from zero) */
  153785. void *pCtx /* Pointer to MatchInfo structure */
  153786. ){
  153787. LcsIterator *aIter = (LcsIterator *)pCtx;
  153788. aIter[iPhrase].pExpr = pExpr;
  153789. return SQLITE_OK;
  153790. }
  153791. /*
  153792. ** Advance the iterator passed as an argument to the next position. Return
  153793. ** 1 if the iterator is at EOF or if it now points to the start of the
  153794. ** position list for the next column.
  153795. */
  153796. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  153797. char *pRead = pIter->pRead;
  153798. sqlite3_int64 iRead;
  153799. int rc = 0;
  153800. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  153801. if( iRead==0 || iRead==1 ){
  153802. pRead = 0;
  153803. rc = 1;
  153804. }else{
  153805. pIter->iPos += (int)(iRead-2);
  153806. }
  153807. pIter->pRead = pRead;
  153808. return rc;
  153809. }
  153810. /*
  153811. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  153812. **
  153813. ** If the call is successful, the longest-common-substring lengths for each
  153814. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  153815. ** array before returning. SQLITE_OK is returned in this case.
  153816. **
  153817. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  153818. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  153819. ** undefined.
  153820. */
  153821. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  153822. LcsIterator *aIter;
  153823. int i;
  153824. int iCol;
  153825. int nToken = 0;
  153826. /* Allocate and populate the array of LcsIterator objects. The array
  153827. ** contains one element for each matchable phrase in the query.
  153828. **/
  153829. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  153830. if( !aIter ) return SQLITE_NOMEM;
  153831. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  153832. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  153833. for(i=0; i<pInfo->nPhrase; i++){
  153834. LcsIterator *pIter = &aIter[i];
  153835. nToken -= pIter->pExpr->pPhrase->nToken;
  153836. pIter->iPosOffset = nToken;
  153837. }
  153838. for(iCol=0; iCol<pInfo->nCol; iCol++){
  153839. int nLcs = 0; /* LCS value for this column */
  153840. int nLive = 0; /* Number of iterators in aIter not at EOF */
  153841. for(i=0; i<pInfo->nPhrase; i++){
  153842. int rc;
  153843. LcsIterator *pIt = &aIter[i];
  153844. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  153845. if( rc!=SQLITE_OK ) return rc;
  153846. if( pIt->pRead ){
  153847. pIt->iPos = pIt->iPosOffset;
  153848. fts3LcsIteratorAdvance(&aIter[i]);
  153849. nLive++;
  153850. }
  153851. }
  153852. while( nLive>0 ){
  153853. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  153854. int nThisLcs = 0; /* LCS for the current iterator positions */
  153855. for(i=0; i<pInfo->nPhrase; i++){
  153856. LcsIterator *pIter = &aIter[i];
  153857. if( pIter->pRead==0 ){
  153858. /* This iterator is already at EOF for this column. */
  153859. nThisLcs = 0;
  153860. }else{
  153861. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  153862. pAdv = pIter;
  153863. }
  153864. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  153865. nThisLcs++;
  153866. }else{
  153867. nThisLcs = 1;
  153868. }
  153869. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  153870. }
  153871. }
  153872. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  153873. }
  153874. pInfo->aMatchinfo[iCol] = nLcs;
  153875. }
  153876. sqlite3_free(aIter);
  153877. return SQLITE_OK;
  153878. }
  153879. /*
  153880. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  153881. ** be returned by the matchinfo() function. Argument zArg contains the
  153882. ** format string passed as the second argument to matchinfo (or the
  153883. ** default value "pcx" if no second argument was specified). The format
  153884. ** string has already been validated and the pInfo->aMatchinfo[] array
  153885. ** is guaranteed to be large enough for the output.
  153886. **
  153887. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  153888. ** If it is false, then assume that those fields that do not change between
  153889. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  153890. ** have already been populated.
  153891. **
  153892. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  153893. ** occurs. If a value other than SQLITE_OK is returned, the state the
  153894. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  153895. */
  153896. static int fts3MatchinfoValues(
  153897. Fts3Cursor *pCsr, /* FTS3 cursor object */
  153898. int bGlobal, /* True to grab the global stats */
  153899. MatchInfo *pInfo, /* Matchinfo context object */
  153900. const char *zArg /* Matchinfo format string */
  153901. ){
  153902. int rc = SQLITE_OK;
  153903. int i;
  153904. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  153905. sqlite3_stmt *pSelect = 0;
  153906. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  153907. pInfo->flag = zArg[i];
  153908. switch( zArg[i] ){
  153909. case FTS3_MATCHINFO_NPHRASE:
  153910. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  153911. break;
  153912. case FTS3_MATCHINFO_NCOL:
  153913. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  153914. break;
  153915. case FTS3_MATCHINFO_NDOC:
  153916. if( bGlobal ){
  153917. sqlite3_int64 nDoc = 0;
  153918. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  153919. pInfo->aMatchinfo[0] = (u32)nDoc;
  153920. }
  153921. break;
  153922. case FTS3_MATCHINFO_AVGLENGTH:
  153923. if( bGlobal ){
  153924. sqlite3_int64 nDoc; /* Number of rows in table */
  153925. const char *a; /* Aggregate column length array */
  153926. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  153927. if( rc==SQLITE_OK ){
  153928. int iCol;
  153929. for(iCol=0; iCol<pInfo->nCol; iCol++){
  153930. u32 iVal;
  153931. sqlite3_int64 nToken;
  153932. a += sqlite3Fts3GetVarint(a, &nToken);
  153933. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  153934. pInfo->aMatchinfo[iCol] = iVal;
  153935. }
  153936. }
  153937. }
  153938. break;
  153939. case FTS3_MATCHINFO_LENGTH: {
  153940. sqlite3_stmt *pSelectDocsize = 0;
  153941. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  153942. if( rc==SQLITE_OK ){
  153943. int iCol;
  153944. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  153945. for(iCol=0; iCol<pInfo->nCol; iCol++){
  153946. sqlite3_int64 nToken;
  153947. a += sqlite3Fts3GetVarint(a, &nToken);
  153948. pInfo->aMatchinfo[iCol] = (u32)nToken;
  153949. }
  153950. }
  153951. sqlite3_reset(pSelectDocsize);
  153952. break;
  153953. }
  153954. case FTS3_MATCHINFO_LCS:
  153955. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  153956. if( rc==SQLITE_OK ){
  153957. rc = fts3MatchinfoLcs(pCsr, pInfo);
  153958. }
  153959. break;
  153960. case FTS3_MATCHINFO_LHITS_BM:
  153961. case FTS3_MATCHINFO_LHITS: {
  153962. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  153963. memset(pInfo->aMatchinfo, 0, nZero);
  153964. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  153965. break;
  153966. }
  153967. default: {
  153968. Fts3Expr *pExpr;
  153969. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  153970. pExpr = pCsr->pExpr;
  153971. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  153972. if( rc!=SQLITE_OK ) break;
  153973. if( bGlobal ){
  153974. if( pCsr->pDeferred ){
  153975. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  153976. if( rc!=SQLITE_OK ) break;
  153977. }
  153978. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  153979. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  153980. if( rc!=SQLITE_OK ) break;
  153981. }
  153982. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  153983. break;
  153984. }
  153985. }
  153986. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  153987. }
  153988. sqlite3_reset(pSelect);
  153989. return rc;
  153990. }
  153991. /*
  153992. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  153993. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  153994. */
  153995. static void fts3GetMatchinfo(
  153996. sqlite3_context *pCtx, /* Return results here */
  153997. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  153998. const char *zArg /* Second argument to matchinfo() function */
  153999. ){
  154000. MatchInfo sInfo;
  154001. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154002. int rc = SQLITE_OK;
  154003. int bGlobal = 0; /* Collect 'global' stats as well as local */
  154004. u32 *aOut = 0;
  154005. void (*xDestroyOut)(void*) = 0;
  154006. memset(&sInfo, 0, sizeof(MatchInfo));
  154007. sInfo.pCursor = pCsr;
  154008. sInfo.nCol = pTab->nColumn;
  154009. /* If there is cached matchinfo() data, but the format string for the
  154010. ** cache does not match the format string for this request, discard
  154011. ** the cached data. */
  154012. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  154013. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  154014. pCsr->pMIBuffer = 0;
  154015. }
  154016. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  154017. ** matchinfo function has been called for this query. In this case
  154018. ** allocate the array used to accumulate the matchinfo data and
  154019. ** initialize those elements that are constant for every row.
  154020. */
  154021. if( pCsr->pMIBuffer==0 ){
  154022. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  154023. int i; /* Used to iterate through zArg */
  154024. /* Determine the number of phrases in the query */
  154025. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  154026. sInfo.nPhrase = pCsr->nPhrase;
  154027. /* Determine the number of integers in the buffer returned by this call. */
  154028. for(i=0; zArg[i]; i++){
  154029. char *zErr = 0;
  154030. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  154031. sqlite3_result_error(pCtx, zErr, -1);
  154032. sqlite3_free(zErr);
  154033. return;
  154034. }
  154035. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  154036. }
  154037. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  154038. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  154039. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  154040. pCsr->isMatchinfoNeeded = 1;
  154041. bGlobal = 1;
  154042. }
  154043. if( rc==SQLITE_OK ){
  154044. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  154045. if( xDestroyOut==0 ){
  154046. rc = SQLITE_NOMEM;
  154047. }
  154048. }
  154049. if( rc==SQLITE_OK ){
  154050. sInfo.aMatchinfo = aOut;
  154051. sInfo.nPhrase = pCsr->nPhrase;
  154052. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  154053. if( bGlobal ){
  154054. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  154055. }
  154056. }
  154057. if( rc!=SQLITE_OK ){
  154058. sqlite3_result_error_code(pCtx, rc);
  154059. if( xDestroyOut ) xDestroyOut(aOut);
  154060. }else{
  154061. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  154062. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  154063. }
  154064. }
  154065. /*
  154066. ** Implementation of snippet() function.
  154067. */
  154068. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  154069. sqlite3_context *pCtx, /* SQLite function call context */
  154070. Fts3Cursor *pCsr, /* Cursor object */
  154071. const char *zStart, /* Snippet start text - "<b>" */
  154072. const char *zEnd, /* Snippet end text - "</b>" */
  154073. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  154074. int iCol, /* Extract snippet from this column */
  154075. int nToken /* Approximate number of tokens in snippet */
  154076. ){
  154077. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154078. int rc = SQLITE_OK;
  154079. int i;
  154080. StrBuffer res = {0, 0, 0};
  154081. /* The returned text includes up to four fragments of text extracted from
  154082. ** the data in the current row. The first iteration of the for(...) loop
  154083. ** below attempts to locate a single fragment of text nToken tokens in
  154084. ** size that contains at least one instance of all phrases in the query
  154085. ** expression that appear in the current row. If such a fragment of text
  154086. ** cannot be found, the second iteration of the loop attempts to locate
  154087. ** a pair of fragments, and so on.
  154088. */
  154089. int nSnippet = 0; /* Number of fragments in this snippet */
  154090. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  154091. int nFToken = -1; /* Number of tokens in each fragment */
  154092. if( !pCsr->pExpr ){
  154093. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  154094. return;
  154095. }
  154096. for(nSnippet=1; 1; nSnippet++){
  154097. int iSnip; /* Loop counter 0..nSnippet-1 */
  154098. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  154099. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  154100. if( nToken>=0 ){
  154101. nFToken = (nToken+nSnippet-1) / nSnippet;
  154102. }else{
  154103. nFToken = -1 * nToken;
  154104. }
  154105. for(iSnip=0; iSnip<nSnippet; iSnip++){
  154106. int iBestScore = -1; /* Best score of columns checked so far */
  154107. int iRead; /* Used to iterate through columns */
  154108. SnippetFragment *pFragment = &aSnippet[iSnip];
  154109. memset(pFragment, 0, sizeof(*pFragment));
  154110. /* Loop through all columns of the table being considered for snippets.
  154111. ** If the iCol argument to this function was negative, this means all
  154112. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  154113. */
  154114. for(iRead=0; iRead<pTab->nColumn; iRead++){
  154115. SnippetFragment sF = {0, 0, 0, 0};
  154116. int iS = 0;
  154117. if( iCol>=0 && iRead!=iCol ) continue;
  154118. /* Find the best snippet of nFToken tokens in column iRead. */
  154119. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  154120. if( rc!=SQLITE_OK ){
  154121. goto snippet_out;
  154122. }
  154123. if( iS>iBestScore ){
  154124. *pFragment = sF;
  154125. iBestScore = iS;
  154126. }
  154127. }
  154128. mCovered |= pFragment->covered;
  154129. }
  154130. /* If all query phrases seen by fts3BestSnippet() are present in at least
  154131. ** one of the nSnippet snippet fragments, break out of the loop.
  154132. */
  154133. assert( (mCovered&mSeen)==mCovered );
  154134. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  154135. }
  154136. assert( nFToken>0 );
  154137. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  154138. rc = fts3SnippetText(pCsr, &aSnippet[i],
  154139. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  154140. );
  154141. }
  154142. snippet_out:
  154143. sqlite3Fts3SegmentsClose(pTab);
  154144. if( rc!=SQLITE_OK ){
  154145. sqlite3_result_error_code(pCtx, rc);
  154146. sqlite3_free(res.z);
  154147. }else{
  154148. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  154149. }
  154150. }
  154151. typedef struct TermOffset TermOffset;
  154152. typedef struct TermOffsetCtx TermOffsetCtx;
  154153. struct TermOffset {
  154154. char *pList; /* Position-list */
  154155. int iPos; /* Position just read from pList */
  154156. int iOff; /* Offset of this term from read positions */
  154157. };
  154158. struct TermOffsetCtx {
  154159. Fts3Cursor *pCsr;
  154160. int iCol; /* Column of table to populate aTerm for */
  154161. int iTerm;
  154162. sqlite3_int64 iDocid;
  154163. TermOffset *aTerm;
  154164. };
  154165. /*
  154166. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  154167. */
  154168. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  154169. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  154170. int nTerm; /* Number of tokens in phrase */
  154171. int iTerm; /* For looping through nTerm phrase terms */
  154172. char *pList; /* Pointer to position list for phrase */
  154173. int iPos = 0; /* First position in position-list */
  154174. int rc;
  154175. UNUSED_PARAMETER(iPhrase);
  154176. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  154177. nTerm = pExpr->pPhrase->nToken;
  154178. if( pList ){
  154179. fts3GetDeltaPosition(&pList, &iPos);
  154180. assert( iPos>=0 );
  154181. }
  154182. for(iTerm=0; iTerm<nTerm; iTerm++){
  154183. TermOffset *pT = &p->aTerm[p->iTerm++];
  154184. pT->iOff = nTerm-iTerm-1;
  154185. pT->pList = pList;
  154186. pT->iPos = iPos;
  154187. }
  154188. return rc;
  154189. }
  154190. /*
  154191. ** Implementation of offsets() function.
  154192. */
  154193. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  154194. sqlite3_context *pCtx, /* SQLite function call context */
  154195. Fts3Cursor *pCsr /* Cursor object */
  154196. ){
  154197. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154198. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  154199. int rc; /* Return Code */
  154200. int nToken; /* Number of tokens in query */
  154201. int iCol; /* Column currently being processed */
  154202. StrBuffer res = {0, 0, 0}; /* Result string */
  154203. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  154204. if( !pCsr->pExpr ){
  154205. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  154206. return;
  154207. }
  154208. memset(&sCtx, 0, sizeof(sCtx));
  154209. assert( pCsr->isRequireSeek==0 );
  154210. /* Count the number of terms in the query */
  154211. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  154212. if( rc!=SQLITE_OK ) goto offsets_out;
  154213. /* Allocate the array of TermOffset iterators. */
  154214. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  154215. if( 0==sCtx.aTerm ){
  154216. rc = SQLITE_NOMEM;
  154217. goto offsets_out;
  154218. }
  154219. sCtx.iDocid = pCsr->iPrevId;
  154220. sCtx.pCsr = pCsr;
  154221. /* Loop through the table columns, appending offset information to
  154222. ** string-buffer res for each column.
  154223. */
  154224. for(iCol=0; iCol<pTab->nColumn; iCol++){
  154225. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  154226. const char *ZDUMMY; /* Dummy argument used with xNext() */
  154227. int NDUMMY = 0; /* Dummy argument used with xNext() */
  154228. int iStart = 0;
  154229. int iEnd = 0;
  154230. int iCurrent = 0;
  154231. const char *zDoc;
  154232. int nDoc;
  154233. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  154234. ** no way that this operation can fail, so the return code from
  154235. ** fts3ExprIterate() can be discarded.
  154236. */
  154237. sCtx.iCol = iCol;
  154238. sCtx.iTerm = 0;
  154239. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  154240. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  154241. ** in column iCol, jump immediately to the next iteration of the loop.
  154242. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  154243. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  154244. ** to the caller.
  154245. */
  154246. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  154247. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  154248. if( zDoc==0 ){
  154249. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  154250. continue;
  154251. }
  154252. rc = SQLITE_NOMEM;
  154253. goto offsets_out;
  154254. }
  154255. /* Initialize a tokenizer iterator to iterate through column iCol. */
  154256. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  154257. zDoc, nDoc, &pC
  154258. );
  154259. if( rc!=SQLITE_OK ) goto offsets_out;
  154260. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  154261. while( rc==SQLITE_OK ){
  154262. int i; /* Used to loop through terms */
  154263. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  154264. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  154265. for(i=0; i<nToken; i++){
  154266. TermOffset *pT = &sCtx.aTerm[i];
  154267. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  154268. iMinPos = pT->iPos-pT->iOff;
  154269. pTerm = pT;
  154270. }
  154271. }
  154272. if( !pTerm ){
  154273. /* All offsets for this column have been gathered. */
  154274. rc = SQLITE_DONE;
  154275. }else{
  154276. assert( iCurrent<=iMinPos );
  154277. if( 0==(0xFE&*pTerm->pList) ){
  154278. pTerm->pList = 0;
  154279. }else{
  154280. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  154281. }
  154282. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  154283. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  154284. }
  154285. if( rc==SQLITE_OK ){
  154286. char aBuffer[64];
  154287. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  154288. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  154289. );
  154290. rc = fts3StringAppend(&res, aBuffer, -1);
  154291. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  154292. rc = FTS_CORRUPT_VTAB;
  154293. }
  154294. }
  154295. }
  154296. if( rc==SQLITE_DONE ){
  154297. rc = SQLITE_OK;
  154298. }
  154299. pMod->xClose(pC);
  154300. if( rc!=SQLITE_OK ) goto offsets_out;
  154301. }
  154302. offsets_out:
  154303. sqlite3_free(sCtx.aTerm);
  154304. assert( rc!=SQLITE_DONE );
  154305. sqlite3Fts3SegmentsClose(pTab);
  154306. if( rc!=SQLITE_OK ){
  154307. sqlite3_result_error_code(pCtx, rc);
  154308. sqlite3_free(res.z);
  154309. }else{
  154310. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  154311. }
  154312. return;
  154313. }
  154314. /*
  154315. ** Implementation of matchinfo() function.
  154316. */
  154317. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  154318. sqlite3_context *pContext, /* Function call context */
  154319. Fts3Cursor *pCsr, /* FTS3 table cursor */
  154320. const char *zArg /* Second arg to matchinfo() function */
  154321. ){
  154322. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154323. const char *zFormat;
  154324. if( zArg ){
  154325. zFormat = zArg;
  154326. }else{
  154327. zFormat = FTS3_MATCHINFO_DEFAULT;
  154328. }
  154329. if( !pCsr->pExpr ){
  154330. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  154331. return;
  154332. }else{
  154333. /* Retrieve matchinfo() data. */
  154334. fts3GetMatchinfo(pContext, pCsr, zFormat);
  154335. sqlite3Fts3SegmentsClose(pTab);
  154336. }
  154337. }
  154338. #endif
  154339. /************** End of fts3_snippet.c ****************************************/
  154340. /************** Begin file fts3_unicode.c ************************************/
  154341. /*
  154342. ** 2012 May 24
  154343. **
  154344. ** The author disclaims copyright to this source code. In place of
  154345. ** a legal notice, here is a blessing:
  154346. **
  154347. ** May you do good and not evil.
  154348. ** May you find forgiveness for yourself and forgive others.
  154349. ** May you share freely, never taking more than you give.
  154350. **
  154351. ******************************************************************************
  154352. **
  154353. ** Implementation of the "unicode" full-text-search tokenizer.
  154354. */
  154355. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154356. /* #include "fts3Int.h" */
  154357. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  154358. /* #include <assert.h> */
  154359. /* #include <stdlib.h> */
  154360. /* #include <stdio.h> */
  154361. /* #include <string.h> */
  154362. /* #include "fts3_tokenizer.h" */
  154363. /*
  154364. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  154365. ** from the sqlite3 source file utf.c. If this file is compiled as part
  154366. ** of the amalgamation, they are not required.
  154367. */
  154368. #ifndef SQLITE_AMALGAMATION
  154369. static const unsigned char sqlite3Utf8Trans1[] = {
  154370. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  154371. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  154372. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  154373. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  154374. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  154375. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  154376. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  154377. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  154378. };
  154379. #define READ_UTF8(zIn, zTerm, c) \
  154380. c = *(zIn++); \
  154381. if( c>=0xc0 ){ \
  154382. c = sqlite3Utf8Trans1[c-0xc0]; \
  154383. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  154384. c = (c<<6) + (0x3f & *(zIn++)); \
  154385. } \
  154386. if( c<0x80 \
  154387. || (c&0xFFFFF800)==0xD800 \
  154388. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  154389. }
  154390. #define WRITE_UTF8(zOut, c) { \
  154391. if( c<0x00080 ){ \
  154392. *zOut++ = (u8)(c&0xFF); \
  154393. } \
  154394. else if( c<0x00800 ){ \
  154395. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  154396. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  154397. } \
  154398. else if( c<0x10000 ){ \
  154399. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  154400. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  154401. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  154402. }else{ \
  154403. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  154404. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  154405. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  154406. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  154407. } \
  154408. }
  154409. #endif /* ifndef SQLITE_AMALGAMATION */
  154410. typedef struct unicode_tokenizer unicode_tokenizer;
  154411. typedef struct unicode_cursor unicode_cursor;
  154412. struct unicode_tokenizer {
  154413. sqlite3_tokenizer base;
  154414. int bRemoveDiacritic;
  154415. int nException;
  154416. int *aiException;
  154417. };
  154418. struct unicode_cursor {
  154419. sqlite3_tokenizer_cursor base;
  154420. const unsigned char *aInput; /* Input text being tokenized */
  154421. int nInput; /* Size of aInput[] in bytes */
  154422. int iOff; /* Current offset within aInput[] */
  154423. int iToken; /* Index of next token to be returned */
  154424. char *zToken; /* storage for current token */
  154425. int nAlloc; /* space allocated at zToken */
  154426. };
  154427. /*
  154428. ** Destroy a tokenizer allocated by unicodeCreate().
  154429. */
  154430. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  154431. if( pTokenizer ){
  154432. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  154433. sqlite3_free(p->aiException);
  154434. sqlite3_free(p);
  154435. }
  154436. return SQLITE_OK;
  154437. }
  154438. /*
  154439. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  154440. ** statement has specified that the tokenizer for this table shall consider
  154441. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  154442. ** token characters (if bAlnum==1).
  154443. **
  154444. ** For each codepoint in the zIn/nIn string, this function checks if the
  154445. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  154446. ** If so, no action is taken. Otherwise, the codepoint is added to the
  154447. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  154448. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  154449. ** codepoints in the aiException[] array.
  154450. **
  154451. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  154452. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  154453. ** It is not possible to change the behavior of the tokenizer with respect
  154454. ** to these codepoints.
  154455. */
  154456. static int unicodeAddExceptions(
  154457. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  154458. int bAlnum, /* Replace Isalnum() return value with this */
  154459. const char *zIn, /* Array of characters to make exceptions */
  154460. int nIn /* Length of z in bytes */
  154461. ){
  154462. const unsigned char *z = (const unsigned char *)zIn;
  154463. const unsigned char *zTerm = &z[nIn];
  154464. unsigned int iCode;
  154465. int nEntry = 0;
  154466. assert( bAlnum==0 || bAlnum==1 );
  154467. while( z<zTerm ){
  154468. READ_UTF8(z, zTerm, iCode);
  154469. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  154470. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  154471. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  154472. ){
  154473. nEntry++;
  154474. }
  154475. }
  154476. if( nEntry ){
  154477. int *aNew; /* New aiException[] array */
  154478. int nNew; /* Number of valid entries in array aNew[] */
  154479. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  154480. if( aNew==0 ) return SQLITE_NOMEM;
  154481. nNew = p->nException;
  154482. z = (const unsigned char *)zIn;
  154483. while( z<zTerm ){
  154484. READ_UTF8(z, zTerm, iCode);
  154485. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  154486. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  154487. ){
  154488. int i, j;
  154489. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  154490. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  154491. aNew[i] = (int)iCode;
  154492. nNew++;
  154493. }
  154494. }
  154495. p->aiException = aNew;
  154496. p->nException = nNew;
  154497. }
  154498. return SQLITE_OK;
  154499. }
  154500. /*
  154501. ** Return true if the p->aiException[] array contains the value iCode.
  154502. */
  154503. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  154504. if( p->nException>0 ){
  154505. int *a = p->aiException;
  154506. int iLo = 0;
  154507. int iHi = p->nException-1;
  154508. while( iHi>=iLo ){
  154509. int iTest = (iHi + iLo) / 2;
  154510. if( iCode==a[iTest] ){
  154511. return 1;
  154512. }else if( iCode>a[iTest] ){
  154513. iLo = iTest+1;
  154514. }else{
  154515. iHi = iTest-1;
  154516. }
  154517. }
  154518. }
  154519. return 0;
  154520. }
  154521. /*
  154522. ** Return true if, for the purposes of tokenization, codepoint iCode is
  154523. ** considered a token character (not a separator).
  154524. */
  154525. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  154526. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  154527. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  154528. }
  154529. /*
  154530. ** Create a new tokenizer instance.
  154531. */
  154532. static int unicodeCreate(
  154533. int nArg, /* Size of array argv[] */
  154534. const char * const *azArg, /* Tokenizer creation arguments */
  154535. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  154536. ){
  154537. unicode_tokenizer *pNew; /* New tokenizer object */
  154538. int i;
  154539. int rc = SQLITE_OK;
  154540. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  154541. if( pNew==NULL ) return SQLITE_NOMEM;
  154542. memset(pNew, 0, sizeof(unicode_tokenizer));
  154543. pNew->bRemoveDiacritic = 1;
  154544. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  154545. const char *z = azArg[i];
  154546. int n = (int)strlen(z);
  154547. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  154548. pNew->bRemoveDiacritic = 1;
  154549. }
  154550. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  154551. pNew->bRemoveDiacritic = 0;
  154552. }
  154553. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  154554. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  154555. }
  154556. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  154557. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  154558. }
  154559. else{
  154560. /* Unrecognized argument */
  154561. rc = SQLITE_ERROR;
  154562. }
  154563. }
  154564. if( rc!=SQLITE_OK ){
  154565. unicodeDestroy((sqlite3_tokenizer *)pNew);
  154566. pNew = 0;
  154567. }
  154568. *pp = (sqlite3_tokenizer *)pNew;
  154569. return rc;
  154570. }
  154571. /*
  154572. ** Prepare to begin tokenizing a particular string. The input
  154573. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  154574. ** used to incrementally tokenize this string is returned in
  154575. ** *ppCursor.
  154576. */
  154577. static int unicodeOpen(
  154578. sqlite3_tokenizer *p, /* The tokenizer */
  154579. const char *aInput, /* Input string */
  154580. int nInput, /* Size of string aInput in bytes */
  154581. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  154582. ){
  154583. unicode_cursor *pCsr;
  154584. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  154585. if( pCsr==0 ){
  154586. return SQLITE_NOMEM;
  154587. }
  154588. memset(pCsr, 0, sizeof(unicode_cursor));
  154589. pCsr->aInput = (const unsigned char *)aInput;
  154590. if( aInput==0 ){
  154591. pCsr->nInput = 0;
  154592. }else if( nInput<0 ){
  154593. pCsr->nInput = (int)strlen(aInput);
  154594. }else{
  154595. pCsr->nInput = nInput;
  154596. }
  154597. *pp = &pCsr->base;
  154598. UNUSED_PARAMETER(p);
  154599. return SQLITE_OK;
  154600. }
  154601. /*
  154602. ** Close a tokenization cursor previously opened by a call to
  154603. ** simpleOpen() above.
  154604. */
  154605. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  154606. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  154607. sqlite3_free(pCsr->zToken);
  154608. sqlite3_free(pCsr);
  154609. return SQLITE_OK;
  154610. }
  154611. /*
  154612. ** Extract the next token from a tokenization cursor. The cursor must
  154613. ** have been opened by a prior call to simpleOpen().
  154614. */
  154615. static int unicodeNext(
  154616. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  154617. const char **paToken, /* OUT: Token text */
  154618. int *pnToken, /* OUT: Number of bytes at *paToken */
  154619. int *piStart, /* OUT: Starting offset of token */
  154620. int *piEnd, /* OUT: Ending offset of token */
  154621. int *piPos /* OUT: Position integer of token */
  154622. ){
  154623. unicode_cursor *pCsr = (unicode_cursor *)pC;
  154624. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  154625. unsigned int iCode = 0;
  154626. char *zOut;
  154627. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  154628. const unsigned char *zStart = z;
  154629. const unsigned char *zEnd;
  154630. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  154631. /* Scan past any delimiter characters before the start of the next token.
  154632. ** Return SQLITE_DONE early if this takes us all the way to the end of
  154633. ** the input. */
  154634. while( z<zTerm ){
  154635. READ_UTF8(z, zTerm, iCode);
  154636. if( unicodeIsAlnum(p, (int)iCode) ) break;
  154637. zStart = z;
  154638. }
  154639. if( zStart>=zTerm ) return SQLITE_DONE;
  154640. zOut = pCsr->zToken;
  154641. do {
  154642. int iOut;
  154643. /* Grow the output buffer if required. */
  154644. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  154645. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  154646. if( !zNew ) return SQLITE_NOMEM;
  154647. zOut = &zNew[zOut - pCsr->zToken];
  154648. pCsr->zToken = zNew;
  154649. pCsr->nAlloc += 64;
  154650. }
  154651. /* Write the folded case of the last character read to the output */
  154652. zEnd = z;
  154653. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  154654. if( iOut ){
  154655. WRITE_UTF8(zOut, iOut);
  154656. }
  154657. /* If the cursor is not at EOF, read the next character */
  154658. if( z>=zTerm ) break;
  154659. READ_UTF8(z, zTerm, iCode);
  154660. }while( unicodeIsAlnum(p, (int)iCode)
  154661. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  154662. );
  154663. /* Set the output variables and return. */
  154664. pCsr->iOff = (int)(z - pCsr->aInput);
  154665. *paToken = pCsr->zToken;
  154666. *pnToken = (int)(zOut - pCsr->zToken);
  154667. *piStart = (int)(zStart - pCsr->aInput);
  154668. *piEnd = (int)(zEnd - pCsr->aInput);
  154669. *piPos = pCsr->iToken++;
  154670. return SQLITE_OK;
  154671. }
  154672. /*
  154673. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  154674. ** structure for the unicode tokenizer.
  154675. */
  154676. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  154677. static const sqlite3_tokenizer_module module = {
  154678. 0,
  154679. unicodeCreate,
  154680. unicodeDestroy,
  154681. unicodeOpen,
  154682. unicodeClose,
  154683. unicodeNext,
  154684. 0,
  154685. };
  154686. *ppModule = &module;
  154687. }
  154688. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  154689. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  154690. /************** End of fts3_unicode.c ****************************************/
  154691. /************** Begin file fts3_unicode2.c ***********************************/
  154692. /*
  154693. ** 2012 May 25
  154694. **
  154695. ** The author disclaims copyright to this source code. In place of
  154696. ** a legal notice, here is a blessing:
  154697. **
  154698. ** May you do good and not evil.
  154699. ** May you find forgiveness for yourself and forgive others.
  154700. ** May you share freely, never taking more than you give.
  154701. **
  154702. ******************************************************************************
  154703. */
  154704. /*
  154705. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  154706. */
  154707. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154708. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  154709. /* #include <assert.h> */
  154710. /*
  154711. ** Return true if the argument corresponds to a unicode codepoint
  154712. ** classified as either a letter or a number. Otherwise false.
  154713. **
  154714. ** The results are undefined if the value passed to this function
  154715. ** is less than zero.
  154716. */
  154717. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  154718. /* Each unsigned integer in the following array corresponds to a contiguous
  154719. ** range of unicode codepoints that are not either letters or numbers (i.e.
  154720. ** codepoints for which this function should return 0).
  154721. **
  154722. ** The most significant 22 bits in each 32-bit value contain the first
  154723. ** codepoint in the range. The least significant 10 bits are used to store
  154724. ** the size of the range (always at least 1). In other words, the value
  154725. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  154726. ** C. It is not possible to represent a range larger than 1023 codepoints
  154727. ** using this format.
  154728. */
  154729. static const unsigned int aEntry[] = {
  154730. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  154731. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  154732. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  154733. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  154734. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  154735. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  154736. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  154737. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  154738. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  154739. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  154740. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  154741. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  154742. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  154743. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  154744. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  154745. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  154746. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  154747. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  154748. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  154749. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  154750. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  154751. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  154752. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  154753. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  154754. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  154755. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  154756. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  154757. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  154758. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  154759. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  154760. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  154761. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  154762. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  154763. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  154764. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  154765. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  154766. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  154767. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  154768. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  154769. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  154770. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  154771. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  154772. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  154773. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  154774. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  154775. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  154776. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  154777. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  154778. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  154779. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  154780. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  154781. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  154782. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  154783. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  154784. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  154785. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  154786. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  154787. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  154788. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  154789. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  154790. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  154791. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  154792. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  154793. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  154794. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  154795. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  154796. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  154797. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  154798. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  154799. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  154800. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  154801. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  154802. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  154803. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  154804. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  154805. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  154806. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  154807. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  154808. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  154809. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  154810. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  154811. 0x380400F0,
  154812. };
  154813. static const unsigned int aAscii[4] = {
  154814. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  154815. };
  154816. if( (unsigned int)c<128 ){
  154817. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  154818. }else if( (unsigned int)c<(1<<22) ){
  154819. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  154820. int iRes = 0;
  154821. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  154822. int iLo = 0;
  154823. while( iHi>=iLo ){
  154824. int iTest = (iHi + iLo) / 2;
  154825. if( key >= aEntry[iTest] ){
  154826. iRes = iTest;
  154827. iLo = iTest+1;
  154828. }else{
  154829. iHi = iTest-1;
  154830. }
  154831. }
  154832. assert( aEntry[0]<key );
  154833. assert( key>=aEntry[iRes] );
  154834. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  154835. }
  154836. return 1;
  154837. }
  154838. /*
  154839. ** If the argument is a codepoint corresponding to a lowercase letter
  154840. ** in the ASCII range with a diacritic added, return the codepoint
  154841. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  154842. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  154843. ** E"). The resuls of passing a codepoint that corresponds to an
  154844. ** uppercase letter are undefined.
  154845. */
  154846. static int remove_diacritic(int c){
  154847. unsigned short aDia[] = {
  154848. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  154849. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  154850. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  154851. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  154852. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  154853. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  154854. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  154855. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  154856. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  154857. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  154858. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  154859. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  154860. 62924, 63050, 63082, 63274, 63390,
  154861. };
  154862. char aChar[] = {
  154863. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  154864. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  154865. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  154866. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  154867. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  154868. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  154869. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  154870. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  154871. 'e', 'i', 'o', 'u', 'y',
  154872. };
  154873. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  154874. int iRes = 0;
  154875. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  154876. int iLo = 0;
  154877. while( iHi>=iLo ){
  154878. int iTest = (iHi + iLo) / 2;
  154879. if( key >= aDia[iTest] ){
  154880. iRes = iTest;
  154881. iLo = iTest+1;
  154882. }else{
  154883. iHi = iTest-1;
  154884. }
  154885. }
  154886. assert( key>=aDia[iRes] );
  154887. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  154888. }
  154889. /*
  154890. ** Return true if the argument interpreted as a unicode codepoint
  154891. ** is a diacritical modifier character.
  154892. */
  154893. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  154894. unsigned int mask0 = 0x08029FDF;
  154895. unsigned int mask1 = 0x000361F8;
  154896. if( c<768 || c>817 ) return 0;
  154897. return (c < 768+32) ?
  154898. (mask0 & (1 << (c-768))) :
  154899. (mask1 & (1 << (c-768-32)));
  154900. }
  154901. /*
  154902. ** Interpret the argument as a unicode codepoint. If the codepoint
  154903. ** is an upper case character that has a lower case equivalent,
  154904. ** return the codepoint corresponding to the lower case version.
  154905. ** Otherwise, return a copy of the argument.
  154906. **
  154907. ** The results are undefined if the value passed to this function
  154908. ** is less than zero.
  154909. */
  154910. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  154911. /* Each entry in the following array defines a rule for folding a range
  154912. ** of codepoints to lower case. The rule applies to a range of nRange
  154913. ** codepoints starting at codepoint iCode.
  154914. **
  154915. ** If the least significant bit in flags is clear, then the rule applies
  154916. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  154917. ** need to be folded). Or, if it is set, then the rule only applies to
  154918. ** every second codepoint in the range, starting with codepoint C.
  154919. **
  154920. ** The 7 most significant bits in flags are an index into the aiOff[]
  154921. ** array. If a specific codepoint C does require folding, then its lower
  154922. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  154923. **
  154924. ** The contents of this array are generated by parsing the CaseFolding.txt
  154925. ** file distributed as part of the "Unicode Character Database". See
  154926. ** http://www.unicode.org for details.
  154927. */
  154928. static const struct TableEntry {
  154929. unsigned short iCode;
  154930. unsigned char flags;
  154931. unsigned char nRange;
  154932. } aEntry[] = {
  154933. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  154934. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  154935. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  154936. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  154937. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  154938. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  154939. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  154940. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  154941. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  154942. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  154943. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  154944. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  154945. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  154946. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  154947. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  154948. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  154949. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  154950. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  154951. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  154952. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  154953. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  154954. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  154955. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  154956. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  154957. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  154958. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  154959. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  154960. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  154961. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  154962. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  154963. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  154964. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  154965. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  154966. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  154967. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  154968. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  154969. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  154970. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  154971. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  154972. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  154973. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  154974. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  154975. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  154976. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  154977. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  154978. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  154979. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  154980. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  154981. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  154982. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  154983. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  154984. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  154985. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  154986. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  154987. {65313, 14, 26},
  154988. };
  154989. static const unsigned short aiOff[] = {
  154990. 1, 2, 8, 15, 16, 26, 28, 32,
  154991. 37, 38, 40, 48, 63, 64, 69, 71,
  154992. 79, 80, 116, 202, 203, 205, 206, 207,
  154993. 209, 210, 211, 213, 214, 217, 218, 219,
  154994. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  154995. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  154996. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  154997. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  154998. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  154999. 65514, 65521, 65527, 65528, 65529,
  155000. };
  155001. int ret = c;
  155002. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  155003. if( c<128 ){
  155004. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  155005. }else if( c<65536 ){
  155006. const struct TableEntry *p;
  155007. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  155008. int iLo = 0;
  155009. int iRes = -1;
  155010. assert( c>aEntry[0].iCode );
  155011. while( iHi>=iLo ){
  155012. int iTest = (iHi + iLo) / 2;
  155013. int cmp = (c - aEntry[iTest].iCode);
  155014. if( cmp>=0 ){
  155015. iRes = iTest;
  155016. iLo = iTest+1;
  155017. }else{
  155018. iHi = iTest-1;
  155019. }
  155020. }
  155021. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  155022. p = &aEntry[iRes];
  155023. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  155024. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  155025. assert( ret>0 );
  155026. }
  155027. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  155028. }
  155029. else if( c>=66560 && c<66600 ){
  155030. ret = c + 40;
  155031. }
  155032. return ret;
  155033. }
  155034. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  155035. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  155036. /************** End of fts3_unicode2.c ***************************************/
  155037. /************** Begin file rtree.c *******************************************/
  155038. /*
  155039. ** 2001 September 15
  155040. **
  155041. ** The author disclaims copyright to this source code. In place of
  155042. ** a legal notice, here is a blessing:
  155043. **
  155044. ** May you do good and not evil.
  155045. ** May you find forgiveness for yourself and forgive others.
  155046. ** May you share freely, never taking more than you give.
  155047. **
  155048. *************************************************************************
  155049. ** This file contains code for implementations of the r-tree and r*-tree
  155050. ** algorithms packaged as an SQLite virtual table module.
  155051. */
  155052. /*
  155053. ** Database Format of R-Tree Tables
  155054. ** --------------------------------
  155055. **
  155056. ** The data structure for a single virtual r-tree table is stored in three
  155057. ** native SQLite tables declared as follows. In each case, the '%' character
  155058. ** in the table name is replaced with the user-supplied name of the r-tree
  155059. ** table.
  155060. **
  155061. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  155062. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  155063. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  155064. **
  155065. ** The data for each node of the r-tree structure is stored in the %_node
  155066. ** table. For each node that is not the root node of the r-tree, there is
  155067. ** an entry in the %_parent table associating the node with its parent.
  155068. ** And for each row of data in the table, there is an entry in the %_rowid
  155069. ** table that maps from the entries rowid to the id of the node that it
  155070. ** is stored on.
  155071. **
  155072. ** The root node of an r-tree always exists, even if the r-tree table is
  155073. ** empty. The nodeno of the root node is always 1. All other nodes in the
  155074. ** table must be the same size as the root node. The content of each node
  155075. ** is formatted as follows:
  155076. **
  155077. ** 1. If the node is the root node (node 1), then the first 2 bytes
  155078. ** of the node contain the tree depth as a big-endian integer.
  155079. ** For non-root nodes, the first 2 bytes are left unused.
  155080. **
  155081. ** 2. The next 2 bytes contain the number of entries currently
  155082. ** stored in the node.
  155083. **
  155084. ** 3. The remainder of the node contains the node entries. Each entry
  155085. ** consists of a single 8-byte integer followed by an even number
  155086. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  155087. ** of a record. For internal nodes it is the node number of a
  155088. ** child page.
  155089. */
  155090. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  155091. #ifndef SQLITE_CORE
  155092. /* #include "sqlite3ext.h" */
  155093. SQLITE_EXTENSION_INIT1
  155094. #else
  155095. /* #include "sqlite3.h" */
  155096. #endif
  155097. /* #include <string.h> */
  155098. /* #include <assert.h> */
  155099. /* #include <stdio.h> */
  155100. #ifndef SQLITE_AMALGAMATION
  155101. #include "sqlite3rtree.h"
  155102. typedef sqlite3_int64 i64;
  155103. typedef sqlite3_uint64 u64;
  155104. typedef unsigned char u8;
  155105. typedef unsigned short u16;
  155106. typedef unsigned int u32;
  155107. #endif
  155108. /* The following macro is used to suppress compiler warnings.
  155109. */
  155110. #ifndef UNUSED_PARAMETER
  155111. # define UNUSED_PARAMETER(x) (void)(x)
  155112. #endif
  155113. typedef struct Rtree Rtree;
  155114. typedef struct RtreeCursor RtreeCursor;
  155115. typedef struct RtreeNode RtreeNode;
  155116. typedef struct RtreeCell RtreeCell;
  155117. typedef struct RtreeConstraint RtreeConstraint;
  155118. typedef struct RtreeMatchArg RtreeMatchArg;
  155119. typedef struct RtreeGeomCallback RtreeGeomCallback;
  155120. typedef union RtreeCoord RtreeCoord;
  155121. typedef struct RtreeSearchPoint RtreeSearchPoint;
  155122. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  155123. #define RTREE_MAX_DIMENSIONS 5
  155124. /* Size of hash table Rtree.aHash. This hash table is not expected to
  155125. ** ever contain very many entries, so a fixed number of buckets is
  155126. ** used.
  155127. */
  155128. #define HASHSIZE 97
  155129. /* The xBestIndex method of this virtual table requires an estimate of
  155130. ** the number of rows in the virtual table to calculate the costs of
  155131. ** various strategies. If possible, this estimate is loaded from the
  155132. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  155133. ** Otherwise, if no sqlite_stat1 entry is available, use
  155134. ** RTREE_DEFAULT_ROWEST.
  155135. */
  155136. #define RTREE_DEFAULT_ROWEST 1048576
  155137. #define RTREE_MIN_ROWEST 100
  155138. /*
  155139. ** An rtree virtual-table object.
  155140. */
  155141. struct Rtree {
  155142. sqlite3_vtab base; /* Base class. Must be first */
  155143. sqlite3 *db; /* Host database connection */
  155144. int iNodeSize; /* Size in bytes of each node in the node table */
  155145. u8 nDim; /* Number of dimensions */
  155146. u8 nDim2; /* Twice the number of dimensions */
  155147. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  155148. u8 nBytesPerCell; /* Bytes consumed per cell */
  155149. u8 inWrTrans; /* True if inside write transaction */
  155150. int iDepth; /* Current depth of the r-tree structure */
  155151. char *zDb; /* Name of database containing r-tree table */
  155152. char *zName; /* Name of r-tree table */
  155153. u32 nBusy; /* Current number of users of this structure */
  155154. i64 nRowEst; /* Estimated number of rows in this table */
  155155. u32 nCursor; /* Number of open cursors */
  155156. /* List of nodes removed during a CondenseTree operation. List is
  155157. ** linked together via the pointer normally used for hash chains -
  155158. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  155159. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  155160. */
  155161. RtreeNode *pDeleted;
  155162. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  155163. /* Blob I/O on xxx_node */
  155164. sqlite3_blob *pNodeBlob;
  155165. /* Statements to read/write/delete a record from xxx_node */
  155166. sqlite3_stmt *pWriteNode;
  155167. sqlite3_stmt *pDeleteNode;
  155168. /* Statements to read/write/delete a record from xxx_rowid */
  155169. sqlite3_stmt *pReadRowid;
  155170. sqlite3_stmt *pWriteRowid;
  155171. sqlite3_stmt *pDeleteRowid;
  155172. /* Statements to read/write/delete a record from xxx_parent */
  155173. sqlite3_stmt *pReadParent;
  155174. sqlite3_stmt *pWriteParent;
  155175. sqlite3_stmt *pDeleteParent;
  155176. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  155177. };
  155178. /* Possible values for Rtree.eCoordType: */
  155179. #define RTREE_COORD_REAL32 0
  155180. #define RTREE_COORD_INT32 1
  155181. /*
  155182. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  155183. ** only deal with integer coordinates. No floating point operations
  155184. ** will be done.
  155185. */
  155186. #ifdef SQLITE_RTREE_INT_ONLY
  155187. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  155188. typedef int RtreeValue; /* Low accuracy coordinate */
  155189. # define RTREE_ZERO 0
  155190. #else
  155191. typedef double RtreeDValue; /* High accuracy coordinate */
  155192. typedef float RtreeValue; /* Low accuracy coordinate */
  155193. # define RTREE_ZERO 0.0
  155194. #endif
  155195. /*
  155196. ** When doing a search of an r-tree, instances of the following structure
  155197. ** record intermediate results from the tree walk.
  155198. **
  155199. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  155200. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  155201. ** the id is of the parent node and the cell that RtreeSearchPoint
  155202. ** represents is the iCell-th entry in the parent node.
  155203. */
  155204. struct RtreeSearchPoint {
  155205. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  155206. sqlite3_int64 id; /* Node ID */
  155207. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  155208. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  155209. u8 iCell; /* Cell index within the node */
  155210. };
  155211. /*
  155212. ** The minimum number of cells allowed for a node is a third of the
  155213. ** maximum. In Gutman's notation:
  155214. **
  155215. ** m = M/3
  155216. **
  155217. ** If an R*-tree "Reinsert" operation is required, the same number of
  155218. ** cells are removed from the overfull node and reinserted into the tree.
  155219. */
  155220. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  155221. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  155222. #define RTREE_MAXCELLS 51
  155223. /*
  155224. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  155225. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  155226. ** Therefore all non-root nodes must contain at least 3 entries. Since
  155227. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  155228. ** 40 or less.
  155229. */
  155230. #define RTREE_MAX_DEPTH 40
  155231. /*
  155232. ** Number of entries in the cursor RtreeNode cache. The first entry is
  155233. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  155234. ** entries cache the RtreeNode for the first elements of the priority queue.
  155235. */
  155236. #define RTREE_CACHE_SZ 5
  155237. /*
  155238. ** An rtree cursor object.
  155239. */
  155240. struct RtreeCursor {
  155241. sqlite3_vtab_cursor base; /* Base class. Must be first */
  155242. u8 atEOF; /* True if at end of search */
  155243. u8 bPoint; /* True if sPoint is valid */
  155244. int iStrategy; /* Copy of idxNum search parameter */
  155245. int nConstraint; /* Number of entries in aConstraint */
  155246. RtreeConstraint *aConstraint; /* Search constraints. */
  155247. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  155248. int nPoint; /* Number of slots used in aPoint[] */
  155249. int mxLevel; /* iLevel value for root of the tree */
  155250. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  155251. RtreeSearchPoint sPoint; /* Cached next search point */
  155252. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  155253. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  155254. };
  155255. /* Return the Rtree of a RtreeCursor */
  155256. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  155257. /*
  155258. ** A coordinate can be either a floating point number or a integer. All
  155259. ** coordinates within a single R-Tree are always of the same time.
  155260. */
  155261. union RtreeCoord {
  155262. RtreeValue f; /* Floating point value */
  155263. int i; /* Integer value */
  155264. u32 u; /* Unsigned for byte-order conversions */
  155265. };
  155266. /*
  155267. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  155268. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  155269. ** variable pRtree points to the Rtree structure associated with the
  155270. ** RtreeCoord.
  155271. */
  155272. #ifdef SQLITE_RTREE_INT_ONLY
  155273. # define DCOORD(coord) ((RtreeDValue)coord.i)
  155274. #else
  155275. # define DCOORD(coord) ( \
  155276. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  155277. ((double)coord.f) : \
  155278. ((double)coord.i) \
  155279. )
  155280. #endif
  155281. /*
  155282. ** A search constraint.
  155283. */
  155284. struct RtreeConstraint {
  155285. int iCoord; /* Index of constrained coordinate */
  155286. int op; /* Constraining operation */
  155287. union {
  155288. RtreeDValue rValue; /* Constraint value. */
  155289. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  155290. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  155291. } u;
  155292. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  155293. };
  155294. /* Possible values for RtreeConstraint.op */
  155295. #define RTREE_EQ 0x41 /* A */
  155296. #define RTREE_LE 0x42 /* B */
  155297. #define RTREE_LT 0x43 /* C */
  155298. #define RTREE_GE 0x44 /* D */
  155299. #define RTREE_GT 0x45 /* E */
  155300. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  155301. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  155302. /*
  155303. ** An rtree structure node.
  155304. */
  155305. struct RtreeNode {
  155306. RtreeNode *pParent; /* Parent node */
  155307. i64 iNode; /* The node number */
  155308. int nRef; /* Number of references to this node */
  155309. int isDirty; /* True if the node needs to be written to disk */
  155310. u8 *zData; /* Content of the node, as should be on disk */
  155311. RtreeNode *pNext; /* Next node in this hash collision chain */
  155312. };
  155313. /* Return the number of cells in a node */
  155314. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  155315. /*
  155316. ** A single cell from a node, deserialized
  155317. */
  155318. struct RtreeCell {
  155319. i64 iRowid; /* Node or entry ID */
  155320. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  155321. };
  155322. /*
  155323. ** This object becomes the sqlite3_user_data() for the SQL functions
  155324. ** that are created by sqlite3_rtree_geometry_callback() and
  155325. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  155326. ** operators in order to constrain a search.
  155327. **
  155328. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  155329. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  155330. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  155331. ** sqlite3_rtree_query_callback().
  155332. **
  155333. ** This object is deleted automatically by the destructor mechanism in
  155334. ** sqlite3_create_function_v2().
  155335. */
  155336. struct RtreeGeomCallback {
  155337. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  155338. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  155339. void (*xDestructor)(void*);
  155340. void *pContext;
  155341. };
  155342. /*
  155343. ** An instance of this structure (in the form of a BLOB) is returned by
  155344. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  155345. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  155346. ** operand to the MATCH operator of an R-Tree.
  155347. */
  155348. struct RtreeMatchArg {
  155349. u32 iSize; /* Size of this object */
  155350. RtreeGeomCallback cb; /* Info about the callback functions */
  155351. int nParam; /* Number of parameters to the SQL function */
  155352. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  155353. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  155354. };
  155355. #ifndef MAX
  155356. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  155357. #endif
  155358. #ifndef MIN
  155359. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  155360. #endif
  155361. /* What version of GCC is being used. 0 means GCC is not being used .
  155362. ** Note that the GCC_VERSION macro will also be set correctly when using
  155363. ** clang, since clang works hard to be gcc compatible. So the gcc
  155364. ** optimizations will also work when compiling with clang.
  155365. */
  155366. #ifndef GCC_VERSION
  155367. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  155368. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  155369. #else
  155370. # define GCC_VERSION 0
  155371. #endif
  155372. #endif
  155373. /* The testcase() macro should already be defined in the amalgamation. If
  155374. ** it is not, make it a no-op.
  155375. */
  155376. #ifndef SQLITE_AMALGAMATION
  155377. # define testcase(X)
  155378. #endif
  155379. /*
  155380. ** Macros to determine whether the machine is big or little endian,
  155381. ** and whether or not that determination is run-time or compile-time.
  155382. **
  155383. ** For best performance, an attempt is made to guess at the byte-order
  155384. ** using C-preprocessor macros. If that is unsuccessful, or if
  155385. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  155386. ** at run-time.
  155387. */
  155388. #ifndef SQLITE_BYTEORDER
  155389. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  155390. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  155391. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  155392. defined(__arm__)
  155393. # define SQLITE_BYTEORDER 1234
  155394. #elif defined(sparc) || defined(__ppc__)
  155395. # define SQLITE_BYTEORDER 4321
  155396. #else
  155397. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  155398. #endif
  155399. #endif
  155400. /* What version of MSVC is being used. 0 means MSVC is not being used */
  155401. #ifndef MSVC_VERSION
  155402. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  155403. # define MSVC_VERSION _MSC_VER
  155404. #else
  155405. # define MSVC_VERSION 0
  155406. #endif
  155407. #endif
  155408. /*
  155409. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  155410. ** 64 bit integer. The deserialized value is returned.
  155411. */
  155412. static int readInt16(u8 *p){
  155413. return (p[0]<<8) + p[1];
  155414. }
  155415. static void readCoord(u8 *p, RtreeCoord *pCoord){
  155416. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  155417. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  155418. pCoord->u = _byteswap_ulong(*(u32*)p);
  155419. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  155420. pCoord->u = __builtin_bswap32(*(u32*)p);
  155421. #elif SQLITE_BYTEORDER==4321
  155422. pCoord->u = *(u32*)p;
  155423. #else
  155424. pCoord->u = (
  155425. (((u32)p[0]) << 24) +
  155426. (((u32)p[1]) << 16) +
  155427. (((u32)p[2]) << 8) +
  155428. (((u32)p[3]) << 0)
  155429. );
  155430. #endif
  155431. }
  155432. static i64 readInt64(u8 *p){
  155433. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  155434. u64 x;
  155435. memcpy(&x, p, 8);
  155436. return (i64)_byteswap_uint64(x);
  155437. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  155438. u64 x;
  155439. memcpy(&x, p, 8);
  155440. return (i64)__builtin_bswap64(x);
  155441. #elif SQLITE_BYTEORDER==4321
  155442. i64 x;
  155443. memcpy(&x, p, 8);
  155444. return x;
  155445. #else
  155446. return (i64)(
  155447. (((u64)p[0]) << 56) +
  155448. (((u64)p[1]) << 48) +
  155449. (((u64)p[2]) << 40) +
  155450. (((u64)p[3]) << 32) +
  155451. (((u64)p[4]) << 24) +
  155452. (((u64)p[5]) << 16) +
  155453. (((u64)p[6]) << 8) +
  155454. (((u64)p[7]) << 0)
  155455. );
  155456. #endif
  155457. }
  155458. /*
  155459. ** Functions to serialize a 16 bit integer, 32 bit real number and
  155460. ** 64 bit integer. The value returned is the number of bytes written
  155461. ** to the argument buffer (always 2, 4 and 8 respectively).
  155462. */
  155463. static void writeInt16(u8 *p, int i){
  155464. p[0] = (i>> 8)&0xFF;
  155465. p[1] = (i>> 0)&0xFF;
  155466. }
  155467. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  155468. u32 i;
  155469. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  155470. assert( sizeof(RtreeCoord)==4 );
  155471. assert( sizeof(u32)==4 );
  155472. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  155473. i = __builtin_bswap32(pCoord->u);
  155474. memcpy(p, &i, 4);
  155475. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  155476. i = _byteswap_ulong(pCoord->u);
  155477. memcpy(p, &i, 4);
  155478. #elif SQLITE_BYTEORDER==4321
  155479. i = pCoord->u;
  155480. memcpy(p, &i, 4);
  155481. #else
  155482. i = pCoord->u;
  155483. p[0] = (i>>24)&0xFF;
  155484. p[1] = (i>>16)&0xFF;
  155485. p[2] = (i>> 8)&0xFF;
  155486. p[3] = (i>> 0)&0xFF;
  155487. #endif
  155488. return 4;
  155489. }
  155490. static int writeInt64(u8 *p, i64 i){
  155491. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  155492. i = (i64)__builtin_bswap64((u64)i);
  155493. memcpy(p, &i, 8);
  155494. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  155495. i = (i64)_byteswap_uint64((u64)i);
  155496. memcpy(p, &i, 8);
  155497. #elif SQLITE_BYTEORDER==4321
  155498. memcpy(p, &i, 8);
  155499. #else
  155500. p[0] = (i>>56)&0xFF;
  155501. p[1] = (i>>48)&0xFF;
  155502. p[2] = (i>>40)&0xFF;
  155503. p[3] = (i>>32)&0xFF;
  155504. p[4] = (i>>24)&0xFF;
  155505. p[5] = (i>>16)&0xFF;
  155506. p[6] = (i>> 8)&0xFF;
  155507. p[7] = (i>> 0)&0xFF;
  155508. #endif
  155509. return 8;
  155510. }
  155511. /*
  155512. ** Increment the reference count of node p.
  155513. */
  155514. static void nodeReference(RtreeNode *p){
  155515. if( p ){
  155516. p->nRef++;
  155517. }
  155518. }
  155519. /*
  155520. ** Clear the content of node p (set all bytes to 0x00).
  155521. */
  155522. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  155523. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  155524. p->isDirty = 1;
  155525. }
  155526. /*
  155527. ** Given a node number iNode, return the corresponding key to use
  155528. ** in the Rtree.aHash table.
  155529. */
  155530. static int nodeHash(i64 iNode){
  155531. return iNode % HASHSIZE;
  155532. }
  155533. /*
  155534. ** Search the node hash table for node iNode. If found, return a pointer
  155535. ** to it. Otherwise, return 0.
  155536. */
  155537. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  155538. RtreeNode *p;
  155539. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  155540. return p;
  155541. }
  155542. /*
  155543. ** Add node pNode to the node hash table.
  155544. */
  155545. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  155546. int iHash;
  155547. assert( pNode->pNext==0 );
  155548. iHash = nodeHash(pNode->iNode);
  155549. pNode->pNext = pRtree->aHash[iHash];
  155550. pRtree->aHash[iHash] = pNode;
  155551. }
  155552. /*
  155553. ** Remove node pNode from the node hash table.
  155554. */
  155555. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  155556. RtreeNode **pp;
  155557. if( pNode->iNode!=0 ){
  155558. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  155559. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  155560. *pp = pNode->pNext;
  155561. pNode->pNext = 0;
  155562. }
  155563. }
  155564. /*
  155565. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  155566. ** indicating that node has not yet been assigned a node number. It is
  155567. ** assigned a node number when nodeWrite() is called to write the
  155568. ** node contents out to the database.
  155569. */
  155570. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  155571. RtreeNode *pNode;
  155572. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  155573. if( pNode ){
  155574. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  155575. pNode->zData = (u8 *)&pNode[1];
  155576. pNode->nRef = 1;
  155577. pNode->pParent = pParent;
  155578. pNode->isDirty = 1;
  155579. nodeReference(pParent);
  155580. }
  155581. return pNode;
  155582. }
  155583. /*
  155584. ** Clear the Rtree.pNodeBlob object
  155585. */
  155586. static void nodeBlobReset(Rtree *pRtree){
  155587. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  155588. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  155589. pRtree->pNodeBlob = 0;
  155590. sqlite3_blob_close(pBlob);
  155591. }
  155592. }
  155593. /*
  155594. ** Obtain a reference to an r-tree node.
  155595. */
  155596. static int nodeAcquire(
  155597. Rtree *pRtree, /* R-tree structure */
  155598. i64 iNode, /* Node number to load */
  155599. RtreeNode *pParent, /* Either the parent node or NULL */
  155600. RtreeNode **ppNode /* OUT: Acquired node */
  155601. ){
  155602. int rc = SQLITE_OK;
  155603. RtreeNode *pNode = 0;
  155604. /* Check if the requested node is already in the hash table. If so,
  155605. ** increase its reference count and return it.
  155606. */
  155607. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  155608. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  155609. if( pParent && !pNode->pParent ){
  155610. nodeReference(pParent);
  155611. pNode->pParent = pParent;
  155612. }
  155613. pNode->nRef++;
  155614. *ppNode = pNode;
  155615. return SQLITE_OK;
  155616. }
  155617. if( pRtree->pNodeBlob ){
  155618. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  155619. pRtree->pNodeBlob = 0;
  155620. rc = sqlite3_blob_reopen(pBlob, iNode);
  155621. pRtree->pNodeBlob = pBlob;
  155622. if( rc ){
  155623. nodeBlobReset(pRtree);
  155624. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  155625. }
  155626. }
  155627. if( pRtree->pNodeBlob==0 ){
  155628. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  155629. if( zTab==0 ) return SQLITE_NOMEM;
  155630. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  155631. &pRtree->pNodeBlob);
  155632. sqlite3_free(zTab);
  155633. }
  155634. if( rc ){
  155635. nodeBlobReset(pRtree);
  155636. *ppNode = 0;
  155637. /* If unable to open an sqlite3_blob on the desired row, that can only
  155638. ** be because the shadow tables hold erroneous data. */
  155639. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  155640. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  155641. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  155642. if( !pNode ){
  155643. rc = SQLITE_NOMEM;
  155644. }else{
  155645. pNode->pParent = pParent;
  155646. pNode->zData = (u8 *)&pNode[1];
  155647. pNode->nRef = 1;
  155648. pNode->iNode = iNode;
  155649. pNode->isDirty = 0;
  155650. pNode->pNext = 0;
  155651. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  155652. pRtree->iNodeSize, 0);
  155653. nodeReference(pParent);
  155654. }
  155655. }
  155656. /* If the root node was just loaded, set pRtree->iDepth to the height
  155657. ** of the r-tree structure. A height of zero means all data is stored on
  155658. ** the root node. A height of one means the children of the root node
  155659. ** are the leaves, and so on. If the depth as specified on the root node
  155660. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  155661. */
  155662. if( pNode && iNode==1 ){
  155663. pRtree->iDepth = readInt16(pNode->zData);
  155664. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  155665. rc = SQLITE_CORRUPT_VTAB;
  155666. }
  155667. }
  155668. /* If no error has occurred so far, check if the "number of entries"
  155669. ** field on the node is too large. If so, set the return code to
  155670. ** SQLITE_CORRUPT_VTAB.
  155671. */
  155672. if( pNode && rc==SQLITE_OK ){
  155673. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  155674. rc = SQLITE_CORRUPT_VTAB;
  155675. }
  155676. }
  155677. if( rc==SQLITE_OK ){
  155678. if( pNode!=0 ){
  155679. nodeHashInsert(pRtree, pNode);
  155680. }else{
  155681. rc = SQLITE_CORRUPT_VTAB;
  155682. }
  155683. *ppNode = pNode;
  155684. }else{
  155685. sqlite3_free(pNode);
  155686. *ppNode = 0;
  155687. }
  155688. return rc;
  155689. }
  155690. /*
  155691. ** Overwrite cell iCell of node pNode with the contents of pCell.
  155692. */
  155693. static void nodeOverwriteCell(
  155694. Rtree *pRtree, /* The overall R-Tree */
  155695. RtreeNode *pNode, /* The node into which the cell is to be written */
  155696. RtreeCell *pCell, /* The cell to write */
  155697. int iCell /* Index into pNode into which pCell is written */
  155698. ){
  155699. int ii;
  155700. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  155701. p += writeInt64(p, pCell->iRowid);
  155702. for(ii=0; ii<pRtree->nDim2; ii++){
  155703. p += writeCoord(p, &pCell->aCoord[ii]);
  155704. }
  155705. pNode->isDirty = 1;
  155706. }
  155707. /*
  155708. ** Remove the cell with index iCell from node pNode.
  155709. */
  155710. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  155711. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  155712. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  155713. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  155714. memmove(pDst, pSrc, nByte);
  155715. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  155716. pNode->isDirty = 1;
  155717. }
  155718. /*
  155719. ** Insert the contents of cell pCell into node pNode. If the insert
  155720. ** is successful, return SQLITE_OK.
  155721. **
  155722. ** If there is not enough free space in pNode, return SQLITE_FULL.
  155723. */
  155724. static int nodeInsertCell(
  155725. Rtree *pRtree, /* The overall R-Tree */
  155726. RtreeNode *pNode, /* Write new cell into this node */
  155727. RtreeCell *pCell /* The cell to be inserted */
  155728. ){
  155729. int nCell; /* Current number of cells in pNode */
  155730. int nMaxCell; /* Maximum number of cells for pNode */
  155731. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  155732. nCell = NCELL(pNode);
  155733. assert( nCell<=nMaxCell );
  155734. if( nCell<nMaxCell ){
  155735. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  155736. writeInt16(&pNode->zData[2], nCell+1);
  155737. pNode->isDirty = 1;
  155738. }
  155739. return (nCell==nMaxCell);
  155740. }
  155741. /*
  155742. ** If the node is dirty, write it out to the database.
  155743. */
  155744. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  155745. int rc = SQLITE_OK;
  155746. if( pNode->isDirty ){
  155747. sqlite3_stmt *p = pRtree->pWriteNode;
  155748. if( pNode->iNode ){
  155749. sqlite3_bind_int64(p, 1, pNode->iNode);
  155750. }else{
  155751. sqlite3_bind_null(p, 1);
  155752. }
  155753. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  155754. sqlite3_step(p);
  155755. pNode->isDirty = 0;
  155756. rc = sqlite3_reset(p);
  155757. if( pNode->iNode==0 && rc==SQLITE_OK ){
  155758. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  155759. nodeHashInsert(pRtree, pNode);
  155760. }
  155761. }
  155762. return rc;
  155763. }
  155764. /*
  155765. ** Release a reference to a node. If the node is dirty and the reference
  155766. ** count drops to zero, the node data is written to the database.
  155767. */
  155768. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  155769. int rc = SQLITE_OK;
  155770. if( pNode ){
  155771. assert( pNode->nRef>0 );
  155772. pNode->nRef--;
  155773. if( pNode->nRef==0 ){
  155774. if( pNode->iNode==1 ){
  155775. pRtree->iDepth = -1;
  155776. }
  155777. if( pNode->pParent ){
  155778. rc = nodeRelease(pRtree, pNode->pParent);
  155779. }
  155780. if( rc==SQLITE_OK ){
  155781. rc = nodeWrite(pRtree, pNode);
  155782. }
  155783. nodeHashDelete(pRtree, pNode);
  155784. sqlite3_free(pNode);
  155785. }
  155786. }
  155787. return rc;
  155788. }
  155789. /*
  155790. ** Return the 64-bit integer value associated with cell iCell of
  155791. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  155792. ** an internal node, then the 64-bit integer is a child page number.
  155793. */
  155794. static i64 nodeGetRowid(
  155795. Rtree *pRtree, /* The overall R-Tree */
  155796. RtreeNode *pNode, /* The node from which to extract the ID */
  155797. int iCell /* The cell index from which to extract the ID */
  155798. ){
  155799. assert( iCell<NCELL(pNode) );
  155800. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  155801. }
  155802. /*
  155803. ** Return coordinate iCoord from cell iCell in node pNode.
  155804. */
  155805. static void nodeGetCoord(
  155806. Rtree *pRtree, /* The overall R-Tree */
  155807. RtreeNode *pNode, /* The node from which to extract a coordinate */
  155808. int iCell, /* The index of the cell within the node */
  155809. int iCoord, /* Which coordinate to extract */
  155810. RtreeCoord *pCoord /* OUT: Space to write result to */
  155811. ){
  155812. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  155813. }
  155814. /*
  155815. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  155816. ** to by pCell with the results.
  155817. */
  155818. static void nodeGetCell(
  155819. Rtree *pRtree, /* The overall R-Tree */
  155820. RtreeNode *pNode, /* The node containing the cell to be read */
  155821. int iCell, /* Index of the cell within the node */
  155822. RtreeCell *pCell /* OUT: Write the cell contents here */
  155823. ){
  155824. u8 *pData;
  155825. RtreeCoord *pCoord;
  155826. int ii = 0;
  155827. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  155828. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  155829. pCoord = pCell->aCoord;
  155830. do{
  155831. readCoord(pData, &pCoord[ii]);
  155832. readCoord(pData+4, &pCoord[ii+1]);
  155833. pData += 8;
  155834. ii += 2;
  155835. }while( ii<pRtree->nDim2 );
  155836. }
  155837. /* Forward declaration for the function that does the work of
  155838. ** the virtual table module xCreate() and xConnect() methods.
  155839. */
  155840. static int rtreeInit(
  155841. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  155842. );
  155843. /*
  155844. ** Rtree virtual table module xCreate method.
  155845. */
  155846. static int rtreeCreate(
  155847. sqlite3 *db,
  155848. void *pAux,
  155849. int argc, const char *const*argv,
  155850. sqlite3_vtab **ppVtab,
  155851. char **pzErr
  155852. ){
  155853. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  155854. }
  155855. /*
  155856. ** Rtree virtual table module xConnect method.
  155857. */
  155858. static int rtreeConnect(
  155859. sqlite3 *db,
  155860. void *pAux,
  155861. int argc, const char *const*argv,
  155862. sqlite3_vtab **ppVtab,
  155863. char **pzErr
  155864. ){
  155865. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  155866. }
  155867. /*
  155868. ** Increment the r-tree reference count.
  155869. */
  155870. static void rtreeReference(Rtree *pRtree){
  155871. pRtree->nBusy++;
  155872. }
  155873. /*
  155874. ** Decrement the r-tree reference count. When the reference count reaches
  155875. ** zero the structure is deleted.
  155876. */
  155877. static void rtreeRelease(Rtree *pRtree){
  155878. pRtree->nBusy--;
  155879. if( pRtree->nBusy==0 ){
  155880. pRtree->inWrTrans = 0;
  155881. pRtree->nCursor = 0;
  155882. nodeBlobReset(pRtree);
  155883. sqlite3_finalize(pRtree->pWriteNode);
  155884. sqlite3_finalize(pRtree->pDeleteNode);
  155885. sqlite3_finalize(pRtree->pReadRowid);
  155886. sqlite3_finalize(pRtree->pWriteRowid);
  155887. sqlite3_finalize(pRtree->pDeleteRowid);
  155888. sqlite3_finalize(pRtree->pReadParent);
  155889. sqlite3_finalize(pRtree->pWriteParent);
  155890. sqlite3_finalize(pRtree->pDeleteParent);
  155891. sqlite3_free(pRtree);
  155892. }
  155893. }
  155894. /*
  155895. ** Rtree virtual table module xDisconnect method.
  155896. */
  155897. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  155898. rtreeRelease((Rtree *)pVtab);
  155899. return SQLITE_OK;
  155900. }
  155901. /*
  155902. ** Rtree virtual table module xDestroy method.
  155903. */
  155904. static int rtreeDestroy(sqlite3_vtab *pVtab){
  155905. Rtree *pRtree = (Rtree *)pVtab;
  155906. int rc;
  155907. char *zCreate = sqlite3_mprintf(
  155908. "DROP TABLE '%q'.'%q_node';"
  155909. "DROP TABLE '%q'.'%q_rowid';"
  155910. "DROP TABLE '%q'.'%q_parent';",
  155911. pRtree->zDb, pRtree->zName,
  155912. pRtree->zDb, pRtree->zName,
  155913. pRtree->zDb, pRtree->zName
  155914. );
  155915. if( !zCreate ){
  155916. rc = SQLITE_NOMEM;
  155917. }else{
  155918. nodeBlobReset(pRtree);
  155919. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  155920. sqlite3_free(zCreate);
  155921. }
  155922. if( rc==SQLITE_OK ){
  155923. rtreeRelease(pRtree);
  155924. }
  155925. return rc;
  155926. }
  155927. /*
  155928. ** Rtree virtual table module xOpen method.
  155929. */
  155930. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  155931. int rc = SQLITE_NOMEM;
  155932. Rtree *pRtree = (Rtree *)pVTab;
  155933. RtreeCursor *pCsr;
  155934. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  155935. if( pCsr ){
  155936. memset(pCsr, 0, sizeof(RtreeCursor));
  155937. pCsr->base.pVtab = pVTab;
  155938. rc = SQLITE_OK;
  155939. pRtree->nCursor++;
  155940. }
  155941. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  155942. return rc;
  155943. }
  155944. /*
  155945. ** Free the RtreeCursor.aConstraint[] array and its contents.
  155946. */
  155947. static void freeCursorConstraints(RtreeCursor *pCsr){
  155948. if( pCsr->aConstraint ){
  155949. int i; /* Used to iterate through constraint array */
  155950. for(i=0; i<pCsr->nConstraint; i++){
  155951. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  155952. if( pInfo ){
  155953. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  155954. sqlite3_free(pInfo);
  155955. }
  155956. }
  155957. sqlite3_free(pCsr->aConstraint);
  155958. pCsr->aConstraint = 0;
  155959. }
  155960. }
  155961. /*
  155962. ** Rtree virtual table module xClose method.
  155963. */
  155964. static int rtreeClose(sqlite3_vtab_cursor *cur){
  155965. Rtree *pRtree = (Rtree *)(cur->pVtab);
  155966. int ii;
  155967. RtreeCursor *pCsr = (RtreeCursor *)cur;
  155968. assert( pRtree->nCursor>0 );
  155969. freeCursorConstraints(pCsr);
  155970. sqlite3_free(pCsr->aPoint);
  155971. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  155972. sqlite3_free(pCsr);
  155973. pRtree->nCursor--;
  155974. nodeBlobReset(pRtree);
  155975. return SQLITE_OK;
  155976. }
  155977. /*
  155978. ** Rtree virtual table module xEof method.
  155979. **
  155980. ** Return non-zero if the cursor does not currently point to a valid
  155981. ** record (i.e if the scan has finished), or zero otherwise.
  155982. */
  155983. static int rtreeEof(sqlite3_vtab_cursor *cur){
  155984. RtreeCursor *pCsr = (RtreeCursor *)cur;
  155985. return pCsr->atEOF;
  155986. }
  155987. /*
  155988. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  155989. ** The on-disk format is big-endian and needs to be converted for little-
  155990. ** endian platforms. The on-disk record stores integer coordinates if
  155991. ** eInt is true and it stores 32-bit floating point records if eInt is
  155992. ** false. a[] is the four bytes of the on-disk record to be decoded.
  155993. ** Store the results in "r".
  155994. **
  155995. ** There are five versions of this macro. The last one is generic. The
  155996. ** other four are various architectures-specific optimizations.
  155997. */
  155998. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  155999. #define RTREE_DECODE_COORD(eInt, a, r) { \
  156000. RtreeCoord c; /* Coordinate decoded */ \
  156001. c.u = _byteswap_ulong(*(u32*)a); \
  156002. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  156003. }
  156004. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  156005. #define RTREE_DECODE_COORD(eInt, a, r) { \
  156006. RtreeCoord c; /* Coordinate decoded */ \
  156007. c.u = __builtin_bswap32(*(u32*)a); \
  156008. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  156009. }
  156010. #elif SQLITE_BYTEORDER==1234
  156011. #define RTREE_DECODE_COORD(eInt, a, r) { \
  156012. RtreeCoord c; /* Coordinate decoded */ \
  156013. memcpy(&c.u,a,4); \
  156014. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  156015. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  156016. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  156017. }
  156018. #elif SQLITE_BYTEORDER==4321
  156019. #define RTREE_DECODE_COORD(eInt, a, r) { \
  156020. RtreeCoord c; /* Coordinate decoded */ \
  156021. memcpy(&c.u,a,4); \
  156022. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  156023. }
  156024. #else
  156025. #define RTREE_DECODE_COORD(eInt, a, r) { \
  156026. RtreeCoord c; /* Coordinate decoded */ \
  156027. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  156028. +((u32)a[2]<<8) + a[3]; \
  156029. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  156030. }
  156031. #endif
  156032. /*
  156033. ** Check the RTree node or entry given by pCellData and p against the MATCH
  156034. ** constraint pConstraint.
  156035. */
  156036. static int rtreeCallbackConstraint(
  156037. RtreeConstraint *pConstraint, /* The constraint to test */
  156038. int eInt, /* True if RTree holding integer coordinates */
  156039. u8 *pCellData, /* Raw cell content */
  156040. RtreeSearchPoint *pSearch, /* Container of this cell */
  156041. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  156042. int *peWithin /* OUT: visibility of the cell */
  156043. ){
  156044. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  156045. int nCoord = pInfo->nCoord; /* No. of coordinates */
  156046. int rc; /* Callback return code */
  156047. RtreeCoord c; /* Translator union */
  156048. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  156049. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  156050. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  156051. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  156052. pInfo->iRowid = readInt64(pCellData);
  156053. }
  156054. pCellData += 8;
  156055. #ifndef SQLITE_RTREE_INT_ONLY
  156056. if( eInt==0 ){
  156057. switch( nCoord ){
  156058. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  156059. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  156060. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  156061. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  156062. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  156063. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  156064. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  156065. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  156066. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  156067. readCoord(pCellData, &c); aCoord[0] = c.f;
  156068. }
  156069. }else
  156070. #endif
  156071. {
  156072. switch( nCoord ){
  156073. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  156074. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  156075. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  156076. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  156077. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  156078. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  156079. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  156080. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  156081. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  156082. readCoord(pCellData, &c); aCoord[0] = c.i;
  156083. }
  156084. }
  156085. if( pConstraint->op==RTREE_MATCH ){
  156086. int eWithin = 0;
  156087. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  156088. nCoord, aCoord, &eWithin);
  156089. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  156090. *prScore = RTREE_ZERO;
  156091. }else{
  156092. pInfo->aCoord = aCoord;
  156093. pInfo->iLevel = pSearch->iLevel - 1;
  156094. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  156095. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  156096. rc = pConstraint->u.xQueryFunc(pInfo);
  156097. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  156098. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  156099. *prScore = pInfo->rScore;
  156100. }
  156101. }
  156102. return rc;
  156103. }
  156104. /*
  156105. ** Check the internal RTree node given by pCellData against constraint p.
  156106. ** If this constraint cannot be satisfied by any child within the node,
  156107. ** set *peWithin to NOT_WITHIN.
  156108. */
  156109. static void rtreeNonleafConstraint(
  156110. RtreeConstraint *p, /* The constraint to test */
  156111. int eInt, /* True if RTree holds integer coordinates */
  156112. u8 *pCellData, /* Raw cell content as appears on disk */
  156113. int *peWithin /* Adjust downward, as appropriate */
  156114. ){
  156115. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  156116. /* p->iCoord might point to either a lower or upper bound coordinate
  156117. ** in a coordinate pair. But make pCellData point to the lower bound.
  156118. */
  156119. pCellData += 8 + 4*(p->iCoord&0xfe);
  156120. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  156121. || p->op==RTREE_GT || p->op==RTREE_EQ );
  156122. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  156123. switch( p->op ){
  156124. case RTREE_LE:
  156125. case RTREE_LT:
  156126. case RTREE_EQ:
  156127. RTREE_DECODE_COORD(eInt, pCellData, val);
  156128. /* val now holds the lower bound of the coordinate pair */
  156129. if( p->u.rValue>=val ) return;
  156130. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  156131. /* Fall through for the RTREE_EQ case */
  156132. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  156133. pCellData += 4;
  156134. RTREE_DECODE_COORD(eInt, pCellData, val);
  156135. /* val now holds the upper bound of the coordinate pair */
  156136. if( p->u.rValue<=val ) return;
  156137. }
  156138. *peWithin = NOT_WITHIN;
  156139. }
  156140. /*
  156141. ** Check the leaf RTree cell given by pCellData against constraint p.
  156142. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  156143. ** If the constraint is satisfied, leave *peWithin unchanged.
  156144. **
  156145. ** The constraint is of the form: xN op $val
  156146. **
  156147. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  156148. ** pCellData. $val is given by p->u.rValue.
  156149. */
  156150. static void rtreeLeafConstraint(
  156151. RtreeConstraint *p, /* The constraint to test */
  156152. int eInt, /* True if RTree holds integer coordinates */
  156153. u8 *pCellData, /* Raw cell content as appears on disk */
  156154. int *peWithin /* Adjust downward, as appropriate */
  156155. ){
  156156. RtreeDValue xN; /* Coordinate value converted to a double */
  156157. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  156158. || p->op==RTREE_GT || p->op==RTREE_EQ );
  156159. pCellData += 8 + p->iCoord*4;
  156160. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  156161. RTREE_DECODE_COORD(eInt, pCellData, xN);
  156162. switch( p->op ){
  156163. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  156164. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  156165. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  156166. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  156167. default: if( xN == p->u.rValue ) return; break;
  156168. }
  156169. *peWithin = NOT_WITHIN;
  156170. }
  156171. /*
  156172. ** One of the cells in node pNode is guaranteed to have a 64-bit
  156173. ** integer value equal to iRowid. Return the index of this cell.
  156174. */
  156175. static int nodeRowidIndex(
  156176. Rtree *pRtree,
  156177. RtreeNode *pNode,
  156178. i64 iRowid,
  156179. int *piIndex
  156180. ){
  156181. int ii;
  156182. int nCell = NCELL(pNode);
  156183. assert( nCell<200 );
  156184. for(ii=0; ii<nCell; ii++){
  156185. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  156186. *piIndex = ii;
  156187. return SQLITE_OK;
  156188. }
  156189. }
  156190. return SQLITE_CORRUPT_VTAB;
  156191. }
  156192. /*
  156193. ** Return the index of the cell containing a pointer to node pNode
  156194. ** in its parent. If pNode is the root node, return -1.
  156195. */
  156196. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  156197. RtreeNode *pParent = pNode->pParent;
  156198. if( pParent ){
  156199. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  156200. }
  156201. *piIndex = -1;
  156202. return SQLITE_OK;
  156203. }
  156204. /*
  156205. ** Compare two search points. Return negative, zero, or positive if the first
  156206. ** is less than, equal to, or greater than the second.
  156207. **
  156208. ** The rScore is the primary key. Smaller rScore values come first.
  156209. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  156210. ** iLevel values coming first. In this way, if rScore is the same for all
  156211. ** SearchPoints, then iLevel becomes the deciding factor and the result
  156212. ** is a depth-first search, which is the desired default behavior.
  156213. */
  156214. static int rtreeSearchPointCompare(
  156215. const RtreeSearchPoint *pA,
  156216. const RtreeSearchPoint *pB
  156217. ){
  156218. if( pA->rScore<pB->rScore ) return -1;
  156219. if( pA->rScore>pB->rScore ) return +1;
  156220. if( pA->iLevel<pB->iLevel ) return -1;
  156221. if( pA->iLevel>pB->iLevel ) return +1;
  156222. return 0;
  156223. }
  156224. /*
  156225. ** Interchange two search points in a cursor.
  156226. */
  156227. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  156228. RtreeSearchPoint t = p->aPoint[i];
  156229. assert( i<j );
  156230. p->aPoint[i] = p->aPoint[j];
  156231. p->aPoint[j] = t;
  156232. i++; j++;
  156233. if( i<RTREE_CACHE_SZ ){
  156234. if( j>=RTREE_CACHE_SZ ){
  156235. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  156236. p->aNode[i] = 0;
  156237. }else{
  156238. RtreeNode *pTemp = p->aNode[i];
  156239. p->aNode[i] = p->aNode[j];
  156240. p->aNode[j] = pTemp;
  156241. }
  156242. }
  156243. }
  156244. /*
  156245. ** Return the search point with the lowest current score.
  156246. */
  156247. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  156248. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  156249. }
  156250. /*
  156251. ** Get the RtreeNode for the search point with the lowest score.
  156252. */
  156253. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  156254. sqlite3_int64 id;
  156255. int ii = 1 - pCur->bPoint;
  156256. assert( ii==0 || ii==1 );
  156257. assert( pCur->bPoint || pCur->nPoint );
  156258. if( pCur->aNode[ii]==0 ){
  156259. assert( pRC!=0 );
  156260. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  156261. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  156262. }
  156263. return pCur->aNode[ii];
  156264. }
  156265. /*
  156266. ** Push a new element onto the priority queue
  156267. */
  156268. static RtreeSearchPoint *rtreeEnqueue(
  156269. RtreeCursor *pCur, /* The cursor */
  156270. RtreeDValue rScore, /* Score for the new search point */
  156271. u8 iLevel /* Level for the new search point */
  156272. ){
  156273. int i, j;
  156274. RtreeSearchPoint *pNew;
  156275. if( pCur->nPoint>=pCur->nPointAlloc ){
  156276. int nNew = pCur->nPointAlloc*2 + 8;
  156277. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  156278. if( pNew==0 ) return 0;
  156279. pCur->aPoint = pNew;
  156280. pCur->nPointAlloc = nNew;
  156281. }
  156282. i = pCur->nPoint++;
  156283. pNew = pCur->aPoint + i;
  156284. pNew->rScore = rScore;
  156285. pNew->iLevel = iLevel;
  156286. assert( iLevel<=RTREE_MAX_DEPTH );
  156287. while( i>0 ){
  156288. RtreeSearchPoint *pParent;
  156289. j = (i-1)/2;
  156290. pParent = pCur->aPoint + j;
  156291. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  156292. rtreeSearchPointSwap(pCur, j, i);
  156293. i = j;
  156294. pNew = pParent;
  156295. }
  156296. return pNew;
  156297. }
  156298. /*
  156299. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  156300. ** NULL if malloc fails.
  156301. */
  156302. static RtreeSearchPoint *rtreeSearchPointNew(
  156303. RtreeCursor *pCur, /* The cursor */
  156304. RtreeDValue rScore, /* Score for the new search point */
  156305. u8 iLevel /* Level for the new search point */
  156306. ){
  156307. RtreeSearchPoint *pNew, *pFirst;
  156308. pFirst = rtreeSearchPointFirst(pCur);
  156309. pCur->anQueue[iLevel]++;
  156310. if( pFirst==0
  156311. || pFirst->rScore>rScore
  156312. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  156313. ){
  156314. if( pCur->bPoint ){
  156315. int ii;
  156316. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  156317. if( pNew==0 ) return 0;
  156318. ii = (int)(pNew - pCur->aPoint) + 1;
  156319. if( ii<RTREE_CACHE_SZ ){
  156320. assert( pCur->aNode[ii]==0 );
  156321. pCur->aNode[ii] = pCur->aNode[0];
  156322. }else{
  156323. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  156324. }
  156325. pCur->aNode[0] = 0;
  156326. *pNew = pCur->sPoint;
  156327. }
  156328. pCur->sPoint.rScore = rScore;
  156329. pCur->sPoint.iLevel = iLevel;
  156330. pCur->bPoint = 1;
  156331. return &pCur->sPoint;
  156332. }else{
  156333. return rtreeEnqueue(pCur, rScore, iLevel);
  156334. }
  156335. }
  156336. #if 0
  156337. /* Tracing routines for the RtreeSearchPoint queue */
  156338. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  156339. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  156340. printf(" %d.%05lld.%02d %g %d",
  156341. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  156342. );
  156343. idx++;
  156344. if( idx<RTREE_CACHE_SZ ){
  156345. printf(" %p\n", pCur->aNode[idx]);
  156346. }else{
  156347. printf("\n");
  156348. }
  156349. }
  156350. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  156351. int ii;
  156352. printf("=== %9s ", zPrefix);
  156353. if( pCur->bPoint ){
  156354. tracePoint(&pCur->sPoint, -1, pCur);
  156355. }
  156356. for(ii=0; ii<pCur->nPoint; ii++){
  156357. if( ii>0 || pCur->bPoint ) printf(" ");
  156358. tracePoint(&pCur->aPoint[ii], ii, pCur);
  156359. }
  156360. }
  156361. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  156362. #else
  156363. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  156364. #endif
  156365. /* Remove the search point with the lowest current score.
  156366. */
  156367. static void rtreeSearchPointPop(RtreeCursor *p){
  156368. int i, j, k, n;
  156369. i = 1 - p->bPoint;
  156370. assert( i==0 || i==1 );
  156371. if( p->aNode[i] ){
  156372. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  156373. p->aNode[i] = 0;
  156374. }
  156375. if( p->bPoint ){
  156376. p->anQueue[p->sPoint.iLevel]--;
  156377. p->bPoint = 0;
  156378. }else if( p->nPoint ){
  156379. p->anQueue[p->aPoint[0].iLevel]--;
  156380. n = --p->nPoint;
  156381. p->aPoint[0] = p->aPoint[n];
  156382. if( n<RTREE_CACHE_SZ-1 ){
  156383. p->aNode[1] = p->aNode[n+1];
  156384. p->aNode[n+1] = 0;
  156385. }
  156386. i = 0;
  156387. while( (j = i*2+1)<n ){
  156388. k = j+1;
  156389. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  156390. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  156391. rtreeSearchPointSwap(p, i, k);
  156392. i = k;
  156393. }else{
  156394. break;
  156395. }
  156396. }else{
  156397. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  156398. rtreeSearchPointSwap(p, i, j);
  156399. i = j;
  156400. }else{
  156401. break;
  156402. }
  156403. }
  156404. }
  156405. }
  156406. }
  156407. /*
  156408. ** Continue the search on cursor pCur until the front of the queue
  156409. ** contains an entry suitable for returning as a result-set row,
  156410. ** or until the RtreeSearchPoint queue is empty, indicating that the
  156411. ** query has completed.
  156412. */
  156413. static int rtreeStepToLeaf(RtreeCursor *pCur){
  156414. RtreeSearchPoint *p;
  156415. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  156416. RtreeNode *pNode;
  156417. int eWithin;
  156418. int rc = SQLITE_OK;
  156419. int nCell;
  156420. int nConstraint = pCur->nConstraint;
  156421. int ii;
  156422. int eInt;
  156423. RtreeSearchPoint x;
  156424. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  156425. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  156426. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  156427. if( rc ) return rc;
  156428. nCell = NCELL(pNode);
  156429. assert( nCell<200 );
  156430. while( p->iCell<nCell ){
  156431. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  156432. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  156433. eWithin = FULLY_WITHIN;
  156434. for(ii=0; ii<nConstraint; ii++){
  156435. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  156436. if( pConstraint->op>=RTREE_MATCH ){
  156437. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  156438. &rScore, &eWithin);
  156439. if( rc ) return rc;
  156440. }else if( p->iLevel==1 ){
  156441. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  156442. }else{
  156443. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  156444. }
  156445. if( eWithin==NOT_WITHIN ) break;
  156446. }
  156447. p->iCell++;
  156448. if( eWithin==NOT_WITHIN ) continue;
  156449. x.iLevel = p->iLevel - 1;
  156450. if( x.iLevel ){
  156451. x.id = readInt64(pCellData);
  156452. x.iCell = 0;
  156453. }else{
  156454. x.id = p->id;
  156455. x.iCell = p->iCell - 1;
  156456. }
  156457. if( p->iCell>=nCell ){
  156458. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  156459. rtreeSearchPointPop(pCur);
  156460. }
  156461. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  156462. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  156463. if( p==0 ) return SQLITE_NOMEM;
  156464. p->eWithin = (u8)eWithin;
  156465. p->id = x.id;
  156466. p->iCell = x.iCell;
  156467. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  156468. break;
  156469. }
  156470. if( p->iCell>=nCell ){
  156471. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  156472. rtreeSearchPointPop(pCur);
  156473. }
  156474. }
  156475. pCur->atEOF = p==0;
  156476. return SQLITE_OK;
  156477. }
  156478. /*
  156479. ** Rtree virtual table module xNext method.
  156480. */
  156481. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  156482. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  156483. int rc = SQLITE_OK;
  156484. /* Move to the next entry that matches the configured constraints. */
  156485. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  156486. rtreeSearchPointPop(pCsr);
  156487. rc = rtreeStepToLeaf(pCsr);
  156488. return rc;
  156489. }
  156490. /*
  156491. ** Rtree virtual table module xRowid method.
  156492. */
  156493. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  156494. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  156495. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  156496. int rc = SQLITE_OK;
  156497. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  156498. if( rc==SQLITE_OK && p ){
  156499. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  156500. }
  156501. return rc;
  156502. }
  156503. /*
  156504. ** Rtree virtual table module xColumn method.
  156505. */
  156506. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  156507. Rtree *pRtree = (Rtree *)cur->pVtab;
  156508. RtreeCursor *pCsr = (RtreeCursor *)cur;
  156509. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  156510. RtreeCoord c;
  156511. int rc = SQLITE_OK;
  156512. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  156513. if( rc ) return rc;
  156514. if( p==0 ) return SQLITE_OK;
  156515. if( i==0 ){
  156516. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  156517. }else{
  156518. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  156519. #ifndef SQLITE_RTREE_INT_ONLY
  156520. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  156521. sqlite3_result_double(ctx, c.f);
  156522. }else
  156523. #endif
  156524. {
  156525. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  156526. sqlite3_result_int(ctx, c.i);
  156527. }
  156528. }
  156529. return SQLITE_OK;
  156530. }
  156531. /*
  156532. ** Use nodeAcquire() to obtain the leaf node containing the record with
  156533. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  156534. ** return SQLITE_OK. If there is no such record in the table, set
  156535. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  156536. ** to zero and return an SQLite error code.
  156537. */
  156538. static int findLeafNode(
  156539. Rtree *pRtree, /* RTree to search */
  156540. i64 iRowid, /* The rowid searching for */
  156541. RtreeNode **ppLeaf, /* Write the node here */
  156542. sqlite3_int64 *piNode /* Write the node-id here */
  156543. ){
  156544. int rc;
  156545. *ppLeaf = 0;
  156546. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  156547. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  156548. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  156549. if( piNode ) *piNode = iNode;
  156550. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  156551. sqlite3_reset(pRtree->pReadRowid);
  156552. }else{
  156553. rc = sqlite3_reset(pRtree->pReadRowid);
  156554. }
  156555. return rc;
  156556. }
  156557. /*
  156558. ** This function is called to configure the RtreeConstraint object passed
  156559. ** as the second argument for a MATCH constraint. The value passed as the
  156560. ** first argument to this function is the right-hand operand to the MATCH
  156561. ** operator.
  156562. */
  156563. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  156564. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  156565. sqlite3_rtree_query_info *pInfo; /* Callback information */
  156566. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  156567. if( pSrc==0 ) return SQLITE_ERROR;
  156568. pInfo = (sqlite3_rtree_query_info*)
  156569. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  156570. if( !pInfo ) return SQLITE_NOMEM;
  156571. memset(pInfo, 0, sizeof(*pInfo));
  156572. pBlob = (RtreeMatchArg*)&pInfo[1];
  156573. memcpy(pBlob, pSrc, pSrc->iSize);
  156574. pInfo->pContext = pBlob->cb.pContext;
  156575. pInfo->nParam = pBlob->nParam;
  156576. pInfo->aParam = pBlob->aParam;
  156577. pInfo->apSqlParam = pBlob->apSqlParam;
  156578. if( pBlob->cb.xGeom ){
  156579. pCons->u.xGeom = pBlob->cb.xGeom;
  156580. }else{
  156581. pCons->op = RTREE_QUERY;
  156582. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  156583. }
  156584. pCons->pInfo = pInfo;
  156585. return SQLITE_OK;
  156586. }
  156587. /*
  156588. ** Rtree virtual table module xFilter method.
  156589. */
  156590. static int rtreeFilter(
  156591. sqlite3_vtab_cursor *pVtabCursor,
  156592. int idxNum, const char *idxStr,
  156593. int argc, sqlite3_value **argv
  156594. ){
  156595. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  156596. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  156597. RtreeNode *pRoot = 0;
  156598. int ii;
  156599. int rc = SQLITE_OK;
  156600. int iCell = 0;
  156601. rtreeReference(pRtree);
  156602. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  156603. freeCursorConstraints(pCsr);
  156604. sqlite3_free(pCsr->aPoint);
  156605. memset(pCsr, 0, sizeof(RtreeCursor));
  156606. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  156607. pCsr->iStrategy = idxNum;
  156608. if( idxNum==1 ){
  156609. /* Special case - lookup by rowid. */
  156610. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  156611. RtreeSearchPoint *p; /* Search point for the leaf */
  156612. i64 iRowid = sqlite3_value_int64(argv[0]);
  156613. i64 iNode = 0;
  156614. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  156615. if( rc==SQLITE_OK && pLeaf!=0 ){
  156616. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  156617. assert( p!=0 ); /* Always returns pCsr->sPoint */
  156618. pCsr->aNode[0] = pLeaf;
  156619. p->id = iNode;
  156620. p->eWithin = PARTLY_WITHIN;
  156621. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  156622. p->iCell = (u8)iCell;
  156623. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  156624. }else{
  156625. pCsr->atEOF = 1;
  156626. }
  156627. }else{
  156628. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  156629. ** with the configured constraints.
  156630. */
  156631. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  156632. if( rc==SQLITE_OK && argc>0 ){
  156633. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  156634. pCsr->nConstraint = argc;
  156635. if( !pCsr->aConstraint ){
  156636. rc = SQLITE_NOMEM;
  156637. }else{
  156638. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  156639. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  156640. assert( (idxStr==0 && argc==0)
  156641. || (idxStr && (int)strlen(idxStr)==argc*2) );
  156642. for(ii=0; ii<argc; ii++){
  156643. RtreeConstraint *p = &pCsr->aConstraint[ii];
  156644. p->op = idxStr[ii*2];
  156645. p->iCoord = idxStr[ii*2+1]-'0';
  156646. if( p->op>=RTREE_MATCH ){
  156647. /* A MATCH operator. The right-hand-side must be a blob that
  156648. ** can be cast into an RtreeMatchArg object. One created using
  156649. ** an sqlite3_rtree_geometry_callback() SQL user function.
  156650. */
  156651. rc = deserializeGeometry(argv[ii], p);
  156652. if( rc!=SQLITE_OK ){
  156653. break;
  156654. }
  156655. p->pInfo->nCoord = pRtree->nDim2;
  156656. p->pInfo->anQueue = pCsr->anQueue;
  156657. p->pInfo->mxLevel = pRtree->iDepth + 1;
  156658. }else{
  156659. #ifdef SQLITE_RTREE_INT_ONLY
  156660. p->u.rValue = sqlite3_value_int64(argv[ii]);
  156661. #else
  156662. p->u.rValue = sqlite3_value_double(argv[ii]);
  156663. #endif
  156664. }
  156665. }
  156666. }
  156667. }
  156668. if( rc==SQLITE_OK ){
  156669. RtreeSearchPoint *pNew;
  156670. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  156671. if( pNew==0 ) return SQLITE_NOMEM;
  156672. pNew->id = 1;
  156673. pNew->iCell = 0;
  156674. pNew->eWithin = PARTLY_WITHIN;
  156675. assert( pCsr->bPoint==1 );
  156676. pCsr->aNode[0] = pRoot;
  156677. pRoot = 0;
  156678. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  156679. rc = rtreeStepToLeaf(pCsr);
  156680. }
  156681. }
  156682. nodeRelease(pRtree, pRoot);
  156683. rtreeRelease(pRtree);
  156684. return rc;
  156685. }
  156686. /*
  156687. ** Rtree virtual table module xBestIndex method. There are three
  156688. ** table scan strategies to choose from (in order from most to
  156689. ** least desirable):
  156690. **
  156691. ** idxNum idxStr Strategy
  156692. ** ------------------------------------------------
  156693. ** 1 Unused Direct lookup by rowid.
  156694. ** 2 See below R-tree query or full-table scan.
  156695. ** ------------------------------------------------
  156696. **
  156697. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  156698. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  156699. ** constraint used. The first two bytes of idxStr correspond to
  156700. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  156701. ** (argvIndex==1) etc.
  156702. **
  156703. ** The first of each pair of bytes in idxStr identifies the constraint
  156704. ** operator as follows:
  156705. **
  156706. ** Operator Byte Value
  156707. ** ----------------------
  156708. ** = 0x41 ('A')
  156709. ** <= 0x42 ('B')
  156710. ** < 0x43 ('C')
  156711. ** >= 0x44 ('D')
  156712. ** > 0x45 ('E')
  156713. ** MATCH 0x46 ('F')
  156714. ** ----------------------
  156715. **
  156716. ** The second of each pair of bytes identifies the coordinate column
  156717. ** to which the constraint applies. The leftmost coordinate column
  156718. ** is 'a', the second from the left 'b' etc.
  156719. */
  156720. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  156721. Rtree *pRtree = (Rtree*)tab;
  156722. int rc = SQLITE_OK;
  156723. int ii;
  156724. int bMatch = 0; /* True if there exists a MATCH constraint */
  156725. i64 nRow; /* Estimated rows returned by this scan */
  156726. int iIdx = 0;
  156727. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  156728. memset(zIdxStr, 0, sizeof(zIdxStr));
  156729. /* Check if there exists a MATCH constraint - even an unusable one. If there
  156730. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  156731. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  156732. ** possible. */
  156733. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  156734. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  156735. bMatch = 1;
  156736. }
  156737. }
  156738. assert( pIdxInfo->idxStr==0 );
  156739. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  156740. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  156741. if( bMatch==0 && p->usable
  156742. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  156743. ){
  156744. /* We have an equality constraint on the rowid. Use strategy 1. */
  156745. int jj;
  156746. for(jj=0; jj<ii; jj++){
  156747. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  156748. pIdxInfo->aConstraintUsage[jj].omit = 0;
  156749. }
  156750. pIdxInfo->idxNum = 1;
  156751. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  156752. pIdxInfo->aConstraintUsage[jj].omit = 1;
  156753. /* This strategy involves a two rowid lookups on an B-Tree structures
  156754. ** and then a linear search of an R-Tree node. This should be
  156755. ** considered almost as quick as a direct rowid lookup (for which
  156756. ** sqlite uses an internal cost of 0.0). It is expected to return
  156757. ** a single row.
  156758. */
  156759. pIdxInfo->estimatedCost = 30.0;
  156760. pIdxInfo->estimatedRows = 1;
  156761. return SQLITE_OK;
  156762. }
  156763. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  156764. u8 op;
  156765. switch( p->op ){
  156766. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  156767. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  156768. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  156769. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  156770. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  156771. default:
  156772. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  156773. op = RTREE_MATCH;
  156774. break;
  156775. }
  156776. zIdxStr[iIdx++] = op;
  156777. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  156778. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  156779. pIdxInfo->aConstraintUsage[ii].omit = 1;
  156780. }
  156781. }
  156782. pIdxInfo->idxNum = 2;
  156783. pIdxInfo->needToFreeIdxStr = 1;
  156784. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  156785. return SQLITE_NOMEM;
  156786. }
  156787. nRow = pRtree->nRowEst >> (iIdx/2);
  156788. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  156789. pIdxInfo->estimatedRows = nRow;
  156790. return rc;
  156791. }
  156792. /*
  156793. ** Return the N-dimensional volumn of the cell stored in *p.
  156794. */
  156795. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  156796. RtreeDValue area = (RtreeDValue)1;
  156797. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  156798. #ifndef SQLITE_RTREE_INT_ONLY
  156799. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  156800. switch( pRtree->nDim ){
  156801. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  156802. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  156803. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  156804. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  156805. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  156806. }
  156807. }else
  156808. #endif
  156809. {
  156810. switch( pRtree->nDim ){
  156811. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  156812. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  156813. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  156814. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  156815. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  156816. }
  156817. }
  156818. return area;
  156819. }
  156820. /*
  156821. ** Return the margin length of cell p. The margin length is the sum
  156822. ** of the objects size in each dimension.
  156823. */
  156824. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  156825. RtreeDValue margin = 0;
  156826. int ii = pRtree->nDim2 - 2;
  156827. do{
  156828. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  156829. ii -= 2;
  156830. }while( ii>=0 );
  156831. return margin;
  156832. }
  156833. /*
  156834. ** Store the union of cells p1 and p2 in p1.
  156835. */
  156836. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  156837. int ii = 0;
  156838. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  156839. do{
  156840. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  156841. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  156842. ii += 2;
  156843. }while( ii<pRtree->nDim2 );
  156844. }else{
  156845. do{
  156846. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  156847. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  156848. ii += 2;
  156849. }while( ii<pRtree->nDim2 );
  156850. }
  156851. }
  156852. /*
  156853. ** Return true if the area covered by p2 is a subset of the area covered
  156854. ** by p1. False otherwise.
  156855. */
  156856. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  156857. int ii;
  156858. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  156859. for(ii=0; ii<pRtree->nDim2; ii+=2){
  156860. RtreeCoord *a1 = &p1->aCoord[ii];
  156861. RtreeCoord *a2 = &p2->aCoord[ii];
  156862. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  156863. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  156864. ){
  156865. return 0;
  156866. }
  156867. }
  156868. return 1;
  156869. }
  156870. /*
  156871. ** Return the amount cell p would grow by if it were unioned with pCell.
  156872. */
  156873. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  156874. RtreeDValue area;
  156875. RtreeCell cell;
  156876. memcpy(&cell, p, sizeof(RtreeCell));
  156877. area = cellArea(pRtree, &cell);
  156878. cellUnion(pRtree, &cell, pCell);
  156879. return (cellArea(pRtree, &cell)-area);
  156880. }
  156881. static RtreeDValue cellOverlap(
  156882. Rtree *pRtree,
  156883. RtreeCell *p,
  156884. RtreeCell *aCell,
  156885. int nCell
  156886. ){
  156887. int ii;
  156888. RtreeDValue overlap = RTREE_ZERO;
  156889. for(ii=0; ii<nCell; ii++){
  156890. int jj;
  156891. RtreeDValue o = (RtreeDValue)1;
  156892. for(jj=0; jj<pRtree->nDim2; jj+=2){
  156893. RtreeDValue x1, x2;
  156894. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  156895. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  156896. if( x2<x1 ){
  156897. o = (RtreeDValue)0;
  156898. break;
  156899. }else{
  156900. o = o * (x2-x1);
  156901. }
  156902. }
  156903. overlap += o;
  156904. }
  156905. return overlap;
  156906. }
  156907. /*
  156908. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  156909. ** ChooseSubTree in r*tree terminology.
  156910. */
  156911. static int ChooseLeaf(
  156912. Rtree *pRtree, /* Rtree table */
  156913. RtreeCell *pCell, /* Cell to insert into rtree */
  156914. int iHeight, /* Height of sub-tree rooted at pCell */
  156915. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  156916. ){
  156917. int rc;
  156918. int ii;
  156919. RtreeNode *pNode;
  156920. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  156921. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  156922. int iCell;
  156923. sqlite3_int64 iBest = 0;
  156924. RtreeDValue fMinGrowth = RTREE_ZERO;
  156925. RtreeDValue fMinArea = RTREE_ZERO;
  156926. int nCell = NCELL(pNode);
  156927. RtreeCell cell;
  156928. RtreeNode *pChild;
  156929. RtreeCell *aCell = 0;
  156930. /* Select the child node which will be enlarged the least if pCell
  156931. ** is inserted into it. Resolve ties by choosing the entry with
  156932. ** the smallest area.
  156933. */
  156934. for(iCell=0; iCell<nCell; iCell++){
  156935. int bBest = 0;
  156936. RtreeDValue growth;
  156937. RtreeDValue area;
  156938. nodeGetCell(pRtree, pNode, iCell, &cell);
  156939. growth = cellGrowth(pRtree, &cell, pCell);
  156940. area = cellArea(pRtree, &cell);
  156941. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  156942. bBest = 1;
  156943. }
  156944. if( bBest ){
  156945. fMinGrowth = growth;
  156946. fMinArea = area;
  156947. iBest = cell.iRowid;
  156948. }
  156949. }
  156950. sqlite3_free(aCell);
  156951. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  156952. nodeRelease(pRtree, pNode);
  156953. pNode = pChild;
  156954. }
  156955. *ppLeaf = pNode;
  156956. return rc;
  156957. }
  156958. /*
  156959. ** A cell with the same content as pCell has just been inserted into
  156960. ** the node pNode. This function updates the bounding box cells in
  156961. ** all ancestor elements.
  156962. */
  156963. static int AdjustTree(
  156964. Rtree *pRtree, /* Rtree table */
  156965. RtreeNode *pNode, /* Adjust ancestry of this node. */
  156966. RtreeCell *pCell /* This cell was just inserted */
  156967. ){
  156968. RtreeNode *p = pNode;
  156969. while( p->pParent ){
  156970. RtreeNode *pParent = p->pParent;
  156971. RtreeCell cell;
  156972. int iCell;
  156973. if( nodeParentIndex(pRtree, p, &iCell) ){
  156974. return SQLITE_CORRUPT_VTAB;
  156975. }
  156976. nodeGetCell(pRtree, pParent, iCell, &cell);
  156977. if( !cellContains(pRtree, &cell, pCell) ){
  156978. cellUnion(pRtree, &cell, pCell);
  156979. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  156980. }
  156981. p = pParent;
  156982. }
  156983. return SQLITE_OK;
  156984. }
  156985. /*
  156986. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  156987. */
  156988. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  156989. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  156990. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  156991. sqlite3_step(pRtree->pWriteRowid);
  156992. return sqlite3_reset(pRtree->pWriteRowid);
  156993. }
  156994. /*
  156995. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  156996. */
  156997. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  156998. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  156999. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  157000. sqlite3_step(pRtree->pWriteParent);
  157001. return sqlite3_reset(pRtree->pWriteParent);
  157002. }
  157003. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  157004. /*
  157005. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  157006. ** nIdx. The aIdx array contains the set of integers from 0 to
  157007. ** (nIdx-1) in no particular order. This function sorts the values
  157008. ** in aIdx according to the indexed values in aDistance. For
  157009. ** example, assuming the inputs:
  157010. **
  157011. ** aIdx = { 0, 1, 2, 3 }
  157012. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  157013. **
  157014. ** this function sets the aIdx array to contain:
  157015. **
  157016. ** aIdx = { 0, 1, 2, 3 }
  157017. **
  157018. ** The aSpare array is used as temporary working space by the
  157019. ** sorting algorithm.
  157020. */
  157021. static void SortByDistance(
  157022. int *aIdx,
  157023. int nIdx,
  157024. RtreeDValue *aDistance,
  157025. int *aSpare
  157026. ){
  157027. if( nIdx>1 ){
  157028. int iLeft = 0;
  157029. int iRight = 0;
  157030. int nLeft = nIdx/2;
  157031. int nRight = nIdx-nLeft;
  157032. int *aLeft = aIdx;
  157033. int *aRight = &aIdx[nLeft];
  157034. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  157035. SortByDistance(aRight, nRight, aDistance, aSpare);
  157036. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  157037. aLeft = aSpare;
  157038. while( iLeft<nLeft || iRight<nRight ){
  157039. if( iLeft==nLeft ){
  157040. aIdx[iLeft+iRight] = aRight[iRight];
  157041. iRight++;
  157042. }else if( iRight==nRight ){
  157043. aIdx[iLeft+iRight] = aLeft[iLeft];
  157044. iLeft++;
  157045. }else{
  157046. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  157047. RtreeDValue fRight = aDistance[aRight[iRight]];
  157048. if( fLeft<fRight ){
  157049. aIdx[iLeft+iRight] = aLeft[iLeft];
  157050. iLeft++;
  157051. }else{
  157052. aIdx[iLeft+iRight] = aRight[iRight];
  157053. iRight++;
  157054. }
  157055. }
  157056. }
  157057. #if 0
  157058. /* Check that the sort worked */
  157059. {
  157060. int jj;
  157061. for(jj=1; jj<nIdx; jj++){
  157062. RtreeDValue left = aDistance[aIdx[jj-1]];
  157063. RtreeDValue right = aDistance[aIdx[jj]];
  157064. assert( left<=right );
  157065. }
  157066. }
  157067. #endif
  157068. }
  157069. }
  157070. /*
  157071. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  157072. ** nIdx. The aIdx array contains the set of integers from 0 to
  157073. ** (nIdx-1) in no particular order. This function sorts the values
  157074. ** in aIdx according to dimension iDim of the cells in aCell. The
  157075. ** minimum value of dimension iDim is considered first, the
  157076. ** maximum used to break ties.
  157077. **
  157078. ** The aSpare array is used as temporary working space by the
  157079. ** sorting algorithm.
  157080. */
  157081. static void SortByDimension(
  157082. Rtree *pRtree,
  157083. int *aIdx,
  157084. int nIdx,
  157085. int iDim,
  157086. RtreeCell *aCell,
  157087. int *aSpare
  157088. ){
  157089. if( nIdx>1 ){
  157090. int iLeft = 0;
  157091. int iRight = 0;
  157092. int nLeft = nIdx/2;
  157093. int nRight = nIdx-nLeft;
  157094. int *aLeft = aIdx;
  157095. int *aRight = &aIdx[nLeft];
  157096. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  157097. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  157098. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  157099. aLeft = aSpare;
  157100. while( iLeft<nLeft || iRight<nRight ){
  157101. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  157102. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  157103. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  157104. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  157105. if( (iLeft!=nLeft) && ((iRight==nRight)
  157106. || (xleft1<xright1)
  157107. || (xleft1==xright1 && xleft2<xright2)
  157108. )){
  157109. aIdx[iLeft+iRight] = aLeft[iLeft];
  157110. iLeft++;
  157111. }else{
  157112. aIdx[iLeft+iRight] = aRight[iRight];
  157113. iRight++;
  157114. }
  157115. }
  157116. #if 0
  157117. /* Check that the sort worked */
  157118. {
  157119. int jj;
  157120. for(jj=1; jj<nIdx; jj++){
  157121. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  157122. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  157123. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  157124. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  157125. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  157126. }
  157127. }
  157128. #endif
  157129. }
  157130. }
  157131. /*
  157132. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  157133. */
  157134. static int splitNodeStartree(
  157135. Rtree *pRtree,
  157136. RtreeCell *aCell,
  157137. int nCell,
  157138. RtreeNode *pLeft,
  157139. RtreeNode *pRight,
  157140. RtreeCell *pBboxLeft,
  157141. RtreeCell *pBboxRight
  157142. ){
  157143. int **aaSorted;
  157144. int *aSpare;
  157145. int ii;
  157146. int iBestDim = 0;
  157147. int iBestSplit = 0;
  157148. RtreeDValue fBestMargin = RTREE_ZERO;
  157149. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  157150. aaSorted = (int **)sqlite3_malloc(nByte);
  157151. if( !aaSorted ){
  157152. return SQLITE_NOMEM;
  157153. }
  157154. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  157155. memset(aaSorted, 0, nByte);
  157156. for(ii=0; ii<pRtree->nDim; ii++){
  157157. int jj;
  157158. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  157159. for(jj=0; jj<nCell; jj++){
  157160. aaSorted[ii][jj] = jj;
  157161. }
  157162. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  157163. }
  157164. for(ii=0; ii<pRtree->nDim; ii++){
  157165. RtreeDValue margin = RTREE_ZERO;
  157166. RtreeDValue fBestOverlap = RTREE_ZERO;
  157167. RtreeDValue fBestArea = RTREE_ZERO;
  157168. int iBestLeft = 0;
  157169. int nLeft;
  157170. for(
  157171. nLeft=RTREE_MINCELLS(pRtree);
  157172. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  157173. nLeft++
  157174. ){
  157175. RtreeCell left;
  157176. RtreeCell right;
  157177. int kk;
  157178. RtreeDValue overlap;
  157179. RtreeDValue area;
  157180. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  157181. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  157182. for(kk=1; kk<(nCell-1); kk++){
  157183. if( kk<nLeft ){
  157184. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  157185. }else{
  157186. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  157187. }
  157188. }
  157189. margin += cellMargin(pRtree, &left);
  157190. margin += cellMargin(pRtree, &right);
  157191. overlap = cellOverlap(pRtree, &left, &right, 1);
  157192. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  157193. if( (nLeft==RTREE_MINCELLS(pRtree))
  157194. || (overlap<fBestOverlap)
  157195. || (overlap==fBestOverlap && area<fBestArea)
  157196. ){
  157197. iBestLeft = nLeft;
  157198. fBestOverlap = overlap;
  157199. fBestArea = area;
  157200. }
  157201. }
  157202. if( ii==0 || margin<fBestMargin ){
  157203. iBestDim = ii;
  157204. fBestMargin = margin;
  157205. iBestSplit = iBestLeft;
  157206. }
  157207. }
  157208. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  157209. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  157210. for(ii=0; ii<nCell; ii++){
  157211. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  157212. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  157213. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  157214. nodeInsertCell(pRtree, pTarget, pCell);
  157215. cellUnion(pRtree, pBbox, pCell);
  157216. }
  157217. sqlite3_free(aaSorted);
  157218. return SQLITE_OK;
  157219. }
  157220. static int updateMapping(
  157221. Rtree *pRtree,
  157222. i64 iRowid,
  157223. RtreeNode *pNode,
  157224. int iHeight
  157225. ){
  157226. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  157227. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  157228. if( iHeight>0 ){
  157229. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  157230. if( pChild ){
  157231. nodeRelease(pRtree, pChild->pParent);
  157232. nodeReference(pNode);
  157233. pChild->pParent = pNode;
  157234. }
  157235. }
  157236. return xSetMapping(pRtree, iRowid, pNode->iNode);
  157237. }
  157238. static int SplitNode(
  157239. Rtree *pRtree,
  157240. RtreeNode *pNode,
  157241. RtreeCell *pCell,
  157242. int iHeight
  157243. ){
  157244. int i;
  157245. int newCellIsRight = 0;
  157246. int rc = SQLITE_OK;
  157247. int nCell = NCELL(pNode);
  157248. RtreeCell *aCell;
  157249. int *aiUsed;
  157250. RtreeNode *pLeft = 0;
  157251. RtreeNode *pRight = 0;
  157252. RtreeCell leftbbox;
  157253. RtreeCell rightbbox;
  157254. /* Allocate an array and populate it with a copy of pCell and
  157255. ** all cells from node pLeft. Then zero the original node.
  157256. */
  157257. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  157258. if( !aCell ){
  157259. rc = SQLITE_NOMEM;
  157260. goto splitnode_out;
  157261. }
  157262. aiUsed = (int *)&aCell[nCell+1];
  157263. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  157264. for(i=0; i<nCell; i++){
  157265. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  157266. }
  157267. nodeZero(pRtree, pNode);
  157268. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  157269. nCell++;
  157270. if( pNode->iNode==1 ){
  157271. pRight = nodeNew(pRtree, pNode);
  157272. pLeft = nodeNew(pRtree, pNode);
  157273. pRtree->iDepth++;
  157274. pNode->isDirty = 1;
  157275. writeInt16(pNode->zData, pRtree->iDepth);
  157276. }else{
  157277. pLeft = pNode;
  157278. pRight = nodeNew(pRtree, pLeft->pParent);
  157279. nodeReference(pLeft);
  157280. }
  157281. if( !pLeft || !pRight ){
  157282. rc = SQLITE_NOMEM;
  157283. goto splitnode_out;
  157284. }
  157285. memset(pLeft->zData, 0, pRtree->iNodeSize);
  157286. memset(pRight->zData, 0, pRtree->iNodeSize);
  157287. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  157288. &leftbbox, &rightbbox);
  157289. if( rc!=SQLITE_OK ){
  157290. goto splitnode_out;
  157291. }
  157292. /* Ensure both child nodes have node numbers assigned to them by calling
  157293. ** nodeWrite(). Node pRight always needs a node number, as it was created
  157294. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  157295. ** In this case avoid the all to nodeWrite().
  157296. */
  157297. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  157298. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  157299. ){
  157300. goto splitnode_out;
  157301. }
  157302. rightbbox.iRowid = pRight->iNode;
  157303. leftbbox.iRowid = pLeft->iNode;
  157304. if( pNode->iNode==1 ){
  157305. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  157306. if( rc!=SQLITE_OK ){
  157307. goto splitnode_out;
  157308. }
  157309. }else{
  157310. RtreeNode *pParent = pLeft->pParent;
  157311. int iCell;
  157312. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  157313. if( rc==SQLITE_OK ){
  157314. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  157315. rc = AdjustTree(pRtree, pParent, &leftbbox);
  157316. }
  157317. if( rc!=SQLITE_OK ){
  157318. goto splitnode_out;
  157319. }
  157320. }
  157321. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  157322. goto splitnode_out;
  157323. }
  157324. for(i=0; i<NCELL(pRight); i++){
  157325. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  157326. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  157327. if( iRowid==pCell->iRowid ){
  157328. newCellIsRight = 1;
  157329. }
  157330. if( rc!=SQLITE_OK ){
  157331. goto splitnode_out;
  157332. }
  157333. }
  157334. if( pNode->iNode==1 ){
  157335. for(i=0; i<NCELL(pLeft); i++){
  157336. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  157337. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  157338. if( rc!=SQLITE_OK ){
  157339. goto splitnode_out;
  157340. }
  157341. }
  157342. }else if( newCellIsRight==0 ){
  157343. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  157344. }
  157345. if( rc==SQLITE_OK ){
  157346. rc = nodeRelease(pRtree, pRight);
  157347. pRight = 0;
  157348. }
  157349. if( rc==SQLITE_OK ){
  157350. rc = nodeRelease(pRtree, pLeft);
  157351. pLeft = 0;
  157352. }
  157353. splitnode_out:
  157354. nodeRelease(pRtree, pRight);
  157355. nodeRelease(pRtree, pLeft);
  157356. sqlite3_free(aCell);
  157357. return rc;
  157358. }
  157359. /*
  157360. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  157361. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  157362. ** the pLeaf->pParent chain all the way up to the root node.
  157363. **
  157364. ** This operation is required when a row is deleted (or updated - an update
  157365. ** is implemented as a delete followed by an insert). SQLite provides the
  157366. ** rowid of the row to delete, which can be used to find the leaf on which
  157367. ** the entry resides (argument pLeaf). Once the leaf is located, this
  157368. ** function is called to determine its ancestry.
  157369. */
  157370. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  157371. int rc = SQLITE_OK;
  157372. RtreeNode *pChild = pLeaf;
  157373. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  157374. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  157375. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  157376. rc = sqlite3_step(pRtree->pReadParent);
  157377. if( rc==SQLITE_ROW ){
  157378. RtreeNode *pTest; /* Used to test for reference loops */
  157379. i64 iNode; /* Node number of parent node */
  157380. /* Before setting pChild->pParent, test that we are not creating a
  157381. ** loop of references (as we would if, say, pChild==pParent). We don't
  157382. ** want to do this as it leads to a memory leak when trying to delete
  157383. ** the referenced counted node structures.
  157384. */
  157385. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  157386. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  157387. if( !pTest ){
  157388. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  157389. }
  157390. }
  157391. rc = sqlite3_reset(pRtree->pReadParent);
  157392. if( rc==SQLITE_OK ) rc = rc2;
  157393. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  157394. pChild = pChild->pParent;
  157395. }
  157396. return rc;
  157397. }
  157398. static int deleteCell(Rtree *, RtreeNode *, int, int);
  157399. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  157400. int rc;
  157401. int rc2;
  157402. RtreeNode *pParent = 0;
  157403. int iCell;
  157404. assert( pNode->nRef==1 );
  157405. /* Remove the entry in the parent cell. */
  157406. rc = nodeParentIndex(pRtree, pNode, &iCell);
  157407. if( rc==SQLITE_OK ){
  157408. pParent = pNode->pParent;
  157409. pNode->pParent = 0;
  157410. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  157411. }
  157412. rc2 = nodeRelease(pRtree, pParent);
  157413. if( rc==SQLITE_OK ){
  157414. rc = rc2;
  157415. }
  157416. if( rc!=SQLITE_OK ){
  157417. return rc;
  157418. }
  157419. /* Remove the xxx_node entry. */
  157420. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  157421. sqlite3_step(pRtree->pDeleteNode);
  157422. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  157423. return rc;
  157424. }
  157425. /* Remove the xxx_parent entry. */
  157426. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  157427. sqlite3_step(pRtree->pDeleteParent);
  157428. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  157429. return rc;
  157430. }
  157431. /* Remove the node from the in-memory hash table and link it into
  157432. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  157433. */
  157434. nodeHashDelete(pRtree, pNode);
  157435. pNode->iNode = iHeight;
  157436. pNode->pNext = pRtree->pDeleted;
  157437. pNode->nRef++;
  157438. pRtree->pDeleted = pNode;
  157439. return SQLITE_OK;
  157440. }
  157441. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  157442. RtreeNode *pParent = pNode->pParent;
  157443. int rc = SQLITE_OK;
  157444. if( pParent ){
  157445. int ii;
  157446. int nCell = NCELL(pNode);
  157447. RtreeCell box; /* Bounding box for pNode */
  157448. nodeGetCell(pRtree, pNode, 0, &box);
  157449. for(ii=1; ii<nCell; ii++){
  157450. RtreeCell cell;
  157451. nodeGetCell(pRtree, pNode, ii, &cell);
  157452. cellUnion(pRtree, &box, &cell);
  157453. }
  157454. box.iRowid = pNode->iNode;
  157455. rc = nodeParentIndex(pRtree, pNode, &ii);
  157456. if( rc==SQLITE_OK ){
  157457. nodeOverwriteCell(pRtree, pParent, &box, ii);
  157458. rc = fixBoundingBox(pRtree, pParent);
  157459. }
  157460. }
  157461. return rc;
  157462. }
  157463. /*
  157464. ** Delete the cell at index iCell of node pNode. After removing the
  157465. ** cell, adjust the r-tree data structure if required.
  157466. */
  157467. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  157468. RtreeNode *pParent;
  157469. int rc;
  157470. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  157471. return rc;
  157472. }
  157473. /* Remove the cell from the node. This call just moves bytes around
  157474. ** the in-memory node image, so it cannot fail.
  157475. */
  157476. nodeDeleteCell(pRtree, pNode, iCell);
  157477. /* If the node is not the tree root and now has less than the minimum
  157478. ** number of cells, remove it from the tree. Otherwise, update the
  157479. ** cell in the parent node so that it tightly contains the updated
  157480. ** node.
  157481. */
  157482. pParent = pNode->pParent;
  157483. assert( pParent || pNode->iNode==1 );
  157484. if( pParent ){
  157485. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  157486. rc = removeNode(pRtree, pNode, iHeight);
  157487. }else{
  157488. rc = fixBoundingBox(pRtree, pNode);
  157489. }
  157490. }
  157491. return rc;
  157492. }
  157493. static int Reinsert(
  157494. Rtree *pRtree,
  157495. RtreeNode *pNode,
  157496. RtreeCell *pCell,
  157497. int iHeight
  157498. ){
  157499. int *aOrder;
  157500. int *aSpare;
  157501. RtreeCell *aCell;
  157502. RtreeDValue *aDistance;
  157503. int nCell;
  157504. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  157505. int iDim;
  157506. int ii;
  157507. int rc = SQLITE_OK;
  157508. int n;
  157509. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  157510. nCell = NCELL(pNode)+1;
  157511. n = (nCell+1)&(~1);
  157512. /* Allocate the buffers used by this operation. The allocation is
  157513. ** relinquished before this function returns.
  157514. */
  157515. aCell = (RtreeCell *)sqlite3_malloc(n * (
  157516. sizeof(RtreeCell) + /* aCell array */
  157517. sizeof(int) + /* aOrder array */
  157518. sizeof(int) + /* aSpare array */
  157519. sizeof(RtreeDValue) /* aDistance array */
  157520. ));
  157521. if( !aCell ){
  157522. return SQLITE_NOMEM;
  157523. }
  157524. aOrder = (int *)&aCell[n];
  157525. aSpare = (int *)&aOrder[n];
  157526. aDistance = (RtreeDValue *)&aSpare[n];
  157527. for(ii=0; ii<nCell; ii++){
  157528. if( ii==(nCell-1) ){
  157529. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  157530. }else{
  157531. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  157532. }
  157533. aOrder[ii] = ii;
  157534. for(iDim=0; iDim<pRtree->nDim; iDim++){
  157535. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  157536. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  157537. }
  157538. }
  157539. for(iDim=0; iDim<pRtree->nDim; iDim++){
  157540. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  157541. }
  157542. for(ii=0; ii<nCell; ii++){
  157543. aDistance[ii] = RTREE_ZERO;
  157544. for(iDim=0; iDim<pRtree->nDim; iDim++){
  157545. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  157546. DCOORD(aCell[ii].aCoord[iDim*2]));
  157547. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  157548. }
  157549. }
  157550. SortByDistance(aOrder, nCell, aDistance, aSpare);
  157551. nodeZero(pRtree, pNode);
  157552. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  157553. RtreeCell *p = &aCell[aOrder[ii]];
  157554. nodeInsertCell(pRtree, pNode, p);
  157555. if( p->iRowid==pCell->iRowid ){
  157556. if( iHeight==0 ){
  157557. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  157558. }else{
  157559. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  157560. }
  157561. }
  157562. }
  157563. if( rc==SQLITE_OK ){
  157564. rc = fixBoundingBox(pRtree, pNode);
  157565. }
  157566. for(; rc==SQLITE_OK && ii<nCell; ii++){
  157567. /* Find a node to store this cell in. pNode->iNode currently contains
  157568. ** the height of the sub-tree headed by the cell.
  157569. */
  157570. RtreeNode *pInsert;
  157571. RtreeCell *p = &aCell[aOrder[ii]];
  157572. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  157573. if( rc==SQLITE_OK ){
  157574. int rc2;
  157575. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  157576. rc2 = nodeRelease(pRtree, pInsert);
  157577. if( rc==SQLITE_OK ){
  157578. rc = rc2;
  157579. }
  157580. }
  157581. }
  157582. sqlite3_free(aCell);
  157583. return rc;
  157584. }
  157585. /*
  157586. ** Insert cell pCell into node pNode. Node pNode is the head of a
  157587. ** subtree iHeight high (leaf nodes have iHeight==0).
  157588. */
  157589. static int rtreeInsertCell(
  157590. Rtree *pRtree,
  157591. RtreeNode *pNode,
  157592. RtreeCell *pCell,
  157593. int iHeight
  157594. ){
  157595. int rc = SQLITE_OK;
  157596. if( iHeight>0 ){
  157597. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  157598. if( pChild ){
  157599. nodeRelease(pRtree, pChild->pParent);
  157600. nodeReference(pNode);
  157601. pChild->pParent = pNode;
  157602. }
  157603. }
  157604. if( nodeInsertCell(pRtree, pNode, pCell) ){
  157605. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  157606. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  157607. }else{
  157608. pRtree->iReinsertHeight = iHeight;
  157609. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  157610. }
  157611. }else{
  157612. rc = AdjustTree(pRtree, pNode, pCell);
  157613. if( rc==SQLITE_OK ){
  157614. if( iHeight==0 ){
  157615. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  157616. }else{
  157617. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  157618. }
  157619. }
  157620. }
  157621. return rc;
  157622. }
  157623. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  157624. int ii;
  157625. int rc = SQLITE_OK;
  157626. int nCell = NCELL(pNode);
  157627. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  157628. RtreeNode *pInsert;
  157629. RtreeCell cell;
  157630. nodeGetCell(pRtree, pNode, ii, &cell);
  157631. /* Find a node to store this cell in. pNode->iNode currently contains
  157632. ** the height of the sub-tree headed by the cell.
  157633. */
  157634. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  157635. if( rc==SQLITE_OK ){
  157636. int rc2;
  157637. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  157638. rc2 = nodeRelease(pRtree, pInsert);
  157639. if( rc==SQLITE_OK ){
  157640. rc = rc2;
  157641. }
  157642. }
  157643. }
  157644. return rc;
  157645. }
  157646. /*
  157647. ** Select a currently unused rowid for a new r-tree record.
  157648. */
  157649. static int newRowid(Rtree *pRtree, i64 *piRowid){
  157650. int rc;
  157651. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  157652. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  157653. sqlite3_step(pRtree->pWriteRowid);
  157654. rc = sqlite3_reset(pRtree->pWriteRowid);
  157655. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  157656. return rc;
  157657. }
  157658. /*
  157659. ** Remove the entry with rowid=iDelete from the r-tree structure.
  157660. */
  157661. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  157662. int rc; /* Return code */
  157663. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  157664. int iCell; /* Index of iDelete cell in pLeaf */
  157665. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  157666. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  157667. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  157668. /* Obtain a reference to the leaf node that contains the entry
  157669. ** about to be deleted.
  157670. */
  157671. if( rc==SQLITE_OK ){
  157672. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  157673. }
  157674. /* Delete the cell in question from the leaf node. */
  157675. if( rc==SQLITE_OK ){
  157676. int rc2;
  157677. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  157678. if( rc==SQLITE_OK ){
  157679. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  157680. }
  157681. rc2 = nodeRelease(pRtree, pLeaf);
  157682. if( rc==SQLITE_OK ){
  157683. rc = rc2;
  157684. }
  157685. }
  157686. /* Delete the corresponding entry in the <rtree>_rowid table. */
  157687. if( rc==SQLITE_OK ){
  157688. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  157689. sqlite3_step(pRtree->pDeleteRowid);
  157690. rc = sqlite3_reset(pRtree->pDeleteRowid);
  157691. }
  157692. /* Check if the root node now has exactly one child. If so, remove
  157693. ** it, schedule the contents of the child for reinsertion and
  157694. ** reduce the tree height by one.
  157695. **
  157696. ** This is equivalent to copying the contents of the child into
  157697. ** the root node (the operation that Gutman's paper says to perform
  157698. ** in this scenario).
  157699. */
  157700. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  157701. int rc2;
  157702. RtreeNode *pChild;
  157703. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  157704. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  157705. if( rc==SQLITE_OK ){
  157706. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  157707. }
  157708. rc2 = nodeRelease(pRtree, pChild);
  157709. if( rc==SQLITE_OK ) rc = rc2;
  157710. if( rc==SQLITE_OK ){
  157711. pRtree->iDepth--;
  157712. writeInt16(pRoot->zData, pRtree->iDepth);
  157713. pRoot->isDirty = 1;
  157714. }
  157715. }
  157716. /* Re-insert the contents of any underfull nodes removed from the tree. */
  157717. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  157718. if( rc==SQLITE_OK ){
  157719. rc = reinsertNodeContent(pRtree, pLeaf);
  157720. }
  157721. pRtree->pDeleted = pLeaf->pNext;
  157722. sqlite3_free(pLeaf);
  157723. }
  157724. /* Release the reference to the root node. */
  157725. if( rc==SQLITE_OK ){
  157726. rc = nodeRelease(pRtree, pRoot);
  157727. }else{
  157728. nodeRelease(pRtree, pRoot);
  157729. }
  157730. return rc;
  157731. }
  157732. /*
  157733. ** Rounding constants for float->double conversion.
  157734. */
  157735. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  157736. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  157737. #if !defined(SQLITE_RTREE_INT_ONLY)
  157738. /*
  157739. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  157740. ** while taking care to round toward negative or positive, respectively.
  157741. */
  157742. static RtreeValue rtreeValueDown(sqlite3_value *v){
  157743. double d = sqlite3_value_double(v);
  157744. float f = (float)d;
  157745. if( f>d ){
  157746. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  157747. }
  157748. return f;
  157749. }
  157750. static RtreeValue rtreeValueUp(sqlite3_value *v){
  157751. double d = sqlite3_value_double(v);
  157752. float f = (float)d;
  157753. if( f<d ){
  157754. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  157755. }
  157756. return f;
  157757. }
  157758. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  157759. /*
  157760. ** A constraint has failed while inserting a row into an rtree table.
  157761. ** Assuming no OOM error occurs, this function sets the error message
  157762. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  157763. ** SQLITE_CONSTRAINT.
  157764. **
  157765. ** Parameter iCol is the index of the leftmost column involved in the
  157766. ** constraint failure. If it is 0, then the constraint that failed is
  157767. ** the unique constraint on the id column. Otherwise, it is the rtree
  157768. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  157769. **
  157770. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  157771. */
  157772. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  157773. sqlite3_stmt *pStmt = 0;
  157774. char *zSql;
  157775. int rc;
  157776. assert( iCol==0 || iCol%2 );
  157777. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  157778. if( zSql ){
  157779. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  157780. }else{
  157781. rc = SQLITE_NOMEM;
  157782. }
  157783. sqlite3_free(zSql);
  157784. if( rc==SQLITE_OK ){
  157785. if( iCol==0 ){
  157786. const char *zCol = sqlite3_column_name(pStmt, 0);
  157787. pRtree->base.zErrMsg = sqlite3_mprintf(
  157788. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  157789. );
  157790. }else{
  157791. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  157792. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  157793. pRtree->base.zErrMsg = sqlite3_mprintf(
  157794. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  157795. );
  157796. }
  157797. }
  157798. sqlite3_finalize(pStmt);
  157799. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  157800. }
  157801. /*
  157802. ** The xUpdate method for rtree module virtual tables.
  157803. */
  157804. static int rtreeUpdate(
  157805. sqlite3_vtab *pVtab,
  157806. int nData,
  157807. sqlite3_value **azData,
  157808. sqlite_int64 *pRowid
  157809. ){
  157810. Rtree *pRtree = (Rtree *)pVtab;
  157811. int rc = SQLITE_OK;
  157812. RtreeCell cell; /* New cell to insert if nData>1 */
  157813. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  157814. rtreeReference(pRtree);
  157815. assert(nData>=1);
  157816. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  157817. /* Constraint handling. A write operation on an r-tree table may return
  157818. ** SQLITE_CONSTRAINT for two reasons:
  157819. **
  157820. ** 1. A duplicate rowid value, or
  157821. ** 2. The supplied data violates the "x2>=x1" constraint.
  157822. **
  157823. ** In the first case, if the conflict-handling mode is REPLACE, then
  157824. ** the conflicting row can be removed before proceeding. In the second
  157825. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  157826. ** conflict-handling mode specified by the user.
  157827. */
  157828. if( nData>1 ){
  157829. int ii;
  157830. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  157831. **
  157832. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  157833. ** with "column" that are interpreted as table constraints.
  157834. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  157835. ** This problem was discovered after years of use, so we silently ignore
  157836. ** these kinds of misdeclared tables to avoid breaking any legacy.
  157837. */
  157838. assert( nData<=(pRtree->nDim2 + 3) );
  157839. #ifndef SQLITE_RTREE_INT_ONLY
  157840. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  157841. for(ii=0; ii<nData-4; ii+=2){
  157842. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  157843. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  157844. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  157845. rc = rtreeConstraintError(pRtree, ii+1);
  157846. goto constraint;
  157847. }
  157848. }
  157849. }else
  157850. #endif
  157851. {
  157852. for(ii=0; ii<nData-4; ii+=2){
  157853. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  157854. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  157855. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  157856. rc = rtreeConstraintError(pRtree, ii+1);
  157857. goto constraint;
  157858. }
  157859. }
  157860. }
  157861. /* If a rowid value was supplied, check if it is already present in
  157862. ** the table. If so, the constraint has failed. */
  157863. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  157864. cell.iRowid = sqlite3_value_int64(azData[2]);
  157865. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  157866. || sqlite3_value_int64(azData[0])!=cell.iRowid
  157867. ){
  157868. int steprc;
  157869. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  157870. steprc = sqlite3_step(pRtree->pReadRowid);
  157871. rc = sqlite3_reset(pRtree->pReadRowid);
  157872. if( SQLITE_ROW==steprc ){
  157873. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  157874. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  157875. }else{
  157876. rc = rtreeConstraintError(pRtree, 0);
  157877. goto constraint;
  157878. }
  157879. }
  157880. }
  157881. bHaveRowid = 1;
  157882. }
  157883. }
  157884. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  157885. ** record to delete from the r-tree table. The following block does
  157886. ** just that.
  157887. */
  157888. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  157889. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  157890. }
  157891. /* If the azData[] array contains more than one element, elements
  157892. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  157893. ** the r-tree structure.
  157894. */
  157895. if( rc==SQLITE_OK && nData>1 ){
  157896. /* Insert the new record into the r-tree */
  157897. RtreeNode *pLeaf = 0;
  157898. /* Figure out the rowid of the new row. */
  157899. if( bHaveRowid==0 ){
  157900. rc = newRowid(pRtree, &cell.iRowid);
  157901. }
  157902. *pRowid = cell.iRowid;
  157903. if( rc==SQLITE_OK ){
  157904. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  157905. }
  157906. if( rc==SQLITE_OK ){
  157907. int rc2;
  157908. pRtree->iReinsertHeight = -1;
  157909. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  157910. rc2 = nodeRelease(pRtree, pLeaf);
  157911. if( rc==SQLITE_OK ){
  157912. rc = rc2;
  157913. }
  157914. }
  157915. }
  157916. constraint:
  157917. rtreeRelease(pRtree);
  157918. return rc;
  157919. }
  157920. /*
  157921. ** Called when a transaction starts.
  157922. */
  157923. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  157924. Rtree *pRtree = (Rtree *)pVtab;
  157925. assert( pRtree->inWrTrans==0 );
  157926. pRtree->inWrTrans++;
  157927. return SQLITE_OK;
  157928. }
  157929. /*
  157930. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  157931. ** The sqlite3_blob object should be released at this point.
  157932. */
  157933. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  157934. Rtree *pRtree = (Rtree *)pVtab;
  157935. pRtree->inWrTrans = 0;
  157936. nodeBlobReset(pRtree);
  157937. return SQLITE_OK;
  157938. }
  157939. /*
  157940. ** The xRename method for rtree module virtual tables.
  157941. */
  157942. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  157943. Rtree *pRtree = (Rtree *)pVtab;
  157944. int rc = SQLITE_NOMEM;
  157945. char *zSql = sqlite3_mprintf(
  157946. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  157947. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  157948. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  157949. , pRtree->zDb, pRtree->zName, zNewName
  157950. , pRtree->zDb, pRtree->zName, zNewName
  157951. , pRtree->zDb, pRtree->zName, zNewName
  157952. );
  157953. if( zSql ){
  157954. nodeBlobReset(pRtree);
  157955. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  157956. sqlite3_free(zSql);
  157957. }
  157958. return rc;
  157959. }
  157960. /*
  157961. ** The xSavepoint method.
  157962. **
  157963. ** This module does not need to do anything to support savepoints. However,
  157964. ** it uses this hook to close any open blob handle. This is done because a
  157965. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  157966. ** succeed if there are any open blob handles. i.e. if the blob handle were
  157967. ** not closed here, the following would fail:
  157968. **
  157969. ** BEGIN;
  157970. ** INSERT INTO rtree...
  157971. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  157972. ** COMMIT;
  157973. */
  157974. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  157975. Rtree *pRtree = (Rtree *)pVtab;
  157976. int iwt = pRtree->inWrTrans;
  157977. UNUSED_PARAMETER(iSavepoint);
  157978. pRtree->inWrTrans = 0;
  157979. nodeBlobReset(pRtree);
  157980. pRtree->inWrTrans = iwt;
  157981. return SQLITE_OK;
  157982. }
  157983. /*
  157984. ** This function populates the pRtree->nRowEst variable with an estimate
  157985. ** of the number of rows in the virtual table. If possible, this is based
  157986. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  157987. */
  157988. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  157989. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  157990. char *zSql;
  157991. sqlite3_stmt *p;
  157992. int rc;
  157993. i64 nRow = 0;
  157994. rc = sqlite3_table_column_metadata(
  157995. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  157996. );
  157997. if( rc!=SQLITE_OK ){
  157998. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  157999. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  158000. }
  158001. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  158002. if( zSql==0 ){
  158003. rc = SQLITE_NOMEM;
  158004. }else{
  158005. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  158006. if( rc==SQLITE_OK ){
  158007. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  158008. rc = sqlite3_finalize(p);
  158009. }else if( rc!=SQLITE_NOMEM ){
  158010. rc = SQLITE_OK;
  158011. }
  158012. if( rc==SQLITE_OK ){
  158013. if( nRow==0 ){
  158014. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  158015. }else{
  158016. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  158017. }
  158018. }
  158019. sqlite3_free(zSql);
  158020. }
  158021. return rc;
  158022. }
  158023. static sqlite3_module rtreeModule = {
  158024. 2, /* iVersion */
  158025. rtreeCreate, /* xCreate - create a table */
  158026. rtreeConnect, /* xConnect - connect to an existing table */
  158027. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  158028. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  158029. rtreeDestroy, /* xDestroy - Drop a table */
  158030. rtreeOpen, /* xOpen - open a cursor */
  158031. rtreeClose, /* xClose - close a cursor */
  158032. rtreeFilter, /* xFilter - configure scan constraints */
  158033. rtreeNext, /* xNext - advance a cursor */
  158034. rtreeEof, /* xEof */
  158035. rtreeColumn, /* xColumn - read data */
  158036. rtreeRowid, /* xRowid - read data */
  158037. rtreeUpdate, /* xUpdate - write data */
  158038. rtreeBeginTransaction, /* xBegin - begin transaction */
  158039. rtreeEndTransaction, /* xSync - sync transaction */
  158040. rtreeEndTransaction, /* xCommit - commit transaction */
  158041. rtreeEndTransaction, /* xRollback - rollback transaction */
  158042. 0, /* xFindFunction - function overloading */
  158043. rtreeRename, /* xRename - rename the table */
  158044. rtreeSavepoint, /* xSavepoint */
  158045. 0, /* xRelease */
  158046. 0, /* xRollbackTo */
  158047. };
  158048. static int rtreeSqlInit(
  158049. Rtree *pRtree,
  158050. sqlite3 *db,
  158051. const char *zDb,
  158052. const char *zPrefix,
  158053. int isCreate
  158054. ){
  158055. int rc = SQLITE_OK;
  158056. #define N_STATEMENT 8
  158057. static const char *azSql[N_STATEMENT] = {
  158058. /* Write the xxx_node table */
  158059. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  158060. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  158061. /* Read and write the xxx_rowid table */
  158062. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  158063. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  158064. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  158065. /* Read and write the xxx_parent table */
  158066. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  158067. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  158068. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  158069. };
  158070. sqlite3_stmt **appStmt[N_STATEMENT];
  158071. int i;
  158072. pRtree->db = db;
  158073. if( isCreate ){
  158074. char *zCreate = sqlite3_mprintf(
  158075. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  158076. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  158077. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  158078. " parentnode INTEGER);"
  158079. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  158080. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  158081. );
  158082. if( !zCreate ){
  158083. return SQLITE_NOMEM;
  158084. }
  158085. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  158086. sqlite3_free(zCreate);
  158087. if( rc!=SQLITE_OK ){
  158088. return rc;
  158089. }
  158090. }
  158091. appStmt[0] = &pRtree->pWriteNode;
  158092. appStmt[1] = &pRtree->pDeleteNode;
  158093. appStmt[2] = &pRtree->pReadRowid;
  158094. appStmt[3] = &pRtree->pWriteRowid;
  158095. appStmt[4] = &pRtree->pDeleteRowid;
  158096. appStmt[5] = &pRtree->pReadParent;
  158097. appStmt[6] = &pRtree->pWriteParent;
  158098. appStmt[7] = &pRtree->pDeleteParent;
  158099. rc = rtreeQueryStat1(db, pRtree);
  158100. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  158101. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  158102. if( zSql ){
  158103. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  158104. appStmt[i], 0);
  158105. }else{
  158106. rc = SQLITE_NOMEM;
  158107. }
  158108. sqlite3_free(zSql);
  158109. }
  158110. return rc;
  158111. }
  158112. /*
  158113. ** The second argument to this function contains the text of an SQL statement
  158114. ** that returns a single integer value. The statement is compiled and executed
  158115. ** using database connection db. If successful, the integer value returned
  158116. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  158117. ** code is returned and the value of *piVal after returning is not defined.
  158118. */
  158119. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  158120. int rc = SQLITE_NOMEM;
  158121. if( zSql ){
  158122. sqlite3_stmt *pStmt = 0;
  158123. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  158124. if( rc==SQLITE_OK ){
  158125. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  158126. *piVal = sqlite3_column_int(pStmt, 0);
  158127. }
  158128. rc = sqlite3_finalize(pStmt);
  158129. }
  158130. }
  158131. return rc;
  158132. }
  158133. /*
  158134. ** This function is called from within the xConnect() or xCreate() method to
  158135. ** determine the node-size used by the rtree table being created or connected
  158136. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  158137. ** Otherwise, an SQLite error code is returned.
  158138. **
  158139. ** If this function is being called as part of an xConnect(), then the rtree
  158140. ** table already exists. In this case the node-size is determined by inspecting
  158141. ** the root node of the tree.
  158142. **
  158143. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  158144. ** This ensures that each node is stored on a single database page. If the
  158145. ** database page-size is so large that more than RTREE_MAXCELLS entries
  158146. ** would fit in a single node, use a smaller node-size.
  158147. */
  158148. static int getNodeSize(
  158149. sqlite3 *db, /* Database handle */
  158150. Rtree *pRtree, /* Rtree handle */
  158151. int isCreate, /* True for xCreate, false for xConnect */
  158152. char **pzErr /* OUT: Error message, if any */
  158153. ){
  158154. int rc;
  158155. char *zSql;
  158156. if( isCreate ){
  158157. int iPageSize = 0;
  158158. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  158159. rc = getIntFromStmt(db, zSql, &iPageSize);
  158160. if( rc==SQLITE_OK ){
  158161. pRtree->iNodeSize = iPageSize-64;
  158162. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  158163. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  158164. }
  158165. }else{
  158166. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158167. }
  158168. }else{
  158169. zSql = sqlite3_mprintf(
  158170. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  158171. pRtree->zDb, pRtree->zName
  158172. );
  158173. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  158174. if( rc!=SQLITE_OK ){
  158175. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158176. }else if( pRtree->iNodeSize<(512-64) ){
  158177. rc = SQLITE_CORRUPT_VTAB;
  158178. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  158179. pRtree->zName);
  158180. }
  158181. }
  158182. sqlite3_free(zSql);
  158183. return rc;
  158184. }
  158185. /*
  158186. ** This function is the implementation of both the xConnect and xCreate
  158187. ** methods of the r-tree virtual table.
  158188. **
  158189. ** argv[0] -> module name
  158190. ** argv[1] -> database name
  158191. ** argv[2] -> table name
  158192. ** argv[...] -> column names...
  158193. */
  158194. static int rtreeInit(
  158195. sqlite3 *db, /* Database connection */
  158196. void *pAux, /* One of the RTREE_COORD_* constants */
  158197. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  158198. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  158199. char **pzErr, /* OUT: Error message, if any */
  158200. int isCreate /* True for xCreate, false for xConnect */
  158201. ){
  158202. int rc = SQLITE_OK;
  158203. Rtree *pRtree;
  158204. int nDb; /* Length of string argv[1] */
  158205. int nName; /* Length of string argv[2] */
  158206. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  158207. const char *aErrMsg[] = {
  158208. 0, /* 0 */
  158209. "Wrong number of columns for an rtree table", /* 1 */
  158210. "Too few columns for an rtree table", /* 2 */
  158211. "Too many columns for an rtree table" /* 3 */
  158212. };
  158213. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  158214. if( aErrMsg[iErr] ){
  158215. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  158216. return SQLITE_ERROR;
  158217. }
  158218. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  158219. /* Allocate the sqlite3_vtab structure */
  158220. nDb = (int)strlen(argv[1]);
  158221. nName = (int)strlen(argv[2]);
  158222. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  158223. if( !pRtree ){
  158224. return SQLITE_NOMEM;
  158225. }
  158226. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  158227. pRtree->nBusy = 1;
  158228. pRtree->base.pModule = &rtreeModule;
  158229. pRtree->zDb = (char *)&pRtree[1];
  158230. pRtree->zName = &pRtree->zDb[nDb+1];
  158231. pRtree->nDim = (u8)((argc-4)/2);
  158232. pRtree->nDim2 = pRtree->nDim*2;
  158233. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  158234. pRtree->eCoordType = (u8)eCoordType;
  158235. memcpy(pRtree->zDb, argv[1], nDb);
  158236. memcpy(pRtree->zName, argv[2], nName);
  158237. /* Figure out the node size to use. */
  158238. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  158239. /* Create/Connect to the underlying relational database schema. If
  158240. ** that is successful, call sqlite3_declare_vtab() to configure
  158241. ** the r-tree table schema.
  158242. */
  158243. if( rc==SQLITE_OK ){
  158244. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  158245. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158246. }else{
  158247. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  158248. char *zTmp;
  158249. int ii;
  158250. for(ii=4; zSql && ii<argc; ii++){
  158251. zTmp = zSql;
  158252. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  158253. sqlite3_free(zTmp);
  158254. }
  158255. if( zSql ){
  158256. zTmp = zSql;
  158257. zSql = sqlite3_mprintf("%s);", zTmp);
  158258. sqlite3_free(zTmp);
  158259. }
  158260. if( !zSql ){
  158261. rc = SQLITE_NOMEM;
  158262. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  158263. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158264. }
  158265. sqlite3_free(zSql);
  158266. }
  158267. }
  158268. if( rc==SQLITE_OK ){
  158269. *ppVtab = (sqlite3_vtab *)pRtree;
  158270. }else{
  158271. assert( *ppVtab==0 );
  158272. assert( pRtree->nBusy==1 );
  158273. rtreeRelease(pRtree);
  158274. }
  158275. return rc;
  158276. }
  158277. /*
  158278. ** Implementation of a scalar function that decodes r-tree nodes to
  158279. ** human readable strings. This can be used for debugging and analysis.
  158280. **
  158281. ** The scalar function takes two arguments: (1) the number of dimensions
  158282. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  158283. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  158284. ** deserialize all nodes, a statement like:
  158285. **
  158286. ** SELECT rtreenode(2, data) FROM rt_node;
  158287. **
  158288. ** The human readable string takes the form of a Tcl list with one
  158289. ** entry for each cell in the r-tree node. Each entry is itself a
  158290. ** list, containing the 8-byte rowid/pageno followed by the
  158291. ** <num-dimension>*2 coordinates.
  158292. */
  158293. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  158294. char *zText = 0;
  158295. RtreeNode node;
  158296. Rtree tree;
  158297. int ii;
  158298. UNUSED_PARAMETER(nArg);
  158299. memset(&node, 0, sizeof(RtreeNode));
  158300. memset(&tree, 0, sizeof(Rtree));
  158301. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  158302. tree.nDim2 = tree.nDim*2;
  158303. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  158304. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  158305. for(ii=0; ii<NCELL(&node); ii++){
  158306. char zCell[512];
  158307. int nCell = 0;
  158308. RtreeCell cell;
  158309. int jj;
  158310. nodeGetCell(&tree, &node, ii, &cell);
  158311. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  158312. nCell = (int)strlen(zCell);
  158313. for(jj=0; jj<tree.nDim2; jj++){
  158314. #ifndef SQLITE_RTREE_INT_ONLY
  158315. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  158316. (double)cell.aCoord[jj].f);
  158317. #else
  158318. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  158319. cell.aCoord[jj].i);
  158320. #endif
  158321. nCell = (int)strlen(zCell);
  158322. }
  158323. if( zText ){
  158324. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  158325. sqlite3_free(zText);
  158326. zText = zTextNew;
  158327. }else{
  158328. zText = sqlite3_mprintf("{%s}", zCell);
  158329. }
  158330. }
  158331. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  158332. }
  158333. /* This routine implements an SQL function that returns the "depth" parameter
  158334. ** from the front of a blob that is an r-tree node. For example:
  158335. **
  158336. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  158337. **
  158338. ** The depth value is 0 for all nodes other than the root node, and the root
  158339. ** node always has nodeno=1, so the example above is the primary use for this
  158340. ** routine. This routine is intended for testing and analysis only.
  158341. */
  158342. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  158343. UNUSED_PARAMETER(nArg);
  158344. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  158345. || sqlite3_value_bytes(apArg[0])<2
  158346. ){
  158347. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  158348. }else{
  158349. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  158350. sqlite3_result_int(ctx, readInt16(zBlob));
  158351. }
  158352. }
  158353. /*
  158354. ** Register the r-tree module with database handle db. This creates the
  158355. ** virtual table module "rtree" and the debugging/analysis scalar
  158356. ** function "rtreenode".
  158357. */
  158358. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  158359. const int utf8 = SQLITE_UTF8;
  158360. int rc;
  158361. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  158362. if( rc==SQLITE_OK ){
  158363. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  158364. }
  158365. if( rc==SQLITE_OK ){
  158366. #ifdef SQLITE_RTREE_INT_ONLY
  158367. void *c = (void *)RTREE_COORD_INT32;
  158368. #else
  158369. void *c = (void *)RTREE_COORD_REAL32;
  158370. #endif
  158371. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  158372. }
  158373. if( rc==SQLITE_OK ){
  158374. void *c = (void *)RTREE_COORD_INT32;
  158375. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  158376. }
  158377. return rc;
  158378. }
  158379. /*
  158380. ** This routine deletes the RtreeGeomCallback object that was attached
  158381. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  158382. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  158383. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  158384. ** the corresponding SQL function is deleted.
  158385. */
  158386. static void rtreeFreeCallback(void *p){
  158387. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  158388. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  158389. sqlite3_free(p);
  158390. }
  158391. /*
  158392. ** This routine frees the BLOB that is returned by geomCallback().
  158393. */
  158394. static void rtreeMatchArgFree(void *pArg){
  158395. int i;
  158396. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  158397. for(i=0; i<p->nParam; i++){
  158398. sqlite3_value_free(p->apSqlParam[i]);
  158399. }
  158400. sqlite3_free(p);
  158401. }
  158402. /*
  158403. ** Each call to sqlite3_rtree_geometry_callback() or
  158404. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  158405. ** scalar function that is implemented by this routine.
  158406. **
  158407. ** All this function does is construct an RtreeMatchArg object that
  158408. ** contains the geometry-checking callback routines and a list of
  158409. ** parameters to this function, then return that RtreeMatchArg object
  158410. ** as a BLOB.
  158411. **
  158412. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  158413. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  158414. ** out which elements of the R-Tree should be returned by the query.
  158415. */
  158416. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  158417. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  158418. RtreeMatchArg *pBlob;
  158419. int nBlob;
  158420. int memErr = 0;
  158421. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  158422. + nArg*sizeof(sqlite3_value*);
  158423. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  158424. if( !pBlob ){
  158425. sqlite3_result_error_nomem(ctx);
  158426. }else{
  158427. int i;
  158428. pBlob->iSize = nBlob;
  158429. pBlob->cb = pGeomCtx[0];
  158430. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  158431. pBlob->nParam = nArg;
  158432. for(i=0; i<nArg; i++){
  158433. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  158434. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  158435. #ifdef SQLITE_RTREE_INT_ONLY
  158436. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  158437. #else
  158438. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  158439. #endif
  158440. }
  158441. if( memErr ){
  158442. sqlite3_result_error_nomem(ctx);
  158443. rtreeMatchArgFree(pBlob);
  158444. }else{
  158445. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  158446. }
  158447. }
  158448. }
  158449. /*
  158450. ** Register a new geometry function for use with the r-tree MATCH operator.
  158451. */
  158452. SQLITE_API int sqlite3_rtree_geometry_callback(
  158453. sqlite3 *db, /* Register SQL function on this connection */
  158454. const char *zGeom, /* Name of the new SQL function */
  158455. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  158456. void *pContext /* Extra data associated with the callback */
  158457. ){
  158458. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  158459. /* Allocate and populate the context object. */
  158460. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  158461. if( !pGeomCtx ) return SQLITE_NOMEM;
  158462. pGeomCtx->xGeom = xGeom;
  158463. pGeomCtx->xQueryFunc = 0;
  158464. pGeomCtx->xDestructor = 0;
  158465. pGeomCtx->pContext = pContext;
  158466. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  158467. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  158468. );
  158469. }
  158470. /*
  158471. ** Register a new 2nd-generation geometry function for use with the
  158472. ** r-tree MATCH operator.
  158473. */
  158474. SQLITE_API int sqlite3_rtree_query_callback(
  158475. sqlite3 *db, /* Register SQL function on this connection */
  158476. const char *zQueryFunc, /* Name of new SQL function */
  158477. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  158478. void *pContext, /* Extra data passed into the callback */
  158479. void (*xDestructor)(void*) /* Destructor for the extra data */
  158480. ){
  158481. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  158482. /* Allocate and populate the context object. */
  158483. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  158484. if( !pGeomCtx ) return SQLITE_NOMEM;
  158485. pGeomCtx->xGeom = 0;
  158486. pGeomCtx->xQueryFunc = xQueryFunc;
  158487. pGeomCtx->xDestructor = xDestructor;
  158488. pGeomCtx->pContext = pContext;
  158489. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  158490. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  158491. );
  158492. }
  158493. #if !SQLITE_CORE
  158494. #ifdef _WIN32
  158495. __declspec(dllexport)
  158496. #endif
  158497. SQLITE_API int sqlite3_rtree_init(
  158498. sqlite3 *db,
  158499. char **pzErrMsg,
  158500. const sqlite3_api_routines *pApi
  158501. ){
  158502. SQLITE_EXTENSION_INIT2(pApi)
  158503. return sqlite3RtreeInit(db);
  158504. }
  158505. #endif
  158506. #endif
  158507. /************** End of rtree.c ***********************************************/
  158508. /************** Begin file icu.c *********************************************/
  158509. /*
  158510. ** 2007 May 6
  158511. **
  158512. ** The author disclaims copyright to this source code. In place of
  158513. ** a legal notice, here is a blessing:
  158514. **
  158515. ** May you do good and not evil.
  158516. ** May you find forgiveness for yourself and forgive others.
  158517. ** May you share freely, never taking more than you give.
  158518. **
  158519. *************************************************************************
  158520. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  158521. **
  158522. ** This file implements an integration between the ICU library
  158523. ** ("International Components for Unicode", an open-source library
  158524. ** for handling unicode data) and SQLite. The integration uses
  158525. ** ICU to provide the following to SQLite:
  158526. **
  158527. ** * An implementation of the SQL regexp() function (and hence REGEXP
  158528. ** operator) using the ICU uregex_XX() APIs.
  158529. **
  158530. ** * Implementations of the SQL scalar upper() and lower() functions
  158531. ** for case mapping.
  158532. **
  158533. ** * Integration of ICU and SQLite collation sequences.
  158534. **
  158535. ** * An implementation of the LIKE operator that uses ICU to
  158536. ** provide case-independent matching.
  158537. */
  158538. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  158539. /* Include ICU headers */
  158540. #include <unicode/utypes.h>
  158541. #include <unicode/uregex.h>
  158542. #include <unicode/ustring.h>
  158543. #include <unicode/ucol.h>
  158544. /* #include <assert.h> */
  158545. #ifndef SQLITE_CORE
  158546. /* #include "sqlite3ext.h" */
  158547. SQLITE_EXTENSION_INIT1
  158548. #else
  158549. /* #include "sqlite3.h" */
  158550. #endif
  158551. /*
  158552. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  158553. ** operator.
  158554. */
  158555. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  158556. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  158557. #endif
  158558. /*
  158559. ** Version of sqlite3_free() that is always a function, never a macro.
  158560. */
  158561. static void xFree(void *p){
  158562. sqlite3_free(p);
  158563. }
  158564. /*
  158565. ** This lookup table is used to help decode the first byte of
  158566. ** a multi-byte UTF8 character. It is copied here from SQLite source
  158567. ** code file utf8.c.
  158568. */
  158569. static const unsigned char icuUtf8Trans1[] = {
  158570. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  158571. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  158572. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  158573. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  158574. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  158575. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  158576. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  158577. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  158578. };
  158579. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  158580. c = *(zIn++); \
  158581. if( c>=0xc0 ){ \
  158582. c = icuUtf8Trans1[c-0xc0]; \
  158583. while( (*zIn & 0xc0)==0x80 ){ \
  158584. c = (c<<6) + (0x3f & *(zIn++)); \
  158585. } \
  158586. }
  158587. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  158588. assert( *zIn ); \
  158589. if( *(zIn++)>=0xc0 ){ \
  158590. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  158591. }
  158592. /*
  158593. ** Compare two UTF-8 strings for equality where the first string is
  158594. ** a "LIKE" expression. Return true (1) if they are the same and
  158595. ** false (0) if they are different.
  158596. */
  158597. static int icuLikeCompare(
  158598. const uint8_t *zPattern, /* LIKE pattern */
  158599. const uint8_t *zString, /* The UTF-8 string to compare against */
  158600. const UChar32 uEsc /* The escape character */
  158601. ){
  158602. static const uint32_t MATCH_ONE = (uint32_t)'_';
  158603. static const uint32_t MATCH_ALL = (uint32_t)'%';
  158604. int prevEscape = 0; /* True if the previous character was uEsc */
  158605. while( 1 ){
  158606. /* Read (and consume) the next character from the input pattern. */
  158607. uint32_t uPattern;
  158608. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  158609. if( uPattern==0 ) break;
  158610. /* There are now 4 possibilities:
  158611. **
  158612. ** 1. uPattern is an unescaped match-all character "%",
  158613. ** 2. uPattern is an unescaped match-one character "_",
  158614. ** 3. uPattern is an unescaped escape character, or
  158615. ** 4. uPattern is to be handled as an ordinary character
  158616. */
  158617. if( !prevEscape && uPattern==MATCH_ALL ){
  158618. /* Case 1. */
  158619. uint8_t c;
  158620. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  158621. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  158622. ** test string.
  158623. */
  158624. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  158625. if( c==MATCH_ONE ){
  158626. if( *zString==0 ) return 0;
  158627. SQLITE_ICU_SKIP_UTF8(zString);
  158628. }
  158629. zPattern++;
  158630. }
  158631. if( *zPattern==0 ) return 1;
  158632. while( *zString ){
  158633. if( icuLikeCompare(zPattern, zString, uEsc) ){
  158634. return 1;
  158635. }
  158636. SQLITE_ICU_SKIP_UTF8(zString);
  158637. }
  158638. return 0;
  158639. }else if( !prevEscape && uPattern==MATCH_ONE ){
  158640. /* Case 2. */
  158641. if( *zString==0 ) return 0;
  158642. SQLITE_ICU_SKIP_UTF8(zString);
  158643. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  158644. /* Case 3. */
  158645. prevEscape = 1;
  158646. }else{
  158647. /* Case 4. */
  158648. uint32_t uString;
  158649. SQLITE_ICU_READ_UTF8(zString, uString);
  158650. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  158651. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  158652. if( uString!=uPattern ){
  158653. return 0;
  158654. }
  158655. prevEscape = 0;
  158656. }
  158657. }
  158658. return *zString==0;
  158659. }
  158660. /*
  158661. ** Implementation of the like() SQL function. This function implements
  158662. ** the build-in LIKE operator. The first argument to the function is the
  158663. ** pattern and the second argument is the string. So, the SQL statements:
  158664. **
  158665. ** A LIKE B
  158666. **
  158667. ** is implemented as like(B, A). If there is an escape character E,
  158668. **
  158669. ** A LIKE B ESCAPE E
  158670. **
  158671. ** is mapped to like(B, A, E).
  158672. */
  158673. static void icuLikeFunc(
  158674. sqlite3_context *context,
  158675. int argc,
  158676. sqlite3_value **argv
  158677. ){
  158678. const unsigned char *zA = sqlite3_value_text(argv[0]);
  158679. const unsigned char *zB = sqlite3_value_text(argv[1]);
  158680. UChar32 uEsc = 0;
  158681. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  158682. ** of deep recursion and N*N behavior in patternCompare().
  158683. */
  158684. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  158685. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  158686. return;
  158687. }
  158688. if( argc==3 ){
  158689. /* The escape character string must consist of a single UTF-8 character.
  158690. ** Otherwise, return an error.
  158691. */
  158692. int nE= sqlite3_value_bytes(argv[2]);
  158693. const unsigned char *zE = sqlite3_value_text(argv[2]);
  158694. int i = 0;
  158695. if( zE==0 ) return;
  158696. U8_NEXT(zE, i, nE, uEsc);
  158697. if( i!=nE){
  158698. sqlite3_result_error(context,
  158699. "ESCAPE expression must be a single character", -1);
  158700. return;
  158701. }
  158702. }
  158703. if( zA && zB ){
  158704. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  158705. }
  158706. }
  158707. /*
  158708. ** This function is called when an ICU function called from within
  158709. ** the implementation of an SQL scalar function returns an error.
  158710. **
  158711. ** The scalar function context passed as the first argument is
  158712. ** loaded with an error message based on the following two args.
  158713. */
  158714. static void icuFunctionError(
  158715. sqlite3_context *pCtx, /* SQLite scalar function context */
  158716. const char *zName, /* Name of ICU function that failed */
  158717. UErrorCode e /* Error code returned by ICU function */
  158718. ){
  158719. char zBuf[128];
  158720. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  158721. zBuf[127] = '\0';
  158722. sqlite3_result_error(pCtx, zBuf, -1);
  158723. }
  158724. /*
  158725. ** Function to delete compiled regexp objects. Registered as
  158726. ** a destructor function with sqlite3_set_auxdata().
  158727. */
  158728. static void icuRegexpDelete(void *p){
  158729. URegularExpression *pExpr = (URegularExpression *)p;
  158730. uregex_close(pExpr);
  158731. }
  158732. /*
  158733. ** Implementation of SQLite REGEXP operator. This scalar function takes
  158734. ** two arguments. The first is a regular expression pattern to compile
  158735. ** the second is a string to match against that pattern. If either
  158736. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  158737. ** is 1 if the string matches the pattern, or 0 otherwise.
  158738. **
  158739. ** SQLite maps the regexp() function to the regexp() operator such
  158740. ** that the following two are equivalent:
  158741. **
  158742. ** zString REGEXP zPattern
  158743. ** regexp(zPattern, zString)
  158744. **
  158745. ** Uses the following ICU regexp APIs:
  158746. **
  158747. ** uregex_open()
  158748. ** uregex_matches()
  158749. ** uregex_close()
  158750. */
  158751. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  158752. UErrorCode status = U_ZERO_ERROR;
  158753. URegularExpression *pExpr;
  158754. UBool res;
  158755. const UChar *zString = sqlite3_value_text16(apArg[1]);
  158756. (void)nArg; /* Unused parameter */
  158757. /* If the left hand side of the regexp operator is NULL,
  158758. ** then the result is also NULL.
  158759. */
  158760. if( !zString ){
  158761. return;
  158762. }
  158763. pExpr = sqlite3_get_auxdata(p, 0);
  158764. if( !pExpr ){
  158765. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  158766. if( !zPattern ){
  158767. return;
  158768. }
  158769. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  158770. if( U_SUCCESS(status) ){
  158771. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  158772. }else{
  158773. assert(!pExpr);
  158774. icuFunctionError(p, "uregex_open", status);
  158775. return;
  158776. }
  158777. }
  158778. /* Configure the text that the regular expression operates on. */
  158779. uregex_setText(pExpr, zString, -1, &status);
  158780. if( !U_SUCCESS(status) ){
  158781. icuFunctionError(p, "uregex_setText", status);
  158782. return;
  158783. }
  158784. /* Attempt the match */
  158785. res = uregex_matches(pExpr, 0, &status);
  158786. if( !U_SUCCESS(status) ){
  158787. icuFunctionError(p, "uregex_matches", status);
  158788. return;
  158789. }
  158790. /* Set the text that the regular expression operates on to a NULL
  158791. ** pointer. This is not really necessary, but it is tidier than
  158792. ** leaving the regular expression object configured with an invalid
  158793. ** pointer after this function returns.
  158794. */
  158795. uregex_setText(pExpr, 0, 0, &status);
  158796. /* Return 1 or 0. */
  158797. sqlite3_result_int(p, res ? 1 : 0);
  158798. }
  158799. /*
  158800. ** Implementations of scalar functions for case mapping - upper() and
  158801. ** lower(). Function upper() converts its input to upper-case (ABC).
  158802. ** Function lower() converts to lower-case (abc).
  158803. **
  158804. ** ICU provides two types of case mapping, "general" case mapping and
  158805. ** "language specific". Refer to ICU documentation for the differences
  158806. ** between the two.
  158807. **
  158808. ** To utilise "general" case mapping, the upper() or lower() scalar
  158809. ** functions are invoked with one argument:
  158810. **
  158811. ** upper('ABC') -> 'abc'
  158812. ** lower('abc') -> 'ABC'
  158813. **
  158814. ** To access ICU "language specific" case mapping, upper() or lower()
  158815. ** should be invoked with two arguments. The second argument is the name
  158816. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  158817. ** as the second argument is the same as invoking the 1 argument version
  158818. ** of upper() or lower().
  158819. **
  158820. ** lower('I', 'en_us') -> 'i'
  158821. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  158822. **
  158823. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  158824. */
  158825. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  158826. const UChar *zInput; /* Pointer to input string */
  158827. UChar *zOutput = 0; /* Pointer to output buffer */
  158828. int nInput; /* Size of utf-16 input string in bytes */
  158829. int nOut; /* Size of output buffer in bytes */
  158830. int cnt;
  158831. int bToUpper; /* True for toupper(), false for tolower() */
  158832. UErrorCode status;
  158833. const char *zLocale = 0;
  158834. assert(nArg==1 || nArg==2);
  158835. bToUpper = (sqlite3_user_data(p)!=0);
  158836. if( nArg==2 ){
  158837. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  158838. }
  158839. zInput = sqlite3_value_text16(apArg[0]);
  158840. if( !zInput ){
  158841. return;
  158842. }
  158843. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  158844. if( nOut==0 ){
  158845. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  158846. return;
  158847. }
  158848. for(cnt=0; cnt<2; cnt++){
  158849. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  158850. if( zNew==0 ){
  158851. sqlite3_free(zOutput);
  158852. sqlite3_result_error_nomem(p);
  158853. return;
  158854. }
  158855. zOutput = zNew;
  158856. status = U_ZERO_ERROR;
  158857. if( bToUpper ){
  158858. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  158859. }else{
  158860. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  158861. }
  158862. if( U_SUCCESS(status) ){
  158863. sqlite3_result_text16(p, zOutput, nOut, xFree);
  158864. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  158865. assert( cnt==0 );
  158866. continue;
  158867. }else{
  158868. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  158869. }
  158870. return;
  158871. }
  158872. assert( 0 ); /* Unreachable */
  158873. }
  158874. /*
  158875. ** Collation sequence destructor function. The pCtx argument points to
  158876. ** a UCollator structure previously allocated using ucol_open().
  158877. */
  158878. static void icuCollationDel(void *pCtx){
  158879. UCollator *p = (UCollator *)pCtx;
  158880. ucol_close(p);
  158881. }
  158882. /*
  158883. ** Collation sequence comparison function. The pCtx argument points to
  158884. ** a UCollator structure previously allocated using ucol_open().
  158885. */
  158886. static int icuCollationColl(
  158887. void *pCtx,
  158888. int nLeft,
  158889. const void *zLeft,
  158890. int nRight,
  158891. const void *zRight
  158892. ){
  158893. UCollationResult res;
  158894. UCollator *p = (UCollator *)pCtx;
  158895. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  158896. switch( res ){
  158897. case UCOL_LESS: return -1;
  158898. case UCOL_GREATER: return +1;
  158899. case UCOL_EQUAL: return 0;
  158900. }
  158901. assert(!"Unexpected return value from ucol_strcoll()");
  158902. return 0;
  158903. }
  158904. /*
  158905. ** Implementation of the scalar function icu_load_collation().
  158906. **
  158907. ** This scalar function is used to add ICU collation based collation
  158908. ** types to an SQLite database connection. It is intended to be called
  158909. ** as follows:
  158910. **
  158911. ** SELECT icu_load_collation(<locale>, <collation-name>);
  158912. **
  158913. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  158914. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  158915. ** collation sequence to create.
  158916. */
  158917. static void icuLoadCollation(
  158918. sqlite3_context *p,
  158919. int nArg,
  158920. sqlite3_value **apArg
  158921. ){
  158922. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  158923. UErrorCode status = U_ZERO_ERROR;
  158924. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  158925. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  158926. UCollator *pUCollator; /* ICU library collation object */
  158927. int rc; /* Return code from sqlite3_create_collation_x() */
  158928. assert(nArg==2);
  158929. (void)nArg; /* Unused parameter */
  158930. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  158931. zName = (const char *)sqlite3_value_text(apArg[1]);
  158932. if( !zLocale || !zName ){
  158933. return;
  158934. }
  158935. pUCollator = ucol_open(zLocale, &status);
  158936. if( !U_SUCCESS(status) ){
  158937. icuFunctionError(p, "ucol_open", status);
  158938. return;
  158939. }
  158940. assert(p);
  158941. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  158942. icuCollationColl, icuCollationDel
  158943. );
  158944. if( rc!=SQLITE_OK ){
  158945. ucol_close(pUCollator);
  158946. sqlite3_result_error(p, "Error registering collation function", -1);
  158947. }
  158948. }
  158949. /*
  158950. ** Register the ICU extension functions with database db.
  158951. */
  158952. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  158953. static const struct IcuScalar {
  158954. const char *zName; /* Function name */
  158955. unsigned char nArg; /* Number of arguments */
  158956. unsigned short enc; /* Optimal text encoding */
  158957. unsigned char iContext; /* sqlite3_user_data() context */
  158958. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  158959. } scalars[] = {
  158960. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  158961. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  158962. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  158963. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  158964. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  158965. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  158966. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  158967. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  158968. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  158969. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  158970. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  158971. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  158972. };
  158973. int rc = SQLITE_OK;
  158974. int i;
  158975. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  158976. const struct IcuScalar *p = &scalars[i];
  158977. rc = sqlite3_create_function(
  158978. db, p->zName, p->nArg, p->enc,
  158979. p->iContext ? (void*)db : (void*)0,
  158980. p->xFunc, 0, 0
  158981. );
  158982. }
  158983. return rc;
  158984. }
  158985. #if !SQLITE_CORE
  158986. #ifdef _WIN32
  158987. __declspec(dllexport)
  158988. #endif
  158989. SQLITE_API int sqlite3_icu_init(
  158990. sqlite3 *db,
  158991. char **pzErrMsg,
  158992. const sqlite3_api_routines *pApi
  158993. ){
  158994. SQLITE_EXTENSION_INIT2(pApi)
  158995. return sqlite3IcuInit(db);
  158996. }
  158997. #endif
  158998. #endif
  158999. /************** End of icu.c *************************************************/
  159000. /************** Begin file fts3_icu.c ****************************************/
  159001. /*
  159002. ** 2007 June 22
  159003. **
  159004. ** The author disclaims copyright to this source code. In place of
  159005. ** a legal notice, here is a blessing:
  159006. **
  159007. ** May you do good and not evil.
  159008. ** May you find forgiveness for yourself and forgive others.
  159009. ** May you share freely, never taking more than you give.
  159010. **
  159011. *************************************************************************
  159012. ** This file implements a tokenizer for fts3 based on the ICU library.
  159013. */
  159014. /* #include "fts3Int.h" */
  159015. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159016. #ifdef SQLITE_ENABLE_ICU
  159017. /* #include <assert.h> */
  159018. /* #include <string.h> */
  159019. /* #include "fts3_tokenizer.h" */
  159020. #include <unicode/ubrk.h>
  159021. /* #include <unicode/ucol.h> */
  159022. /* #include <unicode/ustring.h> */
  159023. #include <unicode/utf16.h>
  159024. typedef struct IcuTokenizer IcuTokenizer;
  159025. typedef struct IcuCursor IcuCursor;
  159026. struct IcuTokenizer {
  159027. sqlite3_tokenizer base;
  159028. char *zLocale;
  159029. };
  159030. struct IcuCursor {
  159031. sqlite3_tokenizer_cursor base;
  159032. UBreakIterator *pIter; /* ICU break-iterator object */
  159033. int nChar; /* Number of UChar elements in pInput */
  159034. UChar *aChar; /* Copy of input using utf-16 encoding */
  159035. int *aOffset; /* Offsets of each character in utf-8 input */
  159036. int nBuffer;
  159037. char *zBuffer;
  159038. int iToken;
  159039. };
  159040. /*
  159041. ** Create a new tokenizer instance.
  159042. */
  159043. static int icuCreate(
  159044. int argc, /* Number of entries in argv[] */
  159045. const char * const *argv, /* Tokenizer creation arguments */
  159046. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  159047. ){
  159048. IcuTokenizer *p;
  159049. int n = 0;
  159050. if( argc>0 ){
  159051. n = strlen(argv[0])+1;
  159052. }
  159053. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  159054. if( !p ){
  159055. return SQLITE_NOMEM;
  159056. }
  159057. memset(p, 0, sizeof(IcuTokenizer));
  159058. if( n ){
  159059. p->zLocale = (char *)&p[1];
  159060. memcpy(p->zLocale, argv[0], n);
  159061. }
  159062. *ppTokenizer = (sqlite3_tokenizer *)p;
  159063. return SQLITE_OK;
  159064. }
  159065. /*
  159066. ** Destroy a tokenizer
  159067. */
  159068. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  159069. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  159070. sqlite3_free(p);
  159071. return SQLITE_OK;
  159072. }
  159073. /*
  159074. ** Prepare to begin tokenizing a particular string. The input
  159075. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  159076. ** used to incrementally tokenize this string is returned in
  159077. ** *ppCursor.
  159078. */
  159079. static int icuOpen(
  159080. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  159081. const char *zInput, /* Input string */
  159082. int nInput, /* Length of zInput in bytes */
  159083. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  159084. ){
  159085. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  159086. IcuCursor *pCsr;
  159087. const int32_t opt = U_FOLD_CASE_DEFAULT;
  159088. UErrorCode status = U_ZERO_ERROR;
  159089. int nChar;
  159090. UChar32 c;
  159091. int iInput = 0;
  159092. int iOut = 0;
  159093. *ppCursor = 0;
  159094. if( zInput==0 ){
  159095. nInput = 0;
  159096. zInput = "";
  159097. }else if( nInput<0 ){
  159098. nInput = strlen(zInput);
  159099. }
  159100. nChar = nInput+1;
  159101. pCsr = (IcuCursor *)sqlite3_malloc(
  159102. sizeof(IcuCursor) + /* IcuCursor */
  159103. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  159104. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  159105. );
  159106. if( !pCsr ){
  159107. return SQLITE_NOMEM;
  159108. }
  159109. memset(pCsr, 0, sizeof(IcuCursor));
  159110. pCsr->aChar = (UChar *)&pCsr[1];
  159111. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  159112. pCsr->aOffset[iOut] = iInput;
  159113. U8_NEXT(zInput, iInput, nInput, c);
  159114. while( c>0 ){
  159115. int isError = 0;
  159116. c = u_foldCase(c, opt);
  159117. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  159118. if( isError ){
  159119. sqlite3_free(pCsr);
  159120. return SQLITE_ERROR;
  159121. }
  159122. pCsr->aOffset[iOut] = iInput;
  159123. if( iInput<nInput ){
  159124. U8_NEXT(zInput, iInput, nInput, c);
  159125. }else{
  159126. c = 0;
  159127. }
  159128. }
  159129. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  159130. if( !U_SUCCESS(status) ){
  159131. sqlite3_free(pCsr);
  159132. return SQLITE_ERROR;
  159133. }
  159134. pCsr->nChar = iOut;
  159135. ubrk_first(pCsr->pIter);
  159136. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  159137. return SQLITE_OK;
  159138. }
  159139. /*
  159140. ** Close a tokenization cursor previously opened by a call to icuOpen().
  159141. */
  159142. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  159143. IcuCursor *pCsr = (IcuCursor *)pCursor;
  159144. ubrk_close(pCsr->pIter);
  159145. sqlite3_free(pCsr->zBuffer);
  159146. sqlite3_free(pCsr);
  159147. return SQLITE_OK;
  159148. }
  159149. /*
  159150. ** Extract the next token from a tokenization cursor.
  159151. */
  159152. static int icuNext(
  159153. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  159154. const char **ppToken, /* OUT: *ppToken is the token text */
  159155. int *pnBytes, /* OUT: Number of bytes in token */
  159156. int *piStartOffset, /* OUT: Starting offset of token */
  159157. int *piEndOffset, /* OUT: Ending offset of token */
  159158. int *piPosition /* OUT: Position integer of token */
  159159. ){
  159160. IcuCursor *pCsr = (IcuCursor *)pCursor;
  159161. int iStart = 0;
  159162. int iEnd = 0;
  159163. int nByte = 0;
  159164. while( iStart==iEnd ){
  159165. UChar32 c;
  159166. iStart = ubrk_current(pCsr->pIter);
  159167. iEnd = ubrk_next(pCsr->pIter);
  159168. if( iEnd==UBRK_DONE ){
  159169. return SQLITE_DONE;
  159170. }
  159171. while( iStart<iEnd ){
  159172. int iWhite = iStart;
  159173. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  159174. if( u_isspace(c) ){
  159175. iStart = iWhite;
  159176. }else{
  159177. break;
  159178. }
  159179. }
  159180. assert(iStart<=iEnd);
  159181. }
  159182. do {
  159183. UErrorCode status = U_ZERO_ERROR;
  159184. if( nByte ){
  159185. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  159186. if( !zNew ){
  159187. return SQLITE_NOMEM;
  159188. }
  159189. pCsr->zBuffer = zNew;
  159190. pCsr->nBuffer = nByte;
  159191. }
  159192. u_strToUTF8(
  159193. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  159194. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  159195. &status /* Output success/failure */
  159196. );
  159197. } while( nByte>pCsr->nBuffer );
  159198. *ppToken = pCsr->zBuffer;
  159199. *pnBytes = nByte;
  159200. *piStartOffset = pCsr->aOffset[iStart];
  159201. *piEndOffset = pCsr->aOffset[iEnd];
  159202. *piPosition = pCsr->iToken++;
  159203. return SQLITE_OK;
  159204. }
  159205. /*
  159206. ** The set of routines that implement the simple tokenizer
  159207. */
  159208. static const sqlite3_tokenizer_module icuTokenizerModule = {
  159209. 0, /* iVersion */
  159210. icuCreate, /* xCreate */
  159211. icuDestroy, /* xCreate */
  159212. icuOpen, /* xOpen */
  159213. icuClose, /* xClose */
  159214. icuNext, /* xNext */
  159215. 0, /* xLanguageid */
  159216. };
  159217. /*
  159218. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  159219. */
  159220. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  159221. sqlite3_tokenizer_module const**ppModule
  159222. ){
  159223. *ppModule = &icuTokenizerModule;
  159224. }
  159225. #endif /* defined(SQLITE_ENABLE_ICU) */
  159226. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  159227. /************** End of fts3_icu.c ********************************************/
  159228. /************** Begin file sqlite3rbu.c **************************************/
  159229. /*
  159230. ** 2014 August 30
  159231. **
  159232. ** The author disclaims copyright to this source code. In place of
  159233. ** a legal notice, here is a blessing:
  159234. **
  159235. ** May you do good and not evil.
  159236. ** May you find forgiveness for yourself and forgive others.
  159237. ** May you share freely, never taking more than you give.
  159238. **
  159239. *************************************************************************
  159240. **
  159241. **
  159242. ** OVERVIEW
  159243. **
  159244. ** The RBU extension requires that the RBU update be packaged as an
  159245. ** SQLite database. The tables it expects to find are described in
  159246. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  159247. ** that the user wishes to write to, a corresponding data_xyz table is
  159248. ** created in the RBU database and populated with one row for each row to
  159249. ** update, insert or delete from the target table.
  159250. **
  159251. ** The update proceeds in three stages:
  159252. **
  159253. ** 1) The database is updated. The modified database pages are written
  159254. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  159255. ** that it is named "<database>-oal" instead of "<database>-wal".
  159256. ** Because regular SQLite clients do not look for file named
  159257. ** "<database>-oal", they go on using the original database in
  159258. ** rollback mode while the *-oal file is being generated.
  159259. **
  159260. ** During this stage RBU does not update the database by writing
  159261. ** directly to the target tables. Instead it creates "imposter"
  159262. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  159263. ** to update each b-tree individually. All updates required by each
  159264. ** b-tree are completed before moving on to the next, and all
  159265. ** updates are done in sorted key order.
  159266. **
  159267. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  159268. ** location using a call to rename(2). Before doing this the RBU
  159269. ** module takes an EXCLUSIVE lock on the database file, ensuring
  159270. ** that there are no other active readers.
  159271. **
  159272. ** Once the EXCLUSIVE lock is released, any other database readers
  159273. ** detect the new *-wal file and read the database in wal mode. At
  159274. ** this point they see the new version of the database - including
  159275. ** the updates made as part of the RBU update.
  159276. **
  159277. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  159278. ** as a regular database checkpoint, except that a single frame is
  159279. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  159280. ** handle is closed before the entire *-wal file is checkpointed,
  159281. ** the checkpoint progress is saved in the RBU database and the
  159282. ** checkpoint can be resumed by another RBU client at some point in
  159283. ** the future.
  159284. **
  159285. ** POTENTIAL PROBLEMS
  159286. **
  159287. ** The rename() call might not be portable. And RBU is not currently
  159288. ** syncing the directory after renaming the file.
  159289. **
  159290. ** When state is saved, any commit to the *-oal file and the commit to
  159291. ** the RBU update database are not atomic. So if the power fails at the
  159292. ** wrong moment they might get out of sync. As the main database will be
  159293. ** committed before the RBU update database this will likely either just
  159294. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  159295. ** constraint violations).
  159296. **
  159297. ** If some client does modify the target database mid RBU update, or some
  159298. ** other error occurs, the RBU extension will keep throwing errors. It's
  159299. ** not really clear how to get out of this state. The system could just
  159300. ** by delete the RBU update database and *-oal file and have the device
  159301. ** download the update again and start over.
  159302. **
  159303. ** At present, for an UPDATE, both the new.* and old.* records are
  159304. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  159305. ** fields are collected. This means we're probably writing a lot more
  159306. ** data to disk when saving the state of an ongoing update to the RBU
  159307. ** update database than is strictly necessary.
  159308. **
  159309. */
  159310. /* #include <assert.h> */
  159311. /* #include <string.h> */
  159312. /* #include <stdio.h> */
  159313. /* #include "sqlite3.h" */
  159314. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  159315. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  159316. /************** Begin file sqlite3rbu.h **************************************/
  159317. /*
  159318. ** 2014 August 30
  159319. **
  159320. ** The author disclaims copyright to this source code. In place of
  159321. ** a legal notice, here is a blessing:
  159322. **
  159323. ** May you do good and not evil.
  159324. ** May you find forgiveness for yourself and forgive others.
  159325. ** May you share freely, never taking more than you give.
  159326. **
  159327. *************************************************************************
  159328. **
  159329. ** This file contains the public interface for the RBU extension.
  159330. */
  159331. /*
  159332. ** SUMMARY
  159333. **
  159334. ** Writing a transaction containing a large number of operations on
  159335. ** b-tree indexes that are collectively larger than the available cache
  159336. ** memory can be very inefficient.
  159337. **
  159338. ** The problem is that in order to update a b-tree, the leaf page (at least)
  159339. ** containing the entry being inserted or deleted must be modified. If the
  159340. ** working set of leaves is larger than the available cache memory, then a
  159341. ** single leaf that is modified more than once as part of the transaction
  159342. ** may be loaded from or written to the persistent media multiple times.
  159343. ** Additionally, because the index updates are likely to be applied in
  159344. ** random order, access to pages within the database is also likely to be in
  159345. ** random order, which is itself quite inefficient.
  159346. **
  159347. ** One way to improve the situation is to sort the operations on each index
  159348. ** by index key before applying them to the b-tree. This leads to an IO
  159349. ** pattern that resembles a single linear scan through the index b-tree,
  159350. ** and all but guarantees each modified leaf page is loaded and stored
  159351. ** exactly once. SQLite uses this trick to improve the performance of
  159352. ** CREATE INDEX commands. This extension allows it to be used to improve
  159353. ** the performance of large transactions on existing databases.
  159354. **
  159355. ** Additionally, this extension allows the work involved in writing the
  159356. ** large transaction to be broken down into sub-transactions performed
  159357. ** sequentially by separate processes. This is useful if the system cannot
  159358. ** guarantee that a single update process will run for long enough to apply
  159359. ** the entire update, for example because the update is being applied on a
  159360. ** mobile device that is frequently rebooted. Even after the writer process
  159361. ** has committed one or more sub-transactions, other database clients continue
  159362. ** to read from the original database snapshot. In other words, partially
  159363. ** applied transactions are not visible to other clients.
  159364. **
  159365. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  159366. ** transmitted via a wireless network to a mobile device. A transaction
  159367. ** applied using this extension is hence refered to as an "RBU update".
  159368. **
  159369. **
  159370. ** LIMITATIONS
  159371. **
  159372. ** An "RBU update" transaction is subject to the following limitations:
  159373. **
  159374. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  159375. ** only.
  159376. **
  159377. ** * INSERT statements may not use any default values.
  159378. **
  159379. ** * UPDATE and DELETE statements must identify their target rows by
  159380. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  159381. ** KEY fields may not be updated or deleted. If the table being written
  159382. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  159383. **
  159384. ** * UPDATE statements may not modify PRIMARY KEY columns.
  159385. **
  159386. ** * No triggers will be fired.
  159387. **
  159388. ** * No foreign key violations are detected or reported.
  159389. **
  159390. ** * CHECK constraints are not enforced.
  159391. **
  159392. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  159393. **
  159394. **
  159395. ** PREPARATION
  159396. **
  159397. ** An "RBU update" is stored as a separate SQLite database. A database
  159398. ** containing an RBU update is an "RBU database". For each table in the
  159399. ** target database to be updated, the RBU database should contain a table
  159400. ** named "data_<target name>" containing the same set of columns as the
  159401. ** target table, and one more - "rbu_control". The data_% table should
  159402. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  159403. ** the same type as the corresponding column in the target database.
  159404. ** The "rbu_control" column should have no type at all. For example, if
  159405. ** the target database contains:
  159406. **
  159407. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  159408. **
  159409. ** Then the RBU database should contain:
  159410. **
  159411. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  159412. **
  159413. ** The order of the columns in the data_% table does not matter.
  159414. **
  159415. ** Instead of a regular table, the RBU database may also contain virtual
  159416. ** tables or view named using the data_<target> naming scheme.
  159417. **
  159418. ** Instead of the plain data_<target> naming scheme, RBU database tables
  159419. ** may also be named data<integer>_<target>, where <integer> is any sequence
  159420. ** of zero or more numeric characters (0-9). This can be significant because
  159421. ** tables within the RBU database are always processed in order sorted by
  159422. ** name. By judicious selection of the <integer> portion of the names
  159423. ** of the RBU tables the user can therefore control the order in which they
  159424. ** are processed. This can be useful, for example, to ensure that "external
  159425. ** content" FTS4 tables are updated before their underlying content tables.
  159426. **
  159427. ** If the target database table is a virtual table or a table that has no
  159428. ** PRIMARY KEY declaration, the data_% table must also contain a column
  159429. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  159430. ** key column - "rowid". Virtual tables for which the "rowid" column does
  159431. ** not function like a primary key value cannot be updated using RBU. For
  159432. ** example, if the target db contains either of the following:
  159433. **
  159434. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  159435. ** CREATE TABLE x1(a, b)
  159436. **
  159437. ** then the RBU database should contain:
  159438. **
  159439. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  159440. **
  159441. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  159442. ** target table must be present in the input table. For virtual tables,
  159443. ** hidden columns are optional - they are updated by RBU if present in
  159444. ** the input table, or not otherwise. For example, to write to an fts4
  159445. ** table with a hidden languageid column such as:
  159446. **
  159447. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  159448. **
  159449. ** Either of the following input table schemas may be used:
  159450. **
  159451. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  159452. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  159453. **
  159454. ** For each row to INSERT into the target database as part of the RBU
  159455. ** update, the corresponding data_% table should contain a single record
  159456. ** with the "rbu_control" column set to contain integer value 0. The
  159457. ** other columns should be set to the values that make up the new record
  159458. ** to insert.
  159459. **
  159460. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  159461. ** possible to insert a NULL value into the IPK column. Attempting to
  159462. ** do so results in an SQLITE_MISMATCH error.
  159463. **
  159464. ** For each row to DELETE from the target database as part of the RBU
  159465. ** update, the corresponding data_% table should contain a single record
  159466. ** with the "rbu_control" column set to contain integer value 1. The
  159467. ** real primary key values of the row to delete should be stored in the
  159468. ** corresponding columns of the data_% table. The values stored in the
  159469. ** other columns are not used.
  159470. **
  159471. ** For each row to UPDATE from the target database as part of the RBU
  159472. ** update, the corresponding data_% table should contain a single record
  159473. ** with the "rbu_control" column set to contain a value of type text.
  159474. ** The real primary key values identifying the row to update should be
  159475. ** stored in the corresponding columns of the data_% table row, as should
  159476. ** the new values of all columns being update. The text value in the
  159477. ** "rbu_control" column must contain the same number of characters as
  159478. ** there are columns in the target database table, and must consist entirely
  159479. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  159480. ** each column that is being updated, the corresponding character is set to
  159481. ** 'x'. For those that remain as they are, the corresponding character of the
  159482. ** rbu_control value should be set to '.'. For example, given the tables
  159483. ** above, the update statement:
  159484. **
  159485. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  159486. **
  159487. ** is represented by the data_t1 row created by:
  159488. **
  159489. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  159490. **
  159491. ** Instead of an 'x' character, characters of the rbu_control value specified
  159492. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  159493. ** target table with the value stored in the corresponding data_% column, the
  159494. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  159495. ** the target table column. rbu_delta() is invoked with two arguments - the
  159496. ** original value currently stored in the target table column and the
  159497. ** value specified in the data_xxx table.
  159498. **
  159499. ** For example, this row:
  159500. **
  159501. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  159502. **
  159503. ** is similar to an UPDATE statement such as:
  159504. **
  159505. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  159506. **
  159507. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  159508. ** ota_control string, the contents of the data_xxx table column is assumed
  159509. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  159510. ** format used by the fossil source-code management system. In this case
  159511. ** the existing value within the target database table must be of type BLOB.
  159512. ** It is replaced by the result of applying the specified fossil delta to
  159513. ** itself.
  159514. **
  159515. ** If the target database table is a virtual table or a table with no PRIMARY
  159516. ** KEY, the rbu_control value should not include a character corresponding
  159517. ** to the rbu_rowid value. For example, this:
  159518. **
  159519. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  159520. ** VALUES(NULL, 'usa', 12, '.x');
  159521. **
  159522. ** causes a result similar to:
  159523. **
  159524. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  159525. **
  159526. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  159527. ** However, RBU is more efficient if reading the rows in from each data_xxx
  159528. ** table in "rowid" order is roughly the same as reading them sorted by
  159529. ** the PRIMARY KEY of the corresponding target database table. In other
  159530. ** words, rows should be sorted using the destination table PRIMARY KEY
  159531. ** fields before they are inserted into the data_xxx tables.
  159532. **
  159533. ** USAGE
  159534. **
  159535. ** The API declared below allows an application to apply an RBU update
  159536. ** stored on disk to an existing target database. Essentially, the
  159537. ** application:
  159538. **
  159539. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  159540. **
  159541. ** 2) Registers any required virtual table modules with the database
  159542. ** handle returned by sqlite3rbu_db(). Also, if required, register
  159543. ** the rbu_delta() implementation.
  159544. **
  159545. ** 3) Calls the sqlite3rbu_step() function one or more times on
  159546. ** the new handle. Each call to sqlite3rbu_step() performs a single
  159547. ** b-tree operation, so thousands of calls may be required to apply
  159548. ** a complete update.
  159549. **
  159550. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  159551. ** sqlite3rbu_step() has been called enough times to completely
  159552. ** apply the update to the target database, then the RBU database
  159553. ** is marked as fully applied. Otherwise, the state of the RBU
  159554. ** update application is saved in the RBU database for later
  159555. ** resumption.
  159556. **
  159557. ** See comments below for more detail on APIs.
  159558. **
  159559. ** If an update is only partially applied to the target database by the
  159560. ** time sqlite3rbu_close() is called, various state information is saved
  159561. ** within the RBU database. This allows subsequent processes to automatically
  159562. ** resume the RBU update from where it left off.
  159563. **
  159564. ** To remove all RBU extension state information, returning an RBU database
  159565. ** to its original contents, it is sufficient to drop all tables that begin
  159566. ** with the prefix "rbu_"
  159567. **
  159568. ** DATABASE LOCKING
  159569. **
  159570. ** An RBU update may not be applied to a database in WAL mode. Attempting
  159571. ** to do so is an error (SQLITE_ERROR).
  159572. **
  159573. ** While an RBU handle is open, a SHARED lock may be held on the target
  159574. ** database file. This means it is possible for other clients to read the
  159575. ** database, but not to write it.
  159576. **
  159577. ** If an RBU update is started and then suspended before it is completed,
  159578. ** then an external client writes to the database, then attempting to resume
  159579. ** the suspended RBU update is also an error (SQLITE_BUSY).
  159580. */
  159581. #ifndef _SQLITE3RBU_H
  159582. #define _SQLITE3RBU_H
  159583. /* #include "sqlite3.h" ** Required for error code definitions ** */
  159584. #if 0
  159585. extern "C" {
  159586. #endif
  159587. typedef struct sqlite3rbu sqlite3rbu;
  159588. /*
  159589. ** Open an RBU handle.
  159590. **
  159591. ** Argument zTarget is the path to the target database. Argument zRbu is
  159592. ** the path to the RBU database. Each call to this function must be matched
  159593. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  159594. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  159595. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  159596. ** database URI, not a regular file name.
  159597. **
  159598. ** If the zState argument is passed a NULL value, the RBU extension stores
  159599. ** the current state of the update (how many rows have been updated, which
  159600. ** indexes are yet to be updated etc.) within the RBU database itself. This
  159601. ** can be convenient, as it means that the RBU application does not need to
  159602. ** organize removing a separate state file after the update is concluded.
  159603. ** Or, if zState is non-NULL, it must be a path to a database file in which
  159604. ** the RBU extension can store the state of the update.
  159605. **
  159606. ** When resuming an RBU update, the zState argument must be passed the same
  159607. ** value as when the RBU update was started.
  159608. **
  159609. ** Once the RBU update is finished, the RBU extension does not
  159610. ** automatically remove any zState database file, even if it created it.
  159611. **
  159612. ** By default, RBU uses the default VFS to access the files on disk. To
  159613. ** use a VFS other than the default, an SQLite "file:" URI containing a
  159614. ** "vfs=..." option may be passed as the zTarget option.
  159615. **
  159616. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  159617. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  159618. ** not work out of the box with zipvfs. Refer to the comment describing
  159619. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  159620. */
  159621. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  159622. const char *zTarget,
  159623. const char *zRbu,
  159624. const char *zState
  159625. );
  159626. /*
  159627. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  159628. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  159629. ** that it can be suspended and resumed like an RBU update.
  159630. **
  159631. ** The second argument to this function identifies a database in which
  159632. ** to store the state of the RBU vacuum operation if it is suspended. The
  159633. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  159634. ** operation, the state database should either not exist or be empty
  159635. ** (contain no tables). If an RBU vacuum is suspended by calling
  159636. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  159637. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  159638. ** The vacuum can be resumed by calling this function to open a new RBU
  159639. ** handle specifying the same target and state databases.
  159640. **
  159641. ** If the second argument passed to this function is NULL, then the
  159642. ** name of the state database is "<database>-vacuum", where <database>
  159643. ** is the name of the target database file. In this case, on UNIX, if the
  159644. ** state database is not already present in the file-system, it is created
  159645. ** with the same permissions as the target db is made.
  159646. **
  159647. ** This function does not delete the state database after an RBU vacuum
  159648. ** is completed, even if it created it. However, if the call to
  159649. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  159650. ** of the state tables within the state database are zeroed. This way,
  159651. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  159652. ** new RBU vacuum operation.
  159653. **
  159654. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  159655. ** describing the sqlite3rbu_create_vfs() API function below for
  159656. ** a description of the complications associated with using RBU with
  159657. ** zipvfs databases.
  159658. */
  159659. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  159660. const char *zTarget,
  159661. const char *zState
  159662. );
  159663. /*
  159664. ** Configure a limit for the amount of temp space that may be used by
  159665. ** the RBU handle passed as the first argument. The new limit is specified
  159666. ** in bytes by the second parameter. If it is positive, the limit is updated.
  159667. ** If the second parameter to this function is passed zero, then the limit
  159668. ** is removed entirely. If the second parameter is negative, the limit is
  159669. ** not modified (this is useful for querying the current limit).
  159670. **
  159671. ** In all cases the returned value is the current limit in bytes (zero
  159672. ** indicates unlimited).
  159673. **
  159674. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  159675. ** error is returned.
  159676. */
  159677. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  159678. /*
  159679. ** Return the current amount of temp file space, in bytes, currently used by
  159680. ** the RBU handle passed as the only argument.
  159681. */
  159682. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  159683. /*
  159684. ** Internally, each RBU connection uses a separate SQLite database
  159685. ** connection to access the target and rbu update databases. This
  159686. ** API allows the application direct access to these database handles.
  159687. **
  159688. ** The first argument passed to this function must be a valid, open, RBU
  159689. ** handle. The second argument should be passed zero to access the target
  159690. ** database handle, or non-zero to access the rbu update database handle.
  159691. ** Accessing the underlying database handles may be useful in the
  159692. ** following scenarios:
  159693. **
  159694. ** * If any target tables are virtual tables, it may be necessary to
  159695. ** call sqlite3_create_module() on the target database handle to
  159696. ** register the required virtual table implementations.
  159697. **
  159698. ** * If the data_xxx tables in the RBU source database are virtual
  159699. ** tables, the application may need to call sqlite3_create_module() on
  159700. ** the rbu update db handle to any required virtual table
  159701. ** implementations.
  159702. **
  159703. ** * If the application uses the "rbu_delta()" feature described above,
  159704. ** it must use sqlite3_create_function() or similar to register the
  159705. ** rbu_delta() implementation with the target database handle.
  159706. **
  159707. ** If an error has occurred, either while opening or stepping the RBU object,
  159708. ** this function may return NULL. The error code and message may be collected
  159709. ** when sqlite3rbu_close() is called.
  159710. **
  159711. ** Database handles returned by this function remain valid until the next
  159712. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  159713. */
  159714. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  159715. /*
  159716. ** Do some work towards applying the RBU update to the target db.
  159717. **
  159718. ** Return SQLITE_DONE if the update has been completely applied, or
  159719. ** SQLITE_OK if no error occurs but there remains work to do to apply
  159720. ** the RBU update. If an error does occur, some other error code is
  159721. ** returned.
  159722. **
  159723. ** Once a call to sqlite3rbu_step() has returned a value other than
  159724. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  159725. ** that immediately return the same value.
  159726. */
  159727. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  159728. /*
  159729. ** Force RBU to save its state to disk.
  159730. **
  159731. ** If a power failure or application crash occurs during an update, following
  159732. ** system recovery RBU may resume the update from the point at which the state
  159733. ** was last saved. In other words, from the most recent successful call to
  159734. ** sqlite3rbu_close() or this function.
  159735. **
  159736. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  159737. */
  159738. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  159739. /*
  159740. ** Close an RBU handle.
  159741. **
  159742. ** If the RBU update has been completely applied, mark the RBU database
  159743. ** as fully applied. Otherwise, assuming no error has occurred, save the
  159744. ** current state of the RBU update appliation to the RBU database.
  159745. **
  159746. ** If an error has already occurred as part of an sqlite3rbu_step()
  159747. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  159748. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  159749. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  159750. ** English language error message. It is the responsibility of the caller to
  159751. ** eventually free any such buffer using sqlite3_free().
  159752. **
  159753. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  159754. ** update has been partially applied, or SQLITE_DONE if it has been
  159755. ** completely applied.
  159756. */
  159757. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  159758. /*
  159759. ** Return the total number of key-value operations (inserts, deletes or
  159760. ** updates) that have been performed on the target database since the
  159761. ** current RBU update was started.
  159762. */
  159763. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  159764. /*
  159765. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  159766. ** progress indications for the two stages of an RBU update. This API may
  159767. ** be useful for driving GUI progress indicators and similar.
  159768. **
  159769. ** An RBU update is divided into two stages:
  159770. **
  159771. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  159772. ** * Stage 2, in which the contents of the wal file are copied into the
  159773. ** main database.
  159774. **
  159775. ** The update is visible to non-RBU clients during stage 2. During stage 1
  159776. ** non-RBU reader clients may see the original database.
  159777. **
  159778. ** If this API is called during stage 2 of the update, output variable
  159779. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  159780. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  159781. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  159782. ** 9000 indicates that it is 90% finished, and so on.
  159783. **
  159784. ** If this API is called during stage 1 of the update, output variable
  159785. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  159786. ** value to which (*pnOne) is set depends on whether or not the RBU
  159787. ** database contains an "rbu_count" table. The rbu_count table, if it
  159788. ** exists, must contain the same columns as the following:
  159789. **
  159790. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  159791. **
  159792. ** There must be one row in the table for each source (data_xxx) table within
  159793. ** the RBU database. The 'tbl' column should contain the name of the source
  159794. ** table. The 'cnt' column should contain the number of rows within the
  159795. ** source table.
  159796. **
  159797. ** If the rbu_count table is present and populated correctly and this
  159798. ** API is called during stage 1, the *pnOne output variable is set to the
  159799. ** permyriadage progress of the same stage. If the rbu_count table does
  159800. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  159801. ** table exists but is not correctly populated, the value of the *pnOne
  159802. ** output variable during stage 1 is undefined.
  159803. */
  159804. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  159805. /*
  159806. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  159807. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  159808. ** defined in this file. Return values should be interpreted as follows:
  159809. **
  159810. ** SQLITE_RBU_STATE_OAL:
  159811. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  159812. ** may either add further data to the *-oal file, or compute data that will
  159813. ** be added by a subsequent call.
  159814. **
  159815. ** SQLITE_RBU_STATE_MOVE:
  159816. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  159817. ** will move the *-oal file to the equivalent *-wal path. If the current
  159818. ** operation is an RBU update, then the updated version of the database
  159819. ** file will become visible to ordinary SQLite clients following the next
  159820. ** call to sqlite3rbu_step().
  159821. **
  159822. ** SQLITE_RBU_STATE_CHECKPOINT:
  159823. ** RBU is currently performing an incremental checkpoint. The next call to
  159824. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  159825. ** the target database file.
  159826. **
  159827. ** SQLITE_RBU_STATE_DONE:
  159828. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  159829. ** will immediately return SQLITE_DONE.
  159830. **
  159831. ** SQLITE_RBU_STATE_ERROR:
  159832. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  159833. ** immediately return the SQLite error code associated with the error.
  159834. */
  159835. #define SQLITE_RBU_STATE_OAL 1
  159836. #define SQLITE_RBU_STATE_MOVE 2
  159837. #define SQLITE_RBU_STATE_CHECKPOINT 3
  159838. #define SQLITE_RBU_STATE_DONE 4
  159839. #define SQLITE_RBU_STATE_ERROR 5
  159840. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  159841. /*
  159842. ** Create an RBU VFS named zName that accesses the underlying file-system
  159843. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  159844. ** then the new RBU VFS uses the default system VFS to access the file-system.
  159845. ** The new object is registered as a non-default VFS with SQLite before
  159846. ** returning.
  159847. **
  159848. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  159849. ** object is created and deleted automatically by RBU.
  159850. **
  159851. ** The exception is for applications that also use zipvfs. In this case,
  159852. ** the custom VFS must be explicitly created by the user before the RBU
  159853. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  159854. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  159855. ** (for example multiplexor) to access the file-system. For example,
  159856. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  159857. ** multiplexor (error checking omitted):
  159858. **
  159859. ** // Create a VFS named "multiplex" (not the default).
  159860. ** sqlite3_multiplex_initialize(0, 0);
  159861. **
  159862. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  159863. ** // second argument were replaced with NULL, the "rbu" VFS would
  159864. ** // access the file-system via the system default VFS, bypassing the
  159865. ** // multiplexor.
  159866. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  159867. **
  159868. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  159869. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  159870. **
  159871. ** // Make zipvfs the default VFS.
  159872. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  159873. **
  159874. ** Because the default VFS created above includes a RBU functionality, it
  159875. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  159876. ** that does not include the RBU layer results in an error.
  159877. **
  159878. ** The overhead of adding the "rbu" VFS to the system is negligible for
  159879. ** non-RBU users. There is no harm in an application accessing the
  159880. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  159881. ** occasionally.
  159882. */
  159883. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  159884. /*
  159885. ** Deregister and destroy an RBU vfs created by an earlier call to
  159886. ** sqlite3rbu_create_vfs().
  159887. **
  159888. ** VFS objects are not reference counted. If a VFS object is destroyed
  159889. ** before all database handles that use it have been closed, the results
  159890. ** are undefined.
  159891. */
  159892. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  159893. #if 0
  159894. } /* end of the 'extern "C"' block */
  159895. #endif
  159896. #endif /* _SQLITE3RBU_H */
  159897. /************** End of sqlite3rbu.h ******************************************/
  159898. /************** Continuing where we left off in sqlite3rbu.c *****************/
  159899. #if defined(_WIN32_WCE)
  159900. /* #include "windows.h" */
  159901. #endif
  159902. /* Maximum number of prepared UPDATE statements held by this module */
  159903. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  159904. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  159905. ** to enable checksum verification.
  159906. */
  159907. #ifndef RBU_ENABLE_DELTA_CKSUM
  159908. # define RBU_ENABLE_DELTA_CKSUM 0
  159909. #endif
  159910. /*
  159911. ** Swap two objects of type TYPE.
  159912. */
  159913. #if !defined(SQLITE_AMALGAMATION)
  159914. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  159915. #endif
  159916. /*
  159917. ** The rbu_state table is used to save the state of a partially applied
  159918. ** update so that it can be resumed later. The table consists of integer
  159919. ** keys mapped to values as follows:
  159920. **
  159921. ** RBU_STATE_STAGE:
  159922. ** May be set to integer values 1, 2, 4 or 5. As follows:
  159923. ** 1: the *-rbu file is currently under construction.
  159924. ** 2: the *-rbu file has been constructed, but not yet moved
  159925. ** to the *-wal path.
  159926. ** 4: the checkpoint is underway.
  159927. ** 5: the rbu update has been checkpointed.
  159928. **
  159929. ** RBU_STATE_TBL:
  159930. ** Only valid if STAGE==1. The target database name of the table
  159931. ** currently being written.
  159932. **
  159933. ** RBU_STATE_IDX:
  159934. ** Only valid if STAGE==1. The target database name of the index
  159935. ** currently being written, or NULL if the main table is currently being
  159936. ** updated.
  159937. **
  159938. ** RBU_STATE_ROW:
  159939. ** Only valid if STAGE==1. Number of rows already processed for the current
  159940. ** table/index.
  159941. **
  159942. ** RBU_STATE_PROGRESS:
  159943. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  159944. ** rbu update.
  159945. **
  159946. ** RBU_STATE_CKPT:
  159947. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  159948. ** header created by recovering the *-wal file. This is used to detect
  159949. ** cases when another client appends frames to the *-wal file in the
  159950. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  159951. ** be continued if this happens).
  159952. **
  159953. ** RBU_STATE_COOKIE:
  159954. ** Valid if STAGE==1. The current change-counter cookie value in the
  159955. ** target db file.
  159956. **
  159957. ** RBU_STATE_OALSZ:
  159958. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  159959. */
  159960. #define RBU_STATE_STAGE 1
  159961. #define RBU_STATE_TBL 2
  159962. #define RBU_STATE_IDX 3
  159963. #define RBU_STATE_ROW 4
  159964. #define RBU_STATE_PROGRESS 5
  159965. #define RBU_STATE_CKPT 6
  159966. #define RBU_STATE_COOKIE 7
  159967. #define RBU_STATE_OALSZ 8
  159968. #define RBU_STATE_PHASEONESTEP 9
  159969. #define RBU_STAGE_OAL 1
  159970. #define RBU_STAGE_MOVE 2
  159971. #define RBU_STAGE_CAPTURE 3
  159972. #define RBU_STAGE_CKPT 4
  159973. #define RBU_STAGE_DONE 5
  159974. #define RBU_CREATE_STATE \
  159975. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  159976. typedef struct RbuFrame RbuFrame;
  159977. typedef struct RbuObjIter RbuObjIter;
  159978. typedef struct RbuState RbuState;
  159979. typedef struct rbu_vfs rbu_vfs;
  159980. typedef struct rbu_file rbu_file;
  159981. typedef struct RbuUpdateStmt RbuUpdateStmt;
  159982. #if !defined(SQLITE_AMALGAMATION)
  159983. typedef unsigned int u32;
  159984. typedef unsigned short u16;
  159985. typedef unsigned char u8;
  159986. typedef sqlite3_int64 i64;
  159987. #endif
  159988. /*
  159989. ** These values must match the values defined in wal.c for the equivalent
  159990. ** locks. These are not magic numbers as they are part of the SQLite file
  159991. ** format.
  159992. */
  159993. #define WAL_LOCK_WRITE 0
  159994. #define WAL_LOCK_CKPT 1
  159995. #define WAL_LOCK_READ0 3
  159996. #define SQLITE_FCNTL_RBUCNT 5149216
  159997. /*
  159998. ** A structure to store values read from the rbu_state table in memory.
  159999. */
  160000. struct RbuState {
  160001. int eStage;
  160002. char *zTbl;
  160003. char *zIdx;
  160004. i64 iWalCksum;
  160005. int nRow;
  160006. i64 nProgress;
  160007. u32 iCookie;
  160008. i64 iOalSz;
  160009. i64 nPhaseOneStep;
  160010. };
  160011. struct RbuUpdateStmt {
  160012. char *zMask; /* Copy of update mask used with pUpdate */
  160013. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  160014. RbuUpdateStmt *pNext;
  160015. };
  160016. /*
  160017. ** An iterator of this type is used to iterate through all objects in
  160018. ** the target database that require updating. For each such table, the
  160019. ** iterator visits, in order:
  160020. **
  160021. ** * the table itself,
  160022. ** * each index of the table (zero or more points to visit), and
  160023. ** * a special "cleanup table" state.
  160024. **
  160025. ** abIndexed:
  160026. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  160027. ** it points to an array of flags nTblCol elements in size. The flag is
  160028. ** set for each column that is either a part of the PK or a part of an
  160029. ** index. Or clear otherwise.
  160030. **
  160031. */
  160032. struct RbuObjIter {
  160033. sqlite3_stmt *pTblIter; /* Iterate through tables */
  160034. sqlite3_stmt *pIdxIter; /* Index iterator */
  160035. int nTblCol; /* Size of azTblCol[] array */
  160036. char **azTblCol; /* Array of unquoted target column names */
  160037. char **azTblType; /* Array of target column types */
  160038. int *aiSrcOrder; /* src table col -> target table col */
  160039. u8 *abTblPk; /* Array of flags, set on target PK columns */
  160040. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  160041. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  160042. int eType; /* Table type - an RBU_PK_XXX value */
  160043. /* Output variables. zTbl==0 implies EOF. */
  160044. int bCleanup; /* True in "cleanup" state */
  160045. const char *zTbl; /* Name of target db table */
  160046. const char *zDataTbl; /* Name of rbu db table (or null) */
  160047. const char *zIdx; /* Name of target db index (or null) */
  160048. int iTnum; /* Root page of current object */
  160049. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  160050. int bUnique; /* Current index is unique */
  160051. int nIndex; /* Number of aux. indexes on table zTbl */
  160052. /* Statements created by rbuObjIterPrepareAll() */
  160053. int nCol; /* Number of columns in current object */
  160054. sqlite3_stmt *pSelect; /* Source data */
  160055. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  160056. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  160057. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  160058. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  160059. RbuUpdateStmt *pRbuUpdate;
  160060. };
  160061. /*
  160062. ** Values for RbuObjIter.eType
  160063. **
  160064. ** 0: Table does not exist (error)
  160065. ** 1: Table has an implicit rowid.
  160066. ** 2: Table has an explicit IPK column.
  160067. ** 3: Table has an external PK index.
  160068. ** 4: Table is WITHOUT ROWID.
  160069. ** 5: Table is a virtual table.
  160070. */
  160071. #define RBU_PK_NOTABLE 0
  160072. #define RBU_PK_NONE 1
  160073. #define RBU_PK_IPK 2
  160074. #define RBU_PK_EXTERNAL 3
  160075. #define RBU_PK_WITHOUT_ROWID 4
  160076. #define RBU_PK_VTAB 5
  160077. /*
  160078. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  160079. ** one of the following operations.
  160080. */
  160081. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  160082. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  160083. #define RBU_REPLACE 3 /* Delete and then insert a row */
  160084. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  160085. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  160086. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  160087. /*
  160088. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  160089. ** file should be copied to page iDbPage of the database file.
  160090. */
  160091. struct RbuFrame {
  160092. u32 iDbPage;
  160093. u32 iWalFrame;
  160094. };
  160095. /*
  160096. ** RBU handle.
  160097. **
  160098. ** nPhaseOneStep:
  160099. ** If the RBU database contains an rbu_count table, this value is set to
  160100. ** a running estimate of the number of b-tree operations required to
  160101. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  160102. ** API to calculate the permyriadage progress of populating the *-oal file
  160103. ** using the formula:
  160104. **
  160105. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  160106. **
  160107. ** nPhaseOneStep is initialized to the sum of:
  160108. **
  160109. ** nRow * (nIndex + 1)
  160110. **
  160111. ** for all source tables in the RBU database, where nRow is the number
  160112. ** of rows in the source table and nIndex the number of indexes on the
  160113. ** corresponding target database table.
  160114. **
  160115. ** This estimate is accurate if the RBU update consists entirely of
  160116. ** INSERT operations. However, it is inaccurate if:
  160117. **
  160118. ** * the RBU update contains any UPDATE operations. If the PK specified
  160119. ** for an UPDATE operation does not exist in the target table, then
  160120. ** no b-tree operations are required on index b-trees. Or if the
  160121. ** specified PK does exist, then (nIndex*2) such operations are
  160122. ** required (one delete and one insert on each index b-tree).
  160123. **
  160124. ** * the RBU update contains any DELETE operations for which the specified
  160125. ** PK does not exist. In this case no operations are required on index
  160126. ** b-trees.
  160127. **
  160128. ** * the RBU update contains REPLACE operations. These are similar to
  160129. ** UPDATE operations.
  160130. **
  160131. ** nPhaseOneStep is updated to account for the conditions above during the
  160132. ** first pass of each source table. The updated nPhaseOneStep value is
  160133. ** stored in the rbu_state table if the RBU update is suspended.
  160134. */
  160135. struct sqlite3rbu {
  160136. int eStage; /* Value of RBU_STATE_STAGE field */
  160137. sqlite3 *dbMain; /* target database handle */
  160138. sqlite3 *dbRbu; /* rbu database handle */
  160139. char *zTarget; /* Path to target db */
  160140. char *zRbu; /* Path to rbu db */
  160141. char *zState; /* Path to state db (or NULL if zRbu) */
  160142. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  160143. int rc; /* Value returned by last rbu_step() call */
  160144. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  160145. int nStep; /* Rows processed for current object */
  160146. int nProgress; /* Rows processed for all objects */
  160147. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  160148. const char *zVfsName; /* Name of automatically created rbu vfs */
  160149. rbu_file *pTargetFd; /* File handle open on target db */
  160150. int nPagePerSector; /* Pages per sector for pTargetFd */
  160151. i64 iOalSz;
  160152. i64 nPhaseOneStep;
  160153. /* The following state variables are used as part of the incremental
  160154. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  160155. ** function rbuSetupCheckpoint() for details. */
  160156. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  160157. u32 mLock;
  160158. int nFrame; /* Entries in aFrame[] array */
  160159. int nFrameAlloc; /* Allocated size of aFrame[] array */
  160160. RbuFrame *aFrame;
  160161. int pgsz;
  160162. u8 *aBuf;
  160163. i64 iWalCksum;
  160164. i64 szTemp; /* Current size of all temp files in use */
  160165. i64 szTempLimit; /* Total size limit for temp files */
  160166. /* Used in RBU vacuum mode only */
  160167. int nRbu; /* Number of RBU VFS in the stack */
  160168. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  160169. };
  160170. /*
  160171. ** An rbu VFS is implemented using an instance of this structure.
  160172. **
  160173. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  160174. ** It is NULL for RBU VFS objects created explicitly using
  160175. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  160176. ** space used by the RBU handle.
  160177. */
  160178. struct rbu_vfs {
  160179. sqlite3_vfs base; /* rbu VFS shim methods */
  160180. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  160181. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  160182. sqlite3rbu *pRbu; /* Owner RBU object */
  160183. rbu_file *pMain; /* Linked list of main db files */
  160184. };
  160185. /*
  160186. ** Each file opened by an rbu VFS is represented by an instance of
  160187. ** the following structure.
  160188. **
  160189. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  160190. ** "sz" is set to the current size of the database file.
  160191. */
  160192. struct rbu_file {
  160193. sqlite3_file base; /* sqlite3_file methods */
  160194. sqlite3_file *pReal; /* Underlying file handle */
  160195. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  160196. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  160197. i64 sz; /* Size of file in bytes (temp only) */
  160198. int openFlags; /* Flags this file was opened with */
  160199. u32 iCookie; /* Cookie value for main db files */
  160200. u8 iWriteVer; /* "write-version" value for main db files */
  160201. u8 bNolock; /* True to fail EXCLUSIVE locks */
  160202. int nShm; /* Number of entries in apShm[] array */
  160203. char **apShm; /* Array of mmap'd *-shm regions */
  160204. char *zDel; /* Delete this when closing file */
  160205. const char *zWal; /* Wal filename for this main db file */
  160206. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  160207. rbu_file *pMainNext; /* Next MAIN_DB file */
  160208. };
  160209. /*
  160210. ** True for an RBU vacuum handle, or false otherwise.
  160211. */
  160212. #define rbuIsVacuum(p) ((p)->zTarget==0)
  160213. /*************************************************************************
  160214. ** The following three functions, found below:
  160215. **
  160216. ** rbuDeltaGetInt()
  160217. ** rbuDeltaChecksum()
  160218. ** rbuDeltaApply()
  160219. **
  160220. ** are lifted from the fossil source code (http://fossil-scm.org). They
  160221. ** are used to implement the scalar SQL function rbu_fossil_delta().
  160222. */
  160223. /*
  160224. ** Read bytes from *pz and convert them into a positive integer. When
  160225. ** finished, leave *pz pointing to the first character past the end of
  160226. ** the integer. The *pLen parameter holds the length of the string
  160227. ** in *pz and is decremented once for each character in the integer.
  160228. */
  160229. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  160230. static const signed char zValue[] = {
  160231. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  160232. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  160233. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  160234. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  160235. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  160236. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  160237. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  160238. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  160239. };
  160240. unsigned int v = 0;
  160241. int c;
  160242. unsigned char *z = (unsigned char*)*pz;
  160243. unsigned char *zStart = z;
  160244. while( (c = zValue[0x7f&*(z++)])>=0 ){
  160245. v = (v<<6) + c;
  160246. }
  160247. z--;
  160248. *pLen -= z - zStart;
  160249. *pz = (char*)z;
  160250. return v;
  160251. }
  160252. #if RBU_ENABLE_DELTA_CKSUM
  160253. /*
  160254. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  160255. */
  160256. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  160257. const unsigned char *z = (const unsigned char *)zIn;
  160258. unsigned sum0 = 0;
  160259. unsigned sum1 = 0;
  160260. unsigned sum2 = 0;
  160261. unsigned sum3 = 0;
  160262. while(N >= 16){
  160263. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  160264. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  160265. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  160266. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  160267. z += 16;
  160268. N -= 16;
  160269. }
  160270. while(N >= 4){
  160271. sum0 += z[0];
  160272. sum1 += z[1];
  160273. sum2 += z[2];
  160274. sum3 += z[3];
  160275. z += 4;
  160276. N -= 4;
  160277. }
  160278. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  160279. switch(N){
  160280. case 3: sum3 += (z[2] << 8);
  160281. case 2: sum3 += (z[1] << 16);
  160282. case 1: sum3 += (z[0] << 24);
  160283. default: ;
  160284. }
  160285. return sum3;
  160286. }
  160287. #endif
  160288. /*
  160289. ** Apply a delta.
  160290. **
  160291. ** The output buffer should be big enough to hold the whole output
  160292. ** file and a NUL terminator at the end. The delta_output_size()
  160293. ** routine will determine this size for you.
  160294. **
  160295. ** The delta string should be null-terminated. But the delta string
  160296. ** may contain embedded NUL characters (if the input and output are
  160297. ** binary files) so we also have to pass in the length of the delta in
  160298. ** the lenDelta parameter.
  160299. **
  160300. ** This function returns the size of the output file in bytes (excluding
  160301. ** the final NUL terminator character). Except, if the delta string is
  160302. ** malformed or intended for use with a source file other than zSrc,
  160303. ** then this routine returns -1.
  160304. **
  160305. ** Refer to the delta_create() documentation above for a description
  160306. ** of the delta file format.
  160307. */
  160308. static int rbuDeltaApply(
  160309. const char *zSrc, /* The source or pattern file */
  160310. int lenSrc, /* Length of the source file */
  160311. const char *zDelta, /* Delta to apply to the pattern */
  160312. int lenDelta, /* Length of the delta */
  160313. char *zOut /* Write the output into this preallocated buffer */
  160314. ){
  160315. unsigned int limit;
  160316. unsigned int total = 0;
  160317. #if RBU_ENABLE_DELTA_CKSUM
  160318. char *zOrigOut = zOut;
  160319. #endif
  160320. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  160321. if( *zDelta!='\n' ){
  160322. /* ERROR: size integer not terminated by "\n" */
  160323. return -1;
  160324. }
  160325. zDelta++; lenDelta--;
  160326. while( *zDelta && lenDelta>0 ){
  160327. unsigned int cnt, ofst;
  160328. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  160329. switch( zDelta[0] ){
  160330. case '@': {
  160331. zDelta++; lenDelta--;
  160332. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  160333. if( lenDelta>0 && zDelta[0]!=',' ){
  160334. /* ERROR: copy command not terminated by ',' */
  160335. return -1;
  160336. }
  160337. zDelta++; lenDelta--;
  160338. total += cnt;
  160339. if( total>limit ){
  160340. /* ERROR: copy exceeds output file size */
  160341. return -1;
  160342. }
  160343. if( (int)(ofst+cnt) > lenSrc ){
  160344. /* ERROR: copy extends past end of input */
  160345. return -1;
  160346. }
  160347. memcpy(zOut, &zSrc[ofst], cnt);
  160348. zOut += cnt;
  160349. break;
  160350. }
  160351. case ':': {
  160352. zDelta++; lenDelta--;
  160353. total += cnt;
  160354. if( total>limit ){
  160355. /* ERROR: insert command gives an output larger than predicted */
  160356. return -1;
  160357. }
  160358. if( (int)cnt>lenDelta ){
  160359. /* ERROR: insert count exceeds size of delta */
  160360. return -1;
  160361. }
  160362. memcpy(zOut, zDelta, cnt);
  160363. zOut += cnt;
  160364. zDelta += cnt;
  160365. lenDelta -= cnt;
  160366. break;
  160367. }
  160368. case ';': {
  160369. zDelta++; lenDelta--;
  160370. zOut[0] = 0;
  160371. #if RBU_ENABLE_DELTA_CKSUM
  160372. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  160373. /* ERROR: bad checksum */
  160374. return -1;
  160375. }
  160376. #endif
  160377. if( total!=limit ){
  160378. /* ERROR: generated size does not match predicted size */
  160379. return -1;
  160380. }
  160381. return total;
  160382. }
  160383. default: {
  160384. /* ERROR: unknown delta operator */
  160385. return -1;
  160386. }
  160387. }
  160388. }
  160389. /* ERROR: unterminated delta */
  160390. return -1;
  160391. }
  160392. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  160393. int size;
  160394. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  160395. if( *zDelta!='\n' ){
  160396. /* ERROR: size integer not terminated by "\n" */
  160397. return -1;
  160398. }
  160399. return size;
  160400. }
  160401. /*
  160402. ** End of code taken from fossil.
  160403. *************************************************************************/
  160404. /*
  160405. ** Implementation of SQL scalar function rbu_fossil_delta().
  160406. **
  160407. ** This function applies a fossil delta patch to a blob. Exactly two
  160408. ** arguments must be passed to this function. The first is the blob to
  160409. ** patch and the second the patch to apply. If no error occurs, this
  160410. ** function returns the patched blob.
  160411. */
  160412. static void rbuFossilDeltaFunc(
  160413. sqlite3_context *context,
  160414. int argc,
  160415. sqlite3_value **argv
  160416. ){
  160417. const char *aDelta;
  160418. int nDelta;
  160419. const char *aOrig;
  160420. int nOrig;
  160421. int nOut;
  160422. int nOut2;
  160423. char *aOut;
  160424. assert( argc==2 );
  160425. nOrig = sqlite3_value_bytes(argv[0]);
  160426. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  160427. nDelta = sqlite3_value_bytes(argv[1]);
  160428. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  160429. /* Figure out the size of the output */
  160430. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  160431. if( nOut<0 ){
  160432. sqlite3_result_error(context, "corrupt fossil delta", -1);
  160433. return;
  160434. }
  160435. aOut = sqlite3_malloc(nOut+1);
  160436. if( aOut==0 ){
  160437. sqlite3_result_error_nomem(context);
  160438. }else{
  160439. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  160440. if( nOut2!=nOut ){
  160441. sqlite3_result_error(context, "corrupt fossil delta", -1);
  160442. }else{
  160443. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  160444. }
  160445. }
  160446. }
  160447. /*
  160448. ** Prepare the SQL statement in buffer zSql against database handle db.
  160449. ** If successful, set *ppStmt to point to the new statement and return
  160450. ** SQLITE_OK.
  160451. **
  160452. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  160453. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  160454. ** point to a buffer containing an error message. It is the responsibility
  160455. ** of the caller to (eventually) free this buffer using sqlite3_free().
  160456. */
  160457. static int prepareAndCollectError(
  160458. sqlite3 *db,
  160459. sqlite3_stmt **ppStmt,
  160460. char **pzErrmsg,
  160461. const char *zSql
  160462. ){
  160463. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  160464. if( rc!=SQLITE_OK ){
  160465. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  160466. *ppStmt = 0;
  160467. }
  160468. return rc;
  160469. }
  160470. /*
  160471. ** Reset the SQL statement passed as the first argument. Return a copy
  160472. ** of the value returned by sqlite3_reset().
  160473. **
  160474. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  160475. ** containing an error message. It is the responsibility of the caller
  160476. ** to eventually free this buffer using sqlite3_free().
  160477. */
  160478. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  160479. int rc = sqlite3_reset(pStmt);
  160480. if( rc!=SQLITE_OK ){
  160481. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  160482. }
  160483. return rc;
  160484. }
  160485. /*
  160486. ** Unless it is NULL, argument zSql points to a buffer allocated using
  160487. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  160488. ** statement against database db and frees the buffer. If statement
  160489. ** compilation is successful, *ppStmt is set to point to the new statement
  160490. ** handle and SQLITE_OK is returned.
  160491. **
  160492. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  160493. ** returned. In this case, *pzErrmsg may also be set to point to an error
  160494. ** message. It is the responsibility of the caller to free this error message
  160495. ** buffer using sqlite3_free().
  160496. **
  160497. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  160498. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  160499. */
  160500. static int prepareFreeAndCollectError(
  160501. sqlite3 *db,
  160502. sqlite3_stmt **ppStmt,
  160503. char **pzErrmsg,
  160504. char *zSql
  160505. ){
  160506. int rc;
  160507. assert( *pzErrmsg==0 );
  160508. if( zSql==0 ){
  160509. rc = SQLITE_NOMEM;
  160510. *ppStmt = 0;
  160511. }else{
  160512. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  160513. sqlite3_free(zSql);
  160514. }
  160515. return rc;
  160516. }
  160517. /*
  160518. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  160519. ** by an earlier call to rbuObjIterCacheTableInfo().
  160520. */
  160521. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  160522. int i;
  160523. for(i=0; i<pIter->nTblCol; i++){
  160524. sqlite3_free(pIter->azTblCol[i]);
  160525. sqlite3_free(pIter->azTblType[i]);
  160526. }
  160527. sqlite3_free(pIter->azTblCol);
  160528. pIter->azTblCol = 0;
  160529. pIter->azTblType = 0;
  160530. pIter->aiSrcOrder = 0;
  160531. pIter->abTblPk = 0;
  160532. pIter->abNotNull = 0;
  160533. pIter->nTblCol = 0;
  160534. pIter->eType = 0; /* Invalid value */
  160535. }
  160536. /*
  160537. ** Finalize all statements and free all allocations that are specific to
  160538. ** the current object (table/index pair).
  160539. */
  160540. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  160541. RbuUpdateStmt *pUp;
  160542. sqlite3_finalize(pIter->pSelect);
  160543. sqlite3_finalize(pIter->pInsert);
  160544. sqlite3_finalize(pIter->pDelete);
  160545. sqlite3_finalize(pIter->pTmpInsert);
  160546. pUp = pIter->pRbuUpdate;
  160547. while( pUp ){
  160548. RbuUpdateStmt *pTmp = pUp->pNext;
  160549. sqlite3_finalize(pUp->pUpdate);
  160550. sqlite3_free(pUp);
  160551. pUp = pTmp;
  160552. }
  160553. pIter->pSelect = 0;
  160554. pIter->pInsert = 0;
  160555. pIter->pDelete = 0;
  160556. pIter->pRbuUpdate = 0;
  160557. pIter->pTmpInsert = 0;
  160558. pIter->nCol = 0;
  160559. }
  160560. /*
  160561. ** Clean up any resources allocated as part of the iterator object passed
  160562. ** as the only argument.
  160563. */
  160564. static void rbuObjIterFinalize(RbuObjIter *pIter){
  160565. rbuObjIterClearStatements(pIter);
  160566. sqlite3_finalize(pIter->pTblIter);
  160567. sqlite3_finalize(pIter->pIdxIter);
  160568. rbuObjIterFreeCols(pIter);
  160569. memset(pIter, 0, sizeof(RbuObjIter));
  160570. }
  160571. /*
  160572. ** Advance the iterator to the next position.
  160573. **
  160574. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  160575. ** pointing to the next entry. Otherwise, an error code and message is
  160576. ** left in the RBU handle passed as the first argument. A copy of the
  160577. ** error code is returned.
  160578. */
  160579. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  160580. int rc = p->rc;
  160581. if( rc==SQLITE_OK ){
  160582. /* Free any SQLite statements used while processing the previous object */
  160583. rbuObjIterClearStatements(pIter);
  160584. if( pIter->zIdx==0 ){
  160585. rc = sqlite3_exec(p->dbMain,
  160586. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  160587. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  160588. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  160589. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  160590. , 0, 0, &p->zErrmsg
  160591. );
  160592. }
  160593. if( rc==SQLITE_OK ){
  160594. if( pIter->bCleanup ){
  160595. rbuObjIterFreeCols(pIter);
  160596. pIter->bCleanup = 0;
  160597. rc = sqlite3_step(pIter->pTblIter);
  160598. if( rc!=SQLITE_ROW ){
  160599. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  160600. pIter->zTbl = 0;
  160601. }else{
  160602. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  160603. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  160604. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  160605. }
  160606. }else{
  160607. if( pIter->zIdx==0 ){
  160608. sqlite3_stmt *pIdx = pIter->pIdxIter;
  160609. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  160610. }
  160611. if( rc==SQLITE_OK ){
  160612. rc = sqlite3_step(pIter->pIdxIter);
  160613. if( rc!=SQLITE_ROW ){
  160614. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  160615. pIter->bCleanup = 1;
  160616. pIter->zIdx = 0;
  160617. }else{
  160618. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  160619. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  160620. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  160621. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  160622. }
  160623. }
  160624. }
  160625. }
  160626. }
  160627. if( rc!=SQLITE_OK ){
  160628. rbuObjIterFinalize(pIter);
  160629. p->rc = rc;
  160630. }
  160631. return rc;
  160632. }
  160633. /*
  160634. ** The implementation of the rbu_target_name() SQL function. This function
  160635. ** accepts one or two arguments. The first argument is the name of a table -
  160636. ** the name of a table in the RBU database. The second, if it is present, is 1
  160637. ** for a view or 0 for a table.
  160638. **
  160639. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  160640. **
  160641. ** data[0-9]_<name>
  160642. **
  160643. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  160644. ** Otherwise, if the only argument does not match the above pattern, an SQL
  160645. ** NULL is returned.
  160646. **
  160647. ** "data_t1" -> "t1"
  160648. ** "data0123_t2" -> "t2"
  160649. ** "dataAB_t3" -> NULL
  160650. **
  160651. ** For an rbu vacuum handle, a copy of the first argument is returned if
  160652. ** the second argument is either missing or 0 (not a view).
  160653. */
  160654. static void rbuTargetNameFunc(
  160655. sqlite3_context *pCtx,
  160656. int argc,
  160657. sqlite3_value **argv
  160658. ){
  160659. sqlite3rbu *p = sqlite3_user_data(pCtx);
  160660. const char *zIn;
  160661. assert( argc==1 || argc==2 );
  160662. zIn = (const char*)sqlite3_value_text(argv[0]);
  160663. if( zIn ){
  160664. if( rbuIsVacuum(p) ){
  160665. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  160666. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  160667. }
  160668. }else{
  160669. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  160670. int i;
  160671. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  160672. if( zIn[i]=='_' && zIn[i+1] ){
  160673. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  160674. }
  160675. }
  160676. }
  160677. }
  160678. }
  160679. /*
  160680. ** Initialize the iterator structure passed as the second argument.
  160681. **
  160682. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  160683. ** pointing to the first entry. Otherwise, an error code and message is
  160684. ** left in the RBU handle passed as the first argument. A copy of the
  160685. ** error code is returned.
  160686. */
  160687. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  160688. int rc;
  160689. memset(pIter, 0, sizeof(RbuObjIter));
  160690. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  160691. sqlite3_mprintf(
  160692. "SELECT rbu_target_name(name, type='view') AS target, name "
  160693. "FROM sqlite_master "
  160694. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  160695. " %s "
  160696. "ORDER BY name"
  160697. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  160698. if( rc==SQLITE_OK ){
  160699. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  160700. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  160701. " FROM main.sqlite_master "
  160702. " WHERE type='index' AND tbl_name = ?"
  160703. );
  160704. }
  160705. pIter->bCleanup = 1;
  160706. p->rc = rc;
  160707. return rbuObjIterNext(p, pIter);
  160708. }
  160709. /*
  160710. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  160711. ** an error code is stored in the RBU handle passed as the first argument.
  160712. **
  160713. ** If an error has already occurred (p->rc is already set to something other
  160714. ** than SQLITE_OK), then this function returns NULL without modifying the
  160715. ** stored error code. In this case it still calls sqlite3_free() on any
  160716. ** printf() parameters associated with %z conversions.
  160717. */
  160718. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  160719. char *zSql = 0;
  160720. va_list ap;
  160721. va_start(ap, zFmt);
  160722. zSql = sqlite3_vmprintf(zFmt, ap);
  160723. if( p->rc==SQLITE_OK ){
  160724. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  160725. }else{
  160726. sqlite3_free(zSql);
  160727. zSql = 0;
  160728. }
  160729. va_end(ap);
  160730. return zSql;
  160731. }
  160732. /*
  160733. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  160734. ** arguments are the usual subsitution values. This function performs
  160735. ** the printf() style substitutions and executes the result as an SQL
  160736. ** statement on the RBU handles database.
  160737. **
  160738. ** If an error occurs, an error code and error message is stored in the
  160739. ** RBU handle. If an error has already occurred when this function is
  160740. ** called, it is a no-op.
  160741. */
  160742. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  160743. va_list ap;
  160744. char *zSql;
  160745. va_start(ap, zFmt);
  160746. zSql = sqlite3_vmprintf(zFmt, ap);
  160747. if( p->rc==SQLITE_OK ){
  160748. if( zSql==0 ){
  160749. p->rc = SQLITE_NOMEM;
  160750. }else{
  160751. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  160752. }
  160753. }
  160754. sqlite3_free(zSql);
  160755. va_end(ap);
  160756. return p->rc;
  160757. }
  160758. /*
  160759. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  160760. ** bytes.
  160761. **
  160762. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  160763. ** error code in the rbu handle passed as the first argument. Or, if an
  160764. ** error has already occurred when this function is called, return NULL
  160765. ** immediately without attempting the allocation or modifying the stored
  160766. ** error code.
  160767. */
  160768. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  160769. void *pRet = 0;
  160770. if( p->rc==SQLITE_OK ){
  160771. assert( nByte>0 );
  160772. pRet = sqlite3_malloc64(nByte);
  160773. if( pRet==0 ){
  160774. p->rc = SQLITE_NOMEM;
  160775. }else{
  160776. memset(pRet, 0, nByte);
  160777. }
  160778. }
  160779. return pRet;
  160780. }
  160781. /*
  160782. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  160783. ** there is room for at least nCol elements. If an OOM occurs, store an
  160784. ** error code in the RBU handle passed as the first argument.
  160785. */
  160786. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  160787. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  160788. char **azNew;
  160789. azNew = (char**)rbuMalloc(p, nByte);
  160790. if( azNew ){
  160791. pIter->azTblCol = azNew;
  160792. pIter->azTblType = &azNew[nCol];
  160793. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  160794. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  160795. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  160796. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  160797. }
  160798. }
  160799. /*
  160800. ** The first argument must be a nul-terminated string. This function
  160801. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  160802. ** It is the responsibility of the caller to eventually free this memory
  160803. ** using sqlite3_free().
  160804. **
  160805. ** If an OOM condition is encountered when attempting to allocate memory,
  160806. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  160807. ** if the allocation succeeds, (*pRc) is left unchanged.
  160808. */
  160809. static char *rbuStrndup(const char *zStr, int *pRc){
  160810. char *zRet = 0;
  160811. assert( *pRc==SQLITE_OK );
  160812. if( zStr ){
  160813. size_t nCopy = strlen(zStr) + 1;
  160814. zRet = (char*)sqlite3_malloc64(nCopy);
  160815. if( zRet ){
  160816. memcpy(zRet, zStr, nCopy);
  160817. }else{
  160818. *pRc = SQLITE_NOMEM;
  160819. }
  160820. }
  160821. return zRet;
  160822. }
  160823. /*
  160824. ** Finalize the statement passed as the second argument.
  160825. **
  160826. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  160827. ** rbu handle error code is not already set, set the error code and error
  160828. ** message accordingly.
  160829. */
  160830. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  160831. sqlite3 *db = sqlite3_db_handle(pStmt);
  160832. int rc = sqlite3_finalize(pStmt);
  160833. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  160834. p->rc = rc;
  160835. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  160836. }
  160837. }
  160838. /* Determine the type of a table.
  160839. **
  160840. ** peType is of type (int*), a pointer to an output parameter of type
  160841. ** (int). This call sets the output parameter as follows, depending
  160842. ** on the type of the table specified by parameters dbName and zTbl.
  160843. **
  160844. ** RBU_PK_NOTABLE: No such table.
  160845. ** RBU_PK_NONE: Table has an implicit rowid.
  160846. ** RBU_PK_IPK: Table has an explicit IPK column.
  160847. ** RBU_PK_EXTERNAL: Table has an external PK index.
  160848. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  160849. ** RBU_PK_VTAB: Table is a virtual table.
  160850. **
  160851. ** Argument *piPk is also of type (int*), and also points to an output
  160852. ** parameter. Unless the table has an external primary key index
  160853. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  160854. ** if the table does have an external primary key index, then *piPk
  160855. ** is set to the root page number of the primary key index before
  160856. ** returning.
  160857. **
  160858. ** ALGORITHM:
  160859. **
  160860. ** if( no entry exists in sqlite_master ){
  160861. ** return RBU_PK_NOTABLE
  160862. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  160863. ** return RBU_PK_VTAB
  160864. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  160865. ** if( the index that is the pk exists in sqlite_master ){
  160866. ** *piPK = rootpage of that index.
  160867. ** return RBU_PK_EXTERNAL
  160868. ** }else{
  160869. ** return RBU_PK_WITHOUT_ROWID
  160870. ** }
  160871. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  160872. ** return RBU_PK_IPK
  160873. ** }else{
  160874. ** return RBU_PK_NONE
  160875. ** }
  160876. */
  160877. static void rbuTableType(
  160878. sqlite3rbu *p,
  160879. const char *zTab,
  160880. int *peType,
  160881. int *piTnum,
  160882. int *piPk
  160883. ){
  160884. /*
  160885. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  160886. ** 1) PRAGMA index_list = ?
  160887. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  160888. ** 3) PRAGMA table_info = ?
  160889. */
  160890. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  160891. *peType = RBU_PK_NOTABLE;
  160892. *piPk = 0;
  160893. assert( p->rc==SQLITE_OK );
  160894. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  160895. sqlite3_mprintf(
  160896. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  160897. " FROM sqlite_master"
  160898. " WHERE name=%Q", zTab
  160899. ));
  160900. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  160901. /* Either an error, or no such table. */
  160902. goto rbuTableType_end;
  160903. }
  160904. if( sqlite3_column_int(aStmt[0], 0) ){
  160905. *peType = RBU_PK_VTAB; /* virtual table */
  160906. goto rbuTableType_end;
  160907. }
  160908. *piTnum = sqlite3_column_int(aStmt[0], 1);
  160909. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  160910. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  160911. );
  160912. if( p->rc ) goto rbuTableType_end;
  160913. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  160914. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  160915. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  160916. if( zOrig && zIdx && zOrig[0]=='p' ){
  160917. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  160918. sqlite3_mprintf(
  160919. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  160920. ));
  160921. if( p->rc==SQLITE_OK ){
  160922. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  160923. *piPk = sqlite3_column_int(aStmt[2], 0);
  160924. *peType = RBU_PK_EXTERNAL;
  160925. }else{
  160926. *peType = RBU_PK_WITHOUT_ROWID;
  160927. }
  160928. }
  160929. goto rbuTableType_end;
  160930. }
  160931. }
  160932. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  160933. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  160934. );
  160935. if( p->rc==SQLITE_OK ){
  160936. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  160937. if( sqlite3_column_int(aStmt[3],5)>0 ){
  160938. *peType = RBU_PK_IPK; /* explicit IPK column */
  160939. goto rbuTableType_end;
  160940. }
  160941. }
  160942. *peType = RBU_PK_NONE;
  160943. }
  160944. rbuTableType_end: {
  160945. unsigned int i;
  160946. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  160947. rbuFinalize(p, aStmt[i]);
  160948. }
  160949. }
  160950. }
  160951. /*
  160952. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  160953. ** the pIter->abIndexed[] array.
  160954. */
  160955. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  160956. sqlite3_stmt *pList = 0;
  160957. int bIndex = 0;
  160958. if( p->rc==SQLITE_OK ){
  160959. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  160960. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  160961. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  160962. );
  160963. }
  160964. pIter->nIndex = 0;
  160965. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  160966. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  160967. sqlite3_stmt *pXInfo = 0;
  160968. if( zIdx==0 ) break;
  160969. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  160970. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  160971. );
  160972. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  160973. int iCid = sqlite3_column_int(pXInfo, 1);
  160974. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  160975. }
  160976. rbuFinalize(p, pXInfo);
  160977. bIndex = 1;
  160978. pIter->nIndex++;
  160979. }
  160980. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  160981. /* "PRAGMA index_list" includes the main PK b-tree */
  160982. pIter->nIndex--;
  160983. }
  160984. rbuFinalize(p, pList);
  160985. if( bIndex==0 ) pIter->abIndexed = 0;
  160986. }
  160987. /*
  160988. ** If they are not already populated, populate the pIter->azTblCol[],
  160989. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  160990. ** the table (not index) that the iterator currently points to.
  160991. **
  160992. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  160993. ** an error does occur, an error code and error message are also left in
  160994. ** the RBU handle.
  160995. */
  160996. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  160997. if( pIter->azTblCol==0 ){
  160998. sqlite3_stmt *pStmt = 0;
  160999. int nCol = 0;
  161000. int i; /* for() loop iterator variable */
  161001. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  161002. int iOrder = 0;
  161003. int iTnum = 0;
  161004. /* Figure out the type of table this step will deal with. */
  161005. assert( pIter->eType==0 );
  161006. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  161007. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  161008. p->rc = SQLITE_ERROR;
  161009. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  161010. }
  161011. if( p->rc ) return p->rc;
  161012. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  161013. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  161014. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  161015. || pIter->eType==RBU_PK_VTAB
  161016. );
  161017. /* Populate the azTblCol[] and nTblCol variables based on the columns
  161018. ** of the input table. Ignore any input table columns that begin with
  161019. ** "rbu_". */
  161020. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161021. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  161022. );
  161023. if( p->rc==SQLITE_OK ){
  161024. nCol = sqlite3_column_count(pStmt);
  161025. rbuAllocateIterArrays(p, pIter, nCol);
  161026. }
  161027. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  161028. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  161029. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  161030. char *zCopy = rbuStrndup(zName, &p->rc);
  161031. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  161032. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  161033. }
  161034. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  161035. bRbuRowid = 1;
  161036. }
  161037. }
  161038. sqlite3_finalize(pStmt);
  161039. pStmt = 0;
  161040. if( p->rc==SQLITE_OK
  161041. && rbuIsVacuum(p)==0
  161042. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  161043. ){
  161044. p->rc = SQLITE_ERROR;
  161045. p->zErrmsg = sqlite3_mprintf(
  161046. "table %q %s rbu_rowid column", pIter->zDataTbl,
  161047. (bRbuRowid ? "may not have" : "requires")
  161048. );
  161049. }
  161050. /* Check that all non-HIDDEN columns in the destination table are also
  161051. ** present in the input table. Populate the abTblPk[], azTblType[] and
  161052. ** aiTblOrder[] arrays at the same time. */
  161053. if( p->rc==SQLITE_OK ){
  161054. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  161055. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  161056. );
  161057. }
  161058. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  161059. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  161060. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  161061. for(i=iOrder; i<pIter->nTblCol; i++){
  161062. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  161063. }
  161064. if( i==pIter->nTblCol ){
  161065. p->rc = SQLITE_ERROR;
  161066. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  161067. pIter->zDataTbl, zName
  161068. );
  161069. }else{
  161070. int iPk = sqlite3_column_int(pStmt, 5);
  161071. int bNotNull = sqlite3_column_int(pStmt, 3);
  161072. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  161073. if( i!=iOrder ){
  161074. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  161075. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  161076. }
  161077. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  161078. pIter->abTblPk[iOrder] = (iPk!=0);
  161079. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  161080. iOrder++;
  161081. }
  161082. }
  161083. rbuFinalize(p, pStmt);
  161084. rbuObjIterCacheIndexedCols(p, pIter);
  161085. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  161086. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  161087. }
  161088. return p->rc;
  161089. }
  161090. /*
  161091. ** This function constructs and returns a pointer to a nul-terminated
  161092. ** string containing some SQL clause or list based on one or more of the
  161093. ** column names currently stored in the pIter->azTblCol[] array.
  161094. */
  161095. static char *rbuObjIterGetCollist(
  161096. sqlite3rbu *p, /* RBU object */
  161097. RbuObjIter *pIter /* Object iterator for column names */
  161098. ){
  161099. char *zList = 0;
  161100. const char *zSep = "";
  161101. int i;
  161102. for(i=0; i<pIter->nTblCol; i++){
  161103. const char *z = pIter->azTblCol[i];
  161104. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  161105. zSep = ", ";
  161106. }
  161107. return zList;
  161108. }
  161109. /*
  161110. ** This function is used to create a SELECT list (the list of SQL
  161111. ** expressions that follows a SELECT keyword) for a SELECT statement
  161112. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  161113. ** index object currently indicated by the iterator object passed as the
  161114. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  161115. ** to obtain the required information.
  161116. **
  161117. ** If the index is of the following form:
  161118. **
  161119. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  161120. **
  161121. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  161122. ** "ipk", the returned string is:
  161123. **
  161124. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  161125. **
  161126. ** As well as the returned string, three other malloc'd strings are
  161127. ** returned via output parameters. As follows:
  161128. **
  161129. ** pzImposterCols: ...
  161130. ** pzImposterPk: ...
  161131. ** pzWhere: ...
  161132. */
  161133. static char *rbuObjIterGetIndexCols(
  161134. sqlite3rbu *p, /* RBU object */
  161135. RbuObjIter *pIter, /* Object iterator for column names */
  161136. char **pzImposterCols, /* OUT: Columns for imposter table */
  161137. char **pzImposterPk, /* OUT: Imposter PK clause */
  161138. char **pzWhere, /* OUT: WHERE clause */
  161139. int *pnBind /* OUT: Trbul number of columns */
  161140. ){
  161141. int rc = p->rc; /* Error code */
  161142. int rc2; /* sqlite3_finalize() return code */
  161143. char *zRet = 0; /* String to return */
  161144. char *zImpCols = 0; /* String to return via *pzImposterCols */
  161145. char *zImpPK = 0; /* String to return via *pzImposterPK */
  161146. char *zWhere = 0; /* String to return via *pzWhere */
  161147. int nBind = 0; /* Value to return via *pnBind */
  161148. const char *zCom = ""; /* Set to ", " later on */
  161149. const char *zAnd = ""; /* Set to " AND " later on */
  161150. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  161151. if( rc==SQLITE_OK ){
  161152. assert( p->zErrmsg==0 );
  161153. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  161154. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  161155. );
  161156. }
  161157. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  161158. int iCid = sqlite3_column_int(pXInfo, 1);
  161159. int bDesc = sqlite3_column_int(pXInfo, 3);
  161160. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  161161. const char *zCol;
  161162. const char *zType;
  161163. if( iCid<0 ){
  161164. /* An integer primary key. If the table has an explicit IPK, use
  161165. ** its name. Otherwise, use "rbu_rowid". */
  161166. if( pIter->eType==RBU_PK_IPK ){
  161167. int i;
  161168. for(i=0; pIter->abTblPk[i]==0; i++);
  161169. assert( i<pIter->nTblCol );
  161170. zCol = pIter->azTblCol[i];
  161171. }else if( rbuIsVacuum(p) ){
  161172. zCol = "_rowid_";
  161173. }else{
  161174. zCol = "rbu_rowid";
  161175. }
  161176. zType = "INTEGER";
  161177. }else{
  161178. zCol = pIter->azTblCol[iCid];
  161179. zType = pIter->azTblType[iCid];
  161180. }
  161181. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  161182. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  161183. const char *zOrder = (bDesc ? " DESC" : "");
  161184. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  161185. zImpPK, zCom, nBind, zCol, zOrder
  161186. );
  161187. }
  161188. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  161189. zImpCols, zCom, nBind, zCol, zType, zCollate
  161190. );
  161191. zWhere = sqlite3_mprintf(
  161192. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  161193. );
  161194. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  161195. zCom = ", ";
  161196. zAnd = " AND ";
  161197. nBind++;
  161198. }
  161199. rc2 = sqlite3_finalize(pXInfo);
  161200. if( rc==SQLITE_OK ) rc = rc2;
  161201. if( rc!=SQLITE_OK ){
  161202. sqlite3_free(zRet);
  161203. sqlite3_free(zImpCols);
  161204. sqlite3_free(zImpPK);
  161205. sqlite3_free(zWhere);
  161206. zRet = 0;
  161207. zImpCols = 0;
  161208. zImpPK = 0;
  161209. zWhere = 0;
  161210. p->rc = rc;
  161211. }
  161212. *pzImposterCols = zImpCols;
  161213. *pzImposterPk = zImpPK;
  161214. *pzWhere = zWhere;
  161215. *pnBind = nBind;
  161216. return zRet;
  161217. }
  161218. /*
  161219. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  161220. ** paramter is passed "old", return a string of the form:
  161221. **
  161222. ** "old.a, old.b, old.b"
  161223. **
  161224. ** With the column names escaped.
  161225. **
  161226. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  161227. ** the text ", old._rowid_" to the returned value.
  161228. */
  161229. static char *rbuObjIterGetOldlist(
  161230. sqlite3rbu *p,
  161231. RbuObjIter *pIter,
  161232. const char *zObj
  161233. ){
  161234. char *zList = 0;
  161235. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  161236. const char *zS = "";
  161237. int i;
  161238. for(i=0; i<pIter->nTblCol; i++){
  161239. if( pIter->abIndexed[i] ){
  161240. const char *zCol = pIter->azTblCol[i];
  161241. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  161242. }else{
  161243. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  161244. }
  161245. zS = ", ";
  161246. if( zList==0 ){
  161247. p->rc = SQLITE_NOMEM;
  161248. break;
  161249. }
  161250. }
  161251. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  161252. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  161253. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  161254. }
  161255. }
  161256. return zList;
  161257. }
  161258. /*
  161259. ** Return an expression that can be used in a WHERE clause to match the
  161260. ** primary key of the current table. For example, if the table is:
  161261. **
  161262. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  161263. **
  161264. ** Return the string:
  161265. **
  161266. ** "b = ?1 AND c = ?2"
  161267. */
  161268. static char *rbuObjIterGetWhere(
  161269. sqlite3rbu *p,
  161270. RbuObjIter *pIter
  161271. ){
  161272. char *zList = 0;
  161273. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  161274. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  161275. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  161276. const char *zSep = "";
  161277. int i;
  161278. for(i=0; i<pIter->nTblCol; i++){
  161279. if( pIter->abTblPk[i] ){
  161280. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  161281. zSep = " AND ";
  161282. }
  161283. }
  161284. zList = rbuMPrintf(p,
  161285. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  161286. );
  161287. }else{
  161288. const char *zSep = "";
  161289. int i;
  161290. for(i=0; i<pIter->nTblCol; i++){
  161291. if( pIter->abTblPk[i] ){
  161292. const char *zCol = pIter->azTblCol[i];
  161293. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  161294. zSep = " AND ";
  161295. }
  161296. }
  161297. }
  161298. return zList;
  161299. }
  161300. /*
  161301. ** The SELECT statement iterating through the keys for the current object
  161302. ** (p->objiter.pSelect) currently points to a valid row. However, there
  161303. ** is something wrong with the rbu_control value in the rbu_control value
  161304. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  161305. ** of the RBU handle to something reflecting this.
  161306. */
  161307. static void rbuBadControlError(sqlite3rbu *p){
  161308. p->rc = SQLITE_ERROR;
  161309. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  161310. }
  161311. /*
  161312. ** Return a nul-terminated string containing the comma separated list of
  161313. ** assignments that should be included following the "SET" keyword of
  161314. ** an UPDATE statement used to update the table object that the iterator
  161315. ** passed as the second argument currently points to if the rbu_control
  161316. ** column of the data_xxx table entry is set to zMask.
  161317. **
  161318. ** The memory for the returned string is obtained from sqlite3_malloc().
  161319. ** It is the responsibility of the caller to eventually free it using
  161320. ** sqlite3_free().
  161321. **
  161322. ** If an OOM error is encountered when allocating space for the new
  161323. ** string, an error code is left in the rbu handle passed as the first
  161324. ** argument and NULL is returned. Or, if an error has already occurred
  161325. ** when this function is called, NULL is returned immediately, without
  161326. ** attempting the allocation or modifying the stored error code.
  161327. */
  161328. static char *rbuObjIterGetSetlist(
  161329. sqlite3rbu *p,
  161330. RbuObjIter *pIter,
  161331. const char *zMask
  161332. ){
  161333. char *zList = 0;
  161334. if( p->rc==SQLITE_OK ){
  161335. int i;
  161336. if( (int)strlen(zMask)!=pIter->nTblCol ){
  161337. rbuBadControlError(p);
  161338. }else{
  161339. const char *zSep = "";
  161340. for(i=0; i<pIter->nTblCol; i++){
  161341. char c = zMask[pIter->aiSrcOrder[i]];
  161342. if( c=='x' ){
  161343. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  161344. zList, zSep, pIter->azTblCol[i], i+1
  161345. );
  161346. zSep = ", ";
  161347. }
  161348. else if( c=='d' ){
  161349. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  161350. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  161351. );
  161352. zSep = ", ";
  161353. }
  161354. else if( c=='f' ){
  161355. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  161356. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  161357. );
  161358. zSep = ", ";
  161359. }
  161360. }
  161361. }
  161362. }
  161363. return zList;
  161364. }
  161365. /*
  161366. ** Return a nul-terminated string consisting of nByte comma separated
  161367. ** "?" expressions. For example, if nByte is 3, return a pointer to
  161368. ** a buffer containing the string "?,?,?".
  161369. **
  161370. ** The memory for the returned string is obtained from sqlite3_malloc().
  161371. ** It is the responsibility of the caller to eventually free it using
  161372. ** sqlite3_free().
  161373. **
  161374. ** If an OOM error is encountered when allocating space for the new
  161375. ** string, an error code is left in the rbu handle passed as the first
  161376. ** argument and NULL is returned. Or, if an error has already occurred
  161377. ** when this function is called, NULL is returned immediately, without
  161378. ** attempting the allocation or modifying the stored error code.
  161379. */
  161380. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  161381. char *zRet = 0;
  161382. int nByte = nBind*2 + 1;
  161383. zRet = (char*)rbuMalloc(p, nByte);
  161384. if( zRet ){
  161385. int i;
  161386. for(i=0; i<nBind; i++){
  161387. zRet[i*2] = '?';
  161388. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  161389. }
  161390. }
  161391. return zRet;
  161392. }
  161393. /*
  161394. ** The iterator currently points to a table (not index) of type
  161395. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  161396. ** declaration for the corresponding imposter table. For example,
  161397. ** if the iterator points to a table created as:
  161398. **
  161399. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  161400. **
  161401. ** this function returns:
  161402. **
  161403. ** PRIMARY KEY("b", "a" DESC)
  161404. */
  161405. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  161406. char *z = 0;
  161407. assert( pIter->zIdx==0 );
  161408. if( p->rc==SQLITE_OK ){
  161409. const char *zSep = "PRIMARY KEY(";
  161410. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  161411. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  161412. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  161413. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  161414. );
  161415. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  161416. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  161417. if( zOrig && strcmp(zOrig, "pk")==0 ){
  161418. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  161419. if( zIdx ){
  161420. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  161421. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  161422. );
  161423. }
  161424. break;
  161425. }
  161426. }
  161427. rbuFinalize(p, pXList);
  161428. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  161429. if( sqlite3_column_int(pXInfo, 5) ){
  161430. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  161431. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  161432. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  161433. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  161434. zSep = ", ";
  161435. }
  161436. }
  161437. z = rbuMPrintf(p, "%z)", z);
  161438. rbuFinalize(p, pXInfo);
  161439. }
  161440. return z;
  161441. }
  161442. /*
  161443. ** This function creates the second imposter table used when writing to
  161444. ** a table b-tree where the table has an external primary key. If the
  161445. ** iterator passed as the second argument does not currently point to
  161446. ** a table (not index) with an external primary key, this function is a
  161447. ** no-op.
  161448. **
  161449. ** Assuming the iterator does point to a table with an external PK, this
  161450. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  161451. ** used to access that PK index. For example, if the target table is
  161452. ** declared as follows:
  161453. **
  161454. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  161455. **
  161456. ** then the imposter table schema is:
  161457. **
  161458. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  161459. **
  161460. */
  161461. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  161462. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  161463. int tnum = pIter->iPkTnum; /* Root page of PK index */
  161464. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  161465. const char *zIdx = 0; /* Name of PK index */
  161466. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  161467. const char *zComma = "";
  161468. char *zCols = 0; /* Used to build up list of table cols */
  161469. char *zPk = 0; /* Used to build up table PK declaration */
  161470. /* Figure out the name of the primary key index for the current table.
  161471. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  161472. ** zIdx to point to a nul-terminated string containing this name. */
  161473. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  161474. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  161475. );
  161476. if( p->rc==SQLITE_OK ){
  161477. sqlite3_bind_int(pQuery, 1, tnum);
  161478. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  161479. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  161480. }
  161481. }
  161482. if( zIdx ){
  161483. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  161484. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  161485. );
  161486. }
  161487. rbuFinalize(p, pQuery);
  161488. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  161489. int bKey = sqlite3_column_int(pXInfo, 5);
  161490. if( bKey ){
  161491. int iCid = sqlite3_column_int(pXInfo, 1);
  161492. int bDesc = sqlite3_column_int(pXInfo, 3);
  161493. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  161494. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  161495. iCid, pIter->azTblType[iCid], zCollate
  161496. );
  161497. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  161498. zComma = ", ";
  161499. }
  161500. }
  161501. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  161502. rbuFinalize(p, pXInfo);
  161503. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  161504. rbuMPrintfExec(p, p->dbMain,
  161505. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  161506. zCols, zPk
  161507. );
  161508. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  161509. }
  161510. }
  161511. /*
  161512. ** If an error has already occurred when this function is called, it
  161513. ** immediately returns zero (without doing any work). Or, if an error
  161514. ** occurs during the execution of this function, it sets the error code
  161515. ** in the sqlite3rbu object indicated by the first argument and returns
  161516. ** zero.
  161517. **
  161518. ** The iterator passed as the second argument is guaranteed to point to
  161519. ** a table (not an index) when this function is called. This function
  161520. ** attempts to create any imposter table required to write to the main
  161521. ** table b-tree of the table before returning. Non-zero is returned if
  161522. ** an imposter table are created, or zero otherwise.
  161523. **
  161524. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  161525. ** virtual tables are written to directly. The imposter table has the
  161526. ** same schema as the actual target table (less any UNIQUE constraints).
  161527. ** More precisely, the "same schema" means the same columns, types,
  161528. ** collation sequences. For tables that do not have an external PRIMARY
  161529. ** KEY, it also means the same PRIMARY KEY declaration.
  161530. */
  161531. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  161532. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  161533. int tnum = pIter->iTnum;
  161534. const char *zComma = "";
  161535. char *zSql = 0;
  161536. int iCol;
  161537. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  161538. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  161539. const char *zPk = "";
  161540. const char *zCol = pIter->azTblCol[iCol];
  161541. const char *zColl = 0;
  161542. p->rc = sqlite3_table_column_metadata(
  161543. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  161544. );
  161545. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  161546. /* If the target table column is an "INTEGER PRIMARY KEY", add
  161547. ** "PRIMARY KEY" to the imposter table column declaration. */
  161548. zPk = "PRIMARY KEY ";
  161549. }
  161550. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  161551. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  161552. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  161553. );
  161554. zComma = ", ";
  161555. }
  161556. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  161557. char *zPk = rbuWithoutRowidPK(p, pIter);
  161558. if( zPk ){
  161559. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  161560. }
  161561. }
  161562. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  161563. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  161564. pIter->zTbl, zSql,
  161565. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  161566. );
  161567. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  161568. }
  161569. }
  161570. /*
  161571. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  161572. ** Specifically a statement of the form:
  161573. **
  161574. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  161575. **
  161576. ** The number of bound variables is equal to the number of columns in
  161577. ** the target table, plus one (for the rbu_control column), plus one more
  161578. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  161579. ** virtual table.
  161580. */
  161581. static void rbuObjIterPrepareTmpInsert(
  161582. sqlite3rbu *p,
  161583. RbuObjIter *pIter,
  161584. const char *zCollist,
  161585. const char *zRbuRowid
  161586. ){
  161587. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  161588. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  161589. if( zBind ){
  161590. assert( pIter->pTmpInsert==0 );
  161591. p->rc = prepareFreeAndCollectError(
  161592. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  161593. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  161594. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  161595. ));
  161596. }
  161597. }
  161598. static void rbuTmpInsertFunc(
  161599. sqlite3_context *pCtx,
  161600. int nVal,
  161601. sqlite3_value **apVal
  161602. ){
  161603. sqlite3rbu *p = sqlite3_user_data(pCtx);
  161604. int rc = SQLITE_OK;
  161605. int i;
  161606. assert( sqlite3_value_int(apVal[0])!=0
  161607. || p->objiter.eType==RBU_PK_EXTERNAL
  161608. || p->objiter.eType==RBU_PK_NONE
  161609. );
  161610. if( sqlite3_value_int(apVal[0])!=0 ){
  161611. p->nPhaseOneStep += p->objiter.nIndex;
  161612. }
  161613. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  161614. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  161615. }
  161616. if( rc==SQLITE_OK ){
  161617. sqlite3_step(p->objiter.pTmpInsert);
  161618. rc = sqlite3_reset(p->objiter.pTmpInsert);
  161619. }
  161620. if( rc!=SQLITE_OK ){
  161621. sqlite3_result_error_code(pCtx, rc);
  161622. }
  161623. }
  161624. /*
  161625. ** Ensure that the SQLite statement handles required to update the
  161626. ** target database object currently indicated by the iterator passed
  161627. ** as the second argument are available.
  161628. */
  161629. static int rbuObjIterPrepareAll(
  161630. sqlite3rbu *p,
  161631. RbuObjIter *pIter,
  161632. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  161633. ){
  161634. assert( pIter->bCleanup==0 );
  161635. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  161636. const int tnum = pIter->iTnum;
  161637. char *zCollist = 0; /* List of indexed columns */
  161638. char **pz = &p->zErrmsg;
  161639. const char *zIdx = pIter->zIdx;
  161640. char *zLimit = 0;
  161641. if( nOffset ){
  161642. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  161643. if( !zLimit ) p->rc = SQLITE_NOMEM;
  161644. }
  161645. if( zIdx ){
  161646. const char *zTbl = pIter->zTbl;
  161647. char *zImposterCols = 0; /* Columns for imposter table */
  161648. char *zImposterPK = 0; /* Primary key declaration for imposter */
  161649. char *zWhere = 0; /* WHERE clause on PK columns */
  161650. char *zBind = 0;
  161651. int nBind = 0;
  161652. assert( pIter->eType!=RBU_PK_VTAB );
  161653. zCollist = rbuObjIterGetIndexCols(
  161654. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  161655. );
  161656. zBind = rbuObjIterGetBindlist(p, nBind);
  161657. /* Create the imposter table used to write to this index. */
  161658. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  161659. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  161660. rbuMPrintfExec(p, p->dbMain,
  161661. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  161662. zTbl, zImposterCols, zImposterPK
  161663. );
  161664. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  161665. /* Create the statement to insert index entries */
  161666. pIter->nCol = nBind;
  161667. if( p->rc==SQLITE_OK ){
  161668. p->rc = prepareFreeAndCollectError(
  161669. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  161670. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  161671. );
  161672. }
  161673. /* And to delete index entries */
  161674. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  161675. p->rc = prepareFreeAndCollectError(
  161676. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  161677. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  161678. );
  161679. }
  161680. /* Create the SELECT statement to read keys in sorted order */
  161681. if( p->rc==SQLITE_OK ){
  161682. char *zSql;
  161683. if( rbuIsVacuum(p) ){
  161684. zSql = sqlite3_mprintf(
  161685. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  161686. zCollist,
  161687. pIter->zDataTbl,
  161688. zCollist, zLimit
  161689. );
  161690. }else
  161691. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  161692. zSql = sqlite3_mprintf(
  161693. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  161694. zCollist, p->zStateDb, pIter->zDataTbl,
  161695. zCollist, zLimit
  161696. );
  161697. }else{
  161698. zSql = sqlite3_mprintf(
  161699. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  161700. "UNION ALL "
  161701. "SELECT %s, rbu_control FROM '%q' "
  161702. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  161703. "ORDER BY %s%s",
  161704. zCollist, p->zStateDb, pIter->zDataTbl,
  161705. zCollist, pIter->zDataTbl,
  161706. zCollist, zLimit
  161707. );
  161708. }
  161709. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  161710. }
  161711. sqlite3_free(zImposterCols);
  161712. sqlite3_free(zImposterPK);
  161713. sqlite3_free(zWhere);
  161714. sqlite3_free(zBind);
  161715. }else{
  161716. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  161717. ||(pIter->eType==RBU_PK_NONE)
  161718. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  161719. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  161720. const char *zWrite; /* Imposter table name */
  161721. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  161722. char *zWhere = rbuObjIterGetWhere(p, pIter);
  161723. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  161724. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  161725. zCollist = rbuObjIterGetCollist(p, pIter);
  161726. pIter->nCol = pIter->nTblCol;
  161727. /* Create the imposter table or tables (if required). */
  161728. rbuCreateImposterTable(p, pIter);
  161729. rbuCreateImposterTable2(p, pIter);
  161730. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  161731. /* Create the INSERT statement to write to the target PK b-tree */
  161732. if( p->rc==SQLITE_OK ){
  161733. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  161734. sqlite3_mprintf(
  161735. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  161736. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  161737. )
  161738. );
  161739. }
  161740. /* Create the DELETE statement to write to the target PK b-tree.
  161741. ** Because it only performs INSERT operations, this is not required for
  161742. ** an rbu vacuum handle. */
  161743. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  161744. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  161745. sqlite3_mprintf(
  161746. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  161747. )
  161748. );
  161749. }
  161750. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  161751. const char *zRbuRowid = "";
  161752. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  161753. zRbuRowid = ", rbu_rowid";
  161754. }
  161755. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  161756. rbuMPrintfExec(p, p->dbRbu,
  161757. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  161758. "SELECT *%s FROM '%q' WHERE 0;"
  161759. , p->zStateDb, pIter->zDataTbl
  161760. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  161761. , pIter->zDataTbl
  161762. );
  161763. rbuMPrintfExec(p, p->dbMain,
  161764. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  161765. "BEGIN "
  161766. " SELECT rbu_tmp_insert(3, %s);"
  161767. "END;"
  161768. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  161769. "BEGIN "
  161770. " SELECT rbu_tmp_insert(3, %s);"
  161771. "END;"
  161772. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  161773. "BEGIN "
  161774. " SELECT rbu_tmp_insert(4, %s);"
  161775. "END;",
  161776. zWrite, zTbl, zOldlist,
  161777. zWrite, zTbl, zOldlist,
  161778. zWrite, zTbl, zNewlist
  161779. );
  161780. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  161781. rbuMPrintfExec(p, p->dbMain,
  161782. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  161783. "BEGIN "
  161784. " SELECT rbu_tmp_insert(0, %s);"
  161785. "END;",
  161786. zWrite, zTbl, zNewlist
  161787. );
  161788. }
  161789. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  161790. }
  161791. /* Create the SELECT statement to read keys from data_xxx */
  161792. if( p->rc==SQLITE_OK ){
  161793. const char *zRbuRowid = "";
  161794. if( bRbuRowid ){
  161795. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  161796. }
  161797. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  161798. sqlite3_mprintf(
  161799. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  161800. zCollist,
  161801. (rbuIsVacuum(p) ? "0 AS " : ""),
  161802. zRbuRowid,
  161803. pIter->zDataTbl, zLimit
  161804. )
  161805. );
  161806. }
  161807. sqlite3_free(zWhere);
  161808. sqlite3_free(zOldlist);
  161809. sqlite3_free(zNewlist);
  161810. sqlite3_free(zBindings);
  161811. }
  161812. sqlite3_free(zCollist);
  161813. sqlite3_free(zLimit);
  161814. }
  161815. return p->rc;
  161816. }
  161817. /*
  161818. ** Set output variable *ppStmt to point to an UPDATE statement that may
  161819. ** be used to update the imposter table for the main table b-tree of the
  161820. ** table object that pIter currently points to, assuming that the
  161821. ** rbu_control column of the data_xyz table contains zMask.
  161822. **
  161823. ** If the zMask string does not specify any columns to update, then this
  161824. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  161825. */
  161826. static int rbuGetUpdateStmt(
  161827. sqlite3rbu *p, /* RBU handle */
  161828. RbuObjIter *pIter, /* Object iterator */
  161829. const char *zMask, /* rbu_control value ('x.x.') */
  161830. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  161831. ){
  161832. RbuUpdateStmt **pp;
  161833. RbuUpdateStmt *pUp = 0;
  161834. int nUp = 0;
  161835. /* In case an error occurs */
  161836. *ppStmt = 0;
  161837. /* Search for an existing statement. If one is found, shift it to the front
  161838. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  161839. ** to the number of statements currently in the cache and pUp to the
  161840. ** last object in the list. */
  161841. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  161842. pUp = *pp;
  161843. if( strcmp(pUp->zMask, zMask)==0 ){
  161844. *pp = pUp->pNext;
  161845. pUp->pNext = pIter->pRbuUpdate;
  161846. pIter->pRbuUpdate = pUp;
  161847. *ppStmt = pUp->pUpdate;
  161848. return SQLITE_OK;
  161849. }
  161850. nUp++;
  161851. }
  161852. assert( pUp==0 || pUp->pNext==0 );
  161853. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  161854. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  161855. *pp = 0;
  161856. sqlite3_finalize(pUp->pUpdate);
  161857. pUp->pUpdate = 0;
  161858. }else{
  161859. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  161860. }
  161861. if( pUp ){
  161862. char *zWhere = rbuObjIterGetWhere(p, pIter);
  161863. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  161864. char *zUpdate = 0;
  161865. pUp->zMask = (char*)&pUp[1];
  161866. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  161867. pUp->pNext = pIter->pRbuUpdate;
  161868. pIter->pRbuUpdate = pUp;
  161869. if( zSet ){
  161870. const char *zPrefix = "";
  161871. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  161872. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  161873. zPrefix, pIter->zTbl, zSet, zWhere
  161874. );
  161875. p->rc = prepareFreeAndCollectError(
  161876. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  161877. );
  161878. *ppStmt = pUp->pUpdate;
  161879. }
  161880. sqlite3_free(zWhere);
  161881. sqlite3_free(zSet);
  161882. }
  161883. return p->rc;
  161884. }
  161885. static sqlite3 *rbuOpenDbhandle(
  161886. sqlite3rbu *p,
  161887. const char *zName,
  161888. int bUseVfs
  161889. ){
  161890. sqlite3 *db = 0;
  161891. if( p->rc==SQLITE_OK ){
  161892. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  161893. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  161894. if( p->rc ){
  161895. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  161896. sqlite3_close(db);
  161897. db = 0;
  161898. }
  161899. }
  161900. return db;
  161901. }
  161902. /*
  161903. ** Free an RbuState object allocated by rbuLoadState().
  161904. */
  161905. static void rbuFreeState(RbuState *p){
  161906. if( p ){
  161907. sqlite3_free(p->zTbl);
  161908. sqlite3_free(p->zIdx);
  161909. sqlite3_free(p);
  161910. }
  161911. }
  161912. /*
  161913. ** Allocate an RbuState object and load the contents of the rbu_state
  161914. ** table into it. Return a pointer to the new object. It is the
  161915. ** responsibility of the caller to eventually free the object using
  161916. ** sqlite3_free().
  161917. **
  161918. ** If an error occurs, leave an error code and message in the rbu handle
  161919. ** and return NULL.
  161920. */
  161921. static RbuState *rbuLoadState(sqlite3rbu *p){
  161922. RbuState *pRet = 0;
  161923. sqlite3_stmt *pStmt = 0;
  161924. int rc;
  161925. int rc2;
  161926. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  161927. if( pRet==0 ) return 0;
  161928. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161929. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  161930. );
  161931. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  161932. switch( sqlite3_column_int(pStmt, 0) ){
  161933. case RBU_STATE_STAGE:
  161934. pRet->eStage = sqlite3_column_int(pStmt, 1);
  161935. if( pRet->eStage!=RBU_STAGE_OAL
  161936. && pRet->eStage!=RBU_STAGE_MOVE
  161937. && pRet->eStage!=RBU_STAGE_CKPT
  161938. ){
  161939. p->rc = SQLITE_CORRUPT;
  161940. }
  161941. break;
  161942. case RBU_STATE_TBL:
  161943. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  161944. break;
  161945. case RBU_STATE_IDX:
  161946. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  161947. break;
  161948. case RBU_STATE_ROW:
  161949. pRet->nRow = sqlite3_column_int(pStmt, 1);
  161950. break;
  161951. case RBU_STATE_PROGRESS:
  161952. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  161953. break;
  161954. case RBU_STATE_CKPT:
  161955. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  161956. break;
  161957. case RBU_STATE_COOKIE:
  161958. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  161959. break;
  161960. case RBU_STATE_OALSZ:
  161961. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  161962. break;
  161963. case RBU_STATE_PHASEONESTEP:
  161964. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  161965. break;
  161966. default:
  161967. rc = SQLITE_CORRUPT;
  161968. break;
  161969. }
  161970. }
  161971. rc2 = sqlite3_finalize(pStmt);
  161972. if( rc==SQLITE_OK ) rc = rc2;
  161973. p->rc = rc;
  161974. return pRet;
  161975. }
  161976. /*
  161977. ** Open the database handle and attach the RBU database as "rbu". If an
  161978. ** error occurs, leave an error code and message in the RBU handle.
  161979. */
  161980. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  161981. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  161982. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  161983. /* Open the RBU database */
  161984. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  161985. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  161986. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  161987. if( p->zState==0 ){
  161988. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  161989. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  161990. }
  161991. }
  161992. /* If using separate RBU and state databases, attach the state database to
  161993. ** the RBU db handle now. */
  161994. if( p->zState ){
  161995. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  161996. memcpy(p->zStateDb, "stat", 4);
  161997. }else{
  161998. memcpy(p->zStateDb, "main", 4);
  161999. }
  162000. #if 0
  162001. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  162002. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  162003. }
  162004. #endif
  162005. /* If it has not already been created, create the rbu_state table */
  162006. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  162007. #if 0
  162008. if( rbuIsVacuum(p) ){
  162009. if( p->rc==SQLITE_OK ){
  162010. int rc2;
  162011. int bOk = 0;
  162012. sqlite3_stmt *pCnt = 0;
  162013. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  162014. "SELECT count(*) FROM stat.sqlite_master"
  162015. );
  162016. if( p->rc==SQLITE_OK
  162017. && sqlite3_step(pCnt)==SQLITE_ROW
  162018. && 1==sqlite3_column_int(pCnt, 0)
  162019. ){
  162020. bOk = 1;
  162021. }
  162022. rc2 = sqlite3_finalize(pCnt);
  162023. if( p->rc==SQLITE_OK ) p->rc = rc2;
  162024. if( p->rc==SQLITE_OK && bOk==0 ){
  162025. p->rc = SQLITE_ERROR;
  162026. p->zErrmsg = sqlite3_mprintf("invalid state database");
  162027. }
  162028. if( p->rc==SQLITE_OK ){
  162029. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  162030. }
  162031. }
  162032. }
  162033. #endif
  162034. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  162035. int bOpen = 0;
  162036. int rc;
  162037. p->nRbu = 0;
  162038. p->pRbuFd = 0;
  162039. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  162040. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  162041. if( p->eStage>=RBU_STAGE_MOVE ){
  162042. bOpen = 1;
  162043. }else{
  162044. RbuState *pState = rbuLoadState(p);
  162045. if( pState ){
  162046. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  162047. rbuFreeState(pState);
  162048. }
  162049. }
  162050. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  162051. }
  162052. p->eStage = 0;
  162053. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  162054. if( !rbuIsVacuum(p) ){
  162055. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  162056. }else if( p->pRbuFd->pWalFd ){
  162057. if( pbRetry ){
  162058. p->pRbuFd->bNolock = 0;
  162059. sqlite3_close(p->dbRbu);
  162060. sqlite3_close(p->dbMain);
  162061. p->dbMain = 0;
  162062. p->dbRbu = 0;
  162063. *pbRetry = 1;
  162064. return;
  162065. }
  162066. p->rc = SQLITE_ERROR;
  162067. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  162068. }else{
  162069. char *zTarget;
  162070. char *zExtra = 0;
  162071. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  162072. zExtra = &p->zRbu[5];
  162073. while( *zExtra ){
  162074. if( *zExtra++=='?' ) break;
  162075. }
  162076. if( *zExtra=='\0' ) zExtra = 0;
  162077. }
  162078. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  162079. sqlite3_db_filename(p->dbRbu, "main"),
  162080. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  162081. );
  162082. if( zTarget==0 ){
  162083. p->rc = SQLITE_NOMEM;
  162084. return;
  162085. }
  162086. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  162087. sqlite3_free(zTarget);
  162088. }
  162089. }
  162090. if( p->rc==SQLITE_OK ){
  162091. p->rc = sqlite3_create_function(p->dbMain,
  162092. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  162093. );
  162094. }
  162095. if( p->rc==SQLITE_OK ){
  162096. p->rc = sqlite3_create_function(p->dbMain,
  162097. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  162098. );
  162099. }
  162100. if( p->rc==SQLITE_OK ){
  162101. p->rc = sqlite3_create_function(p->dbRbu,
  162102. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  162103. );
  162104. }
  162105. if( p->rc==SQLITE_OK ){
  162106. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  162107. }
  162108. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  162109. /* Mark the database file just opened as an RBU target database. If
  162110. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  162111. ** This is an error. */
  162112. if( p->rc==SQLITE_OK ){
  162113. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  162114. }
  162115. if( p->rc==SQLITE_NOTFOUND ){
  162116. p->rc = SQLITE_ERROR;
  162117. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  162118. }
  162119. }
  162120. /*
  162121. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  162122. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  162123. **
  162124. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  162125. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  162126. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  162127. ** three characters, then shorten the suffix on z[] to be the last three
  162128. ** characters of the original suffix.
  162129. **
  162130. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  162131. ** do the suffix shortening regardless of URI parameter.
  162132. **
  162133. ** Examples:
  162134. **
  162135. ** test.db-journal => test.nal
  162136. ** test.db-wal => test.wal
  162137. ** test.db-shm => test.shm
  162138. ** test.db-mj7f3319fa => test.9fa
  162139. */
  162140. static void rbuFileSuffix3(const char *zBase, char *z){
  162141. #ifdef SQLITE_ENABLE_8_3_NAMES
  162142. #if SQLITE_ENABLE_8_3_NAMES<2
  162143. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  162144. #endif
  162145. {
  162146. int i, sz;
  162147. sz = (int)strlen(z)&0xffffff;
  162148. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  162149. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  162150. }
  162151. #endif
  162152. }
  162153. /*
  162154. ** Return the current wal-index header checksum for the target database
  162155. ** as a 64-bit integer.
  162156. **
  162157. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  162158. ** blob starting at byte offset 40.
  162159. */
  162160. static i64 rbuShmChecksum(sqlite3rbu *p){
  162161. i64 iRet = 0;
  162162. if( p->rc==SQLITE_OK ){
  162163. sqlite3_file *pDb = p->pTargetFd->pReal;
  162164. u32 volatile *ptr;
  162165. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  162166. if( p->rc==SQLITE_OK ){
  162167. iRet = ((i64)ptr[10] << 32) + ptr[11];
  162168. }
  162169. }
  162170. return iRet;
  162171. }
  162172. /*
  162173. ** This function is called as part of initializing or reinitializing an
  162174. ** incremental checkpoint.
  162175. **
  162176. ** It populates the sqlite3rbu.aFrame[] array with the set of
  162177. ** (wal frame -> db page) copy operations required to checkpoint the
  162178. ** current wal file, and obtains the set of shm locks required to safely
  162179. ** perform the copy operations directly on the file-system.
  162180. **
  162181. ** If argument pState is not NULL, then the incremental checkpoint is
  162182. ** being resumed. In this case, if the checksum of the wal-index-header
  162183. ** following recovery is not the same as the checksum saved in the RbuState
  162184. ** object, then the rbu handle is set to DONE state. This occurs if some
  162185. ** other client appends a transaction to the wal file in the middle of
  162186. ** an incremental checkpoint.
  162187. */
  162188. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  162189. /* If pState is NULL, then the wal file may not have been opened and
  162190. ** recovered. Running a read-statement here to ensure that doing so
  162191. ** does not interfere with the "capture" process below. */
  162192. if( pState==0 ){
  162193. p->eStage = 0;
  162194. if( p->rc==SQLITE_OK ){
  162195. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  162196. }
  162197. }
  162198. /* Assuming no error has occurred, run a "restart" checkpoint with the
  162199. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  162200. ** special behaviour in the rbu VFS:
  162201. **
  162202. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  162203. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  162204. ** proceed with running a passive checkpoint instead of failing).
  162205. **
  162206. ** * Attempts to read from the *-wal file or write to the database file
  162207. ** do not perform any IO. Instead, the frame/page combinations that
  162208. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  162209. ** array.
  162210. **
  162211. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  162212. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  162213. ** no-ops. These locks will not be released until the connection
  162214. ** is closed.
  162215. **
  162216. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  162217. ** error.
  162218. **
  162219. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  162220. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  162221. ** array populated with a set of (frame -> page) mappings. Because the
  162222. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  162223. ** data from the wal file into the database file according to the
  162224. ** contents of aFrame[].
  162225. */
  162226. if( p->rc==SQLITE_OK ){
  162227. int rc2;
  162228. p->eStage = RBU_STAGE_CAPTURE;
  162229. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  162230. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  162231. }
  162232. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  162233. p->eStage = RBU_STAGE_CKPT;
  162234. p->nStep = (pState ? pState->nRow : 0);
  162235. p->aBuf = rbuMalloc(p, p->pgsz);
  162236. p->iWalCksum = rbuShmChecksum(p);
  162237. }
  162238. if( p->rc==SQLITE_OK ){
  162239. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  162240. p->rc = SQLITE_DONE;
  162241. p->eStage = RBU_STAGE_DONE;
  162242. }else{
  162243. int nSectorSize;
  162244. sqlite3_file *pDb = p->pTargetFd->pReal;
  162245. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  162246. assert( p->nPagePerSector==0 );
  162247. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  162248. if( nSectorSize>p->pgsz ){
  162249. p->nPagePerSector = nSectorSize / p->pgsz;
  162250. }else{
  162251. p->nPagePerSector = 1;
  162252. }
  162253. /* Call xSync() on the wal file. This causes SQLite to sync the
  162254. ** directory in which the target database and the wal file reside, in
  162255. ** case it has not been synced since the rename() call in
  162256. ** rbuMoveOalFile(). */
  162257. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  162258. }
  162259. }
  162260. }
  162261. /*
  162262. ** Called when iAmt bytes are read from offset iOff of the wal file while
  162263. ** the rbu object is in capture mode. Record the frame number of the frame
  162264. ** being read in the aFrame[] array.
  162265. */
  162266. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  162267. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  162268. u32 iFrame;
  162269. if( pRbu->mLock!=mReq ){
  162270. pRbu->rc = SQLITE_BUSY;
  162271. return SQLITE_INTERNAL;
  162272. }
  162273. pRbu->pgsz = iAmt;
  162274. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  162275. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  162276. RbuFrame *aNew;
  162277. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  162278. if( aNew==0 ) return SQLITE_NOMEM;
  162279. pRbu->aFrame = aNew;
  162280. pRbu->nFrameAlloc = nNew;
  162281. }
  162282. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  162283. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  162284. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  162285. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  162286. pRbu->nFrame++;
  162287. return SQLITE_OK;
  162288. }
  162289. /*
  162290. ** Called when a page of data is written to offset iOff of the database
  162291. ** file while the rbu handle is in capture mode. Record the page number
  162292. ** of the page being written in the aFrame[] array.
  162293. */
  162294. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  162295. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  162296. return SQLITE_OK;
  162297. }
  162298. /*
  162299. ** This is called as part of an incremental checkpoint operation. Copy
  162300. ** a single frame of data from the wal file into the database file, as
  162301. ** indicated by the RbuFrame object.
  162302. */
  162303. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  162304. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  162305. sqlite3_file *pDb = p->pTargetFd->pReal;
  162306. i64 iOff;
  162307. assert( p->rc==SQLITE_OK );
  162308. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  162309. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  162310. if( p->rc ) return;
  162311. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  162312. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  162313. }
  162314. /*
  162315. ** Take an EXCLUSIVE lock on the database file.
  162316. */
  162317. static void rbuLockDatabase(sqlite3rbu *p){
  162318. sqlite3_file *pReal = p->pTargetFd->pReal;
  162319. assert( p->rc==SQLITE_OK );
  162320. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  162321. if( p->rc==SQLITE_OK ){
  162322. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  162323. }
  162324. }
  162325. #if defined(_WIN32_WCE)
  162326. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  162327. int nChar;
  162328. LPWSTR zWideFilename;
  162329. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  162330. if( nChar==0 ){
  162331. return 0;
  162332. }
  162333. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  162334. if( zWideFilename==0 ){
  162335. return 0;
  162336. }
  162337. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  162338. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  162339. nChar);
  162340. if( nChar==0 ){
  162341. sqlite3_free(zWideFilename);
  162342. zWideFilename = 0;
  162343. }
  162344. return zWideFilename;
  162345. }
  162346. #endif
  162347. /*
  162348. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  162349. ** on the database file. This proc moves the *-oal file to the *-wal path,
  162350. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  162351. ** If an error occurs, leave an error code and error message in the rbu
  162352. ** handle.
  162353. */
  162354. static void rbuMoveOalFile(sqlite3rbu *p){
  162355. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  162356. const char *zMove = zBase;
  162357. char *zOal;
  162358. char *zWal;
  162359. if( rbuIsVacuum(p) ){
  162360. zMove = sqlite3_db_filename(p->dbRbu, "main");
  162361. }
  162362. zOal = sqlite3_mprintf("%s-oal", zMove);
  162363. zWal = sqlite3_mprintf("%s-wal", zMove);
  162364. assert( p->eStage==RBU_STAGE_MOVE );
  162365. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  162366. if( zWal==0 || zOal==0 ){
  162367. p->rc = SQLITE_NOMEM;
  162368. }else{
  162369. /* Move the *-oal file to *-wal. At this point connection p->db is
  162370. ** holding a SHARED lock on the target database file (because it is
  162371. ** in WAL mode). So no other connection may be writing the db.
  162372. **
  162373. ** In order to ensure that there are no database readers, an EXCLUSIVE
  162374. ** lock is obtained here before the *-oal is moved to *-wal.
  162375. */
  162376. rbuLockDatabase(p);
  162377. if( p->rc==SQLITE_OK ){
  162378. rbuFileSuffix3(zBase, zWal);
  162379. rbuFileSuffix3(zBase, zOal);
  162380. /* Re-open the databases. */
  162381. rbuObjIterFinalize(&p->objiter);
  162382. sqlite3_close(p->dbRbu);
  162383. sqlite3_close(p->dbMain);
  162384. p->dbMain = 0;
  162385. p->dbRbu = 0;
  162386. #if defined(_WIN32_WCE)
  162387. {
  162388. LPWSTR zWideOal;
  162389. LPWSTR zWideWal;
  162390. zWideOal = rbuWinUtf8ToUnicode(zOal);
  162391. if( zWideOal ){
  162392. zWideWal = rbuWinUtf8ToUnicode(zWal);
  162393. if( zWideWal ){
  162394. if( MoveFileW(zWideOal, zWideWal) ){
  162395. p->rc = SQLITE_OK;
  162396. }else{
  162397. p->rc = SQLITE_IOERR;
  162398. }
  162399. sqlite3_free(zWideWal);
  162400. }else{
  162401. p->rc = SQLITE_IOERR_NOMEM;
  162402. }
  162403. sqlite3_free(zWideOal);
  162404. }else{
  162405. p->rc = SQLITE_IOERR_NOMEM;
  162406. }
  162407. }
  162408. #else
  162409. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  162410. #endif
  162411. if( p->rc==SQLITE_OK ){
  162412. rbuOpenDatabase(p, 0);
  162413. rbuSetupCheckpoint(p, 0);
  162414. }
  162415. }
  162416. }
  162417. sqlite3_free(zWal);
  162418. sqlite3_free(zOal);
  162419. }
  162420. /*
  162421. ** The SELECT statement iterating through the keys for the current object
  162422. ** (p->objiter.pSelect) currently points to a valid row. This function
  162423. ** determines the type of operation requested by this row and returns
  162424. ** one of the following values to indicate the result:
  162425. **
  162426. ** * RBU_INSERT
  162427. ** * RBU_DELETE
  162428. ** * RBU_IDX_DELETE
  162429. ** * RBU_UPDATE
  162430. **
  162431. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  162432. ** point to the text value indicating the columns to update.
  162433. **
  162434. ** If the rbu_control field contains an invalid value, an error code and
  162435. ** message are left in the RBU handle and zero returned.
  162436. */
  162437. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  162438. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  162439. int res = 0; /* Return value */
  162440. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  162441. case SQLITE_INTEGER: {
  162442. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  162443. switch( iVal ){
  162444. case 0: res = RBU_INSERT; break;
  162445. case 1: res = RBU_DELETE; break;
  162446. case 2: res = RBU_REPLACE; break;
  162447. case 3: res = RBU_IDX_DELETE; break;
  162448. case 4: res = RBU_IDX_INSERT; break;
  162449. }
  162450. break;
  162451. }
  162452. case SQLITE_TEXT: {
  162453. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  162454. if( z==0 ){
  162455. p->rc = SQLITE_NOMEM;
  162456. }else{
  162457. *pzMask = (const char*)z;
  162458. }
  162459. res = RBU_UPDATE;
  162460. break;
  162461. }
  162462. default:
  162463. break;
  162464. }
  162465. if( res==0 ){
  162466. rbuBadControlError(p);
  162467. }
  162468. return res;
  162469. }
  162470. #ifdef SQLITE_DEBUG
  162471. /*
  162472. ** Assert that column iCol of statement pStmt is named zName.
  162473. */
  162474. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  162475. const char *zCol = sqlite3_column_name(pStmt, iCol);
  162476. assert( 0==sqlite3_stricmp(zName, zCol) );
  162477. }
  162478. #else
  162479. # define assertColumnName(x,y,z)
  162480. #endif
  162481. /*
  162482. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  162483. ** RBU_IDX_DELETE. This function performs the work of a single
  162484. ** sqlite3rbu_step() call for the type of operation specified by eType.
  162485. */
  162486. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  162487. RbuObjIter *pIter = &p->objiter;
  162488. sqlite3_value *pVal;
  162489. sqlite3_stmt *pWriter;
  162490. int i;
  162491. assert( p->rc==SQLITE_OK );
  162492. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  162493. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  162494. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  162495. );
  162496. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  162497. ** statement below does actually delete a row, nPhaseOneStep will be
  162498. ** incremented by the same amount when SQL function rbu_tmp_insert()
  162499. ** is invoked by the trigger. */
  162500. if( eType==RBU_DELETE ){
  162501. p->nPhaseOneStep -= p->objiter.nIndex;
  162502. }
  162503. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  162504. pWriter = pIter->pDelete;
  162505. }else{
  162506. pWriter = pIter->pInsert;
  162507. }
  162508. for(i=0; i<pIter->nCol; i++){
  162509. /* If this is an INSERT into a table b-tree and the table has an
  162510. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  162511. ** to write a NULL into the IPK column. That is not permitted. */
  162512. if( eType==RBU_INSERT
  162513. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  162514. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  162515. ){
  162516. p->rc = SQLITE_MISMATCH;
  162517. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  162518. return;
  162519. }
  162520. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  162521. continue;
  162522. }
  162523. pVal = sqlite3_column_value(pIter->pSelect, i);
  162524. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  162525. if( p->rc ) return;
  162526. }
  162527. if( pIter->zIdx==0 ){
  162528. if( pIter->eType==RBU_PK_VTAB
  162529. || pIter->eType==RBU_PK_NONE
  162530. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  162531. ){
  162532. /* For a virtual table, or a table with no primary key, the
  162533. ** SELECT statement is:
  162534. **
  162535. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  162536. **
  162537. ** Hence column_value(pIter->nCol+1).
  162538. */
  162539. assertColumnName(pIter->pSelect, pIter->nCol+1,
  162540. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  162541. );
  162542. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  162543. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  162544. }
  162545. }
  162546. if( p->rc==SQLITE_OK ){
  162547. sqlite3_step(pWriter);
  162548. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  162549. }
  162550. }
  162551. /*
  162552. ** This function does the work for an sqlite3rbu_step() call.
  162553. **
  162554. ** The object-iterator (p->objiter) currently points to a valid object,
  162555. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  162556. ** input row. Perform whatever processing is required and return.
  162557. **
  162558. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  162559. ** and message is left in the RBU handle and a copy of the error code
  162560. ** returned.
  162561. */
  162562. static int rbuStep(sqlite3rbu *p){
  162563. RbuObjIter *pIter = &p->objiter;
  162564. const char *zMask = 0;
  162565. int eType = rbuStepType(p, &zMask);
  162566. if( eType ){
  162567. assert( eType==RBU_INSERT || eType==RBU_DELETE
  162568. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  162569. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  162570. );
  162571. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  162572. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  162573. rbuBadControlError(p);
  162574. }
  162575. else if( eType==RBU_REPLACE ){
  162576. if( pIter->zIdx==0 ){
  162577. p->nPhaseOneStep += p->objiter.nIndex;
  162578. rbuStepOneOp(p, RBU_DELETE);
  162579. }
  162580. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  162581. }
  162582. else if( eType!=RBU_UPDATE ){
  162583. rbuStepOneOp(p, eType);
  162584. }
  162585. else{
  162586. sqlite3_value *pVal;
  162587. sqlite3_stmt *pUpdate = 0;
  162588. assert( eType==RBU_UPDATE );
  162589. p->nPhaseOneStep -= p->objiter.nIndex;
  162590. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  162591. if( pUpdate ){
  162592. int i;
  162593. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  162594. char c = zMask[pIter->aiSrcOrder[i]];
  162595. pVal = sqlite3_column_value(pIter->pSelect, i);
  162596. if( pIter->abTblPk[i] || c!='.' ){
  162597. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  162598. }
  162599. }
  162600. if( p->rc==SQLITE_OK
  162601. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  162602. ){
  162603. /* Bind the rbu_rowid value to column _rowid_ */
  162604. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  162605. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  162606. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  162607. }
  162608. if( p->rc==SQLITE_OK ){
  162609. sqlite3_step(pUpdate);
  162610. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  162611. }
  162612. }
  162613. }
  162614. }
  162615. return p->rc;
  162616. }
  162617. /*
  162618. ** Increment the schema cookie of the main database opened by p->dbMain.
  162619. **
  162620. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  162621. ** opened by p->dbMain to one more than the schema cookie of the main
  162622. ** db opened by p->dbRbu.
  162623. */
  162624. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  162625. if( p->rc==SQLITE_OK ){
  162626. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  162627. int iCookie = 1000000;
  162628. sqlite3_stmt *pStmt;
  162629. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  162630. "PRAGMA schema_version"
  162631. );
  162632. if( p->rc==SQLITE_OK ){
  162633. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  162634. ** is already a transaction open, so the prepared statement cannot
  162635. ** throw an SQLITE_SCHEMA exception. The only database page the
  162636. ** statement reads is page 1, which is guaranteed to be in the cache.
  162637. ** And no memory allocations are required. */
  162638. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162639. iCookie = sqlite3_column_int(pStmt, 0);
  162640. }
  162641. rbuFinalize(p, pStmt);
  162642. }
  162643. if( p->rc==SQLITE_OK ){
  162644. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  162645. }
  162646. }
  162647. }
  162648. /*
  162649. ** Update the contents of the rbu_state table within the rbu database. The
  162650. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  162651. ** are determined by inspecting the rbu handle passed as the first argument.
  162652. */
  162653. static void rbuSaveState(sqlite3rbu *p, int eStage){
  162654. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  162655. sqlite3_stmt *pInsert = 0;
  162656. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  162657. int rc;
  162658. assert( p->zErrmsg==0 );
  162659. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  162660. sqlite3_mprintf(
  162661. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  162662. "(%d, %d), "
  162663. "(%d, %Q), "
  162664. "(%d, %Q), "
  162665. "(%d, %d), "
  162666. "(%d, %d), "
  162667. "(%d, %lld), "
  162668. "(%d, %lld), "
  162669. "(%d, %lld), "
  162670. "(%d, %lld) ",
  162671. p->zStateDb,
  162672. RBU_STATE_STAGE, eStage,
  162673. RBU_STATE_TBL, p->objiter.zTbl,
  162674. RBU_STATE_IDX, p->objiter.zIdx,
  162675. RBU_STATE_ROW, p->nStep,
  162676. RBU_STATE_PROGRESS, p->nProgress,
  162677. RBU_STATE_CKPT, p->iWalCksum,
  162678. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  162679. RBU_STATE_OALSZ, p->iOalSz,
  162680. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
  162681. )
  162682. );
  162683. assert( pInsert==0 || rc==SQLITE_OK );
  162684. if( rc==SQLITE_OK ){
  162685. sqlite3_step(pInsert);
  162686. rc = sqlite3_finalize(pInsert);
  162687. }
  162688. if( rc!=SQLITE_OK ) p->rc = rc;
  162689. }
  162690. }
  162691. /*
  162692. ** The second argument passed to this function is the name of a PRAGMA
  162693. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  162694. ** This function executes the following on sqlite3rbu.dbRbu:
  162695. **
  162696. ** "PRAGMA main.$zPragma"
  162697. **
  162698. ** where $zPragma is the string passed as the second argument, then
  162699. ** on sqlite3rbu.dbMain:
  162700. **
  162701. ** "PRAGMA main.$zPragma = $val"
  162702. **
  162703. ** where $val is the value returned by the first PRAGMA invocation.
  162704. **
  162705. ** In short, it copies the value of the specified PRAGMA setting from
  162706. ** dbRbu to dbMain.
  162707. */
  162708. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  162709. if( p->rc==SQLITE_OK ){
  162710. sqlite3_stmt *pPragma = 0;
  162711. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  162712. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  162713. );
  162714. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  162715. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  162716. zPragma, sqlite3_column_int(pPragma, 0)
  162717. );
  162718. }
  162719. rbuFinalize(p, pPragma);
  162720. }
  162721. }
  162722. /*
  162723. ** The RBU handle passed as the only argument has just been opened and
  162724. ** the state database is empty. If this RBU handle was opened for an
  162725. ** RBU vacuum operation, create the schema in the target db.
  162726. */
  162727. static void rbuCreateTargetSchema(sqlite3rbu *p){
  162728. sqlite3_stmt *pSql = 0;
  162729. sqlite3_stmt *pInsert = 0;
  162730. assert( rbuIsVacuum(p) );
  162731. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  162732. if( p->rc==SQLITE_OK ){
  162733. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  162734. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  162735. " AND name!='sqlite_sequence' "
  162736. " ORDER BY type DESC"
  162737. );
  162738. }
  162739. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  162740. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  162741. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  162742. }
  162743. rbuFinalize(p, pSql);
  162744. if( p->rc!=SQLITE_OK ) return;
  162745. if( p->rc==SQLITE_OK ){
  162746. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  162747. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  162748. );
  162749. }
  162750. if( p->rc==SQLITE_OK ){
  162751. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  162752. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  162753. );
  162754. }
  162755. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  162756. int i;
  162757. for(i=0; i<5; i++){
  162758. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  162759. }
  162760. sqlite3_step(pInsert);
  162761. p->rc = sqlite3_reset(pInsert);
  162762. }
  162763. if( p->rc==SQLITE_OK ){
  162764. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  162765. }
  162766. rbuFinalize(p, pSql);
  162767. rbuFinalize(p, pInsert);
  162768. }
  162769. /*
  162770. ** Step the RBU object.
  162771. */
  162772. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  162773. if( p ){
  162774. switch( p->eStage ){
  162775. case RBU_STAGE_OAL: {
  162776. RbuObjIter *pIter = &p->objiter;
  162777. /* If this is an RBU vacuum operation and the state table was empty
  162778. ** when this handle was opened, create the target database schema. */
  162779. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  162780. rbuCreateTargetSchema(p);
  162781. rbuCopyPragma(p, "user_version");
  162782. rbuCopyPragma(p, "application_id");
  162783. }
  162784. while( p->rc==SQLITE_OK && pIter->zTbl ){
  162785. if( pIter->bCleanup ){
  162786. /* Clean up the rbu_tmp_xxx table for the previous table. It
  162787. ** cannot be dropped as there are currently active SQL statements.
  162788. ** But the contents can be deleted. */
  162789. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  162790. rbuMPrintfExec(p, p->dbRbu,
  162791. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  162792. );
  162793. }
  162794. }else{
  162795. rbuObjIterPrepareAll(p, pIter, 0);
  162796. /* Advance to the next row to process. */
  162797. if( p->rc==SQLITE_OK ){
  162798. int rc = sqlite3_step(pIter->pSelect);
  162799. if( rc==SQLITE_ROW ){
  162800. p->nProgress++;
  162801. p->nStep++;
  162802. return rbuStep(p);
  162803. }
  162804. p->rc = sqlite3_reset(pIter->pSelect);
  162805. p->nStep = 0;
  162806. }
  162807. }
  162808. rbuObjIterNext(p, pIter);
  162809. }
  162810. if( p->rc==SQLITE_OK ){
  162811. assert( pIter->zTbl==0 );
  162812. rbuSaveState(p, RBU_STAGE_MOVE);
  162813. rbuIncrSchemaCookie(p);
  162814. if( p->rc==SQLITE_OK ){
  162815. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  162816. }
  162817. if( p->rc==SQLITE_OK ){
  162818. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  162819. }
  162820. p->eStage = RBU_STAGE_MOVE;
  162821. }
  162822. break;
  162823. }
  162824. case RBU_STAGE_MOVE: {
  162825. if( p->rc==SQLITE_OK ){
  162826. rbuMoveOalFile(p);
  162827. p->nProgress++;
  162828. }
  162829. break;
  162830. }
  162831. case RBU_STAGE_CKPT: {
  162832. if( p->rc==SQLITE_OK ){
  162833. if( p->nStep>=p->nFrame ){
  162834. sqlite3_file *pDb = p->pTargetFd->pReal;
  162835. /* Sync the db file */
  162836. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  162837. /* Update nBackfill */
  162838. if( p->rc==SQLITE_OK ){
  162839. void volatile *ptr;
  162840. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  162841. if( p->rc==SQLITE_OK ){
  162842. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  162843. }
  162844. }
  162845. if( p->rc==SQLITE_OK ){
  162846. p->eStage = RBU_STAGE_DONE;
  162847. p->rc = SQLITE_DONE;
  162848. }
  162849. }else{
  162850. /* At one point the following block copied a single frame from the
  162851. ** wal file to the database file. So that one call to sqlite3rbu_step()
  162852. ** checkpointed a single frame.
  162853. **
  162854. ** However, if the sector-size is larger than the page-size, and the
  162855. ** application calls sqlite3rbu_savestate() or close() immediately
  162856. ** after this step, then rbu_step() again, then a power failure occurs,
  162857. ** then the database page written here may be damaged. Work around
  162858. ** this by checkpointing frames until the next page in the aFrame[]
  162859. ** lies on a different disk sector to the current one. */
  162860. u32 iSector;
  162861. do{
  162862. RbuFrame *pFrame = &p->aFrame[p->nStep];
  162863. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  162864. rbuCheckpointFrame(p, pFrame);
  162865. p->nStep++;
  162866. }while( p->nStep<p->nFrame
  162867. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  162868. && p->rc==SQLITE_OK
  162869. );
  162870. }
  162871. p->nProgress++;
  162872. }
  162873. break;
  162874. }
  162875. default:
  162876. break;
  162877. }
  162878. return p->rc;
  162879. }else{
  162880. return SQLITE_NOMEM;
  162881. }
  162882. }
  162883. /*
  162884. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  162885. ** otherwise. Either or both argument may be NULL. Two NULL values are
  162886. ** considered equal, and NULL is considered distinct from all other values.
  162887. */
  162888. static int rbuStrCompare(const char *z1, const char *z2){
  162889. if( z1==0 && z2==0 ) return 0;
  162890. if( z1==0 || z2==0 ) return 1;
  162891. return (sqlite3_stricmp(z1, z2)!=0);
  162892. }
  162893. /*
  162894. ** This function is called as part of sqlite3rbu_open() when initializing
  162895. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  162896. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  162897. ** things so that the next call to sqlite3rbu_step() continues on from
  162898. ** where the previous rbu handle left off.
  162899. **
  162900. ** If an error occurs, an error code and error message are left in the
  162901. ** rbu handle passed as the first argument.
  162902. */
  162903. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  162904. assert( p->rc==SQLITE_OK );
  162905. if( pState->zTbl ){
  162906. RbuObjIter *pIter = &p->objiter;
  162907. int rc = SQLITE_OK;
  162908. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  162909. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  162910. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  162911. )){
  162912. rc = rbuObjIterNext(p, pIter);
  162913. }
  162914. if( rc==SQLITE_OK && !pIter->zTbl ){
  162915. rc = SQLITE_ERROR;
  162916. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  162917. }
  162918. if( rc==SQLITE_OK ){
  162919. p->nStep = pState->nRow;
  162920. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  162921. }
  162922. p->rc = rc;
  162923. }
  162924. }
  162925. /*
  162926. ** If there is a "*-oal" file in the file-system corresponding to the
  162927. ** target database in the file-system, delete it. If an error occurs,
  162928. ** leave an error code and error message in the rbu handle.
  162929. */
  162930. static void rbuDeleteOalFile(sqlite3rbu *p){
  162931. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  162932. if( zOal ){
  162933. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  162934. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  162935. pVfs->xDelete(pVfs, zOal, 0);
  162936. sqlite3_free(zOal);
  162937. }
  162938. }
  162939. /*
  162940. ** Allocate a private rbu VFS for the rbu handle passed as the only
  162941. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  162942. ** specified a URI with a vfs=? option in place of a target database
  162943. ** file name.
  162944. */
  162945. static void rbuCreateVfs(sqlite3rbu *p){
  162946. int rnd;
  162947. char zRnd[64];
  162948. assert( p->rc==SQLITE_OK );
  162949. sqlite3_randomness(sizeof(int), (void*)&rnd);
  162950. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  162951. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  162952. if( p->rc==SQLITE_OK ){
  162953. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  162954. assert( pVfs );
  162955. p->zVfsName = pVfs->zName;
  162956. ((rbu_vfs*)pVfs)->pRbu = p;
  162957. }
  162958. }
  162959. /*
  162960. ** Destroy the private VFS created for the rbu handle passed as the only
  162961. ** argument by an earlier call to rbuCreateVfs().
  162962. */
  162963. static void rbuDeleteVfs(sqlite3rbu *p){
  162964. if( p->zVfsName ){
  162965. sqlite3rbu_destroy_vfs(p->zVfsName);
  162966. p->zVfsName = 0;
  162967. }
  162968. }
  162969. /*
  162970. ** This user-defined SQL function is invoked with a single argument - the
  162971. ** name of a table expected to appear in the target database. It returns
  162972. ** the number of auxilliary indexes on the table.
  162973. */
  162974. static void rbuIndexCntFunc(
  162975. sqlite3_context *pCtx,
  162976. int nVal,
  162977. sqlite3_value **apVal
  162978. ){
  162979. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  162980. sqlite3_stmt *pStmt = 0;
  162981. char *zErrmsg = 0;
  162982. int rc;
  162983. assert( nVal==1 );
  162984. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  162985. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  162986. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  162987. );
  162988. if( rc!=SQLITE_OK ){
  162989. sqlite3_result_error(pCtx, zErrmsg, -1);
  162990. }else{
  162991. int nIndex = 0;
  162992. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162993. nIndex = sqlite3_column_int(pStmt, 0);
  162994. }
  162995. rc = sqlite3_finalize(pStmt);
  162996. if( rc==SQLITE_OK ){
  162997. sqlite3_result_int(pCtx, nIndex);
  162998. }else{
  162999. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  163000. }
  163001. }
  163002. sqlite3_free(zErrmsg);
  163003. }
  163004. /*
  163005. ** If the RBU database contains the rbu_count table, use it to initialize
  163006. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  163007. ** is assumed to contain the same columns as:
  163008. **
  163009. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  163010. **
  163011. ** There should be one row in the table for each data_xxx table in the
  163012. ** database. The 'tbl' column should contain the name of a data_xxx table,
  163013. ** and the cnt column the number of rows it contains.
  163014. **
  163015. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  163016. ** for all rows in the rbu_count table, where nIndex is the number of
  163017. ** indexes on the corresponding target database table.
  163018. */
  163019. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  163020. if( p->rc==SQLITE_OK ){
  163021. sqlite3_stmt *pStmt = 0;
  163022. int bExists = 0; /* True if rbu_count exists */
  163023. p->nPhaseOneStep = -1;
  163024. p->rc = sqlite3_create_function(p->dbRbu,
  163025. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  163026. );
  163027. /* Check for the rbu_count table. If it does not exist, or if an error
  163028. ** occurs, nPhaseOneStep will be left set to -1. */
  163029. if( p->rc==SQLITE_OK ){
  163030. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  163031. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  163032. );
  163033. }
  163034. if( p->rc==SQLITE_OK ){
  163035. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  163036. bExists = 1;
  163037. }
  163038. p->rc = sqlite3_finalize(pStmt);
  163039. }
  163040. if( p->rc==SQLITE_OK && bExists ){
  163041. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  163042. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  163043. "FROM rbu_count"
  163044. );
  163045. if( p->rc==SQLITE_OK ){
  163046. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  163047. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  163048. }
  163049. p->rc = sqlite3_finalize(pStmt);
  163050. }
  163051. }
  163052. }
  163053. }
  163054. static sqlite3rbu *openRbuHandle(
  163055. const char *zTarget,
  163056. const char *zRbu,
  163057. const char *zState
  163058. ){
  163059. sqlite3rbu *p;
  163060. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  163061. size_t nRbu = strlen(zRbu);
  163062. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  163063. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  163064. if( p ){
  163065. RbuState *pState = 0;
  163066. /* Create the custom VFS. */
  163067. memset(p, 0, sizeof(sqlite3rbu));
  163068. rbuCreateVfs(p);
  163069. /* Open the target, RBU and state databases */
  163070. if( p->rc==SQLITE_OK ){
  163071. char *pCsr = (char*)&p[1];
  163072. int bRetry = 0;
  163073. if( zTarget ){
  163074. p->zTarget = pCsr;
  163075. memcpy(p->zTarget, zTarget, nTarget+1);
  163076. pCsr += nTarget+1;
  163077. }
  163078. p->zRbu = pCsr;
  163079. memcpy(p->zRbu, zRbu, nRbu+1);
  163080. pCsr += nRbu+1;
  163081. if( zState ){
  163082. p->zState = rbuMPrintf(p, "%s", zState);
  163083. }
  163084. /* If the first attempt to open the database file fails and the bRetry
  163085. ** flag it set, this means that the db was not opened because it seemed
  163086. ** to be a wal-mode db. But, this may have happened due to an earlier
  163087. ** RBU vacuum operation leaving an old wal file in the directory.
  163088. ** If this is the case, it will have been checkpointed and deleted
  163089. ** when the handle was closed and a second attempt to open the
  163090. ** database may succeed. */
  163091. rbuOpenDatabase(p, &bRetry);
  163092. if( bRetry ){
  163093. rbuOpenDatabase(p, 0);
  163094. }
  163095. }
  163096. if( p->rc==SQLITE_OK ){
  163097. pState = rbuLoadState(p);
  163098. assert( pState || p->rc!=SQLITE_OK );
  163099. if( p->rc==SQLITE_OK ){
  163100. if( pState->eStage==0 ){
  163101. rbuDeleteOalFile(p);
  163102. rbuInitPhaseOneSteps(p);
  163103. p->eStage = RBU_STAGE_OAL;
  163104. }else{
  163105. p->eStage = pState->eStage;
  163106. p->nPhaseOneStep = pState->nPhaseOneStep;
  163107. }
  163108. p->nProgress = pState->nProgress;
  163109. p->iOalSz = pState->iOalSz;
  163110. }
  163111. }
  163112. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  163113. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  163114. if( p->eStage==RBU_STAGE_OAL ){
  163115. p->rc = SQLITE_ERROR;
  163116. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  163117. }else if( p->eStage==RBU_STAGE_MOVE ){
  163118. p->eStage = RBU_STAGE_CKPT;
  163119. p->nStep = 0;
  163120. }
  163121. }
  163122. if( p->rc==SQLITE_OK
  163123. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  163124. && pState->eStage!=0
  163125. ){
  163126. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  163127. if( pFd->iCookie!=pState->iCookie ){
  163128. /* At this point (pTargetFd->iCookie) contains the value of the
  163129. ** change-counter cookie (the thing that gets incremented when a
  163130. ** transaction is committed in rollback mode) currently stored on
  163131. ** page 1 of the database file. */
  163132. p->rc = SQLITE_BUSY;
  163133. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  163134. (rbuIsVacuum(p) ? "vacuum" : "update")
  163135. );
  163136. }
  163137. }
  163138. if( p->rc==SQLITE_OK ){
  163139. if( p->eStage==RBU_STAGE_OAL ){
  163140. sqlite3 *db = p->dbMain;
  163141. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  163142. /* Point the object iterator at the first object */
  163143. if( p->rc==SQLITE_OK ){
  163144. p->rc = rbuObjIterFirst(p, &p->objiter);
  163145. }
  163146. /* If the RBU database contains no data_xxx tables, declare the RBU
  163147. ** update finished. */
  163148. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  163149. p->rc = SQLITE_DONE;
  163150. p->eStage = RBU_STAGE_DONE;
  163151. }else{
  163152. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  163153. rbuCopyPragma(p, "page_size");
  163154. rbuCopyPragma(p, "auto_vacuum");
  163155. }
  163156. /* Open transactions both databases. The *-oal file is opened or
  163157. ** created at this point. */
  163158. if( p->rc==SQLITE_OK ){
  163159. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  163160. }
  163161. /* Check if the main database is a zipvfs db. If it is, set the upper
  163162. ** level pager to use "journal_mode=off". This prevents it from
  163163. ** generating a large journal using a temp file. */
  163164. if( p->rc==SQLITE_OK ){
  163165. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  163166. if( frc==SQLITE_OK ){
  163167. p->rc = sqlite3_exec(
  163168. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  163169. }
  163170. }
  163171. if( p->rc==SQLITE_OK ){
  163172. rbuSetupOal(p, pState);
  163173. }
  163174. }
  163175. }else if( p->eStage==RBU_STAGE_MOVE ){
  163176. /* no-op */
  163177. }else if( p->eStage==RBU_STAGE_CKPT ){
  163178. rbuSetupCheckpoint(p, pState);
  163179. }else if( p->eStage==RBU_STAGE_DONE ){
  163180. p->rc = SQLITE_DONE;
  163181. }else{
  163182. p->rc = SQLITE_CORRUPT;
  163183. }
  163184. }
  163185. rbuFreeState(pState);
  163186. }
  163187. return p;
  163188. }
  163189. /*
  163190. ** Allocate and return an RBU handle with all fields zeroed except for the
  163191. ** error code, which is set to SQLITE_MISUSE.
  163192. */
  163193. static sqlite3rbu *rbuMisuseError(void){
  163194. sqlite3rbu *pRet;
  163195. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  163196. if( pRet ){
  163197. memset(pRet, 0, sizeof(sqlite3rbu));
  163198. pRet->rc = SQLITE_MISUSE;
  163199. }
  163200. return pRet;
  163201. }
  163202. /*
  163203. ** Open and return a new RBU handle.
  163204. */
  163205. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  163206. const char *zTarget,
  163207. const char *zRbu,
  163208. const char *zState
  163209. ){
  163210. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  163211. /* TODO: Check that zTarget and zRbu are non-NULL */
  163212. return openRbuHandle(zTarget, zRbu, zState);
  163213. }
  163214. /*
  163215. ** Open a handle to begin or resume an RBU VACUUM operation.
  163216. */
  163217. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  163218. const char *zTarget,
  163219. const char *zState
  163220. ){
  163221. if( zTarget==0 ){ return rbuMisuseError(); }
  163222. /* TODO: Check that both arguments are non-NULL */
  163223. return openRbuHandle(0, zTarget, zState);
  163224. }
  163225. /*
  163226. ** Return the database handle used by pRbu.
  163227. */
  163228. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  163229. sqlite3 *db = 0;
  163230. if( pRbu ){
  163231. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  163232. }
  163233. return db;
  163234. }
  163235. /*
  163236. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  163237. ** then edit any error message string so as to remove all occurrences of
  163238. ** the pattern "rbu_imp_[0-9]*".
  163239. */
  163240. static void rbuEditErrmsg(sqlite3rbu *p){
  163241. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  163242. unsigned int i;
  163243. size_t nErrmsg = strlen(p->zErrmsg);
  163244. for(i=0; i<(nErrmsg-8); i++){
  163245. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  163246. int nDel = 8;
  163247. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  163248. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  163249. nErrmsg -= nDel;
  163250. }
  163251. }
  163252. }
  163253. }
  163254. /*
  163255. ** Close the RBU handle.
  163256. */
  163257. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  163258. int rc;
  163259. if( p ){
  163260. /* Commit the transaction to the *-oal file. */
  163261. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  163262. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  163263. }
  163264. /* Sync the db file if currently doing an incremental checkpoint */
  163265. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  163266. sqlite3_file *pDb = p->pTargetFd->pReal;
  163267. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  163268. }
  163269. rbuSaveState(p, p->eStage);
  163270. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  163271. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  163272. }
  163273. /* Close any open statement handles. */
  163274. rbuObjIterFinalize(&p->objiter);
  163275. /* If this is an RBU vacuum handle and the vacuum has either finished
  163276. ** successfully or encountered an error, delete the contents of the
  163277. ** state table. This causes the next call to sqlite3rbu_vacuum()
  163278. ** specifying the current target and state databases to start a new
  163279. ** vacuum from scratch. */
  163280. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  163281. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  163282. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  163283. }
  163284. /* Close the open database handle and VFS object. */
  163285. sqlite3_close(p->dbRbu);
  163286. sqlite3_close(p->dbMain);
  163287. assert( p->szTemp==0 );
  163288. rbuDeleteVfs(p);
  163289. sqlite3_free(p->aBuf);
  163290. sqlite3_free(p->aFrame);
  163291. rbuEditErrmsg(p);
  163292. rc = p->rc;
  163293. if( pzErrmsg ){
  163294. *pzErrmsg = p->zErrmsg;
  163295. }else{
  163296. sqlite3_free(p->zErrmsg);
  163297. }
  163298. sqlite3_free(p->zState);
  163299. sqlite3_free(p);
  163300. }else{
  163301. rc = SQLITE_NOMEM;
  163302. *pzErrmsg = 0;
  163303. }
  163304. return rc;
  163305. }
  163306. /*
  163307. ** Return the total number of key-value operations (inserts, deletes or
  163308. ** updates) that have been performed on the target database since the
  163309. ** current RBU update was started.
  163310. */
  163311. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  163312. return pRbu->nProgress;
  163313. }
  163314. /*
  163315. ** Return permyriadage progress indications for the two main stages of
  163316. ** an RBU update.
  163317. */
  163318. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  163319. const int MAX_PROGRESS = 10000;
  163320. switch( p->eStage ){
  163321. case RBU_STAGE_OAL:
  163322. if( p->nPhaseOneStep>0 ){
  163323. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  163324. }else{
  163325. *pnOne = -1;
  163326. }
  163327. *pnTwo = 0;
  163328. break;
  163329. case RBU_STAGE_MOVE:
  163330. *pnOne = MAX_PROGRESS;
  163331. *pnTwo = 0;
  163332. break;
  163333. case RBU_STAGE_CKPT:
  163334. *pnOne = MAX_PROGRESS;
  163335. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  163336. break;
  163337. case RBU_STAGE_DONE:
  163338. *pnOne = MAX_PROGRESS;
  163339. *pnTwo = MAX_PROGRESS;
  163340. break;
  163341. default:
  163342. assert( 0 );
  163343. }
  163344. }
  163345. /*
  163346. ** Return the current state of the RBU vacuum or update operation.
  163347. */
  163348. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  163349. int aRes[] = {
  163350. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  163351. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  163352. };
  163353. assert( RBU_STAGE_OAL==1 );
  163354. assert( RBU_STAGE_MOVE==2 );
  163355. assert( RBU_STAGE_CKPT==4 );
  163356. assert( RBU_STAGE_DONE==5 );
  163357. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  163358. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  163359. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  163360. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  163361. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  163362. return SQLITE_RBU_STATE_ERROR;
  163363. }else{
  163364. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  163365. assert( p->eStage==RBU_STAGE_OAL
  163366. || p->eStage==RBU_STAGE_MOVE
  163367. || p->eStage==RBU_STAGE_CKPT
  163368. || p->eStage==RBU_STAGE_DONE
  163369. );
  163370. return aRes[p->eStage];
  163371. }
  163372. }
  163373. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  163374. int rc = p->rc;
  163375. if( rc==SQLITE_DONE ) return SQLITE_OK;
  163376. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  163377. if( p->eStage==RBU_STAGE_OAL ){
  163378. assert( rc!=SQLITE_DONE );
  163379. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  163380. }
  163381. /* Sync the db file */
  163382. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  163383. sqlite3_file *pDb = p->pTargetFd->pReal;
  163384. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  163385. }
  163386. p->rc = rc;
  163387. rbuSaveState(p, p->eStage);
  163388. rc = p->rc;
  163389. if( p->eStage==RBU_STAGE_OAL ){
  163390. assert( rc!=SQLITE_DONE );
  163391. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  163392. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  163393. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  163394. }
  163395. p->rc = rc;
  163396. return rc;
  163397. }
  163398. /**************************************************************************
  163399. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  163400. ** of a standard VFS in the following ways:
  163401. **
  163402. ** 1. Whenever the first page of a main database file is read or
  163403. ** written, the value of the change-counter cookie is stored in
  163404. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  163405. ** database header field is stored in rbu_file.iWriteVer. This ensures
  163406. ** that the values are always trustworthy within an open transaction.
  163407. **
  163408. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  163409. ** member variable of the associated database file descriptor is set
  163410. ** to point to the new file. A mutex protected linked list of all main
  163411. ** db fds opened using a particular RBU VFS is maintained at
  163412. ** rbu_vfs.pMain to facilitate this.
  163413. **
  163414. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  163415. ** object can be marked as the target database of an RBU update. This
  163416. ** turns on the following extra special behaviour:
  163417. **
  163418. ** 3a. If xAccess() is called to check if there exists a *-wal file
  163419. ** associated with an RBU target database currently in RBU_STAGE_OAL
  163420. ** stage (preparing the *-oal file), the following special handling
  163421. ** applies:
  163422. **
  163423. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  163424. ** target database may not be in wal mode already.
  163425. **
  163426. ** * if the *-wal file does not exist, set the output parameter to
  163427. ** non-zero (to tell SQLite that it does exist) anyway.
  163428. **
  163429. ** Then, when xOpen() is called to open the *-wal file associated with
  163430. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  163431. ** file, the rbu vfs opens the corresponding *-oal file instead.
  163432. **
  163433. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  163434. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  163435. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  163436. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  163437. ** because assert() statements in some VFS implementations fail if
  163438. ** xShmLock() is called before xShmMap().
  163439. **
  163440. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  163441. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  163442. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  163443. ** from automatically checkpointing a *-wal (or *-oal) file from within
  163444. ** sqlite3_close().
  163445. **
  163446. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  163447. ** all xWrite() calls on the target database file perform no IO.
  163448. ** Instead the frame and page numbers that would be read and written
  163449. ** are recorded. Additionally, successful attempts to obtain exclusive
  163450. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  163451. ** database file are recorded. xShmLock() calls to unlock the same
  163452. ** locks are no-ops (so that once obtained, these locks are never
  163453. ** relinquished). Finally, calls to xSync() on the target database
  163454. ** file fail with SQLITE_INTERNAL errors.
  163455. */
  163456. static void rbuUnlockShm(rbu_file *p){
  163457. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  163458. if( p->pRbu ){
  163459. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  163460. int i;
  163461. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  163462. if( (1<<i) & p->pRbu->mLock ){
  163463. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  163464. }
  163465. }
  163466. p->pRbu->mLock = 0;
  163467. }
  163468. }
  163469. /*
  163470. */
  163471. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  163472. sqlite3rbu *pRbu = pFd->pRbu;
  163473. i64 nDiff = nNew - pFd->sz;
  163474. pRbu->szTemp += nDiff;
  163475. pFd->sz = nNew;
  163476. assert( pRbu->szTemp>=0 );
  163477. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  163478. return SQLITE_OK;
  163479. }
  163480. /*
  163481. ** Close an rbu file.
  163482. */
  163483. static int rbuVfsClose(sqlite3_file *pFile){
  163484. rbu_file *p = (rbu_file*)pFile;
  163485. int rc;
  163486. int i;
  163487. /* Free the contents of the apShm[] array. And the array itself. */
  163488. for(i=0; i<p->nShm; i++){
  163489. sqlite3_free(p->apShm[i]);
  163490. }
  163491. sqlite3_free(p->apShm);
  163492. p->apShm = 0;
  163493. sqlite3_free(p->zDel);
  163494. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  163495. rbu_file **pp;
  163496. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  163497. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  163498. *pp = p->pMainNext;
  163499. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  163500. rbuUnlockShm(p);
  163501. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  163502. }
  163503. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  163504. rbuUpdateTempSize(p, 0);
  163505. }
  163506. /* Close the underlying file handle */
  163507. rc = p->pReal->pMethods->xClose(p->pReal);
  163508. return rc;
  163509. }
  163510. /*
  163511. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  163512. ** passed as the only argument.
  163513. */
  163514. static u32 rbuGetU32(u8 *aBuf){
  163515. return ((u32)aBuf[0] << 24)
  163516. + ((u32)aBuf[1] << 16)
  163517. + ((u32)aBuf[2] << 8)
  163518. + ((u32)aBuf[3]);
  163519. }
  163520. /*
  163521. ** Write an unsigned 32-bit value in big-endian format to the supplied
  163522. ** buffer.
  163523. */
  163524. static void rbuPutU32(u8 *aBuf, u32 iVal){
  163525. aBuf[0] = (iVal >> 24) & 0xFF;
  163526. aBuf[1] = (iVal >> 16) & 0xFF;
  163527. aBuf[2] = (iVal >> 8) & 0xFF;
  163528. aBuf[3] = (iVal >> 0) & 0xFF;
  163529. }
  163530. static void rbuPutU16(u8 *aBuf, u16 iVal){
  163531. aBuf[0] = (iVal >> 8) & 0xFF;
  163532. aBuf[1] = (iVal >> 0) & 0xFF;
  163533. }
  163534. /*
  163535. ** Read data from an rbuVfs-file.
  163536. */
  163537. static int rbuVfsRead(
  163538. sqlite3_file *pFile,
  163539. void *zBuf,
  163540. int iAmt,
  163541. sqlite_int64 iOfst
  163542. ){
  163543. rbu_file *p = (rbu_file*)pFile;
  163544. sqlite3rbu *pRbu = p->pRbu;
  163545. int rc;
  163546. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  163547. assert( p->openFlags & SQLITE_OPEN_WAL );
  163548. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  163549. }else{
  163550. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  163551. && (p->openFlags & SQLITE_OPEN_WAL)
  163552. && iOfst>=pRbu->iOalSz
  163553. ){
  163554. rc = SQLITE_OK;
  163555. memset(zBuf, 0, iAmt);
  163556. }else{
  163557. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  163558. #if 1
  163559. /* If this is being called to read the first page of the target
  163560. ** database as part of an rbu vacuum operation, synthesize the
  163561. ** contents of the first page if it does not yet exist. Otherwise,
  163562. ** SQLite will not check for a *-wal file. */
  163563. if( pRbu && rbuIsVacuum(pRbu)
  163564. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  163565. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  163566. && pRbu->rc==SQLITE_OK
  163567. ){
  163568. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  163569. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  163570. if( rc==SQLITE_OK ){
  163571. u8 *aBuf = (u8*)zBuf;
  163572. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  163573. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  163574. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  163575. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  163576. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  163577. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  163578. if( iAmt>100 ){
  163579. memset(&aBuf[100], 0, iAmt-100);
  163580. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  163581. aBuf[100] = 0x0D;
  163582. }
  163583. }
  163584. }
  163585. #endif
  163586. }
  163587. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  163588. /* These look like magic numbers. But they are stable, as they are part
  163589. ** of the definition of the SQLite file format, which may not change. */
  163590. u8 *pBuf = (u8*)zBuf;
  163591. p->iCookie = rbuGetU32(&pBuf[24]);
  163592. p->iWriteVer = pBuf[19];
  163593. }
  163594. }
  163595. return rc;
  163596. }
  163597. /*
  163598. ** Write data to an rbuVfs-file.
  163599. */
  163600. static int rbuVfsWrite(
  163601. sqlite3_file *pFile,
  163602. const void *zBuf,
  163603. int iAmt,
  163604. sqlite_int64 iOfst
  163605. ){
  163606. rbu_file *p = (rbu_file*)pFile;
  163607. sqlite3rbu *pRbu = p->pRbu;
  163608. int rc;
  163609. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  163610. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  163611. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  163612. }else{
  163613. if( pRbu ){
  163614. if( pRbu->eStage==RBU_STAGE_OAL
  163615. && (p->openFlags & SQLITE_OPEN_WAL)
  163616. && iOfst>=pRbu->iOalSz
  163617. ){
  163618. pRbu->iOalSz = iAmt + iOfst;
  163619. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  163620. i64 szNew = iAmt+iOfst;
  163621. if( szNew>p->sz ){
  163622. rc = rbuUpdateTempSize(p, szNew);
  163623. if( rc!=SQLITE_OK ) return rc;
  163624. }
  163625. }
  163626. }
  163627. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  163628. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  163629. /* These look like magic numbers. But they are stable, as they are part
  163630. ** of the definition of the SQLite file format, which may not change. */
  163631. u8 *pBuf = (u8*)zBuf;
  163632. p->iCookie = rbuGetU32(&pBuf[24]);
  163633. p->iWriteVer = pBuf[19];
  163634. }
  163635. }
  163636. return rc;
  163637. }
  163638. /*
  163639. ** Truncate an rbuVfs-file.
  163640. */
  163641. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  163642. rbu_file *p = (rbu_file*)pFile;
  163643. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  163644. int rc = rbuUpdateTempSize(p, size);
  163645. if( rc!=SQLITE_OK ) return rc;
  163646. }
  163647. return p->pReal->pMethods->xTruncate(p->pReal, size);
  163648. }
  163649. /*
  163650. ** Sync an rbuVfs-file.
  163651. */
  163652. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  163653. rbu_file *p = (rbu_file *)pFile;
  163654. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  163655. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  163656. return SQLITE_INTERNAL;
  163657. }
  163658. return SQLITE_OK;
  163659. }
  163660. return p->pReal->pMethods->xSync(p->pReal, flags);
  163661. }
  163662. /*
  163663. ** Return the current file-size of an rbuVfs-file.
  163664. */
  163665. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  163666. rbu_file *p = (rbu_file *)pFile;
  163667. int rc;
  163668. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  163669. /* If this is an RBU vacuum operation and this is the target database,
  163670. ** pretend that it has at least one page. Otherwise, SQLite will not
  163671. ** check for the existance of a *-wal file. rbuVfsRead() contains
  163672. ** similar logic. */
  163673. if( rc==SQLITE_OK && *pSize==0
  163674. && p->pRbu && rbuIsVacuum(p->pRbu)
  163675. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  163676. ){
  163677. *pSize = 1024;
  163678. }
  163679. return rc;
  163680. }
  163681. /*
  163682. ** Lock an rbuVfs-file.
  163683. */
  163684. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  163685. rbu_file *p = (rbu_file*)pFile;
  163686. sqlite3rbu *pRbu = p->pRbu;
  163687. int rc = SQLITE_OK;
  163688. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  163689. if( eLock==SQLITE_LOCK_EXCLUSIVE
  163690. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  163691. ){
  163692. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  163693. ** prevents it from checkpointing the database from sqlite3_close(). */
  163694. rc = SQLITE_BUSY;
  163695. }else{
  163696. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  163697. }
  163698. return rc;
  163699. }
  163700. /*
  163701. ** Unlock an rbuVfs-file.
  163702. */
  163703. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  163704. rbu_file *p = (rbu_file *)pFile;
  163705. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  163706. }
  163707. /*
  163708. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  163709. */
  163710. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  163711. rbu_file *p = (rbu_file *)pFile;
  163712. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  163713. }
  163714. /*
  163715. ** File control method. For custom operations on an rbuVfs-file.
  163716. */
  163717. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  163718. rbu_file *p = (rbu_file *)pFile;
  163719. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  163720. int rc;
  163721. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  163722. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  163723. );
  163724. if( op==SQLITE_FCNTL_RBU ){
  163725. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  163726. /* First try to find another RBU vfs lower down in the vfs stack. If
  163727. ** one is found, this vfs will operate in pass-through mode. The lower
  163728. ** level vfs will do the special RBU handling. */
  163729. rc = xControl(p->pReal, op, pArg);
  163730. if( rc==SQLITE_NOTFOUND ){
  163731. /* Now search for a zipvfs instance lower down in the VFS stack. If
  163732. ** one is found, this is an error. */
  163733. void *dummy = 0;
  163734. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  163735. if( rc==SQLITE_OK ){
  163736. rc = SQLITE_ERROR;
  163737. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  163738. }else if( rc==SQLITE_NOTFOUND ){
  163739. pRbu->pTargetFd = p;
  163740. p->pRbu = pRbu;
  163741. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  163742. rc = SQLITE_OK;
  163743. }
  163744. }
  163745. return rc;
  163746. }
  163747. else if( op==SQLITE_FCNTL_RBUCNT ){
  163748. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  163749. pRbu->nRbu++;
  163750. pRbu->pRbuFd = p;
  163751. p->bNolock = 1;
  163752. }
  163753. rc = xControl(p->pReal, op, pArg);
  163754. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  163755. rbu_vfs *pRbuVfs = p->pRbuVfs;
  163756. char *zIn = *(char**)pArg;
  163757. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  163758. *(char**)pArg = zOut;
  163759. if( zOut==0 ) rc = SQLITE_NOMEM;
  163760. }
  163761. return rc;
  163762. }
  163763. /*
  163764. ** Return the sector-size in bytes for an rbuVfs-file.
  163765. */
  163766. static int rbuVfsSectorSize(sqlite3_file *pFile){
  163767. rbu_file *p = (rbu_file *)pFile;
  163768. return p->pReal->pMethods->xSectorSize(p->pReal);
  163769. }
  163770. /*
  163771. ** Return the device characteristic flags supported by an rbuVfs-file.
  163772. */
  163773. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  163774. rbu_file *p = (rbu_file *)pFile;
  163775. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  163776. }
  163777. /*
  163778. ** Take or release a shared-memory lock.
  163779. */
  163780. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  163781. rbu_file *p = (rbu_file*)pFile;
  163782. sqlite3rbu *pRbu = p->pRbu;
  163783. int rc = SQLITE_OK;
  163784. #ifdef SQLITE_AMALGAMATION
  163785. assert( WAL_CKPT_LOCK==1 );
  163786. #endif
  163787. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  163788. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  163789. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  163790. ** taking this lock also prevents any checkpoints from occurring.
  163791. ** todo: really, it's not clear why this might occur, as
  163792. ** wal_autocheckpoint ought to be turned off. */
  163793. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  163794. }else{
  163795. int bCapture = 0;
  163796. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  163797. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  163798. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  163799. ){
  163800. bCapture = 1;
  163801. }
  163802. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  163803. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  163804. if( bCapture && rc==SQLITE_OK ){
  163805. pRbu->mLock |= (1 << ofst);
  163806. }
  163807. }
  163808. }
  163809. return rc;
  163810. }
  163811. /*
  163812. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  163813. */
  163814. static int rbuVfsShmMap(
  163815. sqlite3_file *pFile,
  163816. int iRegion,
  163817. int szRegion,
  163818. int isWrite,
  163819. void volatile **pp
  163820. ){
  163821. rbu_file *p = (rbu_file*)pFile;
  163822. int rc = SQLITE_OK;
  163823. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  163824. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  163825. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  163826. ** instead of a file on disk. */
  163827. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  163828. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  163829. if( iRegion<=p->nShm ){
  163830. int nByte = (iRegion+1) * sizeof(char*);
  163831. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  163832. if( apNew==0 ){
  163833. rc = SQLITE_NOMEM;
  163834. }else{
  163835. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  163836. p->apShm = apNew;
  163837. p->nShm = iRegion+1;
  163838. }
  163839. }
  163840. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  163841. char *pNew = (char*)sqlite3_malloc64(szRegion);
  163842. if( pNew==0 ){
  163843. rc = SQLITE_NOMEM;
  163844. }else{
  163845. memset(pNew, 0, szRegion);
  163846. p->apShm[iRegion] = pNew;
  163847. }
  163848. }
  163849. if( rc==SQLITE_OK ){
  163850. *pp = p->apShm[iRegion];
  163851. }else{
  163852. *pp = 0;
  163853. }
  163854. }else{
  163855. assert( p->apShm==0 );
  163856. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  163857. }
  163858. return rc;
  163859. }
  163860. /*
  163861. ** Memory barrier.
  163862. */
  163863. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  163864. rbu_file *p = (rbu_file *)pFile;
  163865. p->pReal->pMethods->xShmBarrier(p->pReal);
  163866. }
  163867. /*
  163868. ** The xShmUnmap method.
  163869. */
  163870. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  163871. rbu_file *p = (rbu_file*)pFile;
  163872. int rc = SQLITE_OK;
  163873. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  163874. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  163875. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  163876. /* no-op */
  163877. }else{
  163878. /* Release the checkpointer and writer locks */
  163879. rbuUnlockShm(p);
  163880. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  163881. }
  163882. return rc;
  163883. }
  163884. /*
  163885. ** Given that zWal points to a buffer containing a wal file name passed to
  163886. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  163887. ** file-handle opened by the same database connection on the corresponding
  163888. ** database file.
  163889. */
  163890. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  163891. rbu_file *pDb;
  163892. sqlite3_mutex_enter(pRbuVfs->mutex);
  163893. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  163894. sqlite3_mutex_leave(pRbuVfs->mutex);
  163895. return pDb;
  163896. }
  163897. /*
  163898. ** A main database named zName has just been opened. The following
  163899. ** function returns a pointer to a buffer owned by SQLite that contains
  163900. ** the name of the *-wal file this db connection will use. SQLite
  163901. ** happens to pass a pointer to this buffer when using xAccess()
  163902. ** or xOpen() to operate on the *-wal file.
  163903. */
  163904. static const char *rbuMainToWal(const char *zName, int flags){
  163905. int n = (int)strlen(zName);
  163906. const char *z = &zName[n];
  163907. if( flags & SQLITE_OPEN_URI ){
  163908. int odd = 0;
  163909. while( 1 ){
  163910. if( z[0]==0 ){
  163911. odd = 1 - odd;
  163912. if( odd && z[1]==0 ) break;
  163913. }
  163914. z++;
  163915. }
  163916. z += 2;
  163917. }else{
  163918. while( *z==0 ) z++;
  163919. }
  163920. z += (n + 8 + 1);
  163921. return z;
  163922. }
  163923. /*
  163924. ** Open an rbu file handle.
  163925. */
  163926. static int rbuVfsOpen(
  163927. sqlite3_vfs *pVfs,
  163928. const char *zName,
  163929. sqlite3_file *pFile,
  163930. int flags,
  163931. int *pOutFlags
  163932. ){
  163933. static sqlite3_io_methods rbuvfs_io_methods = {
  163934. 2, /* iVersion */
  163935. rbuVfsClose, /* xClose */
  163936. rbuVfsRead, /* xRead */
  163937. rbuVfsWrite, /* xWrite */
  163938. rbuVfsTruncate, /* xTruncate */
  163939. rbuVfsSync, /* xSync */
  163940. rbuVfsFileSize, /* xFileSize */
  163941. rbuVfsLock, /* xLock */
  163942. rbuVfsUnlock, /* xUnlock */
  163943. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  163944. rbuVfsFileControl, /* xFileControl */
  163945. rbuVfsSectorSize, /* xSectorSize */
  163946. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  163947. rbuVfsShmMap, /* xShmMap */
  163948. rbuVfsShmLock, /* xShmLock */
  163949. rbuVfsShmBarrier, /* xShmBarrier */
  163950. rbuVfsShmUnmap, /* xShmUnmap */
  163951. 0, 0 /* xFetch, xUnfetch */
  163952. };
  163953. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  163954. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  163955. rbu_file *pFd = (rbu_file *)pFile;
  163956. int rc = SQLITE_OK;
  163957. const char *zOpen = zName;
  163958. int oflags = flags;
  163959. memset(pFd, 0, sizeof(rbu_file));
  163960. pFd->pReal = (sqlite3_file*)&pFd[1];
  163961. pFd->pRbuVfs = pRbuVfs;
  163962. pFd->openFlags = flags;
  163963. if( zName ){
  163964. if( flags & SQLITE_OPEN_MAIN_DB ){
  163965. /* A main database has just been opened. The following block sets
  163966. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  163967. ** the name of the *-wal file this db connection will use. SQLite
  163968. ** happens to pass a pointer to this buffer when using xAccess()
  163969. ** or xOpen() to operate on the *-wal file. */
  163970. pFd->zWal = rbuMainToWal(zName, flags);
  163971. }
  163972. else if( flags & SQLITE_OPEN_WAL ){
  163973. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  163974. if( pDb ){
  163975. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  163976. /* This call is to open a *-wal file. Intead, open the *-oal. This
  163977. ** code ensures that the string passed to xOpen() is terminated by a
  163978. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  163979. ** parameter from it. */
  163980. const char *zBase = zName;
  163981. size_t nCopy;
  163982. char *zCopy;
  163983. if( rbuIsVacuum(pDb->pRbu) ){
  163984. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  163985. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  163986. }
  163987. nCopy = strlen(zBase);
  163988. zCopy = sqlite3_malloc64(nCopy+2);
  163989. if( zCopy ){
  163990. memcpy(zCopy, zBase, nCopy);
  163991. zCopy[nCopy-3] = 'o';
  163992. zCopy[nCopy] = '\0';
  163993. zCopy[nCopy+1] = '\0';
  163994. zOpen = (const char*)(pFd->zDel = zCopy);
  163995. }else{
  163996. rc = SQLITE_NOMEM;
  163997. }
  163998. pFd->pRbu = pDb->pRbu;
  163999. }
  164000. pDb->pWalFd = pFd;
  164001. }
  164002. }
  164003. }else{
  164004. pFd->pRbu = pRbuVfs->pRbu;
  164005. }
  164006. if( oflags & SQLITE_OPEN_MAIN_DB
  164007. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  164008. ){
  164009. assert( oflags & SQLITE_OPEN_MAIN_DB );
  164010. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  164011. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  164012. zOpen = 0;
  164013. }
  164014. if( rc==SQLITE_OK ){
  164015. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  164016. }
  164017. if( pFd->pReal->pMethods ){
  164018. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  164019. ** pointer and, if the file is a main database file, link it into the
  164020. ** mutex protected linked list of all such files. */
  164021. pFile->pMethods = &rbuvfs_io_methods;
  164022. if( flags & SQLITE_OPEN_MAIN_DB ){
  164023. sqlite3_mutex_enter(pRbuVfs->mutex);
  164024. pFd->pMainNext = pRbuVfs->pMain;
  164025. pRbuVfs->pMain = pFd;
  164026. sqlite3_mutex_leave(pRbuVfs->mutex);
  164027. }
  164028. }else{
  164029. sqlite3_free(pFd->zDel);
  164030. }
  164031. return rc;
  164032. }
  164033. /*
  164034. ** Delete the file located at zPath.
  164035. */
  164036. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  164037. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164038. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  164039. }
  164040. /*
  164041. ** Test for access permissions. Return true if the requested permission
  164042. ** is available, or false otherwise.
  164043. */
  164044. static int rbuVfsAccess(
  164045. sqlite3_vfs *pVfs,
  164046. const char *zPath,
  164047. int flags,
  164048. int *pResOut
  164049. ){
  164050. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  164051. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  164052. int rc;
  164053. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  164054. /* If this call is to check if a *-wal file associated with an RBU target
  164055. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  164056. ** the following special handling is activated:
  164057. **
  164058. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  164059. ** ensures that the RBU extension never tries to update a database
  164060. ** in wal mode, even if the first page of the database file has
  164061. ** been damaged.
  164062. **
  164063. ** b) if the *-wal file does not exist, claim that it does anyway,
  164064. ** causing SQLite to call xOpen() to open it. This call will also
  164065. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  164066. ** file opened instead.
  164067. */
  164068. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  164069. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  164070. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  164071. if( *pResOut ){
  164072. rc = SQLITE_CANTOPEN;
  164073. }else{
  164074. sqlite3_int64 sz = 0;
  164075. rc = rbuVfsFileSize(&pDb->base, &sz);
  164076. *pResOut = (sz>0);
  164077. }
  164078. }
  164079. }
  164080. return rc;
  164081. }
  164082. /*
  164083. ** Populate buffer zOut with the full canonical pathname corresponding
  164084. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  164085. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  164086. */
  164087. static int rbuVfsFullPathname(
  164088. sqlite3_vfs *pVfs,
  164089. const char *zPath,
  164090. int nOut,
  164091. char *zOut
  164092. ){
  164093. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164094. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  164095. }
  164096. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  164097. /*
  164098. ** Open the dynamic library located at zPath and return a handle.
  164099. */
  164100. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  164101. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164102. return pRealVfs->xDlOpen(pRealVfs, zPath);
  164103. }
  164104. /*
  164105. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  164106. ** utf-8 string describing the most recent error encountered associated
  164107. ** with dynamic libraries.
  164108. */
  164109. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  164110. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164111. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  164112. }
  164113. /*
  164114. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  164115. */
  164116. static void (*rbuVfsDlSym(
  164117. sqlite3_vfs *pVfs,
  164118. void *pArg,
  164119. const char *zSym
  164120. ))(void){
  164121. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164122. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  164123. }
  164124. /*
  164125. ** Close the dynamic library handle pHandle.
  164126. */
  164127. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  164128. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164129. pRealVfs->xDlClose(pRealVfs, pHandle);
  164130. }
  164131. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  164132. /*
  164133. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  164134. ** random data.
  164135. */
  164136. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  164137. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164138. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  164139. }
  164140. /*
  164141. ** Sleep for nMicro microseconds. Return the number of microseconds
  164142. ** actually slept.
  164143. */
  164144. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  164145. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164146. return pRealVfs->xSleep(pRealVfs, nMicro);
  164147. }
  164148. /*
  164149. ** Return the current time as a Julian Day number in *pTimeOut.
  164150. */
  164151. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  164152. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  164153. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  164154. }
  164155. /*
  164156. ** No-op.
  164157. */
  164158. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  164159. return 0;
  164160. }
  164161. /*
  164162. ** Deregister and destroy an RBU vfs created by an earlier call to
  164163. ** sqlite3rbu_create_vfs().
  164164. */
  164165. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  164166. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  164167. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  164168. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  164169. sqlite3_vfs_unregister(pVfs);
  164170. sqlite3_free(pVfs);
  164171. }
  164172. }
  164173. /*
  164174. ** Create an RBU VFS named zName that accesses the underlying file-system
  164175. ** via existing VFS zParent. The new object is registered as a non-default
  164176. ** VFS with SQLite before returning.
  164177. */
  164178. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  164179. /* Template for VFS */
  164180. static sqlite3_vfs vfs_template = {
  164181. 1, /* iVersion */
  164182. 0, /* szOsFile */
  164183. 0, /* mxPathname */
  164184. 0, /* pNext */
  164185. 0, /* zName */
  164186. 0, /* pAppData */
  164187. rbuVfsOpen, /* xOpen */
  164188. rbuVfsDelete, /* xDelete */
  164189. rbuVfsAccess, /* xAccess */
  164190. rbuVfsFullPathname, /* xFullPathname */
  164191. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  164192. rbuVfsDlOpen, /* xDlOpen */
  164193. rbuVfsDlError, /* xDlError */
  164194. rbuVfsDlSym, /* xDlSym */
  164195. rbuVfsDlClose, /* xDlClose */
  164196. #else
  164197. 0, 0, 0, 0,
  164198. #endif
  164199. rbuVfsRandomness, /* xRandomness */
  164200. rbuVfsSleep, /* xSleep */
  164201. rbuVfsCurrentTime, /* xCurrentTime */
  164202. rbuVfsGetLastError, /* xGetLastError */
  164203. 0, /* xCurrentTimeInt64 (version 2) */
  164204. 0, 0, 0 /* Unimplemented version 3 methods */
  164205. };
  164206. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  164207. int rc = SQLITE_OK;
  164208. size_t nName;
  164209. size_t nByte;
  164210. nName = strlen(zName);
  164211. nByte = sizeof(rbu_vfs) + nName + 1;
  164212. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  164213. if( pNew==0 ){
  164214. rc = SQLITE_NOMEM;
  164215. }else{
  164216. sqlite3_vfs *pParent; /* Parent VFS */
  164217. memset(pNew, 0, nByte);
  164218. pParent = sqlite3_vfs_find(zParent);
  164219. if( pParent==0 ){
  164220. rc = SQLITE_NOTFOUND;
  164221. }else{
  164222. char *zSpace;
  164223. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  164224. pNew->base.mxPathname = pParent->mxPathname;
  164225. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  164226. pNew->pRealVfs = pParent;
  164227. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  164228. memcpy(zSpace, zName, nName);
  164229. /* Allocate the mutex and register the new VFS (not as the default) */
  164230. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  164231. if( pNew->mutex==0 ){
  164232. rc = SQLITE_NOMEM;
  164233. }else{
  164234. rc = sqlite3_vfs_register(&pNew->base, 0);
  164235. }
  164236. }
  164237. if( rc!=SQLITE_OK ){
  164238. sqlite3_mutex_free(pNew->mutex);
  164239. sqlite3_free(pNew);
  164240. }
  164241. }
  164242. return rc;
  164243. }
  164244. /*
  164245. ** Configure the aggregate temp file size limit for this RBU handle.
  164246. */
  164247. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  164248. if( n>=0 ){
  164249. pRbu->szTempLimit = n;
  164250. }
  164251. return pRbu->szTempLimit;
  164252. }
  164253. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  164254. return pRbu->szTemp;
  164255. }
  164256. /**************************************************************************/
  164257. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  164258. /************** End of sqlite3rbu.c ******************************************/
  164259. /************** Begin file dbstat.c ******************************************/
  164260. /*
  164261. ** 2010 July 12
  164262. **
  164263. ** The author disclaims copyright to this source code. In place of
  164264. ** a legal notice, here is a blessing:
  164265. **
  164266. ** May you do good and not evil.
  164267. ** May you find forgiveness for yourself and forgive others.
  164268. ** May you share freely, never taking more than you give.
  164269. **
  164270. ******************************************************************************
  164271. **
  164272. ** This file contains an implementation of the "dbstat" virtual table.
  164273. **
  164274. ** The dbstat virtual table is used to extract low-level formatting
  164275. ** information from an SQLite database in order to implement the
  164276. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  164277. ** for an example implementation.
  164278. **
  164279. ** Additional information is available on the "dbstat.html" page of the
  164280. ** official SQLite documentation.
  164281. */
  164282. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  164283. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  164284. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  164285. /*
  164286. ** Page paths:
  164287. **
  164288. ** The value of the 'path' column describes the path taken from the
  164289. ** root-node of the b-tree structure to each page. The value of the
  164290. ** root-node path is '/'.
  164291. **
  164292. ** The value of the path for the left-most child page of the root of
  164293. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  164294. ** so the pages to the left have smaller keys than the pages to the right.)
  164295. ** The next to left-most child of the root page is
  164296. ** '/001', and so on, each sibling page identified by a 3-digit hex
  164297. ** value. The children of the 451st left-most sibling have paths such
  164298. ** as '/1c2/000/, '/1c2/001/' etc.
  164299. **
  164300. ** Overflow pages are specified by appending a '+' character and a
  164301. ** six-digit hexadecimal value to the path to the cell they are linked
  164302. ** from. For example, the three overflow pages in a chain linked from
  164303. ** the left-most cell of the 450th child of the root page are identified
  164304. ** by the paths:
  164305. **
  164306. ** '/1c2/000+000000' // First page in overflow chain
  164307. ** '/1c2/000+000001' // Second page in overflow chain
  164308. ** '/1c2/000+000002' // Third page in overflow chain
  164309. **
  164310. ** If the paths are sorted using the BINARY collation sequence, then
  164311. ** the overflow pages associated with a cell will appear earlier in the
  164312. ** sort-order than its child page:
  164313. **
  164314. ** '/1c2/000/' // Left-most child of 451st child of root
  164315. */
  164316. #define VTAB_SCHEMA \
  164317. "CREATE TABLE xx( " \
  164318. " name TEXT, /* Name of table or index */" \
  164319. " path TEXT, /* Path to page from root */" \
  164320. " pageno INTEGER, /* Page number */" \
  164321. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  164322. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  164323. " payload INTEGER, /* Bytes of payload on this page */" \
  164324. " unused INTEGER, /* Bytes of unused space on this page */" \
  164325. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  164326. " pgoffset INTEGER, /* Offset of page in file */" \
  164327. " pgsize INTEGER, /* Size of the page */" \
  164328. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  164329. ");"
  164330. typedef struct StatTable StatTable;
  164331. typedef struct StatCursor StatCursor;
  164332. typedef struct StatPage StatPage;
  164333. typedef struct StatCell StatCell;
  164334. struct StatCell {
  164335. int nLocal; /* Bytes of local payload */
  164336. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  164337. int nOvfl; /* Entries in aOvfl[] */
  164338. u32 *aOvfl; /* Array of overflow page numbers */
  164339. int nLastOvfl; /* Bytes of payload on final overflow page */
  164340. int iOvfl; /* Iterates through aOvfl[] */
  164341. };
  164342. struct StatPage {
  164343. u32 iPgno;
  164344. DbPage *pPg;
  164345. int iCell;
  164346. char *zPath; /* Path to this page */
  164347. /* Variables populated by statDecodePage(): */
  164348. u8 flags; /* Copy of flags byte */
  164349. int nCell; /* Number of cells on page */
  164350. int nUnused; /* Number of unused bytes on page */
  164351. StatCell *aCell; /* Array of parsed cells */
  164352. u32 iRightChildPg; /* Right-child page number (or 0) */
  164353. int nMxPayload; /* Largest payload of any cell on this page */
  164354. };
  164355. struct StatCursor {
  164356. sqlite3_vtab_cursor base;
  164357. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  164358. int isEof; /* After pStmt has returned SQLITE_DONE */
  164359. int iDb; /* Schema used for this query */
  164360. StatPage aPage[32];
  164361. int iPage; /* Current entry in aPage[] */
  164362. /* Values to return. */
  164363. char *zName; /* Value of 'name' column */
  164364. char *zPath; /* Value of 'path' column */
  164365. u32 iPageno; /* Value of 'pageno' column */
  164366. char *zPagetype; /* Value of 'pagetype' column */
  164367. int nCell; /* Value of 'ncell' column */
  164368. int nPayload; /* Value of 'payload' column */
  164369. int nUnused; /* Value of 'unused' column */
  164370. int nMxPayload; /* Value of 'mx_payload' column */
  164371. i64 iOffset; /* Value of 'pgOffset' column */
  164372. int szPage; /* Value of 'pgSize' column */
  164373. };
  164374. struct StatTable {
  164375. sqlite3_vtab base;
  164376. sqlite3 *db;
  164377. int iDb; /* Index of database to analyze */
  164378. };
  164379. #ifndef get2byte
  164380. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  164381. #endif
  164382. /*
  164383. ** Connect to or create a statvfs virtual table.
  164384. */
  164385. static int statConnect(
  164386. sqlite3 *db,
  164387. void *pAux,
  164388. int argc, const char *const*argv,
  164389. sqlite3_vtab **ppVtab,
  164390. char **pzErr
  164391. ){
  164392. StatTable *pTab = 0;
  164393. int rc = SQLITE_OK;
  164394. int iDb;
  164395. if( argc>=4 ){
  164396. Token nm;
  164397. sqlite3TokenInit(&nm, (char*)argv[3]);
  164398. iDb = sqlite3FindDb(db, &nm);
  164399. if( iDb<0 ){
  164400. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  164401. return SQLITE_ERROR;
  164402. }
  164403. }else{
  164404. iDb = 0;
  164405. }
  164406. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  164407. if( rc==SQLITE_OK ){
  164408. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  164409. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  164410. }
  164411. assert( rc==SQLITE_OK || pTab==0 );
  164412. if( rc==SQLITE_OK ){
  164413. memset(pTab, 0, sizeof(StatTable));
  164414. pTab->db = db;
  164415. pTab->iDb = iDb;
  164416. }
  164417. *ppVtab = (sqlite3_vtab*)pTab;
  164418. return rc;
  164419. }
  164420. /*
  164421. ** Disconnect from or destroy a statvfs virtual table.
  164422. */
  164423. static int statDisconnect(sqlite3_vtab *pVtab){
  164424. sqlite3_free(pVtab);
  164425. return SQLITE_OK;
  164426. }
  164427. /*
  164428. ** There is no "best-index". This virtual table always does a linear
  164429. ** scan. However, a schema=? constraint should cause this table to
  164430. ** operate on a different database schema, so check for it.
  164431. **
  164432. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  164433. */
  164434. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  164435. int i;
  164436. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  164437. /* Look for a valid schema=? constraint. If found, change the idxNum to
  164438. ** 1 and request the value of that constraint be sent to xFilter. And
  164439. ** lower the cost estimate to encourage the constrained version to be
  164440. ** used.
  164441. */
  164442. for(i=0; i<pIdxInfo->nConstraint; i++){
  164443. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  164444. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  164445. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  164446. pIdxInfo->idxNum = 1;
  164447. pIdxInfo->estimatedCost = 1.0;
  164448. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  164449. pIdxInfo->aConstraintUsage[i].omit = 1;
  164450. break;
  164451. }
  164452. /* Records are always returned in ascending order of (name, path).
  164453. ** If this will satisfy the client, set the orderByConsumed flag so that
  164454. ** SQLite does not do an external sort.
  164455. */
  164456. if( ( pIdxInfo->nOrderBy==1
  164457. && pIdxInfo->aOrderBy[0].iColumn==0
  164458. && pIdxInfo->aOrderBy[0].desc==0
  164459. ) ||
  164460. ( pIdxInfo->nOrderBy==2
  164461. && pIdxInfo->aOrderBy[0].iColumn==0
  164462. && pIdxInfo->aOrderBy[0].desc==0
  164463. && pIdxInfo->aOrderBy[1].iColumn==1
  164464. && pIdxInfo->aOrderBy[1].desc==0
  164465. )
  164466. ){
  164467. pIdxInfo->orderByConsumed = 1;
  164468. }
  164469. return SQLITE_OK;
  164470. }
  164471. /*
  164472. ** Open a new statvfs cursor.
  164473. */
  164474. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  164475. StatTable *pTab = (StatTable *)pVTab;
  164476. StatCursor *pCsr;
  164477. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  164478. if( pCsr==0 ){
  164479. return SQLITE_NOMEM_BKPT;
  164480. }else{
  164481. memset(pCsr, 0, sizeof(StatCursor));
  164482. pCsr->base.pVtab = pVTab;
  164483. pCsr->iDb = pTab->iDb;
  164484. }
  164485. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  164486. return SQLITE_OK;
  164487. }
  164488. static void statClearPage(StatPage *p){
  164489. int i;
  164490. if( p->aCell ){
  164491. for(i=0; i<p->nCell; i++){
  164492. sqlite3_free(p->aCell[i].aOvfl);
  164493. }
  164494. sqlite3_free(p->aCell);
  164495. }
  164496. sqlite3PagerUnref(p->pPg);
  164497. sqlite3_free(p->zPath);
  164498. memset(p, 0, sizeof(StatPage));
  164499. }
  164500. static void statResetCsr(StatCursor *pCsr){
  164501. int i;
  164502. sqlite3_reset(pCsr->pStmt);
  164503. for(i=0; i<ArraySize(pCsr->aPage); i++){
  164504. statClearPage(&pCsr->aPage[i]);
  164505. }
  164506. pCsr->iPage = 0;
  164507. sqlite3_free(pCsr->zPath);
  164508. pCsr->zPath = 0;
  164509. pCsr->isEof = 0;
  164510. }
  164511. /*
  164512. ** Close a statvfs cursor.
  164513. */
  164514. static int statClose(sqlite3_vtab_cursor *pCursor){
  164515. StatCursor *pCsr = (StatCursor *)pCursor;
  164516. statResetCsr(pCsr);
  164517. sqlite3_finalize(pCsr->pStmt);
  164518. sqlite3_free(pCsr);
  164519. return SQLITE_OK;
  164520. }
  164521. static void getLocalPayload(
  164522. int nUsable, /* Usable bytes per page */
  164523. u8 flags, /* Page flags */
  164524. int nTotal, /* Total record (payload) size */
  164525. int *pnLocal /* OUT: Bytes stored locally */
  164526. ){
  164527. int nLocal;
  164528. int nMinLocal;
  164529. int nMaxLocal;
  164530. if( flags==0x0D ){ /* Table leaf node */
  164531. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  164532. nMaxLocal = nUsable - 35;
  164533. }else{ /* Index interior and leaf nodes */
  164534. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  164535. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  164536. }
  164537. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  164538. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  164539. *pnLocal = nLocal;
  164540. }
  164541. static int statDecodePage(Btree *pBt, StatPage *p){
  164542. int nUnused;
  164543. int iOff;
  164544. int nHdr;
  164545. int isLeaf;
  164546. int szPage;
  164547. u8 *aData = sqlite3PagerGetData(p->pPg);
  164548. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  164549. p->flags = aHdr[0];
  164550. p->nCell = get2byte(&aHdr[3]);
  164551. p->nMxPayload = 0;
  164552. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  164553. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  164554. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  164555. nUnused += (int)aHdr[7];
  164556. iOff = get2byte(&aHdr[1]);
  164557. while( iOff ){
  164558. nUnused += get2byte(&aData[iOff+2]);
  164559. iOff = get2byte(&aData[iOff]);
  164560. }
  164561. p->nUnused = nUnused;
  164562. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  164563. szPage = sqlite3BtreeGetPageSize(pBt);
  164564. if( p->nCell ){
  164565. int i; /* Used to iterate through cells */
  164566. int nUsable; /* Usable bytes per page */
  164567. sqlite3BtreeEnter(pBt);
  164568. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  164569. sqlite3BtreeLeave(pBt);
  164570. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  164571. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  164572. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  164573. for(i=0; i<p->nCell; i++){
  164574. StatCell *pCell = &p->aCell[i];
  164575. iOff = get2byte(&aData[nHdr+i*2]);
  164576. if( !isLeaf ){
  164577. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  164578. iOff += 4;
  164579. }
  164580. if( p->flags==0x05 ){
  164581. /* A table interior node. nPayload==0. */
  164582. }else{
  164583. u32 nPayload; /* Bytes of payload total (local+overflow) */
  164584. int nLocal; /* Bytes of payload stored locally */
  164585. iOff += getVarint32(&aData[iOff], nPayload);
  164586. if( p->flags==0x0D ){
  164587. u64 dummy;
  164588. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  164589. }
  164590. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  164591. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  164592. pCell->nLocal = nLocal;
  164593. assert( nLocal>=0 );
  164594. assert( nPayload>=(u32)nLocal );
  164595. assert( nLocal<=(nUsable-35) );
  164596. if( nPayload>(u32)nLocal ){
  164597. int j;
  164598. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  164599. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  164600. pCell->nOvfl = nOvfl;
  164601. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  164602. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  164603. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  164604. for(j=1; j<nOvfl; j++){
  164605. int rc;
  164606. u32 iPrev = pCell->aOvfl[j-1];
  164607. DbPage *pPg = 0;
  164608. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  164609. if( rc!=SQLITE_OK ){
  164610. assert( pPg==0 );
  164611. return rc;
  164612. }
  164613. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  164614. sqlite3PagerUnref(pPg);
  164615. }
  164616. }
  164617. }
  164618. }
  164619. }
  164620. return SQLITE_OK;
  164621. }
  164622. /*
  164623. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  164624. ** the current value of pCsr->iPageno.
  164625. */
  164626. static void statSizeAndOffset(StatCursor *pCsr){
  164627. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  164628. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  164629. Pager *pPager = sqlite3BtreePager(pBt);
  164630. sqlite3_file *fd;
  164631. sqlite3_int64 x[2];
  164632. /* The default page size and offset */
  164633. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  164634. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  164635. /* If connected to a ZIPVFS backend, override the page size and
  164636. ** offset with actual values obtained from ZIPVFS.
  164637. */
  164638. fd = sqlite3PagerFile(pPager);
  164639. x[0] = pCsr->iPageno;
  164640. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  164641. pCsr->iOffset = x[0];
  164642. pCsr->szPage = (int)x[1];
  164643. }
  164644. }
  164645. /*
  164646. ** Move a statvfs cursor to the next entry in the file.
  164647. */
  164648. static int statNext(sqlite3_vtab_cursor *pCursor){
  164649. int rc;
  164650. int nPayload;
  164651. char *z;
  164652. StatCursor *pCsr = (StatCursor *)pCursor;
  164653. StatTable *pTab = (StatTable *)pCursor->pVtab;
  164654. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  164655. Pager *pPager = sqlite3BtreePager(pBt);
  164656. sqlite3_free(pCsr->zPath);
  164657. pCsr->zPath = 0;
  164658. statNextRestart:
  164659. if( pCsr->aPage[0].pPg==0 ){
  164660. rc = sqlite3_step(pCsr->pStmt);
  164661. if( rc==SQLITE_ROW ){
  164662. int nPage;
  164663. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  164664. sqlite3PagerPagecount(pPager, &nPage);
  164665. if( nPage==0 ){
  164666. pCsr->isEof = 1;
  164667. return sqlite3_reset(pCsr->pStmt);
  164668. }
  164669. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  164670. pCsr->aPage[0].iPgno = iRoot;
  164671. pCsr->aPage[0].iCell = 0;
  164672. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  164673. pCsr->iPage = 0;
  164674. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  164675. }else{
  164676. pCsr->isEof = 1;
  164677. return sqlite3_reset(pCsr->pStmt);
  164678. }
  164679. }else{
  164680. /* Page p itself has already been visited. */
  164681. StatPage *p = &pCsr->aPage[pCsr->iPage];
  164682. while( p->iCell<p->nCell ){
  164683. StatCell *pCell = &p->aCell[p->iCell];
  164684. if( pCell->iOvfl<pCell->nOvfl ){
  164685. int nUsable;
  164686. sqlite3BtreeEnter(pBt);
  164687. nUsable = sqlite3BtreeGetPageSize(pBt) -
  164688. sqlite3BtreeGetReserveNoMutex(pBt);
  164689. sqlite3BtreeLeave(pBt);
  164690. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  164691. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  164692. pCsr->zPagetype = "overflow";
  164693. pCsr->nCell = 0;
  164694. pCsr->nMxPayload = 0;
  164695. pCsr->zPath = z = sqlite3_mprintf(
  164696. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  164697. );
  164698. if( pCell->iOvfl<pCell->nOvfl-1 ){
  164699. pCsr->nUnused = 0;
  164700. pCsr->nPayload = nUsable - 4;
  164701. }else{
  164702. pCsr->nPayload = pCell->nLastOvfl;
  164703. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  164704. }
  164705. pCell->iOvfl++;
  164706. statSizeAndOffset(pCsr);
  164707. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  164708. }
  164709. if( p->iRightChildPg ) break;
  164710. p->iCell++;
  164711. }
  164712. if( !p->iRightChildPg || p->iCell>p->nCell ){
  164713. statClearPage(p);
  164714. if( pCsr->iPage==0 ) return statNext(pCursor);
  164715. pCsr->iPage--;
  164716. goto statNextRestart; /* Tail recursion */
  164717. }
  164718. pCsr->iPage++;
  164719. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  164720. if( p->iCell==p->nCell ){
  164721. p[1].iPgno = p->iRightChildPg;
  164722. }else{
  164723. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  164724. }
  164725. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  164726. p[1].iCell = 0;
  164727. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  164728. p->iCell++;
  164729. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  164730. }
  164731. /* Populate the StatCursor fields with the values to be returned
  164732. ** by the xColumn() and xRowid() methods.
  164733. */
  164734. if( rc==SQLITE_OK ){
  164735. int i;
  164736. StatPage *p = &pCsr->aPage[pCsr->iPage];
  164737. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  164738. pCsr->iPageno = p->iPgno;
  164739. rc = statDecodePage(pBt, p);
  164740. if( rc==SQLITE_OK ){
  164741. statSizeAndOffset(pCsr);
  164742. switch( p->flags ){
  164743. case 0x05: /* table internal */
  164744. case 0x02: /* index internal */
  164745. pCsr->zPagetype = "internal";
  164746. break;
  164747. case 0x0D: /* table leaf */
  164748. case 0x0A: /* index leaf */
  164749. pCsr->zPagetype = "leaf";
  164750. break;
  164751. default:
  164752. pCsr->zPagetype = "corrupted";
  164753. break;
  164754. }
  164755. pCsr->nCell = p->nCell;
  164756. pCsr->nUnused = p->nUnused;
  164757. pCsr->nMxPayload = p->nMxPayload;
  164758. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  164759. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  164760. nPayload = 0;
  164761. for(i=0; i<p->nCell; i++){
  164762. nPayload += p->aCell[i].nLocal;
  164763. }
  164764. pCsr->nPayload = nPayload;
  164765. }
  164766. }
  164767. return rc;
  164768. }
  164769. static int statEof(sqlite3_vtab_cursor *pCursor){
  164770. StatCursor *pCsr = (StatCursor *)pCursor;
  164771. return pCsr->isEof;
  164772. }
  164773. static int statFilter(
  164774. sqlite3_vtab_cursor *pCursor,
  164775. int idxNum, const char *idxStr,
  164776. int argc, sqlite3_value **argv
  164777. ){
  164778. StatCursor *pCsr = (StatCursor *)pCursor;
  164779. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  164780. char *zSql;
  164781. int rc = SQLITE_OK;
  164782. char *zMaster;
  164783. if( idxNum==1 ){
  164784. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  164785. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  164786. if( pCsr->iDb<0 ){
  164787. sqlite3_free(pCursor->pVtab->zErrMsg);
  164788. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  164789. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  164790. }
  164791. }else{
  164792. pCsr->iDb = pTab->iDb;
  164793. }
  164794. statResetCsr(pCsr);
  164795. sqlite3_finalize(pCsr->pStmt);
  164796. pCsr->pStmt = 0;
  164797. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  164798. zSql = sqlite3_mprintf(
  164799. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  164800. " UNION ALL "
  164801. "SELECT name, rootpage, type"
  164802. " FROM \"%w\".%s WHERE rootpage!=0"
  164803. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  164804. if( zSql==0 ){
  164805. return SQLITE_NOMEM_BKPT;
  164806. }else{
  164807. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  164808. sqlite3_free(zSql);
  164809. }
  164810. if( rc==SQLITE_OK ){
  164811. rc = statNext(pCursor);
  164812. }
  164813. return rc;
  164814. }
  164815. static int statColumn(
  164816. sqlite3_vtab_cursor *pCursor,
  164817. sqlite3_context *ctx,
  164818. int i
  164819. ){
  164820. StatCursor *pCsr = (StatCursor *)pCursor;
  164821. switch( i ){
  164822. case 0: /* name */
  164823. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  164824. break;
  164825. case 1: /* path */
  164826. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  164827. break;
  164828. case 2: /* pageno */
  164829. sqlite3_result_int64(ctx, pCsr->iPageno);
  164830. break;
  164831. case 3: /* pagetype */
  164832. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  164833. break;
  164834. case 4: /* ncell */
  164835. sqlite3_result_int(ctx, pCsr->nCell);
  164836. break;
  164837. case 5: /* payload */
  164838. sqlite3_result_int(ctx, pCsr->nPayload);
  164839. break;
  164840. case 6: /* unused */
  164841. sqlite3_result_int(ctx, pCsr->nUnused);
  164842. break;
  164843. case 7: /* mx_payload */
  164844. sqlite3_result_int(ctx, pCsr->nMxPayload);
  164845. break;
  164846. case 8: /* pgoffset */
  164847. sqlite3_result_int64(ctx, pCsr->iOffset);
  164848. break;
  164849. case 9: /* pgsize */
  164850. sqlite3_result_int(ctx, pCsr->szPage);
  164851. break;
  164852. default: { /* schema */
  164853. sqlite3 *db = sqlite3_context_db_handle(ctx);
  164854. int iDb = pCsr->iDb;
  164855. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  164856. break;
  164857. }
  164858. }
  164859. return SQLITE_OK;
  164860. }
  164861. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  164862. StatCursor *pCsr = (StatCursor *)pCursor;
  164863. *pRowid = pCsr->iPageno;
  164864. return SQLITE_OK;
  164865. }
  164866. /*
  164867. ** Invoke this routine to register the "dbstat" virtual table module
  164868. */
  164869. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  164870. static sqlite3_module dbstat_module = {
  164871. 0, /* iVersion */
  164872. statConnect, /* xCreate */
  164873. statConnect, /* xConnect */
  164874. statBestIndex, /* xBestIndex */
  164875. statDisconnect, /* xDisconnect */
  164876. statDisconnect, /* xDestroy */
  164877. statOpen, /* xOpen - open a cursor */
  164878. statClose, /* xClose - close a cursor */
  164879. statFilter, /* xFilter - configure scan constraints */
  164880. statNext, /* xNext - advance a cursor */
  164881. statEof, /* xEof - check for end of scan */
  164882. statColumn, /* xColumn - read data */
  164883. statRowid, /* xRowid - read data */
  164884. 0, /* xUpdate */
  164885. 0, /* xBegin */
  164886. 0, /* xSync */
  164887. 0, /* xCommit */
  164888. 0, /* xRollback */
  164889. 0, /* xFindMethod */
  164890. 0, /* xRename */
  164891. 0, /* xSavepoint */
  164892. 0, /* xRelease */
  164893. 0, /* xRollbackTo */
  164894. };
  164895. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  164896. }
  164897. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  164898. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  164899. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  164900. /************** End of dbstat.c **********************************************/
  164901. /************** Begin file dbpage.c ******************************************/
  164902. /*
  164903. ** 2017-10-11
  164904. **
  164905. ** The author disclaims copyright to this source code. In place of
  164906. ** a legal notice, here is a blessing:
  164907. **
  164908. ** May you do good and not evil.
  164909. ** May you find forgiveness for yourself and forgive others.
  164910. ** May you share freely, never taking more than you give.
  164911. **
  164912. ******************************************************************************
  164913. **
  164914. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  164915. **
  164916. ** The sqlite_dbpage virtual table is used to read or write whole raw
  164917. ** pages of the database file. The pager interface is used so that
  164918. ** uncommitted changes and changes recorded in the WAL file are correctly
  164919. ** retrieved.
  164920. **
  164921. ** Usage example:
  164922. **
  164923. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  164924. **
  164925. ** This is an eponymous virtual table so it does not need to be created before
  164926. ** use. The optional argument to the sqlite_dbpage() table name is the
  164927. ** schema for the database file that is to be read. The default schema is
  164928. ** "main".
  164929. **
  164930. ** The data field of sqlite_dbpage table can be updated. The new
  164931. ** value must be a BLOB which is the correct page size, otherwise the
  164932. ** update fails. Rows may not be deleted or inserted.
  164933. */
  164934. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  164935. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  164936. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  164937. typedef struct DbpageTable DbpageTable;
  164938. typedef struct DbpageCursor DbpageCursor;
  164939. struct DbpageCursor {
  164940. sqlite3_vtab_cursor base; /* Base class. Must be first */
  164941. int pgno; /* Current page number */
  164942. int mxPgno; /* Last page to visit on this scan */
  164943. };
  164944. struct DbpageTable {
  164945. sqlite3_vtab base; /* Base class. Must be first */
  164946. sqlite3 *db; /* The database */
  164947. Pager *pPager; /* Pager being read/written */
  164948. int iDb; /* Index of database to analyze */
  164949. int szPage; /* Size of each page in bytes */
  164950. int nPage; /* Number of pages in the file */
  164951. };
  164952. /*
  164953. ** Connect to or create a dbpagevfs virtual table.
  164954. */
  164955. static int dbpageConnect(
  164956. sqlite3 *db,
  164957. void *pAux,
  164958. int argc, const char *const*argv,
  164959. sqlite3_vtab **ppVtab,
  164960. char **pzErr
  164961. ){
  164962. DbpageTable *pTab = 0;
  164963. int rc = SQLITE_OK;
  164964. int iDb;
  164965. if( argc>=4 ){
  164966. Token nm;
  164967. sqlite3TokenInit(&nm, (char*)argv[3]);
  164968. iDb = sqlite3FindDb(db, &nm);
  164969. if( iDb<0 ){
  164970. *pzErr = sqlite3_mprintf("no such schema: %s", argv[3]);
  164971. return SQLITE_ERROR;
  164972. }
  164973. }else{
  164974. iDb = 0;
  164975. }
  164976. rc = sqlite3_declare_vtab(db,
  164977. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  164978. if( rc==SQLITE_OK ){
  164979. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  164980. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  164981. }
  164982. assert( rc==SQLITE_OK || pTab==0 );
  164983. if( rc==SQLITE_OK ){
  164984. Btree *pBt = db->aDb[iDb].pBt;
  164985. memset(pTab, 0, sizeof(DbpageTable));
  164986. pTab->db = db;
  164987. pTab->iDb = iDb;
  164988. pTab->pPager = pBt ? sqlite3BtreePager(pBt) : 0;
  164989. }
  164990. *ppVtab = (sqlite3_vtab*)pTab;
  164991. return rc;
  164992. }
  164993. /*
  164994. ** Disconnect from or destroy a dbpagevfs virtual table.
  164995. */
  164996. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  164997. sqlite3_free(pVtab);
  164998. return SQLITE_OK;
  164999. }
  165000. /*
  165001. ** idxNum:
  165002. **
  165003. ** 0 full table scan
  165004. ** 1 pgno=?1
  165005. */
  165006. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  165007. int i;
  165008. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  165009. for(i=0; i<pIdxInfo->nConstraint; i++){
  165010. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  165011. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  165012. pIdxInfo->estimatedRows = 1;
  165013. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  165014. pIdxInfo->estimatedCost = 1.0;
  165015. pIdxInfo->idxNum = 1;
  165016. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  165017. pIdxInfo->aConstraintUsage[i].omit = 1;
  165018. break;
  165019. }
  165020. }
  165021. if( pIdxInfo->nOrderBy>=1
  165022. && pIdxInfo->aOrderBy[0].iColumn<=0
  165023. && pIdxInfo->aOrderBy[0].desc==0
  165024. ){
  165025. pIdxInfo->orderByConsumed = 1;
  165026. }
  165027. return SQLITE_OK;
  165028. }
  165029. /*
  165030. ** Open a new dbpagevfs cursor.
  165031. */
  165032. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  165033. DbpageCursor *pCsr;
  165034. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  165035. if( pCsr==0 ){
  165036. return SQLITE_NOMEM_BKPT;
  165037. }else{
  165038. memset(pCsr, 0, sizeof(DbpageCursor));
  165039. pCsr->base.pVtab = pVTab;
  165040. pCsr->pgno = -1;
  165041. }
  165042. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  165043. return SQLITE_OK;
  165044. }
  165045. /*
  165046. ** Close a dbpagevfs cursor.
  165047. */
  165048. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  165049. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165050. sqlite3_free(pCsr);
  165051. return SQLITE_OK;
  165052. }
  165053. /*
  165054. ** Move a dbpagevfs cursor to the next entry in the file.
  165055. */
  165056. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  165057. int rc = SQLITE_OK;
  165058. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165059. pCsr->pgno++;
  165060. return rc;
  165061. }
  165062. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  165063. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165064. return pCsr->pgno > pCsr->mxPgno;
  165065. }
  165066. static int dbpageFilter(
  165067. sqlite3_vtab_cursor *pCursor,
  165068. int idxNum, const char *idxStr,
  165069. int argc, sqlite3_value **argv
  165070. ){
  165071. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165072. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  165073. int rc = SQLITE_OK;
  165074. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  165075. pTab->szPage = sqlite3BtreeGetPageSize(pBt);
  165076. pTab->nPage = sqlite3BtreeLastPage(pBt);
  165077. if( idxNum==1 ){
  165078. pCsr->pgno = sqlite3_value_int(argv[0]);
  165079. if( pCsr->pgno<1 || pCsr->pgno>pTab->nPage ){
  165080. pCsr->pgno = 1;
  165081. pCsr->mxPgno = 0;
  165082. }else{
  165083. pCsr->mxPgno = pCsr->pgno;
  165084. }
  165085. }else{
  165086. pCsr->pgno = 1;
  165087. pCsr->mxPgno = pTab->nPage;
  165088. }
  165089. return rc;
  165090. }
  165091. static int dbpageColumn(
  165092. sqlite3_vtab_cursor *pCursor,
  165093. sqlite3_context *ctx,
  165094. int i
  165095. ){
  165096. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165097. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  165098. int rc = SQLITE_OK;
  165099. switch( i ){
  165100. case 0: { /* pgno */
  165101. sqlite3_result_int(ctx, pCsr->pgno);
  165102. break;
  165103. }
  165104. case 1: { /* data */
  165105. DbPage *pDbPage = 0;
  165106. rc = sqlite3PagerGet(pTab->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  165107. if( rc==SQLITE_OK ){
  165108. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pTab->szPage,
  165109. SQLITE_TRANSIENT);
  165110. }
  165111. sqlite3PagerUnref(pDbPage);
  165112. break;
  165113. }
  165114. default: { /* schema */
  165115. sqlite3 *db = sqlite3_context_db_handle(ctx);
  165116. sqlite3_result_text(ctx, db->aDb[pTab->iDb].zDbSName, -1, SQLITE_STATIC);
  165117. break;
  165118. }
  165119. }
  165120. return SQLITE_OK;
  165121. }
  165122. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  165123. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  165124. *pRowid = pCsr->pgno;
  165125. return SQLITE_OK;
  165126. }
  165127. static int dbpageUpdate(
  165128. sqlite3_vtab *pVtab,
  165129. int argc,
  165130. sqlite3_value **argv,
  165131. sqlite_int64 *pRowid
  165132. ){
  165133. DbpageTable *pTab = (DbpageTable *)pVtab;
  165134. int pgno;
  165135. DbPage *pDbPage = 0;
  165136. int rc = SQLITE_OK;
  165137. char *zErr = 0;
  165138. if( argc==1 ){
  165139. zErr = "cannot delete";
  165140. goto update_fail;
  165141. }
  165142. pgno = sqlite3_value_int(argv[0]);
  165143. if( pgno<1 || pgno>pTab->nPage ){
  165144. zErr = "bad page number";
  165145. goto update_fail;
  165146. }
  165147. if( sqlite3_value_int(argv[1])!=pgno ){
  165148. zErr = "cannot insert";
  165149. goto update_fail;
  165150. }
  165151. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  165152. || sqlite3_value_bytes(argv[3])!=pTab->szPage
  165153. ){
  165154. zErr = "bad page value";
  165155. goto update_fail;
  165156. }
  165157. rc = sqlite3PagerGet(pTab->pPager, pgno, (DbPage**)&pDbPage, 0);
  165158. if( rc==SQLITE_OK ){
  165159. rc = sqlite3PagerWrite(pDbPage);
  165160. if( rc==SQLITE_OK ){
  165161. memcpy(sqlite3PagerGetData(pDbPage),
  165162. sqlite3_value_blob(argv[3]),
  165163. pTab->szPage);
  165164. }
  165165. }
  165166. sqlite3PagerUnref(pDbPage);
  165167. return rc;
  165168. update_fail:
  165169. sqlite3_free(pVtab->zErrMsg);
  165170. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  165171. return SQLITE_ERROR;
  165172. }
  165173. /*
  165174. ** Invoke this routine to register the "dbpage" virtual table module
  165175. */
  165176. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  165177. static sqlite3_module dbpage_module = {
  165178. 0, /* iVersion */
  165179. dbpageConnect, /* xCreate */
  165180. dbpageConnect, /* xConnect */
  165181. dbpageBestIndex, /* xBestIndex */
  165182. dbpageDisconnect, /* xDisconnect */
  165183. dbpageDisconnect, /* xDestroy */
  165184. dbpageOpen, /* xOpen - open a cursor */
  165185. dbpageClose, /* xClose - close a cursor */
  165186. dbpageFilter, /* xFilter - configure scan constraints */
  165187. dbpageNext, /* xNext - advance a cursor */
  165188. dbpageEof, /* xEof - check for end of scan */
  165189. dbpageColumn, /* xColumn - read data */
  165190. dbpageRowid, /* xRowid - read data */
  165191. dbpageUpdate, /* xUpdate */
  165192. 0, /* xBegin */
  165193. 0, /* xSync */
  165194. 0, /* xCommit */
  165195. 0, /* xRollback */
  165196. 0, /* xFindMethod */
  165197. 0, /* xRename */
  165198. 0, /* xSavepoint */
  165199. 0, /* xRelease */
  165200. 0, /* xRollbackTo */
  165201. };
  165202. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  165203. }
  165204. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  165205. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  165206. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  165207. /************** End of dbpage.c **********************************************/
  165208. /************** Begin file sqlite3session.c **********************************/
  165209. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  165210. /* #include "sqlite3session.h" */
  165211. /* #include <assert.h> */
  165212. /* #include <string.h> */
  165213. #ifndef SQLITE_AMALGAMATION
  165214. /* # include "sqliteInt.h" */
  165215. /* # include "vdbeInt.h" */
  165216. #endif
  165217. typedef struct SessionTable SessionTable;
  165218. typedef struct SessionChange SessionChange;
  165219. typedef struct SessionBuffer SessionBuffer;
  165220. typedef struct SessionInput SessionInput;
  165221. /*
  165222. ** Minimum chunk size used by streaming versions of functions.
  165223. */
  165224. #ifndef SESSIONS_STRM_CHUNK_SIZE
  165225. # ifdef SQLITE_TEST
  165226. # define SESSIONS_STRM_CHUNK_SIZE 64
  165227. # else
  165228. # define SESSIONS_STRM_CHUNK_SIZE 1024
  165229. # endif
  165230. #endif
  165231. typedef struct SessionHook SessionHook;
  165232. struct SessionHook {
  165233. void *pCtx;
  165234. int (*xOld)(void*,int,sqlite3_value**);
  165235. int (*xNew)(void*,int,sqlite3_value**);
  165236. int (*xCount)(void*);
  165237. int (*xDepth)(void*);
  165238. };
  165239. /*
  165240. ** Session handle structure.
  165241. */
  165242. struct sqlite3_session {
  165243. sqlite3 *db; /* Database handle session is attached to */
  165244. char *zDb; /* Name of database session is attached to */
  165245. int bEnable; /* True if currently recording */
  165246. int bIndirect; /* True if all changes are indirect */
  165247. int bAutoAttach; /* True to auto-attach tables */
  165248. int rc; /* Non-zero if an error has occurred */
  165249. void *pFilterCtx; /* First argument to pass to xTableFilter */
  165250. int (*xTableFilter)(void *pCtx, const char *zTab);
  165251. sqlite3_session *pNext; /* Next session object on same db. */
  165252. SessionTable *pTable; /* List of attached tables */
  165253. SessionHook hook; /* APIs to grab new and old data with */
  165254. };
  165255. /*
  165256. ** Instances of this structure are used to build strings or binary records.
  165257. */
  165258. struct SessionBuffer {
  165259. u8 *aBuf; /* Pointer to changeset buffer */
  165260. int nBuf; /* Size of buffer aBuf */
  165261. int nAlloc; /* Size of allocation containing aBuf */
  165262. };
  165263. /*
  165264. ** An object of this type is used internally as an abstraction for
  165265. ** input data. Input data may be supplied either as a single large buffer
  165266. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  165267. ** sqlite3changeset_start_strm()).
  165268. */
  165269. struct SessionInput {
  165270. int bNoDiscard; /* If true, discard no data */
  165271. int iCurrent; /* Offset in aData[] of current change */
  165272. int iNext; /* Offset in aData[] of next change */
  165273. u8 *aData; /* Pointer to buffer containing changeset */
  165274. int nData; /* Number of bytes in aData */
  165275. SessionBuffer buf; /* Current read buffer */
  165276. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  165277. void *pIn; /* First argument to xInput */
  165278. int bEof; /* Set to true after xInput finished */
  165279. };
  165280. /*
  165281. ** Structure for changeset iterators.
  165282. */
  165283. struct sqlite3_changeset_iter {
  165284. SessionInput in; /* Input buffer or stream */
  165285. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  165286. int bPatchset; /* True if this is a patchset */
  165287. int rc; /* Iterator error code */
  165288. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  165289. char *zTab; /* Current table */
  165290. int nCol; /* Number of columns in zTab */
  165291. int op; /* Current operation */
  165292. int bIndirect; /* True if current change was indirect */
  165293. u8 *abPK; /* Primary key array */
  165294. sqlite3_value **apValue; /* old.* and new.* values */
  165295. };
  165296. /*
  165297. ** Each session object maintains a set of the following structures, one
  165298. ** for each table the session object is monitoring. The structures are
  165299. ** stored in a linked list starting at sqlite3_session.pTable.
  165300. **
  165301. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  165302. ** been modified in any way since the session object was attached to the
  165303. ** table.
  165304. **
  165305. ** The data associated with each hash-table entry is a structure containing
  165306. ** a subset of the initial values that the modified row contained at the
  165307. ** start of the session. Or no initial values if the row was inserted.
  165308. */
  165309. struct SessionTable {
  165310. SessionTable *pNext;
  165311. char *zName; /* Local name of table */
  165312. int nCol; /* Number of columns in table zName */
  165313. const char **azCol; /* Column names */
  165314. u8 *abPK; /* Array of primary key flags */
  165315. int nEntry; /* Total number of entries in hash table */
  165316. int nChange; /* Size of apChange[] array */
  165317. SessionChange **apChange; /* Hash table buckets */
  165318. };
  165319. /*
  165320. ** RECORD FORMAT:
  165321. **
  165322. ** The following record format is similar to (but not compatible with) that
  165323. ** used in SQLite database files. This format is used as part of the
  165324. ** change-set binary format, and so must be architecture independent.
  165325. **
  165326. ** Unlike the SQLite database record format, each field is self-contained -
  165327. ** there is no separation of header and data. Each field begins with a
  165328. ** single byte describing its type, as follows:
  165329. **
  165330. ** 0x00: Undefined value.
  165331. ** 0x01: Integer value.
  165332. ** 0x02: Real value.
  165333. ** 0x03: Text value.
  165334. ** 0x04: Blob value.
  165335. ** 0x05: SQL NULL value.
  165336. **
  165337. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  165338. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  165339. ** only of the single type byte. For other types of values, the type byte
  165340. ** is followed by:
  165341. **
  165342. ** Text values:
  165343. ** A varint containing the number of bytes in the value (encoded using
  165344. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  165345. ** of the text value. There is no nul terminator.
  165346. **
  165347. ** Blob values:
  165348. ** A varint containing the number of bytes in the value, followed by
  165349. ** a buffer containing the value itself.
  165350. **
  165351. ** Integer values:
  165352. ** An 8-byte big-endian integer value.
  165353. **
  165354. ** Real values:
  165355. ** An 8-byte big-endian IEEE 754-2008 real value.
  165356. **
  165357. ** Varint values are encoded in the same way as varints in the SQLite
  165358. ** record format.
  165359. **
  165360. ** CHANGESET FORMAT:
  165361. **
  165362. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  165363. ** one or more tables. Operations on a single table are grouped together,
  165364. ** but may occur in any order (i.e. deletes, updates and inserts are all
  165365. ** mixed together).
  165366. **
  165367. ** Each group of changes begins with a table header:
  165368. **
  165369. ** 1 byte: Constant 0x54 (capital 'T')
  165370. ** Varint: Number of columns in the table.
  165371. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  165372. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  165373. **
  165374. ** Followed by one or more changes to the table.
  165375. **
  165376. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  165377. ** 1 byte: The "indirect-change" flag.
  165378. ** old.* record: (delete and update only)
  165379. ** new.* record: (insert and update only)
  165380. **
  165381. ** The "old.*" and "new.*" records, if present, are N field records in the
  165382. ** format described above under "RECORD FORMAT", where N is the number of
  165383. ** columns in the table. The i'th field of each record is associated with
  165384. ** the i'th column of the table, counting from left to right in the order
  165385. ** in which columns were declared in the CREATE TABLE statement.
  165386. **
  165387. ** The new.* record that is part of each INSERT change contains the values
  165388. ** that make up the new row. Similarly, the old.* record that is part of each
  165389. ** DELETE change contains the values that made up the row that was deleted
  165390. ** from the database. In the changeset format, the records that are part
  165391. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  165392. ** fields.
  165393. **
  165394. ** Within the old.* record associated with an UPDATE change, all fields
  165395. ** associated with table columns that are not PRIMARY KEY columns and are
  165396. ** not modified by the UPDATE change are set to "undefined". Other fields
  165397. ** are set to the values that made up the row before the UPDATE that the
  165398. ** change records took place. Within the new.* record, fields associated
  165399. ** with table columns modified by the UPDATE change contain the new
  165400. ** values. Fields associated with table columns that are not modified
  165401. ** are set to "undefined".
  165402. **
  165403. ** PATCHSET FORMAT:
  165404. **
  165405. ** A patchset is also a collection of changes. It is similar to a changeset,
  165406. ** but leaves undefined those fields that are not useful if no conflict
  165407. ** resolution is required when applying the changeset.
  165408. **
  165409. ** Each group of changes begins with a table header:
  165410. **
  165411. ** 1 byte: Constant 0x50 (capital 'P')
  165412. ** Varint: Number of columns in the table.
  165413. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  165414. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  165415. **
  165416. ** Followed by one or more changes to the table.
  165417. **
  165418. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  165419. ** 1 byte: The "indirect-change" flag.
  165420. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  165421. ** full record for INSERT).
  165422. **
  165423. ** As in the changeset format, each field of the single record that is part
  165424. ** of a patchset change is associated with the correspondingly positioned
  165425. ** table column, counting from left to right within the CREATE TABLE
  165426. ** statement.
  165427. **
  165428. ** For a DELETE change, all fields within the record except those associated
  165429. ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
  165430. ** contain the values identifying the row to delete.
  165431. **
  165432. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  165433. ** columns and columns that are modified by the UPDATE are set to "undefined".
  165434. ** PRIMARY KEY fields contain the values identifying the table row to update,
  165435. ** and fields associated with modified columns contain the new column values.
  165436. **
  165437. ** The records associated with INSERT changes are in the same format as for
  165438. ** changesets. It is not possible for a record associated with an INSERT
  165439. ** change to contain a field set to "undefined".
  165440. */
  165441. /*
  165442. ** For each row modified during a session, there exists a single instance of
  165443. ** this structure stored in a SessionTable.aChange[] hash table.
  165444. */
  165445. struct SessionChange {
  165446. int op; /* One of UPDATE, DELETE, INSERT */
  165447. int bIndirect; /* True if this change is "indirect" */
  165448. int nRecord; /* Number of bytes in buffer aRecord[] */
  165449. u8 *aRecord; /* Buffer containing old.* record */
  165450. SessionChange *pNext; /* For hash-table collisions */
  165451. };
  165452. /*
  165453. ** Write a varint with value iVal into the buffer at aBuf. Return the
  165454. ** number of bytes written.
  165455. */
  165456. static int sessionVarintPut(u8 *aBuf, int iVal){
  165457. return putVarint32(aBuf, iVal);
  165458. }
  165459. /*
  165460. ** Return the number of bytes required to store value iVal as a varint.
  165461. */
  165462. static int sessionVarintLen(int iVal){
  165463. return sqlite3VarintLen(iVal);
  165464. }
  165465. /*
  165466. ** Read a varint value from aBuf[] into *piVal. Return the number of
  165467. ** bytes read.
  165468. */
  165469. static int sessionVarintGet(u8 *aBuf, int *piVal){
  165470. return getVarint32(aBuf, *piVal);
  165471. }
  165472. /* Load an unaligned and unsigned 32-bit integer */
  165473. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  165474. /*
  165475. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  165476. ** the value read.
  165477. */
  165478. static sqlite3_int64 sessionGetI64(u8 *aRec){
  165479. u64 x = SESSION_UINT32(aRec);
  165480. u32 y = SESSION_UINT32(aRec+4);
  165481. x = (x<<32) + y;
  165482. return (sqlite3_int64)x;
  165483. }
  165484. /*
  165485. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  165486. */
  165487. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  165488. aBuf[0] = (i>>56) & 0xFF;
  165489. aBuf[1] = (i>>48) & 0xFF;
  165490. aBuf[2] = (i>>40) & 0xFF;
  165491. aBuf[3] = (i>>32) & 0xFF;
  165492. aBuf[4] = (i>>24) & 0xFF;
  165493. aBuf[5] = (i>>16) & 0xFF;
  165494. aBuf[6] = (i>> 8) & 0xFF;
  165495. aBuf[7] = (i>> 0) & 0xFF;
  165496. }
  165497. /*
  165498. ** This function is used to serialize the contents of value pValue (see
  165499. ** comment titled "RECORD FORMAT" above).
  165500. **
  165501. ** If it is non-NULL, the serialized form of the value is written to
  165502. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  165503. ** returning. Or, if aBuf is NULL, the only thing this function does is
  165504. ** set *pnWrite.
  165505. **
  165506. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  165507. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  165508. ** SQLITE_NOMEM is returned.
  165509. */
  165510. static int sessionSerializeValue(
  165511. u8 *aBuf, /* If non-NULL, write serialized value here */
  165512. sqlite3_value *pValue, /* Value to serialize */
  165513. int *pnWrite /* IN/OUT: Increment by bytes written */
  165514. ){
  165515. int nByte; /* Size of serialized value in bytes */
  165516. if( pValue ){
  165517. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  165518. eType = sqlite3_value_type(pValue);
  165519. if( aBuf ) aBuf[0] = eType;
  165520. switch( eType ){
  165521. case SQLITE_NULL:
  165522. nByte = 1;
  165523. break;
  165524. case SQLITE_INTEGER:
  165525. case SQLITE_FLOAT:
  165526. if( aBuf ){
  165527. /* TODO: SQLite does something special to deal with mixed-endian
  165528. ** floating point values (e.g. ARM7). This code probably should
  165529. ** too. */
  165530. u64 i;
  165531. if( eType==SQLITE_INTEGER ){
  165532. i = (u64)sqlite3_value_int64(pValue);
  165533. }else{
  165534. double r;
  165535. assert( sizeof(double)==8 && sizeof(u64)==8 );
  165536. r = sqlite3_value_double(pValue);
  165537. memcpy(&i, &r, 8);
  165538. }
  165539. sessionPutI64(&aBuf[1], i);
  165540. }
  165541. nByte = 9;
  165542. break;
  165543. default: {
  165544. u8 *z;
  165545. int n;
  165546. int nVarint;
  165547. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  165548. if( eType==SQLITE_TEXT ){
  165549. z = (u8 *)sqlite3_value_text(pValue);
  165550. }else{
  165551. z = (u8 *)sqlite3_value_blob(pValue);
  165552. }
  165553. n = sqlite3_value_bytes(pValue);
  165554. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  165555. nVarint = sessionVarintLen(n);
  165556. if( aBuf ){
  165557. sessionVarintPut(&aBuf[1], n);
  165558. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  165559. }
  165560. nByte = 1 + nVarint + n;
  165561. break;
  165562. }
  165563. }
  165564. }else{
  165565. nByte = 1;
  165566. if( aBuf ) aBuf[0] = '\0';
  165567. }
  165568. if( pnWrite ) *pnWrite += nByte;
  165569. return SQLITE_OK;
  165570. }
  165571. /*
  165572. ** This macro is used to calculate hash key values for data structures. In
  165573. ** order to use this macro, the entire data structure must be represented
  165574. ** as a series of unsigned integers. In order to calculate a hash-key value
  165575. ** for a data structure represented as three such integers, the macro may
  165576. ** then be used as follows:
  165577. **
  165578. ** int hash_key_value;
  165579. ** hash_key_value = HASH_APPEND(0, <value 1>);
  165580. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  165581. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  165582. **
  165583. ** In practice, the data structures this macro is used for are the primary
  165584. ** key values of modified rows.
  165585. */
  165586. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  165587. /*
  165588. ** Append the hash of the 64-bit integer passed as the second argument to the
  165589. ** hash-key value passed as the first. Return the new hash-key value.
  165590. */
  165591. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  165592. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  165593. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  165594. }
  165595. /*
  165596. ** Append the hash of the blob passed via the second and third arguments to
  165597. ** the hash-key value passed as the first. Return the new hash-key value.
  165598. */
  165599. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  165600. int i;
  165601. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  165602. return h;
  165603. }
  165604. /*
  165605. ** Append the hash of the data type passed as the second argument to the
  165606. ** hash-key value passed as the first. Return the new hash-key value.
  165607. */
  165608. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  165609. return HASH_APPEND(h, eType);
  165610. }
  165611. /*
  165612. ** This function may only be called from within a pre-update callback.
  165613. ** It calculates a hash based on the primary key values of the old.* or
  165614. ** new.* row currently available and, assuming no error occurs, writes it to
  165615. ** *piHash before returning. If the primary key contains one or more NULL
  165616. ** values, *pbNullPK is set to true before returning.
  165617. **
  165618. ** If an error occurs, an SQLite error code is returned and the final values
  165619. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  165620. ** and the output variables are set as described above.
  165621. */
  165622. static int sessionPreupdateHash(
  165623. sqlite3_session *pSession, /* Session object that owns pTab */
  165624. SessionTable *pTab, /* Session table handle */
  165625. int bNew, /* True to hash the new.* PK */
  165626. int *piHash, /* OUT: Hash value */
  165627. int *pbNullPK /* OUT: True if there are NULL values in PK */
  165628. ){
  165629. unsigned int h = 0; /* Hash value to return */
  165630. int i; /* Used to iterate through columns */
  165631. assert( *pbNullPK==0 );
  165632. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  165633. for(i=0; i<pTab->nCol; i++){
  165634. if( pTab->abPK[i] ){
  165635. int rc;
  165636. int eType;
  165637. sqlite3_value *pVal;
  165638. if( bNew ){
  165639. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  165640. }else{
  165641. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  165642. }
  165643. if( rc!=SQLITE_OK ) return rc;
  165644. eType = sqlite3_value_type(pVal);
  165645. h = sessionHashAppendType(h, eType);
  165646. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165647. i64 iVal;
  165648. if( eType==SQLITE_INTEGER ){
  165649. iVal = sqlite3_value_int64(pVal);
  165650. }else{
  165651. double rVal = sqlite3_value_double(pVal);
  165652. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  165653. memcpy(&iVal, &rVal, 8);
  165654. }
  165655. h = sessionHashAppendI64(h, iVal);
  165656. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165657. const u8 *z;
  165658. int n;
  165659. if( eType==SQLITE_TEXT ){
  165660. z = (const u8 *)sqlite3_value_text(pVal);
  165661. }else{
  165662. z = (const u8 *)sqlite3_value_blob(pVal);
  165663. }
  165664. n = sqlite3_value_bytes(pVal);
  165665. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  165666. h = sessionHashAppendBlob(h, n, z);
  165667. }else{
  165668. assert( eType==SQLITE_NULL );
  165669. *pbNullPK = 1;
  165670. }
  165671. }
  165672. }
  165673. *piHash = (h % pTab->nChange);
  165674. return SQLITE_OK;
  165675. }
  165676. /*
  165677. ** The buffer that the argument points to contains a serialized SQL value.
  165678. ** Return the number of bytes of space occupied by the value (including
  165679. ** the type byte).
  165680. */
  165681. static int sessionSerialLen(u8 *a){
  165682. int e = *a;
  165683. int n;
  165684. if( e==0 ) return 1;
  165685. if( e==SQLITE_NULL ) return 1;
  165686. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  165687. return sessionVarintGet(&a[1], &n) + 1 + n;
  165688. }
  165689. /*
  165690. ** Based on the primary key values stored in change aRecord, calculate a
  165691. ** hash key. Assume the has table has nBucket buckets. The hash keys
  165692. ** calculated by this function are compatible with those calculated by
  165693. ** sessionPreupdateHash().
  165694. **
  165695. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  165696. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  165697. */
  165698. static unsigned int sessionChangeHash(
  165699. SessionTable *pTab, /* Table handle */
  165700. int bPkOnly, /* Record consists of PK fields only */
  165701. u8 *aRecord, /* Change record */
  165702. int nBucket /* Assume this many buckets in hash table */
  165703. ){
  165704. unsigned int h = 0; /* Value to return */
  165705. int i; /* Used to iterate through columns */
  165706. u8 *a = aRecord; /* Used to iterate through change record */
  165707. for(i=0; i<pTab->nCol; i++){
  165708. int eType = *a;
  165709. int isPK = pTab->abPK[i];
  165710. if( bPkOnly && isPK==0 ) continue;
  165711. /* It is not possible for eType to be SQLITE_NULL here. The session
  165712. ** module does not record changes for rows with NULL values stored in
  165713. ** primary key columns. */
  165714. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  165715. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  165716. || eType==SQLITE_NULL || eType==0
  165717. );
  165718. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  165719. if( isPK ){
  165720. a++;
  165721. h = sessionHashAppendType(h, eType);
  165722. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165723. h = sessionHashAppendI64(h, sessionGetI64(a));
  165724. a += 8;
  165725. }else{
  165726. int n;
  165727. a += sessionVarintGet(a, &n);
  165728. h = sessionHashAppendBlob(h, n, a);
  165729. a += n;
  165730. }
  165731. }else{
  165732. a += sessionSerialLen(a);
  165733. }
  165734. }
  165735. return (h % nBucket);
  165736. }
  165737. /*
  165738. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  165739. ** This function returns true if the two records apply to the same row (i.e.
  165740. ** have the same values stored in the primary key columns), or false
  165741. ** otherwise.
  165742. */
  165743. static int sessionChangeEqual(
  165744. SessionTable *pTab, /* Table used for PK definition */
  165745. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  165746. u8 *aLeft, /* Change record */
  165747. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  165748. u8 *aRight /* Change record */
  165749. ){
  165750. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  165751. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  165752. int iCol; /* Used to iterate through table columns */
  165753. for(iCol=0; iCol<pTab->nCol; iCol++){
  165754. if( pTab->abPK[iCol] ){
  165755. int n1 = sessionSerialLen(a1);
  165756. int n2 = sessionSerialLen(a2);
  165757. if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
  165758. return 0;
  165759. }
  165760. a1 += n1;
  165761. a2 += n2;
  165762. }else{
  165763. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  165764. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  165765. }
  165766. }
  165767. return 1;
  165768. }
  165769. /*
  165770. ** Arguments aLeft and aRight both point to buffers containing change
  165771. ** records with nCol columns. This function "merges" the two records into
  165772. ** a single records which is written to the buffer at *paOut. *paOut is
  165773. ** then set to point to one byte after the last byte written before
  165774. ** returning.
  165775. **
  165776. ** The merging of records is done as follows: For each column, if the
  165777. ** aRight record contains a value for the column, copy the value from
  165778. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  165779. ** record contains a value for a given column, then neither does the
  165780. ** output record.
  165781. */
  165782. static void sessionMergeRecord(
  165783. u8 **paOut,
  165784. int nCol,
  165785. u8 *aLeft,
  165786. u8 *aRight
  165787. ){
  165788. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  165789. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  165790. u8 *aOut = *paOut; /* Output cursor */
  165791. int iCol; /* Used to iterate from 0 to nCol */
  165792. for(iCol=0; iCol<nCol; iCol++){
  165793. int n1 = sessionSerialLen(a1);
  165794. int n2 = sessionSerialLen(a2);
  165795. if( *a2 ){
  165796. memcpy(aOut, a2, n2);
  165797. aOut += n2;
  165798. }else{
  165799. memcpy(aOut, a1, n1);
  165800. aOut += n1;
  165801. }
  165802. a1 += n1;
  165803. a2 += n2;
  165804. }
  165805. *paOut = aOut;
  165806. }
  165807. /*
  165808. ** This is a helper function used by sessionMergeUpdate().
  165809. **
  165810. ** When this function is called, both *paOne and *paTwo point to a value
  165811. ** within a change record. Before it returns, both have been advanced so
  165812. ** as to point to the next value in the record.
  165813. **
  165814. ** If, when this function is called, *paTwo points to a valid value (i.e.
  165815. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  165816. ** pointer is returned and *pnVal is set to the number of bytes in the
  165817. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  165818. ** set to the number of bytes in the value at *paOne. If *paOne points
  165819. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  165820. **
  165821. ** if( *paTwo is valid ) return *paTwo;
  165822. ** return *paOne;
  165823. **
  165824. */
  165825. static u8 *sessionMergeValue(
  165826. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  165827. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  165828. int *pnVal /* OUT: Bytes in returned value */
  165829. ){
  165830. u8 *a1 = *paOne;
  165831. u8 *a2 = *paTwo;
  165832. u8 *pRet = 0;
  165833. int n1;
  165834. assert( a1 );
  165835. if( a2 ){
  165836. int n2 = sessionSerialLen(a2);
  165837. if( *a2 ){
  165838. *pnVal = n2;
  165839. pRet = a2;
  165840. }
  165841. *paTwo = &a2[n2];
  165842. }
  165843. n1 = sessionSerialLen(a1);
  165844. if( pRet==0 ){
  165845. *pnVal = n1;
  165846. pRet = a1;
  165847. }
  165848. *paOne = &a1[n1];
  165849. return pRet;
  165850. }
  165851. /*
  165852. ** This function is used by changeset_concat() to merge two UPDATE changes
  165853. ** on the same row.
  165854. */
  165855. static int sessionMergeUpdate(
  165856. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  165857. SessionTable *pTab, /* Table change pertains to */
  165858. int bPatchset, /* True if records are patchset records */
  165859. u8 *aOldRecord1, /* old.* record for first change */
  165860. u8 *aOldRecord2, /* old.* record for second change */
  165861. u8 *aNewRecord1, /* new.* record for first change */
  165862. u8 *aNewRecord2 /* new.* record for second change */
  165863. ){
  165864. u8 *aOld1 = aOldRecord1;
  165865. u8 *aOld2 = aOldRecord2;
  165866. u8 *aNew1 = aNewRecord1;
  165867. u8 *aNew2 = aNewRecord2;
  165868. u8 *aOut = *paOut;
  165869. int i;
  165870. if( bPatchset==0 ){
  165871. int bRequired = 0;
  165872. assert( aOldRecord1 && aNewRecord1 );
  165873. /* Write the old.* vector first. */
  165874. for(i=0; i<pTab->nCol; i++){
  165875. int nOld;
  165876. u8 *aOld;
  165877. int nNew;
  165878. u8 *aNew;
  165879. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  165880. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  165881. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  165882. if( pTab->abPK[i]==0 ) bRequired = 1;
  165883. memcpy(aOut, aOld, nOld);
  165884. aOut += nOld;
  165885. }else{
  165886. *(aOut++) = '\0';
  165887. }
  165888. }
  165889. if( !bRequired ) return 0;
  165890. }
  165891. /* Write the new.* vector */
  165892. aOld1 = aOldRecord1;
  165893. aOld2 = aOldRecord2;
  165894. aNew1 = aNewRecord1;
  165895. aNew2 = aNewRecord2;
  165896. for(i=0; i<pTab->nCol; i++){
  165897. int nOld;
  165898. u8 *aOld;
  165899. int nNew;
  165900. u8 *aNew;
  165901. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  165902. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  165903. if( bPatchset==0
  165904. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  165905. ){
  165906. *(aOut++) = '\0';
  165907. }else{
  165908. memcpy(aOut, aNew, nNew);
  165909. aOut += nNew;
  165910. }
  165911. }
  165912. *paOut = aOut;
  165913. return 1;
  165914. }
  165915. /*
  165916. ** This function is only called from within a pre-update-hook callback.
  165917. ** It determines if the current pre-update-hook change affects the same row
  165918. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  165919. ** if the pre-update-hook does not affect the same row as pChange, it returns
  165920. ** false.
  165921. */
  165922. static int sessionPreupdateEqual(
  165923. sqlite3_session *pSession, /* Session object that owns SessionTable */
  165924. SessionTable *pTab, /* Table associated with change */
  165925. SessionChange *pChange, /* Change to compare to */
  165926. int op /* Current pre-update operation */
  165927. ){
  165928. int iCol; /* Used to iterate through columns */
  165929. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  165930. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  165931. for(iCol=0; iCol<pTab->nCol; iCol++){
  165932. if( !pTab->abPK[iCol] ){
  165933. a += sessionSerialLen(a);
  165934. }else{
  165935. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  165936. int rc; /* Error code from preupdate_new/old */
  165937. int eType = *a++; /* Type of value from change record */
  165938. /* The following calls to preupdate_new() and preupdate_old() can not
  165939. ** fail. This is because they cache their return values, and by the
  165940. ** time control flows to here they have already been called once from
  165941. ** within sessionPreupdateHash(). The first two asserts below verify
  165942. ** this (that the method has already been called). */
  165943. if( op==SQLITE_INSERT ){
  165944. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  165945. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  165946. }else{
  165947. /* assert( db->pPreUpdate->pUnpacked ); */
  165948. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  165949. }
  165950. assert( rc==SQLITE_OK );
  165951. if( sqlite3_value_type(pVal)!=eType ) return 0;
  165952. /* A SessionChange object never has a NULL value in a PK column */
  165953. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  165954. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  165955. );
  165956. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165957. i64 iVal = sessionGetI64(a);
  165958. a += 8;
  165959. if( eType==SQLITE_INTEGER ){
  165960. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  165961. }else{
  165962. double rVal;
  165963. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  165964. memcpy(&rVal, &iVal, 8);
  165965. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  165966. }
  165967. }else{
  165968. int n;
  165969. const u8 *z;
  165970. a += sessionVarintGet(a, &n);
  165971. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  165972. if( eType==SQLITE_TEXT ){
  165973. z = sqlite3_value_text(pVal);
  165974. }else{
  165975. z = sqlite3_value_blob(pVal);
  165976. }
  165977. if( memcmp(a, z, n) ) return 0;
  165978. a += n;
  165979. break;
  165980. }
  165981. }
  165982. }
  165983. return 1;
  165984. }
  165985. /*
  165986. ** If required, grow the hash table used to store changes on table pTab
  165987. ** (part of the session pSession). If a fatal OOM error occurs, set the
  165988. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  165989. ** SQLITE_OK.
  165990. **
  165991. ** It is possible that a non-fatal OOM error occurs in this function. In
  165992. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  165993. ** Growing the hash table in this case is a performance optimization only,
  165994. ** it is not required for correct operation.
  165995. */
  165996. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  165997. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  165998. int i;
  165999. SessionChange **apNew;
  166000. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  166001. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  166002. if( apNew==0 ){
  166003. if( pTab->nChange==0 ){
  166004. return SQLITE_ERROR;
  166005. }
  166006. return SQLITE_OK;
  166007. }
  166008. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  166009. for(i=0; i<pTab->nChange; i++){
  166010. SessionChange *p;
  166011. SessionChange *pNext;
  166012. for(p=pTab->apChange[i]; p; p=pNext){
  166013. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  166014. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  166015. pNext = p->pNext;
  166016. p->pNext = apNew[iHash];
  166017. apNew[iHash] = p;
  166018. }
  166019. }
  166020. sqlite3_free(pTab->apChange);
  166021. pTab->nChange = nNew;
  166022. pTab->apChange = apNew;
  166023. }
  166024. return SQLITE_OK;
  166025. }
  166026. /*
  166027. ** This function queries the database for the names of the columns of table
  166028. ** zThis, in schema zDb. It is expected that the table has nCol columns. If
  166029. ** not, SQLITE_SCHEMA is returned and none of the output variables are
  166030. ** populated.
  166031. **
  166032. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  166033. ** of columns in the database table and variable *pzTab is set to point to a
  166034. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  166035. ** point to an array of pointers to column names. And *pabPK (again, if not
  166036. ** NULL) is set to point to an array of booleans - true if the corresponding
  166037. ** column is part of the primary key.
  166038. **
  166039. ** For example, if the table is declared as:
  166040. **
  166041. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  166042. **
  166043. ** Then the four output variables are populated as follows:
  166044. **
  166045. ** *pnCol = 4
  166046. ** *pzTab = "tbl1"
  166047. ** *pazCol = {"w", "x", "y", "z"}
  166048. ** *pabPK = {1, 0, 0, 1}
  166049. **
  166050. ** All returned buffers are part of the same single allocation, which must
  166051. ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
  166052. ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
  166053. ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
  166054. */
  166055. static int sessionTableInfo(
  166056. sqlite3 *db, /* Database connection */
  166057. const char *zDb, /* Name of attached database (e.g. "main") */
  166058. const char *zThis, /* Table name */
  166059. int *pnCol, /* OUT: number of columns */
  166060. const char **pzTab, /* OUT: Copy of zThis */
  166061. const char ***pazCol, /* OUT: Array of column names for table */
  166062. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  166063. ){
  166064. char *zPragma;
  166065. sqlite3_stmt *pStmt;
  166066. int rc;
  166067. int nByte;
  166068. int nDbCol = 0;
  166069. int nThis;
  166070. int i;
  166071. u8 *pAlloc = 0;
  166072. char **azCol = 0;
  166073. u8 *abPK = 0;
  166074. assert( pazCol && pabPK );
  166075. nThis = sqlite3Strlen30(zThis);
  166076. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  166077. if( !zPragma ) return SQLITE_NOMEM;
  166078. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  166079. sqlite3_free(zPragma);
  166080. if( rc!=SQLITE_OK ) return rc;
  166081. nByte = nThis + 1;
  166082. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  166083. nByte += sqlite3_column_bytes(pStmt, 1);
  166084. nDbCol++;
  166085. }
  166086. rc = sqlite3_reset(pStmt);
  166087. if( rc==SQLITE_OK ){
  166088. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  166089. pAlloc = sqlite3_malloc(nByte);
  166090. if( pAlloc==0 ){
  166091. rc = SQLITE_NOMEM;
  166092. }
  166093. }
  166094. if( rc==SQLITE_OK ){
  166095. azCol = (char **)pAlloc;
  166096. pAlloc = (u8 *)&azCol[nDbCol];
  166097. abPK = (u8 *)pAlloc;
  166098. pAlloc = &abPK[nDbCol];
  166099. if( pzTab ){
  166100. memcpy(pAlloc, zThis, nThis+1);
  166101. *pzTab = (char *)pAlloc;
  166102. pAlloc += nThis+1;
  166103. }
  166104. i = 0;
  166105. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  166106. int nName = sqlite3_column_bytes(pStmt, 1);
  166107. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  166108. if( zName==0 ) break;
  166109. memcpy(pAlloc, zName, nName+1);
  166110. azCol[i] = (char *)pAlloc;
  166111. pAlloc += nName+1;
  166112. abPK[i] = sqlite3_column_int(pStmt, 5);
  166113. i++;
  166114. }
  166115. rc = sqlite3_reset(pStmt);
  166116. }
  166117. /* If successful, populate the output variables. Otherwise, zero them and
  166118. ** free any allocation made. An error code will be returned in this case.
  166119. */
  166120. if( rc==SQLITE_OK ){
  166121. *pazCol = (const char **)azCol;
  166122. *pabPK = abPK;
  166123. *pnCol = nDbCol;
  166124. }else{
  166125. *pazCol = 0;
  166126. *pabPK = 0;
  166127. *pnCol = 0;
  166128. if( pzTab ) *pzTab = 0;
  166129. sqlite3_free(azCol);
  166130. }
  166131. sqlite3_finalize(pStmt);
  166132. return rc;
  166133. }
  166134. /*
  166135. ** This function is only called from within a pre-update handler for a
  166136. ** write to table pTab, part of session pSession. If this is the first
  166137. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  166138. ** abPK[] arrays accordingly.
  166139. **
  166140. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  166141. ** non-zero returned. Or, if no error occurs but the table has no primary
  166142. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  166143. ** indicate that updates on this table should be ignored. SessionTable.abPK
  166144. ** is set to NULL in this case.
  166145. */
  166146. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  166147. if( pTab->nCol==0 ){
  166148. u8 *abPK;
  166149. assert( pTab->azCol==0 || pTab->abPK==0 );
  166150. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  166151. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  166152. );
  166153. if( pSession->rc==SQLITE_OK ){
  166154. int i;
  166155. for(i=0; i<pTab->nCol; i++){
  166156. if( abPK[i] ){
  166157. pTab->abPK = abPK;
  166158. break;
  166159. }
  166160. }
  166161. }
  166162. }
  166163. return (pSession->rc || pTab->abPK==0);
  166164. }
  166165. /*
  166166. ** This function is only called from with a pre-update-hook reporting a
  166167. ** change on table pTab (attached to session pSession). The type of change
  166168. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  166169. **
  166170. ** Unless one is already present or an error occurs, an entry is added
  166171. ** to the changed-rows hash table associated with table pTab.
  166172. */
  166173. static void sessionPreupdateOneChange(
  166174. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  166175. sqlite3_session *pSession, /* Session object pTab is attached to */
  166176. SessionTable *pTab /* Table that change applies to */
  166177. ){
  166178. int iHash;
  166179. int bNull = 0;
  166180. int rc = SQLITE_OK;
  166181. if( pSession->rc ) return;
  166182. /* Load table details if required */
  166183. if( sessionInitTable(pSession, pTab) ) return;
  166184. /* Check the number of columns in this xPreUpdate call matches the
  166185. ** number of columns in the table. */
  166186. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  166187. pSession->rc = SQLITE_SCHEMA;
  166188. return;
  166189. }
  166190. /* Grow the hash table if required */
  166191. if( sessionGrowHash(0, pTab) ){
  166192. pSession->rc = SQLITE_NOMEM;
  166193. return;
  166194. }
  166195. /* Calculate the hash-key for this change. If the primary key of the row
  166196. ** includes a NULL value, exit early. Such changes are ignored by the
  166197. ** session module. */
  166198. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  166199. if( rc!=SQLITE_OK ) goto error_out;
  166200. if( bNull==0 ){
  166201. /* Search the hash table for an existing record for this row. */
  166202. SessionChange *pC;
  166203. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  166204. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  166205. }
  166206. if( pC==0 ){
  166207. /* Create a new change object containing all the old values (if
  166208. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  166209. ** values (if this is an INSERT). */
  166210. SessionChange *pChange; /* New change object */
  166211. int nByte; /* Number of bytes to allocate */
  166212. int i; /* Used to iterate through columns */
  166213. assert( rc==SQLITE_OK );
  166214. pTab->nEntry++;
  166215. /* Figure out how large an allocation is required */
  166216. nByte = sizeof(SessionChange);
  166217. for(i=0; i<pTab->nCol; i++){
  166218. sqlite3_value *p = 0;
  166219. if( op!=SQLITE_INSERT ){
  166220. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  166221. assert( trc==SQLITE_OK );
  166222. }else if( pTab->abPK[i] ){
  166223. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  166224. assert( trc==SQLITE_OK );
  166225. }
  166226. /* This may fail if SQLite value p contains a utf-16 string that must
  166227. ** be converted to utf-8 and an OOM error occurs while doing so. */
  166228. rc = sessionSerializeValue(0, p, &nByte);
  166229. if( rc!=SQLITE_OK ) goto error_out;
  166230. }
  166231. /* Allocate the change object */
  166232. pChange = (SessionChange *)sqlite3_malloc(nByte);
  166233. if( !pChange ){
  166234. rc = SQLITE_NOMEM;
  166235. goto error_out;
  166236. }else{
  166237. memset(pChange, 0, sizeof(SessionChange));
  166238. pChange->aRecord = (u8 *)&pChange[1];
  166239. }
  166240. /* Populate the change object. None of the preupdate_old(),
  166241. ** preupdate_new() or SerializeValue() calls below may fail as all
  166242. ** required values and encodings have already been cached in memory.
  166243. ** It is not possible for an OOM to occur in this block. */
  166244. nByte = 0;
  166245. for(i=0; i<pTab->nCol; i++){
  166246. sqlite3_value *p = 0;
  166247. if( op!=SQLITE_INSERT ){
  166248. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  166249. }else if( pTab->abPK[i] ){
  166250. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  166251. }
  166252. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  166253. }
  166254. /* Add the change to the hash-table */
  166255. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  166256. pChange->bIndirect = 1;
  166257. }
  166258. pChange->nRecord = nByte;
  166259. pChange->op = op;
  166260. pChange->pNext = pTab->apChange[iHash];
  166261. pTab->apChange[iHash] = pChange;
  166262. }else if( pC->bIndirect ){
  166263. /* If the existing change is considered "indirect", but this current
  166264. ** change is "direct", mark the change object as direct. */
  166265. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  166266. && pSession->bIndirect==0
  166267. ){
  166268. pC->bIndirect = 0;
  166269. }
  166270. }
  166271. }
  166272. /* If an error has occurred, mark the session object as failed. */
  166273. error_out:
  166274. if( rc!=SQLITE_OK ){
  166275. pSession->rc = rc;
  166276. }
  166277. }
  166278. static int sessionFindTable(
  166279. sqlite3_session *pSession,
  166280. const char *zName,
  166281. SessionTable **ppTab
  166282. ){
  166283. int rc = SQLITE_OK;
  166284. int nName = sqlite3Strlen30(zName);
  166285. SessionTable *pRet;
  166286. /* Search for an existing table */
  166287. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  166288. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  166289. }
  166290. if( pRet==0 && pSession->bAutoAttach ){
  166291. /* If there is a table-filter configured, invoke it. If it returns 0,
  166292. ** do not automatically add the new table. */
  166293. if( pSession->xTableFilter==0
  166294. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  166295. ){
  166296. rc = sqlite3session_attach(pSession, zName);
  166297. if( rc==SQLITE_OK ){
  166298. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  166299. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  166300. }
  166301. }
  166302. }
  166303. assert( rc==SQLITE_OK || pRet==0 );
  166304. *ppTab = pRet;
  166305. return rc;
  166306. }
  166307. /*
  166308. ** The 'pre-update' hook registered by this module with SQLite databases.
  166309. */
  166310. static void xPreUpdate(
  166311. void *pCtx, /* Copy of third arg to preupdate_hook() */
  166312. sqlite3 *db, /* Database handle */
  166313. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  166314. char const *zDb, /* Database name */
  166315. char const *zName, /* Table name */
  166316. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  166317. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  166318. ){
  166319. sqlite3_session *pSession;
  166320. int nDb = sqlite3Strlen30(zDb);
  166321. assert( sqlite3_mutex_held(db->mutex) );
  166322. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  166323. SessionTable *pTab;
  166324. /* If this session is attached to a different database ("main", "temp"
  166325. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  166326. ** to the next session object attached to this database. */
  166327. if( pSession->bEnable==0 ) continue;
  166328. if( pSession->rc ) continue;
  166329. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  166330. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  166331. if( pTab ){
  166332. assert( pSession->rc==SQLITE_OK );
  166333. sessionPreupdateOneChange(op, pSession, pTab);
  166334. if( op==SQLITE_UPDATE ){
  166335. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  166336. }
  166337. }
  166338. }
  166339. }
  166340. /*
  166341. ** The pre-update hook implementations.
  166342. */
  166343. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  166344. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  166345. }
  166346. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  166347. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  166348. }
  166349. static int sessionPreupdateCount(void *pCtx){
  166350. return sqlite3_preupdate_count((sqlite3*)pCtx);
  166351. }
  166352. static int sessionPreupdateDepth(void *pCtx){
  166353. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  166354. }
  166355. /*
  166356. ** Install the pre-update hooks on the session object passed as the only
  166357. ** argument.
  166358. */
  166359. static void sessionPreupdateHooks(
  166360. sqlite3_session *pSession
  166361. ){
  166362. pSession->hook.pCtx = (void*)pSession->db;
  166363. pSession->hook.xOld = sessionPreupdateOld;
  166364. pSession->hook.xNew = sessionPreupdateNew;
  166365. pSession->hook.xCount = sessionPreupdateCount;
  166366. pSession->hook.xDepth = sessionPreupdateDepth;
  166367. }
  166368. typedef struct SessionDiffCtx SessionDiffCtx;
  166369. struct SessionDiffCtx {
  166370. sqlite3_stmt *pStmt;
  166371. int nOldOff;
  166372. };
  166373. /*
  166374. ** The diff hook implementations.
  166375. */
  166376. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  166377. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  166378. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  166379. return SQLITE_OK;
  166380. }
  166381. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  166382. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  166383. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  166384. return SQLITE_OK;
  166385. }
  166386. static int sessionDiffCount(void *pCtx){
  166387. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  166388. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  166389. }
  166390. static int sessionDiffDepth(void *pCtx){
  166391. return 0;
  166392. }
  166393. /*
  166394. ** Install the diff hooks on the session object passed as the only
  166395. ** argument.
  166396. */
  166397. static void sessionDiffHooks(
  166398. sqlite3_session *pSession,
  166399. SessionDiffCtx *pDiffCtx
  166400. ){
  166401. pSession->hook.pCtx = (void*)pDiffCtx;
  166402. pSession->hook.xOld = sessionDiffOld;
  166403. pSession->hook.xNew = sessionDiffNew;
  166404. pSession->hook.xCount = sessionDiffCount;
  166405. pSession->hook.xDepth = sessionDiffDepth;
  166406. }
  166407. static char *sessionExprComparePK(
  166408. int nCol,
  166409. const char *zDb1, const char *zDb2,
  166410. const char *zTab,
  166411. const char **azCol, u8 *abPK
  166412. ){
  166413. int i;
  166414. const char *zSep = "";
  166415. char *zRet = 0;
  166416. for(i=0; i<nCol; i++){
  166417. if( abPK[i] ){
  166418. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  166419. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  166420. );
  166421. zSep = " AND ";
  166422. if( zRet==0 ) break;
  166423. }
  166424. }
  166425. return zRet;
  166426. }
  166427. static char *sessionExprCompareOther(
  166428. int nCol,
  166429. const char *zDb1, const char *zDb2,
  166430. const char *zTab,
  166431. const char **azCol, u8 *abPK
  166432. ){
  166433. int i;
  166434. const char *zSep = "";
  166435. char *zRet = 0;
  166436. int bHave = 0;
  166437. for(i=0; i<nCol; i++){
  166438. if( abPK[i]==0 ){
  166439. bHave = 1;
  166440. zRet = sqlite3_mprintf(
  166441. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  166442. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  166443. );
  166444. zSep = " OR ";
  166445. if( zRet==0 ) break;
  166446. }
  166447. }
  166448. if( bHave==0 ){
  166449. assert( zRet==0 );
  166450. zRet = sqlite3_mprintf("0");
  166451. }
  166452. return zRet;
  166453. }
  166454. static char *sessionSelectFindNew(
  166455. int nCol,
  166456. const char *zDb1, /* Pick rows in this db only */
  166457. const char *zDb2, /* But not in this one */
  166458. const char *zTbl, /* Table name */
  166459. const char *zExpr
  166460. ){
  166461. char *zRet = sqlite3_mprintf(
  166462. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  166463. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  166464. ")",
  166465. zDb1, zTbl, zDb2, zTbl, zExpr
  166466. );
  166467. return zRet;
  166468. }
  166469. static int sessionDiffFindNew(
  166470. int op,
  166471. sqlite3_session *pSession,
  166472. SessionTable *pTab,
  166473. const char *zDb1,
  166474. const char *zDb2,
  166475. char *zExpr
  166476. ){
  166477. int rc = SQLITE_OK;
  166478. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  166479. if( zStmt==0 ){
  166480. rc = SQLITE_NOMEM;
  166481. }else{
  166482. sqlite3_stmt *pStmt;
  166483. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  166484. if( rc==SQLITE_OK ){
  166485. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  166486. pDiffCtx->pStmt = pStmt;
  166487. pDiffCtx->nOldOff = 0;
  166488. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  166489. sessionPreupdateOneChange(op, pSession, pTab);
  166490. }
  166491. rc = sqlite3_finalize(pStmt);
  166492. }
  166493. sqlite3_free(zStmt);
  166494. }
  166495. return rc;
  166496. }
  166497. static int sessionDiffFindModified(
  166498. sqlite3_session *pSession,
  166499. SessionTable *pTab,
  166500. const char *zFrom,
  166501. const char *zExpr
  166502. ){
  166503. int rc = SQLITE_OK;
  166504. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  166505. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  166506. );
  166507. if( zExpr2==0 ){
  166508. rc = SQLITE_NOMEM;
  166509. }else{
  166510. char *zStmt = sqlite3_mprintf(
  166511. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  166512. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  166513. );
  166514. if( zStmt==0 ){
  166515. rc = SQLITE_NOMEM;
  166516. }else{
  166517. sqlite3_stmt *pStmt;
  166518. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  166519. if( rc==SQLITE_OK ){
  166520. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  166521. pDiffCtx->pStmt = pStmt;
  166522. pDiffCtx->nOldOff = pTab->nCol;
  166523. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  166524. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  166525. }
  166526. rc = sqlite3_finalize(pStmt);
  166527. }
  166528. sqlite3_free(zStmt);
  166529. }
  166530. }
  166531. return rc;
  166532. }
  166533. SQLITE_API int sqlite3session_diff(
  166534. sqlite3_session *pSession,
  166535. const char *zFrom,
  166536. const char *zTbl,
  166537. char **pzErrMsg
  166538. ){
  166539. const char *zDb = pSession->zDb;
  166540. int rc = pSession->rc;
  166541. SessionDiffCtx d;
  166542. memset(&d, 0, sizeof(d));
  166543. sessionDiffHooks(pSession, &d);
  166544. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  166545. if( pzErrMsg ) *pzErrMsg = 0;
  166546. if( rc==SQLITE_OK ){
  166547. char *zExpr = 0;
  166548. sqlite3 *db = pSession->db;
  166549. SessionTable *pTo; /* Table zTbl */
  166550. /* Locate and if necessary initialize the target table object */
  166551. rc = sessionFindTable(pSession, zTbl, &pTo);
  166552. if( pTo==0 ) goto diff_out;
  166553. if( sessionInitTable(pSession, pTo) ){
  166554. rc = pSession->rc;
  166555. goto diff_out;
  166556. }
  166557. /* Check the table schemas match */
  166558. if( rc==SQLITE_OK ){
  166559. int bHasPk = 0;
  166560. int bMismatch = 0;
  166561. int nCol; /* Columns in zFrom.zTbl */
  166562. u8 *abPK;
  166563. const char **azCol = 0;
  166564. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  166565. if( rc==SQLITE_OK ){
  166566. if( pTo->nCol!=nCol ){
  166567. bMismatch = 1;
  166568. }else{
  166569. int i;
  166570. for(i=0; i<nCol; i++){
  166571. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  166572. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  166573. if( abPK[i] ) bHasPk = 1;
  166574. }
  166575. }
  166576. }
  166577. sqlite3_free((char*)azCol);
  166578. if( bMismatch ){
  166579. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  166580. rc = SQLITE_SCHEMA;
  166581. }
  166582. if( bHasPk==0 ){
  166583. /* Ignore tables with no primary keys */
  166584. goto diff_out;
  166585. }
  166586. }
  166587. if( rc==SQLITE_OK ){
  166588. zExpr = sessionExprComparePK(pTo->nCol,
  166589. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  166590. );
  166591. }
  166592. /* Find new rows */
  166593. if( rc==SQLITE_OK ){
  166594. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  166595. }
  166596. /* Find old rows */
  166597. if( rc==SQLITE_OK ){
  166598. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  166599. }
  166600. /* Find modified rows */
  166601. if( rc==SQLITE_OK ){
  166602. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  166603. }
  166604. sqlite3_free(zExpr);
  166605. }
  166606. diff_out:
  166607. sessionPreupdateHooks(pSession);
  166608. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  166609. return rc;
  166610. }
  166611. /*
  166612. ** Create a session object. This session object will record changes to
  166613. ** database zDb attached to connection db.
  166614. */
  166615. SQLITE_API int sqlite3session_create(
  166616. sqlite3 *db, /* Database handle */
  166617. const char *zDb, /* Name of db (e.g. "main") */
  166618. sqlite3_session **ppSession /* OUT: New session object */
  166619. ){
  166620. sqlite3_session *pNew; /* Newly allocated session object */
  166621. sqlite3_session *pOld; /* Session object already attached to db */
  166622. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  166623. /* Zero the output value in case an error occurs. */
  166624. *ppSession = 0;
  166625. /* Allocate and populate the new session object. */
  166626. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  166627. if( !pNew ) return SQLITE_NOMEM;
  166628. memset(pNew, 0, sizeof(sqlite3_session));
  166629. pNew->db = db;
  166630. pNew->zDb = (char *)&pNew[1];
  166631. pNew->bEnable = 1;
  166632. memcpy(pNew->zDb, zDb, nDb+1);
  166633. sessionPreupdateHooks(pNew);
  166634. /* Add the new session object to the linked list of session objects
  166635. ** attached to database handle $db. Do this under the cover of the db
  166636. ** handle mutex. */
  166637. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  166638. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  166639. pNew->pNext = pOld;
  166640. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  166641. *ppSession = pNew;
  166642. return SQLITE_OK;
  166643. }
  166644. /*
  166645. ** Free the list of table objects passed as the first argument. The contents
  166646. ** of the changed-rows hash tables are also deleted.
  166647. */
  166648. static void sessionDeleteTable(SessionTable *pList){
  166649. SessionTable *pNext;
  166650. SessionTable *pTab;
  166651. for(pTab=pList; pTab; pTab=pNext){
  166652. int i;
  166653. pNext = pTab->pNext;
  166654. for(i=0; i<pTab->nChange; i++){
  166655. SessionChange *p;
  166656. SessionChange *pNextChange;
  166657. for(p=pTab->apChange[i]; p; p=pNextChange){
  166658. pNextChange = p->pNext;
  166659. sqlite3_free(p);
  166660. }
  166661. }
  166662. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  166663. sqlite3_free(pTab->apChange);
  166664. sqlite3_free(pTab);
  166665. }
  166666. }
  166667. /*
  166668. ** Delete a session object previously allocated using sqlite3session_create().
  166669. */
  166670. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  166671. sqlite3 *db = pSession->db;
  166672. sqlite3_session *pHead;
  166673. sqlite3_session **pp;
  166674. /* Unlink the session from the linked list of sessions attached to the
  166675. ** database handle. Hold the db mutex while doing so. */
  166676. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  166677. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  166678. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  166679. if( (*pp)==pSession ){
  166680. *pp = (*pp)->pNext;
  166681. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  166682. break;
  166683. }
  166684. }
  166685. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  166686. /* Delete all attached table objects. And the contents of their
  166687. ** associated hash-tables. */
  166688. sessionDeleteTable(pSession->pTable);
  166689. /* Free the session object itself. */
  166690. sqlite3_free(pSession);
  166691. }
  166692. /*
  166693. ** Set a table filter on a Session Object.
  166694. */
  166695. SQLITE_API void sqlite3session_table_filter(
  166696. sqlite3_session *pSession,
  166697. int(*xFilter)(void*, const char*),
  166698. void *pCtx /* First argument passed to xFilter */
  166699. ){
  166700. pSession->bAutoAttach = 1;
  166701. pSession->pFilterCtx = pCtx;
  166702. pSession->xTableFilter = xFilter;
  166703. }
  166704. /*
  166705. ** Attach a table to a session. All subsequent changes made to the table
  166706. ** while the session object is enabled will be recorded.
  166707. **
  166708. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  166709. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  166710. ** or not.
  166711. */
  166712. SQLITE_API int sqlite3session_attach(
  166713. sqlite3_session *pSession, /* Session object */
  166714. const char *zName /* Table name */
  166715. ){
  166716. int rc = SQLITE_OK;
  166717. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  166718. if( !zName ){
  166719. pSession->bAutoAttach = 1;
  166720. }else{
  166721. SessionTable *pTab; /* New table object (if required) */
  166722. int nName; /* Number of bytes in string zName */
  166723. /* First search for an existing entry. If one is found, this call is
  166724. ** a no-op. Return early. */
  166725. nName = sqlite3Strlen30(zName);
  166726. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  166727. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  166728. }
  166729. if( !pTab ){
  166730. /* Allocate new SessionTable object. */
  166731. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  166732. if( !pTab ){
  166733. rc = SQLITE_NOMEM;
  166734. }else{
  166735. /* Populate the new SessionTable object and link it into the list.
  166736. ** The new object must be linked onto the end of the list, not
  166737. ** simply added to the start of it in order to ensure that tables
  166738. ** appear in the correct order when a changeset or patchset is
  166739. ** eventually generated. */
  166740. SessionTable **ppTab;
  166741. memset(pTab, 0, sizeof(SessionTable));
  166742. pTab->zName = (char *)&pTab[1];
  166743. memcpy(pTab->zName, zName, nName+1);
  166744. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  166745. *ppTab = pTab;
  166746. }
  166747. }
  166748. }
  166749. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  166750. return rc;
  166751. }
  166752. /*
  166753. ** Ensure that there is room in the buffer to append nByte bytes of data.
  166754. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  166755. **
  166756. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  166757. ** set *pRc to SQLITE_NOMEM and return non-zero.
  166758. */
  166759. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  166760. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  166761. u8 *aNew;
  166762. int nNew = p->nAlloc ? p->nAlloc : 128;
  166763. do {
  166764. nNew = nNew*2;
  166765. }while( nNew<(p->nBuf+nByte) );
  166766. aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
  166767. if( 0==aNew ){
  166768. *pRc = SQLITE_NOMEM;
  166769. }else{
  166770. p->aBuf = aNew;
  166771. p->nAlloc = nNew;
  166772. }
  166773. }
  166774. return (*pRc!=SQLITE_OK);
  166775. }
  166776. /*
  166777. ** Append the value passed as the second argument to the buffer passed
  166778. ** as the first.
  166779. **
  166780. ** This function is a no-op if *pRc is non-zero when it is called.
  166781. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  166782. ** before returning.
  166783. */
  166784. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  166785. int rc = *pRc;
  166786. if( rc==SQLITE_OK ){
  166787. int nByte = 0;
  166788. rc = sessionSerializeValue(0, pVal, &nByte);
  166789. sessionBufferGrow(p, nByte, &rc);
  166790. if( rc==SQLITE_OK ){
  166791. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  166792. p->nBuf += nByte;
  166793. }else{
  166794. *pRc = rc;
  166795. }
  166796. }
  166797. }
  166798. /*
  166799. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166800. ** called. Otherwise, append a single byte to the buffer.
  166801. **
  166802. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166803. ** returning.
  166804. */
  166805. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  166806. if( 0==sessionBufferGrow(p, 1, pRc) ){
  166807. p->aBuf[p->nBuf++] = v;
  166808. }
  166809. }
  166810. /*
  166811. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166812. ** called. Otherwise, append a single varint to the buffer.
  166813. **
  166814. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166815. ** returning.
  166816. */
  166817. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  166818. if( 0==sessionBufferGrow(p, 9, pRc) ){
  166819. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  166820. }
  166821. }
  166822. /*
  166823. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166824. ** called. Otherwise, append a blob of data to the buffer.
  166825. **
  166826. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166827. ** returning.
  166828. */
  166829. static void sessionAppendBlob(
  166830. SessionBuffer *p,
  166831. const u8 *aBlob,
  166832. int nBlob,
  166833. int *pRc
  166834. ){
  166835. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  166836. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  166837. p->nBuf += nBlob;
  166838. }
  166839. }
  166840. /*
  166841. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166842. ** called. Otherwise, append a string to the buffer. All bytes in the string
  166843. ** up to (but not including) the nul-terminator are written to the buffer.
  166844. **
  166845. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166846. ** returning.
  166847. */
  166848. static void sessionAppendStr(
  166849. SessionBuffer *p,
  166850. const char *zStr,
  166851. int *pRc
  166852. ){
  166853. int nStr = sqlite3Strlen30(zStr);
  166854. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  166855. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  166856. p->nBuf += nStr;
  166857. }
  166858. }
  166859. /*
  166860. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166861. ** called. Otherwise, append the string representation of integer iVal
  166862. ** to the buffer. No nul-terminator is written.
  166863. **
  166864. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166865. ** returning.
  166866. */
  166867. static void sessionAppendInteger(
  166868. SessionBuffer *p, /* Buffer to append to */
  166869. int iVal, /* Value to write the string rep. of */
  166870. int *pRc /* IN/OUT: Error code */
  166871. ){
  166872. char aBuf[24];
  166873. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  166874. sessionAppendStr(p, aBuf, pRc);
  166875. }
  166876. /*
  166877. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166878. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  166879. ** with any embedded quote characters escaped to the buffer. No
  166880. ** nul-terminator byte is written.
  166881. **
  166882. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  166883. ** returning.
  166884. */
  166885. static void sessionAppendIdent(
  166886. SessionBuffer *p, /* Buffer to a append to */
  166887. const char *zStr, /* String to quote, escape and append */
  166888. int *pRc /* IN/OUT: Error code */
  166889. ){
  166890. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  166891. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  166892. char *zOut = (char *)&p->aBuf[p->nBuf];
  166893. const char *zIn = zStr;
  166894. *zOut++ = '"';
  166895. while( *zIn ){
  166896. if( *zIn=='"' ) *zOut++ = '"';
  166897. *zOut++ = *(zIn++);
  166898. }
  166899. *zOut++ = '"';
  166900. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  166901. }
  166902. }
  166903. /*
  166904. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  166905. ** called. Otherwse, it appends the serialized version of the value stored
  166906. ** in column iCol of the row that SQL statement pStmt currently points
  166907. ** to to the buffer.
  166908. */
  166909. static void sessionAppendCol(
  166910. SessionBuffer *p, /* Buffer to append to */
  166911. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  166912. int iCol, /* Column to read value from */
  166913. int *pRc /* IN/OUT: Error code */
  166914. ){
  166915. if( *pRc==SQLITE_OK ){
  166916. int eType = sqlite3_column_type(pStmt, iCol);
  166917. sessionAppendByte(p, (u8)eType, pRc);
  166918. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  166919. sqlite3_int64 i;
  166920. u8 aBuf[8];
  166921. if( eType==SQLITE_INTEGER ){
  166922. i = sqlite3_column_int64(pStmt, iCol);
  166923. }else{
  166924. double r = sqlite3_column_double(pStmt, iCol);
  166925. memcpy(&i, &r, 8);
  166926. }
  166927. sessionPutI64(aBuf, i);
  166928. sessionAppendBlob(p, aBuf, 8, pRc);
  166929. }
  166930. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  166931. u8 *z;
  166932. int nByte;
  166933. if( eType==SQLITE_BLOB ){
  166934. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  166935. }else{
  166936. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  166937. }
  166938. nByte = sqlite3_column_bytes(pStmt, iCol);
  166939. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  166940. sessionAppendVarint(p, nByte, pRc);
  166941. sessionAppendBlob(p, z, nByte, pRc);
  166942. }else{
  166943. *pRc = SQLITE_NOMEM;
  166944. }
  166945. }
  166946. }
  166947. }
  166948. /*
  166949. **
  166950. ** This function appends an update change to the buffer (see the comments
  166951. ** under "CHANGESET FORMAT" at the top of the file). An update change
  166952. ** consists of:
  166953. **
  166954. ** 1 byte: SQLITE_UPDATE (0x17)
  166955. ** n bytes: old.* record (see RECORD FORMAT)
  166956. ** m bytes: new.* record (see RECORD FORMAT)
  166957. **
  166958. ** The SessionChange object passed as the third argument contains the
  166959. ** values that were stored in the row when the session began (the old.*
  166960. ** values). The statement handle passed as the second argument points
  166961. ** at the current version of the row (the new.* values).
  166962. **
  166963. ** If all of the old.* values are equal to their corresponding new.* value
  166964. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  166965. **
  166966. ** Otherwise, the old.* record contains all primary key values and the
  166967. ** original values of any fields that have been modified. The new.* record
  166968. ** contains the new values of only those fields that have been modified.
  166969. */
  166970. static int sessionAppendUpdate(
  166971. SessionBuffer *pBuf, /* Buffer to append to */
  166972. int bPatchset, /* True for "patchset", 0 for "changeset" */
  166973. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  166974. SessionChange *p, /* Object containing old values */
  166975. u8 *abPK /* Boolean array - true for PK columns */
  166976. ){
  166977. int rc = SQLITE_OK;
  166978. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  166979. int bNoop = 1; /* Set to zero if any values are modified */
  166980. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  166981. int i; /* Used to iterate through columns */
  166982. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  166983. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  166984. sessionAppendByte(pBuf, p->bIndirect, &rc);
  166985. for(i=0; i<sqlite3_column_count(pStmt); i++){
  166986. int bChanged = 0;
  166987. int nAdvance;
  166988. int eType = *pCsr;
  166989. switch( eType ){
  166990. case SQLITE_NULL:
  166991. nAdvance = 1;
  166992. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  166993. bChanged = 1;
  166994. }
  166995. break;
  166996. case SQLITE_FLOAT:
  166997. case SQLITE_INTEGER: {
  166998. nAdvance = 9;
  166999. if( eType==sqlite3_column_type(pStmt, i) ){
  167000. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  167001. if( eType==SQLITE_INTEGER ){
  167002. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  167003. }else{
  167004. double dVal;
  167005. memcpy(&dVal, &iVal, 8);
  167006. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  167007. }
  167008. }
  167009. bChanged = 1;
  167010. break;
  167011. }
  167012. default: {
  167013. int n;
  167014. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  167015. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  167016. nAdvance = nHdr + n;
  167017. if( eType==sqlite3_column_type(pStmt, i)
  167018. && n==sqlite3_column_bytes(pStmt, i)
  167019. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  167020. ){
  167021. break;
  167022. }
  167023. bChanged = 1;
  167024. }
  167025. }
  167026. /* If at least one field has been modified, this is not a no-op. */
  167027. if( bChanged ) bNoop = 0;
  167028. /* Add a field to the old.* record. This is omitted if this modules is
  167029. ** currently generating a patchset. */
  167030. if( bPatchset==0 ){
  167031. if( bChanged || abPK[i] ){
  167032. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  167033. }else{
  167034. sessionAppendByte(pBuf, 0, &rc);
  167035. }
  167036. }
  167037. /* Add a field to the new.* record. Or the only record if currently
  167038. ** generating a patchset. */
  167039. if( bChanged || (bPatchset && abPK[i]) ){
  167040. sessionAppendCol(&buf2, pStmt, i, &rc);
  167041. }else{
  167042. sessionAppendByte(&buf2, 0, &rc);
  167043. }
  167044. pCsr += nAdvance;
  167045. }
  167046. if( bNoop ){
  167047. pBuf->nBuf = nRewind;
  167048. }else{
  167049. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  167050. }
  167051. sqlite3_free(buf2.aBuf);
  167052. return rc;
  167053. }
  167054. /*
  167055. ** Append a DELETE change to the buffer passed as the first argument. Use
  167056. ** the changeset format if argument bPatchset is zero, or the patchset
  167057. ** format otherwise.
  167058. */
  167059. static int sessionAppendDelete(
  167060. SessionBuffer *pBuf, /* Buffer to append to */
  167061. int bPatchset, /* True for "patchset", 0 for "changeset" */
  167062. SessionChange *p, /* Object containing old values */
  167063. int nCol, /* Number of columns in table */
  167064. u8 *abPK /* Boolean array - true for PK columns */
  167065. ){
  167066. int rc = SQLITE_OK;
  167067. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  167068. sessionAppendByte(pBuf, p->bIndirect, &rc);
  167069. if( bPatchset==0 ){
  167070. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  167071. }else{
  167072. int i;
  167073. u8 *a = p->aRecord;
  167074. for(i=0; i<nCol; i++){
  167075. u8 *pStart = a;
  167076. int eType = *a++;
  167077. switch( eType ){
  167078. case 0:
  167079. case SQLITE_NULL:
  167080. assert( abPK[i]==0 );
  167081. break;
  167082. case SQLITE_FLOAT:
  167083. case SQLITE_INTEGER:
  167084. a += 8;
  167085. break;
  167086. default: {
  167087. int n;
  167088. a += sessionVarintGet(a, &n);
  167089. a += n;
  167090. break;
  167091. }
  167092. }
  167093. if( abPK[i] ){
  167094. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  167095. }
  167096. }
  167097. assert( (a - p->aRecord)==p->nRecord );
  167098. }
  167099. return rc;
  167100. }
  167101. /*
  167102. ** Formulate and prepare a SELECT statement to retrieve a row from table
  167103. ** zTab in database zDb based on its primary key. i.e.
  167104. **
  167105. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  167106. */
  167107. static int sessionSelectStmt(
  167108. sqlite3 *db, /* Database handle */
  167109. const char *zDb, /* Database name */
  167110. const char *zTab, /* Table name */
  167111. int nCol, /* Number of columns in table */
  167112. const char **azCol, /* Names of table columns */
  167113. u8 *abPK, /* PRIMARY KEY array */
  167114. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  167115. ){
  167116. int rc = SQLITE_OK;
  167117. int i;
  167118. const char *zSep = "";
  167119. SessionBuffer buf = {0, 0, 0};
  167120. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  167121. sessionAppendIdent(&buf, zDb, &rc);
  167122. sessionAppendStr(&buf, ".", &rc);
  167123. sessionAppendIdent(&buf, zTab, &rc);
  167124. sessionAppendStr(&buf, " WHERE ", &rc);
  167125. for(i=0; i<nCol; i++){
  167126. if( abPK[i] ){
  167127. sessionAppendStr(&buf, zSep, &rc);
  167128. sessionAppendIdent(&buf, azCol[i], &rc);
  167129. sessionAppendStr(&buf, " = ?", &rc);
  167130. sessionAppendInteger(&buf, i+1, &rc);
  167131. zSep = " AND ";
  167132. }
  167133. }
  167134. if( rc==SQLITE_OK ){
  167135. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
  167136. }
  167137. sqlite3_free(buf.aBuf);
  167138. return rc;
  167139. }
  167140. /*
  167141. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  167142. ** to the SELECT statement passed as the first argument. The SELECT statement
  167143. ** is as prepared by function sessionSelectStmt().
  167144. **
  167145. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  167146. ** error code (e.g. SQLITE_NOMEM) otherwise.
  167147. */
  167148. static int sessionSelectBind(
  167149. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  167150. int nCol, /* Number of columns in table */
  167151. u8 *abPK, /* PRIMARY KEY array */
  167152. SessionChange *pChange /* Change structure */
  167153. ){
  167154. int i;
  167155. int rc = SQLITE_OK;
  167156. u8 *a = pChange->aRecord;
  167157. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  167158. int eType = *a++;
  167159. switch( eType ){
  167160. case 0:
  167161. case SQLITE_NULL:
  167162. assert( abPK[i]==0 );
  167163. break;
  167164. case SQLITE_INTEGER: {
  167165. if( abPK[i] ){
  167166. i64 iVal = sessionGetI64(a);
  167167. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  167168. }
  167169. a += 8;
  167170. break;
  167171. }
  167172. case SQLITE_FLOAT: {
  167173. if( abPK[i] ){
  167174. double rVal;
  167175. i64 iVal = sessionGetI64(a);
  167176. memcpy(&rVal, &iVal, 8);
  167177. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  167178. }
  167179. a += 8;
  167180. break;
  167181. }
  167182. case SQLITE_TEXT: {
  167183. int n;
  167184. a += sessionVarintGet(a, &n);
  167185. if( abPK[i] ){
  167186. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  167187. }
  167188. a += n;
  167189. break;
  167190. }
  167191. default: {
  167192. int n;
  167193. assert( eType==SQLITE_BLOB );
  167194. a += sessionVarintGet(a, &n);
  167195. if( abPK[i] ){
  167196. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  167197. }
  167198. a += n;
  167199. break;
  167200. }
  167201. }
  167202. }
  167203. return rc;
  167204. }
  167205. /*
  167206. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  167207. ** is called. Otherwise, append a serialized table header (part of the binary
  167208. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  167209. ** SQLite error code before returning.
  167210. */
  167211. static void sessionAppendTableHdr(
  167212. SessionBuffer *pBuf, /* Append header to this buffer */
  167213. int bPatchset, /* Use the patchset format if true */
  167214. SessionTable *pTab, /* Table object to append header for */
  167215. int *pRc /* IN/OUT: Error code */
  167216. ){
  167217. /* Write a table header */
  167218. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  167219. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  167220. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  167221. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  167222. }
  167223. /*
  167224. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  167225. ** (if it is non-zero) based on the current contents of the session object
  167226. ** passed as the first argument.
  167227. **
  167228. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  167229. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  167230. ** occurs, an SQLite error code is returned and both output variables set
  167231. ** to 0.
  167232. */
  167233. static int sessionGenerateChangeset(
  167234. sqlite3_session *pSession, /* Session object */
  167235. int bPatchset, /* True for patchset, false for changeset */
  167236. int (*xOutput)(void *pOut, const void *pData, int nData),
  167237. void *pOut, /* First argument for xOutput */
  167238. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  167239. void **ppChangeset /* OUT: Buffer containing changeset */
  167240. ){
  167241. sqlite3 *db = pSession->db; /* Source database handle */
  167242. SessionTable *pTab; /* Used to iterate through attached tables */
  167243. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  167244. int rc; /* Return code */
  167245. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  167246. /* Zero the output variables in case an error occurs. If this session
  167247. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  167248. ** this call will be a no-op. */
  167249. if( xOutput==0 ){
  167250. *pnChangeset = 0;
  167251. *ppChangeset = 0;
  167252. }
  167253. if( pSession->rc ) return pSession->rc;
  167254. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  167255. if( rc!=SQLITE_OK ) return rc;
  167256. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  167257. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  167258. if( pTab->nEntry ){
  167259. const char *zName = pTab->zName;
  167260. int nCol; /* Number of columns in table */
  167261. u8 *abPK; /* Primary key array */
  167262. const char **azCol = 0; /* Table columns */
  167263. int i; /* Used to iterate through hash buckets */
  167264. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  167265. int nRewind = buf.nBuf; /* Initial size of write buffer */
  167266. int nNoop; /* Size of buffer after writing tbl header */
  167267. /* Check the table schema is still Ok. */
  167268. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  167269. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  167270. rc = SQLITE_SCHEMA;
  167271. }
  167272. /* Write a table header */
  167273. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  167274. /* Build and compile a statement to execute: */
  167275. if( rc==SQLITE_OK ){
  167276. rc = sessionSelectStmt(
  167277. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  167278. }
  167279. nNoop = buf.nBuf;
  167280. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  167281. SessionChange *p; /* Used to iterate through changes */
  167282. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  167283. rc = sessionSelectBind(pSel, nCol, abPK, p);
  167284. if( rc!=SQLITE_OK ) continue;
  167285. if( sqlite3_step(pSel)==SQLITE_ROW ){
  167286. if( p->op==SQLITE_INSERT ){
  167287. int iCol;
  167288. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  167289. sessionAppendByte(&buf, p->bIndirect, &rc);
  167290. for(iCol=0; iCol<nCol; iCol++){
  167291. sessionAppendCol(&buf, pSel, iCol, &rc);
  167292. }
  167293. }else{
  167294. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  167295. }
  167296. }else if( p->op!=SQLITE_INSERT ){
  167297. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  167298. }
  167299. if( rc==SQLITE_OK ){
  167300. rc = sqlite3_reset(pSel);
  167301. }
  167302. /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
  167303. ** its contents to the xOutput() callback. */
  167304. if( xOutput
  167305. && rc==SQLITE_OK
  167306. && buf.nBuf>nNoop
  167307. && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
  167308. ){
  167309. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  167310. nNoop = -1;
  167311. buf.nBuf = 0;
  167312. }
  167313. }
  167314. }
  167315. sqlite3_finalize(pSel);
  167316. if( buf.nBuf==nNoop ){
  167317. buf.nBuf = nRewind;
  167318. }
  167319. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  167320. }
  167321. }
  167322. if( rc==SQLITE_OK ){
  167323. if( xOutput==0 ){
  167324. *pnChangeset = buf.nBuf;
  167325. *ppChangeset = buf.aBuf;
  167326. buf.aBuf = 0;
  167327. }else if( buf.nBuf>0 ){
  167328. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  167329. }
  167330. }
  167331. sqlite3_free(buf.aBuf);
  167332. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  167333. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  167334. return rc;
  167335. }
  167336. /*
  167337. ** Obtain a changeset object containing all changes recorded by the
  167338. ** session object passed as the first argument.
  167339. **
  167340. ** It is the responsibility of the caller to eventually free the buffer
  167341. ** using sqlite3_free().
  167342. */
  167343. SQLITE_API int sqlite3session_changeset(
  167344. sqlite3_session *pSession, /* Session object */
  167345. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  167346. void **ppChangeset /* OUT: Buffer containing changeset */
  167347. ){
  167348. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  167349. }
  167350. /*
  167351. ** Streaming version of sqlite3session_changeset().
  167352. */
  167353. SQLITE_API int sqlite3session_changeset_strm(
  167354. sqlite3_session *pSession,
  167355. int (*xOutput)(void *pOut, const void *pData, int nData),
  167356. void *pOut
  167357. ){
  167358. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  167359. }
  167360. /*
  167361. ** Streaming version of sqlite3session_patchset().
  167362. */
  167363. SQLITE_API int sqlite3session_patchset_strm(
  167364. sqlite3_session *pSession,
  167365. int (*xOutput)(void *pOut, const void *pData, int nData),
  167366. void *pOut
  167367. ){
  167368. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  167369. }
  167370. /*
  167371. ** Obtain a patchset object containing all changes recorded by the
  167372. ** session object passed as the first argument.
  167373. **
  167374. ** It is the responsibility of the caller to eventually free the buffer
  167375. ** using sqlite3_free().
  167376. */
  167377. SQLITE_API int sqlite3session_patchset(
  167378. sqlite3_session *pSession, /* Session object */
  167379. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  167380. void **ppPatchset /* OUT: Buffer containing changeset */
  167381. ){
  167382. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  167383. }
  167384. /*
  167385. ** Enable or disable the session object passed as the first argument.
  167386. */
  167387. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  167388. int ret;
  167389. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  167390. if( bEnable>=0 ){
  167391. pSession->bEnable = bEnable;
  167392. }
  167393. ret = pSession->bEnable;
  167394. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  167395. return ret;
  167396. }
  167397. /*
  167398. ** Enable or disable the session object passed as the first argument.
  167399. */
  167400. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  167401. int ret;
  167402. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  167403. if( bIndirect>=0 ){
  167404. pSession->bIndirect = bIndirect;
  167405. }
  167406. ret = pSession->bIndirect;
  167407. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  167408. return ret;
  167409. }
  167410. /*
  167411. ** Return true if there have been no changes to monitored tables recorded
  167412. ** by the session object passed as the only argument.
  167413. */
  167414. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  167415. int ret = 0;
  167416. SessionTable *pTab;
  167417. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  167418. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  167419. ret = (pTab->nEntry>0);
  167420. }
  167421. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  167422. return (ret==0);
  167423. }
  167424. /*
  167425. ** Do the work for either sqlite3changeset_start() or start_strm().
  167426. */
  167427. static int sessionChangesetStart(
  167428. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  167429. int (*xInput)(void *pIn, void *pData, int *pnData),
  167430. void *pIn,
  167431. int nChangeset, /* Size of buffer pChangeset in bytes */
  167432. void *pChangeset /* Pointer to buffer containing changeset */
  167433. ){
  167434. sqlite3_changeset_iter *pRet; /* Iterator to return */
  167435. int nByte; /* Number of bytes to allocate for iterator */
  167436. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  167437. /* Zero the output variable in case an error occurs. */
  167438. *pp = 0;
  167439. /* Allocate and initialize the iterator structure. */
  167440. nByte = sizeof(sqlite3_changeset_iter);
  167441. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  167442. if( !pRet ) return SQLITE_NOMEM;
  167443. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  167444. pRet->in.aData = (u8 *)pChangeset;
  167445. pRet->in.nData = nChangeset;
  167446. pRet->in.xInput = xInput;
  167447. pRet->in.pIn = pIn;
  167448. pRet->in.bEof = (xInput ? 0 : 1);
  167449. /* Populate the output variable and return success. */
  167450. *pp = pRet;
  167451. return SQLITE_OK;
  167452. }
  167453. /*
  167454. ** Create an iterator used to iterate through the contents of a changeset.
  167455. */
  167456. SQLITE_API int sqlite3changeset_start(
  167457. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  167458. int nChangeset, /* Size of buffer pChangeset in bytes */
  167459. void *pChangeset /* Pointer to buffer containing changeset */
  167460. ){
  167461. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
  167462. }
  167463. /*
  167464. ** Streaming version of sqlite3changeset_start().
  167465. */
  167466. SQLITE_API int sqlite3changeset_start_strm(
  167467. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  167468. int (*xInput)(void *pIn, void *pData, int *pnData),
  167469. void *pIn
  167470. ){
  167471. return sessionChangesetStart(pp, xInput, pIn, 0, 0);
  167472. }
  167473. /*
  167474. ** If the SessionInput object passed as the only argument is a streaming
  167475. ** object and the buffer is full, discard some data to free up space.
  167476. */
  167477. static void sessionDiscardData(SessionInput *pIn){
  167478. if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
  167479. int nMove = pIn->buf.nBuf - pIn->iNext;
  167480. assert( nMove>=0 );
  167481. if( nMove>0 ){
  167482. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  167483. }
  167484. pIn->buf.nBuf -= pIn->iNext;
  167485. pIn->iNext = 0;
  167486. pIn->nData = pIn->buf.nBuf;
  167487. }
  167488. }
  167489. /*
  167490. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  167491. ** if there are not nByte bytes remaining in the input, that all available
  167492. ** data is in the buffer.
  167493. **
  167494. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  167495. */
  167496. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  167497. int rc = SQLITE_OK;
  167498. if( pIn->xInput ){
  167499. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  167500. int nNew = SESSIONS_STRM_CHUNK_SIZE;
  167501. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  167502. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  167503. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  167504. if( nNew==0 ){
  167505. pIn->bEof = 1;
  167506. }else{
  167507. pIn->buf.nBuf += nNew;
  167508. }
  167509. }
  167510. pIn->aData = pIn->buf.aBuf;
  167511. pIn->nData = pIn->buf.nBuf;
  167512. }
  167513. }
  167514. return rc;
  167515. }
  167516. /*
  167517. ** When this function is called, *ppRec points to the start of a record
  167518. ** that contains nCol values. This function advances the pointer *ppRec
  167519. ** until it points to the byte immediately following that record.
  167520. */
  167521. static void sessionSkipRecord(
  167522. u8 **ppRec, /* IN/OUT: Record pointer */
  167523. int nCol /* Number of values in record */
  167524. ){
  167525. u8 *aRec = *ppRec;
  167526. int i;
  167527. for(i=0; i<nCol; i++){
  167528. int eType = *aRec++;
  167529. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  167530. int nByte;
  167531. aRec += sessionVarintGet((u8*)aRec, &nByte);
  167532. aRec += nByte;
  167533. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  167534. aRec += 8;
  167535. }
  167536. }
  167537. *ppRec = aRec;
  167538. }
  167539. /*
  167540. ** This function sets the value of the sqlite3_value object passed as the
  167541. ** first argument to a copy of the string or blob held in the aData[]
  167542. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  167543. ** error occurs.
  167544. */
  167545. static int sessionValueSetStr(
  167546. sqlite3_value *pVal, /* Set the value of this object */
  167547. u8 *aData, /* Buffer containing string or blob data */
  167548. int nData, /* Size of buffer aData[] in bytes */
  167549. u8 enc /* String encoding (0 for blobs) */
  167550. ){
  167551. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  167552. ** argument to sqlite3ValueSetStr() and have the copy created
  167553. ** automatically. But doing so makes it difficult to detect any OOM
  167554. ** error. Hence the code to create the copy externally. */
  167555. u8 *aCopy = sqlite3_malloc(nData+1);
  167556. if( aCopy==0 ) return SQLITE_NOMEM;
  167557. memcpy(aCopy, aData, nData);
  167558. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  167559. return SQLITE_OK;
  167560. }
  167561. /*
  167562. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  167563. ** for details.
  167564. **
  167565. ** When this function is called, *paChange points to the start of the record
  167566. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  167567. ** one byte after the end of the same record before this function returns.
  167568. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  167569. ** if abPK is other than NULL, then the record contains only the PK fields
  167570. ** (in other words, it is a patchset DELETE record).
  167571. **
  167572. ** If successful, each element of the apOut[] array (allocated by the caller)
  167573. ** is set to point to an sqlite3_value object containing the value read
  167574. ** from the corresponding position in the record. If that value is not
  167575. ** included in the record (i.e. because the record is part of an UPDATE change
  167576. ** and the field was not modified), the corresponding element of apOut[] is
  167577. ** set to NULL.
  167578. **
  167579. ** It is the responsibility of the caller to free all sqlite_value structures
  167580. ** using sqlite3_free().
  167581. **
  167582. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  167583. ** The apOut[] array may have been partially populated in this case.
  167584. */
  167585. static int sessionReadRecord(
  167586. SessionInput *pIn, /* Input data */
  167587. int nCol, /* Number of values in record */
  167588. u8 *abPK, /* Array of primary key flags, or NULL */
  167589. sqlite3_value **apOut /* Write values to this array */
  167590. ){
  167591. int i; /* Used to iterate through columns */
  167592. int rc = SQLITE_OK;
  167593. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  167594. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  167595. if( abPK && abPK[i]==0 ) continue;
  167596. rc = sessionInputBuffer(pIn, 9);
  167597. if( rc==SQLITE_OK ){
  167598. eType = pIn->aData[pIn->iNext++];
  167599. }
  167600. assert( apOut[i]==0 );
  167601. if( eType ){
  167602. apOut[i] = sqlite3ValueNew(0);
  167603. if( !apOut[i] ) rc = SQLITE_NOMEM;
  167604. }
  167605. if( rc==SQLITE_OK ){
  167606. u8 *aVal = &pIn->aData[pIn->iNext];
  167607. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  167608. int nByte;
  167609. pIn->iNext += sessionVarintGet(aVal, &nByte);
  167610. rc = sessionInputBuffer(pIn, nByte);
  167611. if( rc==SQLITE_OK ){
  167612. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  167613. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  167614. }
  167615. pIn->iNext += nByte;
  167616. }
  167617. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  167618. sqlite3_int64 v = sessionGetI64(aVal);
  167619. if( eType==SQLITE_INTEGER ){
  167620. sqlite3VdbeMemSetInt64(apOut[i], v);
  167621. }else{
  167622. double d;
  167623. memcpy(&d, &v, 8);
  167624. sqlite3VdbeMemSetDouble(apOut[i], d);
  167625. }
  167626. pIn->iNext += 8;
  167627. }
  167628. }
  167629. }
  167630. return rc;
  167631. }
  167632. /*
  167633. ** The input pointer currently points to the second byte of a table-header.
  167634. ** Specifically, to the following:
  167635. **
  167636. ** + number of columns in table (varint)
  167637. ** + array of PK flags (1 byte per column),
  167638. ** + table name (nul terminated).
  167639. **
  167640. ** This function ensures that all of the above is present in the input
  167641. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  167642. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  167643. ** The input pointer is not moved.
  167644. */
  167645. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  167646. int rc = SQLITE_OK;
  167647. int nCol = 0;
  167648. int nRead = 0;
  167649. rc = sessionInputBuffer(pIn, 9);
  167650. if( rc==SQLITE_OK ){
  167651. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  167652. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  167653. nRead += nCol;
  167654. }
  167655. while( rc==SQLITE_OK ){
  167656. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  167657. nRead++;
  167658. }
  167659. if( (pIn->iNext + nRead)<pIn->nData ) break;
  167660. rc = sessionInputBuffer(pIn, nRead + 100);
  167661. }
  167662. *pnByte = nRead+1;
  167663. return rc;
  167664. }
  167665. /*
  167666. ** The input pointer currently points to the first byte of the first field
  167667. ** of a record consisting of nCol columns. This function ensures the entire
  167668. ** record is buffered. It does not move the input pointer.
  167669. **
  167670. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  167671. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  167672. ** final value of *pnByte is undefined in this case.
  167673. */
  167674. static int sessionChangesetBufferRecord(
  167675. SessionInput *pIn, /* Input data */
  167676. int nCol, /* Number of columns in record */
  167677. int *pnByte /* OUT: Size of record in bytes */
  167678. ){
  167679. int rc = SQLITE_OK;
  167680. int nByte = 0;
  167681. int i;
  167682. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  167683. int eType;
  167684. rc = sessionInputBuffer(pIn, nByte + 10);
  167685. if( rc==SQLITE_OK ){
  167686. eType = pIn->aData[pIn->iNext + nByte++];
  167687. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  167688. int n;
  167689. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  167690. nByte += n;
  167691. rc = sessionInputBuffer(pIn, nByte);
  167692. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  167693. nByte += 8;
  167694. }
  167695. }
  167696. }
  167697. *pnByte = nByte;
  167698. return rc;
  167699. }
  167700. /*
  167701. ** The input pointer currently points to the second byte of a table-header.
  167702. ** Specifically, to the following:
  167703. **
  167704. ** + number of columns in table (varint)
  167705. ** + array of PK flags (1 byte per column),
  167706. ** + table name (nul terminated).
  167707. **
  167708. ** This function decodes the table-header and populates the p->nCol,
  167709. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  167710. ** also allocated or resized according to the new value of p->nCol. The
  167711. ** input pointer is left pointing to the byte following the table header.
  167712. **
  167713. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  167714. ** is returned and the final values of the various fields enumerated above
  167715. ** are undefined.
  167716. */
  167717. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  167718. int rc;
  167719. int nCopy;
  167720. assert( p->rc==SQLITE_OK );
  167721. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  167722. if( rc==SQLITE_OK ){
  167723. int nByte;
  167724. int nVarint;
  167725. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  167726. nCopy -= nVarint;
  167727. p->in.iNext += nVarint;
  167728. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  167729. p->tblhdr.nBuf = 0;
  167730. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  167731. }
  167732. if( rc==SQLITE_OK ){
  167733. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  167734. memset(p->tblhdr.aBuf, 0, iPK);
  167735. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  167736. p->in.iNext += nCopy;
  167737. }
  167738. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  167739. p->abPK = (u8*)&p->apValue[p->nCol*2];
  167740. p->zTab = (char*)&p->abPK[p->nCol];
  167741. return (p->rc = rc);
  167742. }
  167743. /*
  167744. ** Advance the changeset iterator to the next change.
  167745. **
  167746. ** If both paRec and pnRec are NULL, then this function works like the public
  167747. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  167748. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  167749. **
  167750. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  167751. ** record is written to *paRec before returning and the number of bytes in
  167752. ** the record to *pnRec.
  167753. **
  167754. ** Either way, this function returns SQLITE_ROW if the iterator is
  167755. ** successfully advanced to the next change in the changeset, an SQLite
  167756. ** error code if an error occurs, or SQLITE_DONE if there are no further
  167757. ** changes in the changeset.
  167758. */
  167759. static int sessionChangesetNext(
  167760. sqlite3_changeset_iter *p, /* Changeset iterator */
  167761. u8 **paRec, /* If non-NULL, store record pointer here */
  167762. int *pnRec /* If non-NULL, store size of record here */
  167763. ){
  167764. int i;
  167765. u8 op;
  167766. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  167767. /* If the iterator is in the error-state, return immediately. */
  167768. if( p->rc!=SQLITE_OK ) return p->rc;
  167769. /* Free the current contents of p->apValue[], if any. */
  167770. if( p->apValue ){
  167771. for(i=0; i<p->nCol*2; i++){
  167772. sqlite3ValueFree(p->apValue[i]);
  167773. }
  167774. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  167775. }
  167776. /* Make sure the buffer contains at least 10 bytes of input data, or all
  167777. ** remaining data if there are less than 10 bytes available. This is
  167778. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  167779. ** it, or for the two single byte values otherwise. */
  167780. p->rc = sessionInputBuffer(&p->in, 2);
  167781. if( p->rc!=SQLITE_OK ) return p->rc;
  167782. /* If the iterator is already at the end of the changeset, return DONE. */
  167783. if( p->in.iNext>=p->in.nData ){
  167784. return SQLITE_DONE;
  167785. }
  167786. sessionDiscardData(&p->in);
  167787. p->in.iCurrent = p->in.iNext;
  167788. op = p->in.aData[p->in.iNext++];
  167789. while( op=='T' || op=='P' ){
  167790. p->bPatchset = (op=='P');
  167791. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  167792. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  167793. p->in.iCurrent = p->in.iNext;
  167794. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  167795. op = p->in.aData[p->in.iNext++];
  167796. }
  167797. p->op = op;
  167798. p->bIndirect = p->in.aData[p->in.iNext++];
  167799. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  167800. return (p->rc = SQLITE_CORRUPT_BKPT);
  167801. }
  167802. if( paRec ){
  167803. int nVal; /* Number of values to buffer */
  167804. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  167805. nVal = p->nCol * 2;
  167806. }else if( p->bPatchset && op==SQLITE_DELETE ){
  167807. nVal = 0;
  167808. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  167809. }else{
  167810. nVal = p->nCol;
  167811. }
  167812. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  167813. if( p->rc!=SQLITE_OK ) return p->rc;
  167814. *paRec = &p->in.aData[p->in.iNext];
  167815. p->in.iNext += *pnRec;
  167816. }else{
  167817. /* If this is an UPDATE or DELETE, read the old.* record. */
  167818. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  167819. u8 *abPK = p->bPatchset ? p->abPK : 0;
  167820. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
  167821. if( p->rc!=SQLITE_OK ) return p->rc;
  167822. }
  167823. /* If this is an INSERT or UPDATE, read the new.* record. */
  167824. if( p->op!=SQLITE_DELETE ){
  167825. p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
  167826. if( p->rc!=SQLITE_OK ) return p->rc;
  167827. }
  167828. if( p->bPatchset && p->op==SQLITE_UPDATE ){
  167829. /* If this is an UPDATE that is part of a patchset, then all PK and
  167830. ** modified fields are present in the new.* record. The old.* record
  167831. ** is currently completely empty. This block shifts the PK fields from
  167832. ** new.* to old.*, to accommodate the code that reads these arrays. */
  167833. for(i=0; i<p->nCol; i++){
  167834. assert( p->apValue[i]==0 );
  167835. assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
  167836. if( p->abPK[i] ){
  167837. p->apValue[i] = p->apValue[i+p->nCol];
  167838. p->apValue[i+p->nCol] = 0;
  167839. }
  167840. }
  167841. }
  167842. }
  167843. return SQLITE_ROW;
  167844. }
  167845. /*
  167846. ** Advance an iterator created by sqlite3changeset_start() to the next
  167847. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  167848. ** or SQLITE_CORRUPT.
  167849. **
  167850. ** This function may not be called on iterators passed to a conflict handler
  167851. ** callback by changeset_apply().
  167852. */
  167853. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  167854. return sessionChangesetNext(p, 0, 0);
  167855. }
  167856. /*
  167857. ** The following function extracts information on the current change
  167858. ** from a changeset iterator. It may only be called after changeset_next()
  167859. ** has returned SQLITE_ROW.
  167860. */
  167861. SQLITE_API int sqlite3changeset_op(
  167862. sqlite3_changeset_iter *pIter, /* Iterator handle */
  167863. const char **pzTab, /* OUT: Pointer to table name */
  167864. int *pnCol, /* OUT: Number of columns in table */
  167865. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  167866. int *pbIndirect /* OUT: True if change is indirect */
  167867. ){
  167868. *pOp = pIter->op;
  167869. *pnCol = pIter->nCol;
  167870. *pzTab = pIter->zTab;
  167871. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  167872. return SQLITE_OK;
  167873. }
  167874. /*
  167875. ** Return information regarding the PRIMARY KEY and number of columns in
  167876. ** the database table affected by the change that pIter currently points
  167877. ** to. This function may only be called after changeset_next() returns
  167878. ** SQLITE_ROW.
  167879. */
  167880. SQLITE_API int sqlite3changeset_pk(
  167881. sqlite3_changeset_iter *pIter, /* Iterator object */
  167882. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  167883. int *pnCol /* OUT: Number of entries in output array */
  167884. ){
  167885. *pabPK = pIter->abPK;
  167886. if( pnCol ) *pnCol = pIter->nCol;
  167887. return SQLITE_OK;
  167888. }
  167889. /*
  167890. ** This function may only be called while the iterator is pointing to an
  167891. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  167892. ** Otherwise, SQLITE_MISUSE is returned.
  167893. **
  167894. ** It sets *ppValue to point to an sqlite3_value structure containing the
  167895. ** iVal'th value in the old.* record. Or, if that particular value is not
  167896. ** included in the record (because the change is an UPDATE and the field
  167897. ** was not modified and is not a PK column), set *ppValue to NULL.
  167898. **
  167899. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  167900. ** not modified. Otherwise, SQLITE_OK.
  167901. */
  167902. SQLITE_API int sqlite3changeset_old(
  167903. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  167904. int iVal, /* Index of old.* value to retrieve */
  167905. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  167906. ){
  167907. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  167908. return SQLITE_MISUSE;
  167909. }
  167910. if( iVal<0 || iVal>=pIter->nCol ){
  167911. return SQLITE_RANGE;
  167912. }
  167913. *ppValue = pIter->apValue[iVal];
  167914. return SQLITE_OK;
  167915. }
  167916. /*
  167917. ** This function may only be called while the iterator is pointing to an
  167918. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  167919. ** Otherwise, SQLITE_MISUSE is returned.
  167920. **
  167921. ** It sets *ppValue to point to an sqlite3_value structure containing the
  167922. ** iVal'th value in the new.* record. Or, if that particular value is not
  167923. ** included in the record (because the change is an UPDATE and the field
  167924. ** was not modified), set *ppValue to NULL.
  167925. **
  167926. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  167927. ** not modified. Otherwise, SQLITE_OK.
  167928. */
  167929. SQLITE_API int sqlite3changeset_new(
  167930. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  167931. int iVal, /* Index of new.* value to retrieve */
  167932. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  167933. ){
  167934. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  167935. return SQLITE_MISUSE;
  167936. }
  167937. if( iVal<0 || iVal>=pIter->nCol ){
  167938. return SQLITE_RANGE;
  167939. }
  167940. *ppValue = pIter->apValue[pIter->nCol+iVal];
  167941. return SQLITE_OK;
  167942. }
  167943. /*
  167944. ** The following two macros are used internally. They are similar to the
  167945. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  167946. ** they omit all error checking and return a pointer to the requested value.
  167947. */
  167948. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  167949. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  167950. /*
  167951. ** This function may only be called with a changeset iterator that has been
  167952. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  167953. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  167954. **
  167955. ** If successful, *ppValue is set to point to an sqlite3_value structure
  167956. ** containing the iVal'th value of the conflicting record.
  167957. **
  167958. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  167959. ** code is returned. Otherwise, SQLITE_OK.
  167960. */
  167961. SQLITE_API int sqlite3changeset_conflict(
  167962. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  167963. int iVal, /* Index of conflict record value to fetch */
  167964. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  167965. ){
  167966. if( !pIter->pConflict ){
  167967. return SQLITE_MISUSE;
  167968. }
  167969. if( iVal<0 || iVal>=pIter->nCol ){
  167970. return SQLITE_RANGE;
  167971. }
  167972. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  167973. return SQLITE_OK;
  167974. }
  167975. /*
  167976. ** This function may only be called with an iterator passed to an
  167977. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  167978. ** it sets the output variable to the total number of known foreign key
  167979. ** violations in the destination database and returns SQLITE_OK.
  167980. **
  167981. ** In all other cases this function returns SQLITE_MISUSE.
  167982. */
  167983. SQLITE_API int sqlite3changeset_fk_conflicts(
  167984. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  167985. int *pnOut /* OUT: Number of FK violations */
  167986. ){
  167987. if( pIter->pConflict || pIter->apValue ){
  167988. return SQLITE_MISUSE;
  167989. }
  167990. *pnOut = pIter->nCol;
  167991. return SQLITE_OK;
  167992. }
  167993. /*
  167994. ** Finalize an iterator allocated with sqlite3changeset_start().
  167995. **
  167996. ** This function may not be called on iterators passed to a conflict handler
  167997. ** callback by changeset_apply().
  167998. */
  167999. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  168000. int rc = SQLITE_OK;
  168001. if( p ){
  168002. int i; /* Used to iterate through p->apValue[] */
  168003. rc = p->rc;
  168004. if( p->apValue ){
  168005. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  168006. }
  168007. sqlite3_free(p->tblhdr.aBuf);
  168008. sqlite3_free(p->in.buf.aBuf);
  168009. sqlite3_free(p);
  168010. }
  168011. return rc;
  168012. }
  168013. static int sessionChangesetInvert(
  168014. SessionInput *pInput, /* Input changeset */
  168015. int (*xOutput)(void *pOut, const void *pData, int nData),
  168016. void *pOut,
  168017. int *pnInverted, /* OUT: Number of bytes in output changeset */
  168018. void **ppInverted /* OUT: Inverse of pChangeset */
  168019. ){
  168020. int rc = SQLITE_OK; /* Return value */
  168021. SessionBuffer sOut; /* Output buffer */
  168022. int nCol = 0; /* Number of cols in current table */
  168023. u8 *abPK = 0; /* PK array for current table */
  168024. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  168025. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  168026. /* Initialize the output buffer */
  168027. memset(&sOut, 0, sizeof(SessionBuffer));
  168028. /* Zero the output variables in case an error occurs. */
  168029. if( ppInverted ){
  168030. *ppInverted = 0;
  168031. *pnInverted = 0;
  168032. }
  168033. while( 1 ){
  168034. u8 eType;
  168035. /* Test for EOF. */
  168036. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  168037. if( pInput->iNext>=pInput->nData ) break;
  168038. eType = pInput->aData[pInput->iNext];
  168039. switch( eType ){
  168040. case 'T': {
  168041. /* A 'table' record consists of:
  168042. **
  168043. ** * A constant 'T' character,
  168044. ** * Number of columns in said table (a varint),
  168045. ** * An array of nCol bytes (sPK),
  168046. ** * A nul-terminated table name.
  168047. */
  168048. int nByte;
  168049. int nVar;
  168050. pInput->iNext++;
  168051. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  168052. goto finished_invert;
  168053. }
  168054. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  168055. sPK.nBuf = 0;
  168056. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  168057. sessionAppendByte(&sOut, eType, &rc);
  168058. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  168059. if( rc ) goto finished_invert;
  168060. pInput->iNext += nByte;
  168061. sqlite3_free(apVal);
  168062. apVal = 0;
  168063. abPK = sPK.aBuf;
  168064. break;
  168065. }
  168066. case SQLITE_INSERT:
  168067. case SQLITE_DELETE: {
  168068. int nByte;
  168069. int bIndirect = pInput->aData[pInput->iNext+1];
  168070. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  168071. pInput->iNext += 2;
  168072. assert( rc==SQLITE_OK );
  168073. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  168074. sessionAppendByte(&sOut, eType2, &rc);
  168075. sessionAppendByte(&sOut, bIndirect, &rc);
  168076. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  168077. pInput->iNext += nByte;
  168078. if( rc ) goto finished_invert;
  168079. break;
  168080. }
  168081. case SQLITE_UPDATE: {
  168082. int iCol;
  168083. if( 0==apVal ){
  168084. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  168085. if( 0==apVal ){
  168086. rc = SQLITE_NOMEM;
  168087. goto finished_invert;
  168088. }
  168089. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  168090. }
  168091. /* Write the header for the new UPDATE change. Same as the original. */
  168092. sessionAppendByte(&sOut, eType, &rc);
  168093. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  168094. /* Read the old.* and new.* records for the update change. */
  168095. pInput->iNext += 2;
  168096. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  168097. if( rc==SQLITE_OK ){
  168098. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  168099. }
  168100. /* Write the new old.* record. Consists of the PK columns from the
  168101. ** original old.* record, and the other values from the original
  168102. ** new.* record. */
  168103. for(iCol=0; iCol<nCol; iCol++){
  168104. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  168105. sessionAppendValue(&sOut, pVal, &rc);
  168106. }
  168107. /* Write the new new.* record. Consists of a copy of all values
  168108. ** from the original old.* record, except for the PK columns, which
  168109. ** are set to "undefined". */
  168110. for(iCol=0; iCol<nCol; iCol++){
  168111. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  168112. sessionAppendValue(&sOut, pVal, &rc);
  168113. }
  168114. for(iCol=0; iCol<nCol*2; iCol++){
  168115. sqlite3ValueFree(apVal[iCol]);
  168116. }
  168117. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  168118. if( rc!=SQLITE_OK ){
  168119. goto finished_invert;
  168120. }
  168121. break;
  168122. }
  168123. default:
  168124. rc = SQLITE_CORRUPT_BKPT;
  168125. goto finished_invert;
  168126. }
  168127. assert( rc==SQLITE_OK );
  168128. if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  168129. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  168130. sOut.nBuf = 0;
  168131. if( rc!=SQLITE_OK ) goto finished_invert;
  168132. }
  168133. }
  168134. assert( rc==SQLITE_OK );
  168135. if( pnInverted ){
  168136. *pnInverted = sOut.nBuf;
  168137. *ppInverted = sOut.aBuf;
  168138. sOut.aBuf = 0;
  168139. }else if( sOut.nBuf>0 ){
  168140. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  168141. }
  168142. finished_invert:
  168143. sqlite3_free(sOut.aBuf);
  168144. sqlite3_free(apVal);
  168145. sqlite3_free(sPK.aBuf);
  168146. return rc;
  168147. }
  168148. /*
  168149. ** Invert a changeset object.
  168150. */
  168151. SQLITE_API int sqlite3changeset_invert(
  168152. int nChangeset, /* Number of bytes in input */
  168153. const void *pChangeset, /* Input changeset */
  168154. int *pnInverted, /* OUT: Number of bytes in output changeset */
  168155. void **ppInverted /* OUT: Inverse of pChangeset */
  168156. ){
  168157. SessionInput sInput;
  168158. /* Set up the input stream */
  168159. memset(&sInput, 0, sizeof(SessionInput));
  168160. sInput.nData = nChangeset;
  168161. sInput.aData = (u8*)pChangeset;
  168162. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  168163. }
  168164. /*
  168165. ** Streaming version of sqlite3changeset_invert().
  168166. */
  168167. SQLITE_API int sqlite3changeset_invert_strm(
  168168. int (*xInput)(void *pIn, void *pData, int *pnData),
  168169. void *pIn,
  168170. int (*xOutput)(void *pOut, const void *pData, int nData),
  168171. void *pOut
  168172. ){
  168173. SessionInput sInput;
  168174. int rc;
  168175. /* Set up the input stream */
  168176. memset(&sInput, 0, sizeof(SessionInput));
  168177. sInput.xInput = xInput;
  168178. sInput.pIn = pIn;
  168179. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  168180. sqlite3_free(sInput.buf.aBuf);
  168181. return rc;
  168182. }
  168183. typedef struct SessionApplyCtx SessionApplyCtx;
  168184. struct SessionApplyCtx {
  168185. sqlite3 *db;
  168186. sqlite3_stmt *pDelete; /* DELETE statement */
  168187. sqlite3_stmt *pUpdate; /* UPDATE statement */
  168188. sqlite3_stmt *pInsert; /* INSERT statement */
  168189. sqlite3_stmt *pSelect; /* SELECT statement */
  168190. int nCol; /* Size of azCol[] and abPK[] arrays */
  168191. const char **azCol; /* Array of column names */
  168192. u8 *abPK; /* Boolean array - true if column is in PK */
  168193. int bDeferConstraints; /* True to defer constraints */
  168194. SessionBuffer constraints; /* Deferred constraints are stored here */
  168195. };
  168196. /*
  168197. ** Formulate a statement to DELETE a row from database db. Assuming a table
  168198. ** structure like this:
  168199. **
  168200. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  168201. **
  168202. ** The DELETE statement looks like this:
  168203. **
  168204. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  168205. **
  168206. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  168207. ** matching b and d values, or 1 otherwise. The second case comes up if the
  168208. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  168209. **
  168210. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  168211. ** pointing to the prepared version of the SQL statement.
  168212. */
  168213. static int sessionDeleteRow(
  168214. sqlite3 *db, /* Database handle */
  168215. const char *zTab, /* Table name */
  168216. SessionApplyCtx *p /* Session changeset-apply context */
  168217. ){
  168218. int i;
  168219. const char *zSep = "";
  168220. int rc = SQLITE_OK;
  168221. SessionBuffer buf = {0, 0, 0};
  168222. int nPk = 0;
  168223. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  168224. sessionAppendIdent(&buf, zTab, &rc);
  168225. sessionAppendStr(&buf, " WHERE ", &rc);
  168226. for(i=0; i<p->nCol; i++){
  168227. if( p->abPK[i] ){
  168228. nPk++;
  168229. sessionAppendStr(&buf, zSep, &rc);
  168230. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168231. sessionAppendStr(&buf, " = ?", &rc);
  168232. sessionAppendInteger(&buf, i+1, &rc);
  168233. zSep = " AND ";
  168234. }
  168235. }
  168236. if( nPk<p->nCol ){
  168237. sessionAppendStr(&buf, " AND (?", &rc);
  168238. sessionAppendInteger(&buf, p->nCol+1, &rc);
  168239. sessionAppendStr(&buf, " OR ", &rc);
  168240. zSep = "";
  168241. for(i=0; i<p->nCol; i++){
  168242. if( !p->abPK[i] ){
  168243. sessionAppendStr(&buf, zSep, &rc);
  168244. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168245. sessionAppendStr(&buf, " IS ?", &rc);
  168246. sessionAppendInteger(&buf, i+1, &rc);
  168247. zSep = "AND ";
  168248. }
  168249. }
  168250. sessionAppendStr(&buf, ")", &rc);
  168251. }
  168252. if( rc==SQLITE_OK ){
  168253. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  168254. }
  168255. sqlite3_free(buf.aBuf);
  168256. return rc;
  168257. }
  168258. /*
  168259. ** Formulate and prepare a statement to UPDATE a row from database db.
  168260. ** Assuming a table structure like this:
  168261. **
  168262. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  168263. **
  168264. ** The UPDATE statement looks like this:
  168265. **
  168266. ** UPDATE x SET
  168267. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  168268. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  168269. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  168270. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  168271. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  168272. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  168273. ** )
  168274. **
  168275. ** For each column in the table, there are three variables to bind:
  168276. **
  168277. ** ?(i*3+1) The old.* value of the column, if any.
  168278. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  168279. ** ?(i*3+3) The new.* value of the column, if any.
  168280. **
  168281. ** Also, a boolean flag that, if set to true, causes the statement to update
  168282. ** a row even if the non-PK values do not match. This is required if the
  168283. ** conflict-handler is invoked with CHANGESET_DATA and returns
  168284. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  168285. **
  168286. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  168287. ** pointing to the prepared version of the SQL statement.
  168288. */
  168289. static int sessionUpdateRow(
  168290. sqlite3 *db, /* Database handle */
  168291. const char *zTab, /* Table name */
  168292. SessionApplyCtx *p /* Session changeset-apply context */
  168293. ){
  168294. int rc = SQLITE_OK;
  168295. int i;
  168296. const char *zSep = "";
  168297. SessionBuffer buf = {0, 0, 0};
  168298. /* Append "UPDATE tbl SET " */
  168299. sessionAppendStr(&buf, "UPDATE ", &rc);
  168300. sessionAppendIdent(&buf, zTab, &rc);
  168301. sessionAppendStr(&buf, " SET ", &rc);
  168302. /* Append the assignments */
  168303. for(i=0; i<p->nCol; i++){
  168304. sessionAppendStr(&buf, zSep, &rc);
  168305. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168306. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  168307. sessionAppendInteger(&buf, i*3+2, &rc);
  168308. sessionAppendStr(&buf, " THEN ?", &rc);
  168309. sessionAppendInteger(&buf, i*3+3, &rc);
  168310. sessionAppendStr(&buf, " ELSE ", &rc);
  168311. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168312. sessionAppendStr(&buf, " END", &rc);
  168313. zSep = ", ";
  168314. }
  168315. /* Append the PK part of the WHERE clause */
  168316. sessionAppendStr(&buf, " WHERE ", &rc);
  168317. for(i=0; i<p->nCol; i++){
  168318. if( p->abPK[i] ){
  168319. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168320. sessionAppendStr(&buf, " = ?", &rc);
  168321. sessionAppendInteger(&buf, i*3+1, &rc);
  168322. sessionAppendStr(&buf, " AND ", &rc);
  168323. }
  168324. }
  168325. /* Append the non-PK part of the WHERE clause */
  168326. sessionAppendStr(&buf, " (?", &rc);
  168327. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  168328. sessionAppendStr(&buf, " OR 1", &rc);
  168329. for(i=0; i<p->nCol; i++){
  168330. if( !p->abPK[i] ){
  168331. sessionAppendStr(&buf, " AND (?", &rc);
  168332. sessionAppendInteger(&buf, i*3+2, &rc);
  168333. sessionAppendStr(&buf, "=0 OR ", &rc);
  168334. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168335. sessionAppendStr(&buf, " IS ?", &rc);
  168336. sessionAppendInteger(&buf, i*3+1, &rc);
  168337. sessionAppendStr(&buf, ")", &rc);
  168338. }
  168339. }
  168340. sessionAppendStr(&buf, ")", &rc);
  168341. if( rc==SQLITE_OK ){
  168342. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  168343. }
  168344. sqlite3_free(buf.aBuf);
  168345. return rc;
  168346. }
  168347. /*
  168348. ** Formulate and prepare an SQL statement to query table zTab by primary
  168349. ** key. Assuming the following table structure:
  168350. **
  168351. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  168352. **
  168353. ** The SELECT statement looks like this:
  168354. **
  168355. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  168356. **
  168357. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  168358. ** pointing to the prepared version of the SQL statement.
  168359. */
  168360. static int sessionSelectRow(
  168361. sqlite3 *db, /* Database handle */
  168362. const char *zTab, /* Table name */
  168363. SessionApplyCtx *p /* Session changeset-apply context */
  168364. ){
  168365. return sessionSelectStmt(
  168366. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  168367. }
  168368. /*
  168369. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  168370. ** For example:
  168371. **
  168372. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  168373. **
  168374. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  168375. ** pointing to the prepared version of the SQL statement.
  168376. */
  168377. static int sessionInsertRow(
  168378. sqlite3 *db, /* Database handle */
  168379. const char *zTab, /* Table name */
  168380. SessionApplyCtx *p /* Session changeset-apply context */
  168381. ){
  168382. int rc = SQLITE_OK;
  168383. int i;
  168384. SessionBuffer buf = {0, 0, 0};
  168385. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  168386. sessionAppendIdent(&buf, zTab, &rc);
  168387. sessionAppendStr(&buf, "(", &rc);
  168388. for(i=0; i<p->nCol; i++){
  168389. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  168390. sessionAppendIdent(&buf, p->azCol[i], &rc);
  168391. }
  168392. sessionAppendStr(&buf, ") VALUES(?", &rc);
  168393. for(i=1; i<p->nCol; i++){
  168394. sessionAppendStr(&buf, ", ?", &rc);
  168395. }
  168396. sessionAppendStr(&buf, ")", &rc);
  168397. if( rc==SQLITE_OK ){
  168398. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  168399. }
  168400. sqlite3_free(buf.aBuf);
  168401. return rc;
  168402. }
  168403. /*
  168404. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  168405. ** See comments in the body of this function for details.
  168406. */
  168407. static int sessionBindValue(
  168408. sqlite3_stmt *pStmt, /* Statement to bind value to */
  168409. int i, /* Parameter number to bind to */
  168410. sqlite3_value *pVal /* Value to bind */
  168411. ){
  168412. int eType = sqlite3_value_type(pVal);
  168413. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  168414. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  168415. ** the (pVal->z) variable remains as it was or the type of the value is
  168416. ** set to SQLITE_NULL. */
  168417. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  168418. /* This condition occurs when an earlier OOM in a call to
  168419. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  168420. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  168421. return SQLITE_NOMEM;
  168422. }
  168423. return sqlite3_bind_value(pStmt, i, pVal);
  168424. }
  168425. /*
  168426. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  168427. ** transfers new.* values from the current iterator entry to statement
  168428. ** pStmt. The table being inserted into has nCol columns.
  168429. **
  168430. ** New.* value $i from the iterator is bound to variable ($i+1) of
  168431. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  168432. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  168433. ** to an array nCol elements in size. In this case only those values for
  168434. ** which abPK[$i] is true are read from the iterator and bound to the
  168435. ** statement.
  168436. **
  168437. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  168438. */
  168439. static int sessionBindRow(
  168440. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  168441. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  168442. int nCol, /* Number of columns */
  168443. u8 *abPK, /* If not NULL, bind only if true */
  168444. sqlite3_stmt *pStmt /* Bind values to this statement */
  168445. ){
  168446. int i;
  168447. int rc = SQLITE_OK;
  168448. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  168449. ** argument iterator points to a suitable entry. Make sure that xValue
  168450. ** is one of these to guarantee that it is safe to ignore the return
  168451. ** in the code below. */
  168452. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  168453. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  168454. if( !abPK || abPK[i] ){
  168455. sqlite3_value *pVal;
  168456. (void)xValue(pIter, i, &pVal);
  168457. rc = sessionBindValue(pStmt, i+1, pVal);
  168458. }
  168459. }
  168460. return rc;
  168461. }
  168462. /*
  168463. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  168464. ** This function binds the primary key values from the change that changeset
  168465. ** iterator pIter points to to the SELECT and attempts to seek to the table
  168466. ** entry. If a row is found, the SELECT statement left pointing at the row
  168467. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  168468. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  168469. ** error occurs, the statement is reset and an SQLite error code is returned.
  168470. **
  168471. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  168472. ** statement pSelect. If any other value is returned, the statement does
  168473. ** not require a reset().
  168474. **
  168475. ** If the iterator currently points to an INSERT record, bind values from the
  168476. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  168477. ** UPDATE, bind values from the old.* record.
  168478. */
  168479. static int sessionSeekToRow(
  168480. sqlite3 *db, /* Database handle */
  168481. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  168482. u8 *abPK, /* Primary key flags array */
  168483. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  168484. ){
  168485. int rc; /* Return code */
  168486. int nCol; /* Number of columns in table */
  168487. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  168488. const char *zDummy; /* Unused */
  168489. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  168490. rc = sessionBindRow(pIter,
  168491. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  168492. nCol, abPK, pSelect
  168493. );
  168494. if( rc==SQLITE_OK ){
  168495. rc = sqlite3_step(pSelect);
  168496. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  168497. }
  168498. return rc;
  168499. }
  168500. /*
  168501. ** Invoke the conflict handler for the change that the changeset iterator
  168502. ** currently points to.
  168503. **
  168504. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  168505. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  168506. ** depends solely on eType, as follows:
  168507. **
  168508. ** eType value Value passed to xConflict
  168509. ** -------------------------------------------------
  168510. ** CHANGESET_DATA CHANGESET_NOTFOUND
  168511. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  168512. **
  168513. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  168514. ** record with the same primary key as the record about to be deleted, updated
  168515. ** or inserted. If such a record can be found, it is available to the conflict
  168516. ** handler as the "conflicting" record. In this case the type of conflict
  168517. ** handler invoked is as follows:
  168518. **
  168519. ** eType value PK Record found? Value passed to xConflict
  168520. ** ----------------------------------------------------------------
  168521. ** CHANGESET_DATA Yes CHANGESET_DATA
  168522. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  168523. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  168524. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  168525. **
  168526. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  168527. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  168528. ** is set to non-zero before returning SQLITE_OK.
  168529. **
  168530. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  168531. ** returned. Or, if the conflict handler returns an invalid value,
  168532. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  168533. ** this function returns SQLITE_OK.
  168534. */
  168535. static int sessionConflictHandler(
  168536. int eType, /* Either CHANGESET_DATA or CONFLICT */
  168537. SessionApplyCtx *p, /* changeset_apply() context */
  168538. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  168539. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  168540. void *pCtx, /* First argument for conflict handler */
  168541. int *pbReplace /* OUT: Set to true if PK row is found */
  168542. ){
  168543. int res = 0; /* Value returned by conflict handler */
  168544. int rc;
  168545. int nCol;
  168546. int op;
  168547. const char *zDummy;
  168548. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  168549. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  168550. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  168551. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  168552. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  168553. if( pbReplace ){
  168554. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  168555. }else{
  168556. rc = SQLITE_OK;
  168557. }
  168558. if( rc==SQLITE_ROW ){
  168559. /* There exists another row with the new.* primary key. */
  168560. pIter->pConflict = p->pSelect;
  168561. res = xConflict(pCtx, eType, pIter);
  168562. pIter->pConflict = 0;
  168563. rc = sqlite3_reset(p->pSelect);
  168564. }else if( rc==SQLITE_OK ){
  168565. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  168566. /* Instead of invoking the conflict handler, append the change blob
  168567. ** to the SessionApplyCtx.constraints buffer. */
  168568. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  168569. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  168570. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  168571. res = SQLITE_CHANGESET_OMIT;
  168572. }else{
  168573. /* No other row with the new.* primary key. */
  168574. res = xConflict(pCtx, eType+1, pIter);
  168575. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  168576. }
  168577. }
  168578. if( rc==SQLITE_OK ){
  168579. switch( res ){
  168580. case SQLITE_CHANGESET_REPLACE:
  168581. assert( pbReplace );
  168582. *pbReplace = 1;
  168583. break;
  168584. case SQLITE_CHANGESET_OMIT:
  168585. break;
  168586. case SQLITE_CHANGESET_ABORT:
  168587. rc = SQLITE_ABORT;
  168588. break;
  168589. default:
  168590. rc = SQLITE_MISUSE;
  168591. break;
  168592. }
  168593. }
  168594. return rc;
  168595. }
  168596. /*
  168597. ** Attempt to apply the change that the iterator passed as the first argument
  168598. ** currently points to to the database. If a conflict is encountered, invoke
  168599. ** the conflict handler callback.
  168600. **
  168601. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  168602. ** one is encountered, update or delete the row with the matching primary key
  168603. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  168604. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  168605. ** to true before returning. In this case the caller will invoke this function
  168606. ** again, this time with pbRetry set to NULL.
  168607. **
  168608. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  168609. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  168610. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  168611. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  168612. ** before retrying. In this case the caller attempts to remove the conflicting
  168613. ** row before invoking this function again, this time with pbReplace set
  168614. ** to NULL.
  168615. **
  168616. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  168617. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  168618. ** returned.
  168619. */
  168620. static int sessionApplyOneOp(
  168621. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  168622. SessionApplyCtx *p, /* changeset_apply() context */
  168623. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  168624. void *pCtx, /* First argument for the conflict handler */
  168625. int *pbReplace, /* OUT: True to remove PK row and retry */
  168626. int *pbRetry /* OUT: True to retry. */
  168627. ){
  168628. const char *zDummy;
  168629. int op;
  168630. int nCol;
  168631. int rc = SQLITE_OK;
  168632. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  168633. assert( p->azCol && p->abPK );
  168634. assert( !pbReplace || *pbReplace==0 );
  168635. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  168636. if( op==SQLITE_DELETE ){
  168637. /* Bind values to the DELETE statement. If conflict handling is required,
  168638. ** bind values for all columns and set bound variable (nCol+1) to true.
  168639. ** Or, if conflict handling is not required, bind just the PK column
  168640. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  168641. ** is not required if:
  168642. **
  168643. ** * this is a patchset, or
  168644. ** * (pbRetry==0), or
  168645. ** * all columns of the table are PK columns (in this case there is
  168646. ** no (nCol+1) variable to bind to).
  168647. */
  168648. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  168649. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  168650. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  168651. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  168652. }
  168653. if( rc!=SQLITE_OK ) return rc;
  168654. sqlite3_step(p->pDelete);
  168655. rc = sqlite3_reset(p->pDelete);
  168656. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  168657. rc = sessionConflictHandler(
  168658. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  168659. );
  168660. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  168661. rc = sessionConflictHandler(
  168662. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  168663. );
  168664. }
  168665. }else if( op==SQLITE_UPDATE ){
  168666. int i;
  168667. /* Bind values to the UPDATE statement. */
  168668. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  168669. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  168670. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  168671. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  168672. if( pOld ){
  168673. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  168674. }
  168675. if( rc==SQLITE_OK && pNew ){
  168676. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  168677. }
  168678. }
  168679. if( rc==SQLITE_OK ){
  168680. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  168681. }
  168682. if( rc!=SQLITE_OK ) return rc;
  168683. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  168684. ** the result will be SQLITE_OK with 0 rows modified. */
  168685. sqlite3_step(p->pUpdate);
  168686. rc = sqlite3_reset(p->pUpdate);
  168687. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  168688. /* A NOTFOUND or DATA error. Search the table to see if it contains
  168689. ** a row with a matching primary key. If so, this is a DATA conflict.
  168690. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  168691. rc = sessionConflictHandler(
  168692. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  168693. );
  168694. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  168695. /* This is always a CONSTRAINT conflict. */
  168696. rc = sessionConflictHandler(
  168697. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  168698. );
  168699. }
  168700. }else{
  168701. assert( op==SQLITE_INSERT );
  168702. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  168703. if( rc!=SQLITE_OK ) return rc;
  168704. sqlite3_step(p->pInsert);
  168705. rc = sqlite3_reset(p->pInsert);
  168706. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  168707. rc = sessionConflictHandler(
  168708. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  168709. );
  168710. }
  168711. }
  168712. return rc;
  168713. }
  168714. /*
  168715. ** Attempt to apply the change that the iterator passed as the first argument
  168716. ** currently points to to the database. If a conflict is encountered, invoke
  168717. ** the conflict handler callback.
  168718. **
  168719. ** The difference between this function and sessionApplyOne() is that this
  168720. ** function handles the case where the conflict-handler is invoked and
  168721. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  168722. ** retried in some manner.
  168723. */
  168724. static int sessionApplyOneWithRetry(
  168725. sqlite3 *db, /* Apply change to "main" db of this handle */
  168726. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  168727. SessionApplyCtx *pApply, /* Apply context */
  168728. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  168729. void *pCtx /* First argument passed to xConflict */
  168730. ){
  168731. int bReplace = 0;
  168732. int bRetry = 0;
  168733. int rc;
  168734. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  168735. assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
  168736. /* If the bRetry flag is set, the change has not been applied due to an
  168737. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  168738. ** a row with the correct PK is present in the db, but one or more other
  168739. ** fields do not contain the expected values) and the conflict handler
  168740. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  168741. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  168742. ** the SQLITE_CHANGESET_DATA problem. */
  168743. if( bRetry ){
  168744. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  168745. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  168746. }
  168747. /* If the bReplace flag is set, the change is an INSERT that has not
  168748. ** been performed because the database already contains a row with the
  168749. ** specified primary key and the conflict handler returned
  168750. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  168751. ** before reattempting the INSERT. */
  168752. else if( bReplace ){
  168753. assert( pIter->op==SQLITE_INSERT );
  168754. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  168755. if( rc==SQLITE_OK ){
  168756. rc = sessionBindRow(pIter,
  168757. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  168758. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  168759. }
  168760. if( rc==SQLITE_OK ){
  168761. sqlite3_step(pApply->pDelete);
  168762. rc = sqlite3_reset(pApply->pDelete);
  168763. }
  168764. if( rc==SQLITE_OK ){
  168765. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  168766. }
  168767. if( rc==SQLITE_OK ){
  168768. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  168769. }
  168770. }
  168771. return rc;
  168772. }
  168773. /*
  168774. ** Retry the changes accumulated in the pApply->constraints buffer.
  168775. */
  168776. static int sessionRetryConstraints(
  168777. sqlite3 *db,
  168778. int bPatchset,
  168779. const char *zTab,
  168780. SessionApplyCtx *pApply,
  168781. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  168782. void *pCtx /* First argument passed to xConflict */
  168783. ){
  168784. int rc = SQLITE_OK;
  168785. while( pApply->constraints.nBuf ){
  168786. sqlite3_changeset_iter *pIter2 = 0;
  168787. SessionBuffer cons = pApply->constraints;
  168788. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  168789. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
  168790. if( rc==SQLITE_OK ){
  168791. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  168792. int rc2;
  168793. pIter2->bPatchset = bPatchset;
  168794. pIter2->zTab = (char*)zTab;
  168795. pIter2->nCol = pApply->nCol;
  168796. pIter2->abPK = pApply->abPK;
  168797. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  168798. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  168799. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  168800. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  168801. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  168802. }
  168803. rc2 = sqlite3changeset_finalize(pIter2);
  168804. if( rc==SQLITE_OK ) rc = rc2;
  168805. }
  168806. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  168807. sqlite3_free(cons.aBuf);
  168808. if( rc!=SQLITE_OK ) break;
  168809. if( pApply->constraints.nBuf>=cons.nBuf ){
  168810. /* No progress was made on the last round. */
  168811. pApply->bDeferConstraints = 0;
  168812. }
  168813. }
  168814. return rc;
  168815. }
  168816. /*
  168817. ** Argument pIter is a changeset iterator that has been initialized, but
  168818. ** not yet passed to sqlite3changeset_next(). This function applies the
  168819. ** changeset to the main database attached to handle "db". The supplied
  168820. ** conflict handler callback is invoked to resolve any conflicts encountered
  168821. ** while applying the change.
  168822. */
  168823. static int sessionChangesetApply(
  168824. sqlite3 *db, /* Apply change to "main" db of this handle */
  168825. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  168826. int(*xFilter)(
  168827. void *pCtx, /* Copy of sixth arg to _apply() */
  168828. const char *zTab /* Table name */
  168829. ),
  168830. int(*xConflict)(
  168831. void *pCtx, /* Copy of fifth arg to _apply() */
  168832. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  168833. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  168834. ),
  168835. void *pCtx /* First argument passed to xConflict */
  168836. ){
  168837. int schemaMismatch = 0;
  168838. int rc; /* Return code */
  168839. const char *zTab = 0; /* Name of current table */
  168840. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  168841. SessionApplyCtx sApply; /* changeset_apply() context object */
  168842. int bPatchset;
  168843. assert( xConflict!=0 );
  168844. pIter->in.bNoDiscard = 1;
  168845. memset(&sApply, 0, sizeof(sApply));
  168846. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  168847. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  168848. if( rc==SQLITE_OK ){
  168849. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  168850. }
  168851. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  168852. int nCol;
  168853. int op;
  168854. const char *zNew;
  168855. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  168856. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  168857. u8 *abPK;
  168858. rc = sessionRetryConstraints(
  168859. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  168860. );
  168861. if( rc!=SQLITE_OK ) break;
  168862. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  168863. sqlite3_finalize(sApply.pDelete);
  168864. sqlite3_finalize(sApply.pUpdate);
  168865. sqlite3_finalize(sApply.pInsert);
  168866. sqlite3_finalize(sApply.pSelect);
  168867. memset(&sApply, 0, sizeof(sApply));
  168868. sApply.db = db;
  168869. sApply.bDeferConstraints = 1;
  168870. /* If an xFilter() callback was specified, invoke it now. If the
  168871. ** xFilter callback returns zero, skip this table. If it returns
  168872. ** non-zero, proceed. */
  168873. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  168874. if( schemaMismatch ){
  168875. zTab = sqlite3_mprintf("%s", zNew);
  168876. if( zTab==0 ){
  168877. rc = SQLITE_NOMEM;
  168878. break;
  168879. }
  168880. nTab = (int)strlen(zTab);
  168881. sApply.azCol = (const char **)zTab;
  168882. }else{
  168883. int nMinCol = 0;
  168884. int i;
  168885. sqlite3changeset_pk(pIter, &abPK, 0);
  168886. rc = sessionTableInfo(
  168887. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  168888. );
  168889. if( rc!=SQLITE_OK ) break;
  168890. for(i=0; i<sApply.nCol; i++){
  168891. if( sApply.abPK[i] ) nMinCol = i+1;
  168892. }
  168893. if( sApply.nCol==0 ){
  168894. schemaMismatch = 1;
  168895. sqlite3_log(SQLITE_SCHEMA,
  168896. "sqlite3changeset_apply(): no such table: %s", zTab
  168897. );
  168898. }
  168899. else if( sApply.nCol<nCol ){
  168900. schemaMismatch = 1;
  168901. sqlite3_log(SQLITE_SCHEMA,
  168902. "sqlite3changeset_apply(): table %s has %d columns, "
  168903. "expected %d or more",
  168904. zTab, sApply.nCol, nCol
  168905. );
  168906. }
  168907. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  168908. schemaMismatch = 1;
  168909. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  168910. "primary key mismatch for table %s", zTab
  168911. );
  168912. }
  168913. else{
  168914. sApply.nCol = nCol;
  168915. if((rc = sessionSelectRow(db, zTab, &sApply))
  168916. || (rc = sessionUpdateRow(db, zTab, &sApply))
  168917. || (rc = sessionDeleteRow(db, zTab, &sApply))
  168918. || (rc = sessionInsertRow(db, zTab, &sApply))
  168919. ){
  168920. break;
  168921. }
  168922. }
  168923. nTab = sqlite3Strlen30(zTab);
  168924. }
  168925. }
  168926. /* If there is a schema mismatch on the current table, proceed to the
  168927. ** next change. A log message has already been issued. */
  168928. if( schemaMismatch ) continue;
  168929. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  168930. }
  168931. bPatchset = pIter->bPatchset;
  168932. if( rc==SQLITE_OK ){
  168933. rc = sqlite3changeset_finalize(pIter);
  168934. }else{
  168935. sqlite3changeset_finalize(pIter);
  168936. }
  168937. if( rc==SQLITE_OK ){
  168938. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  168939. }
  168940. if( rc==SQLITE_OK ){
  168941. int nFk, notUsed;
  168942. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  168943. if( nFk!=0 ){
  168944. int res = SQLITE_CHANGESET_ABORT;
  168945. sqlite3_changeset_iter sIter;
  168946. memset(&sIter, 0, sizeof(sIter));
  168947. sIter.nCol = nFk;
  168948. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  168949. if( res!=SQLITE_CHANGESET_OMIT ){
  168950. rc = SQLITE_CONSTRAINT;
  168951. }
  168952. }
  168953. }
  168954. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  168955. if( rc==SQLITE_OK ){
  168956. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  168957. }else{
  168958. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  168959. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  168960. }
  168961. sqlite3_finalize(sApply.pInsert);
  168962. sqlite3_finalize(sApply.pDelete);
  168963. sqlite3_finalize(sApply.pUpdate);
  168964. sqlite3_finalize(sApply.pSelect);
  168965. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  168966. sqlite3_free((char*)sApply.constraints.aBuf);
  168967. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  168968. return rc;
  168969. }
  168970. /*
  168971. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  168972. ** attached to handle "db". Invoke the supplied conflict handler callback
  168973. ** to resolve any conflicts encountered while applying the change.
  168974. */
  168975. SQLITE_API int sqlite3changeset_apply(
  168976. sqlite3 *db, /* Apply change to "main" db of this handle */
  168977. int nChangeset, /* Size of changeset in bytes */
  168978. void *pChangeset, /* Changeset blob */
  168979. int(*xFilter)(
  168980. void *pCtx, /* Copy of sixth arg to _apply() */
  168981. const char *zTab /* Table name */
  168982. ),
  168983. int(*xConflict)(
  168984. void *pCtx, /* Copy of fifth arg to _apply() */
  168985. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  168986. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  168987. ),
  168988. void *pCtx /* First argument passed to xConflict */
  168989. ){
  168990. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  168991. int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  168992. if( rc==SQLITE_OK ){
  168993. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  168994. }
  168995. return rc;
  168996. }
  168997. /*
  168998. ** Apply the changeset passed via xInput/pIn to the main database
  168999. ** attached to handle "db". Invoke the supplied conflict handler callback
  169000. ** to resolve any conflicts encountered while applying the change.
  169001. */
  169002. SQLITE_API int sqlite3changeset_apply_strm(
  169003. sqlite3 *db, /* Apply change to "main" db of this handle */
  169004. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  169005. void *pIn, /* First arg for xInput */
  169006. int(*xFilter)(
  169007. void *pCtx, /* Copy of sixth arg to _apply() */
  169008. const char *zTab /* Table name */
  169009. ),
  169010. int(*xConflict)(
  169011. void *pCtx, /* Copy of sixth arg to _apply() */
  169012. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  169013. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  169014. ),
  169015. void *pCtx /* First argument passed to xConflict */
  169016. ){
  169017. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  169018. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  169019. if( rc==SQLITE_OK ){
  169020. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  169021. }
  169022. return rc;
  169023. }
  169024. /*
  169025. ** sqlite3_changegroup handle.
  169026. */
  169027. struct sqlite3_changegroup {
  169028. int rc; /* Error code */
  169029. int bPatch; /* True to accumulate patchsets */
  169030. SessionTable *pList; /* List of tables in current patch */
  169031. };
  169032. /*
  169033. ** This function is called to merge two changes to the same row together as
  169034. ** part of an sqlite3changeset_concat() operation. A new change object is
  169035. ** allocated and a pointer to it stored in *ppNew.
  169036. */
  169037. static int sessionChangeMerge(
  169038. SessionTable *pTab, /* Table structure */
  169039. int bPatchset, /* True for patchsets */
  169040. SessionChange *pExist, /* Existing change */
  169041. int op2, /* Second change operation */
  169042. int bIndirect, /* True if second change is indirect */
  169043. u8 *aRec, /* Second change record */
  169044. int nRec, /* Number of bytes in aRec */
  169045. SessionChange **ppNew /* OUT: Merged change */
  169046. ){
  169047. SessionChange *pNew = 0;
  169048. if( !pExist ){
  169049. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  169050. if( !pNew ){
  169051. return SQLITE_NOMEM;
  169052. }
  169053. memset(pNew, 0, sizeof(SessionChange));
  169054. pNew->op = op2;
  169055. pNew->bIndirect = bIndirect;
  169056. pNew->nRecord = nRec;
  169057. pNew->aRecord = (u8*)&pNew[1];
  169058. memcpy(pNew->aRecord, aRec, nRec);
  169059. }else{
  169060. int op1 = pExist->op;
  169061. /*
  169062. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  169063. ** op1=INSERT, op2=UPDATE -> INSERT.
  169064. ** op1=INSERT, op2=DELETE -> (none)
  169065. **
  169066. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  169067. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  169068. ** op1=UPDATE, op2=DELETE -> DELETE.
  169069. **
  169070. ** op1=DELETE, op2=INSERT -> UPDATE.
  169071. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  169072. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  169073. */
  169074. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  169075. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  169076. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  169077. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  169078. ){
  169079. pNew = pExist;
  169080. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  169081. sqlite3_free(pExist);
  169082. assert( pNew==0 );
  169083. }else{
  169084. u8 *aExist = pExist->aRecord;
  169085. int nByte;
  169086. u8 *aCsr;
  169087. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  169088. ** buffer of the new object is large enough to hold any record that
  169089. ** may be generated by combining the input records. */
  169090. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  169091. pNew = (SessionChange *)sqlite3_malloc(nByte);
  169092. if( !pNew ){
  169093. sqlite3_free(pExist);
  169094. return SQLITE_NOMEM;
  169095. }
  169096. memset(pNew, 0, sizeof(SessionChange));
  169097. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  169098. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  169099. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  169100. u8 *a1 = aRec;
  169101. assert( op2==SQLITE_UPDATE );
  169102. pNew->op = SQLITE_INSERT;
  169103. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  169104. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  169105. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  169106. assert( op2==SQLITE_INSERT );
  169107. pNew->op = SQLITE_UPDATE;
  169108. if( bPatchset ){
  169109. memcpy(aCsr, aRec, nRec);
  169110. aCsr += nRec;
  169111. }else{
  169112. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  169113. sqlite3_free(pNew);
  169114. pNew = 0;
  169115. }
  169116. }
  169117. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  169118. u8 *a1 = aExist;
  169119. u8 *a2 = aRec;
  169120. assert( op1==SQLITE_UPDATE );
  169121. if( bPatchset==0 ){
  169122. sessionSkipRecord(&a1, pTab->nCol);
  169123. sessionSkipRecord(&a2, pTab->nCol);
  169124. }
  169125. pNew->op = SQLITE_UPDATE;
  169126. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  169127. sqlite3_free(pNew);
  169128. pNew = 0;
  169129. }
  169130. }else{ /* UPDATE + DELETE */
  169131. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  169132. pNew->op = SQLITE_DELETE;
  169133. if( bPatchset ){
  169134. memcpy(aCsr, aRec, nRec);
  169135. aCsr += nRec;
  169136. }else{
  169137. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  169138. }
  169139. }
  169140. if( pNew ){
  169141. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  169142. }
  169143. sqlite3_free(pExist);
  169144. }
  169145. }
  169146. *ppNew = pNew;
  169147. return SQLITE_OK;
  169148. }
  169149. /*
  169150. ** Add all changes in the changeset traversed by the iterator passed as
  169151. ** the first argument to the changegroup hash tables.
  169152. */
  169153. static int sessionChangesetToHash(
  169154. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  169155. sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
  169156. ){
  169157. u8 *aRec;
  169158. int nRec;
  169159. int rc = SQLITE_OK;
  169160. SessionTable *pTab = 0;
  169161. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
  169162. const char *zNew;
  169163. int nCol;
  169164. int op;
  169165. int iHash;
  169166. int bIndirect;
  169167. SessionChange *pChange;
  169168. SessionChange *pExist = 0;
  169169. SessionChange **pp;
  169170. if( pGrp->pList==0 ){
  169171. pGrp->bPatch = pIter->bPatchset;
  169172. }else if( pIter->bPatchset!=pGrp->bPatch ){
  169173. rc = SQLITE_ERROR;
  169174. break;
  169175. }
  169176. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  169177. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  169178. /* Search the list for a matching table */
  169179. int nNew = (int)strlen(zNew);
  169180. u8 *abPK;
  169181. sqlite3changeset_pk(pIter, &abPK, 0);
  169182. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  169183. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  169184. }
  169185. if( !pTab ){
  169186. SessionTable **ppTab;
  169187. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  169188. if( !pTab ){
  169189. rc = SQLITE_NOMEM;
  169190. break;
  169191. }
  169192. memset(pTab, 0, sizeof(SessionTable));
  169193. pTab->nCol = nCol;
  169194. pTab->abPK = (u8*)&pTab[1];
  169195. memcpy(pTab->abPK, abPK, nCol);
  169196. pTab->zName = (char*)&pTab->abPK[nCol];
  169197. memcpy(pTab->zName, zNew, nNew+1);
  169198. /* The new object must be linked on to the end of the list, not
  169199. ** simply added to the start of it. This is to ensure that the
  169200. ** tables within the output of sqlite3changegroup_output() are in
  169201. ** the right order. */
  169202. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  169203. *ppTab = pTab;
  169204. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  169205. rc = SQLITE_SCHEMA;
  169206. break;
  169207. }
  169208. }
  169209. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  169210. rc = SQLITE_NOMEM;
  169211. break;
  169212. }
  169213. iHash = sessionChangeHash(
  169214. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  169215. );
  169216. /* Search for existing entry. If found, remove it from the hash table.
  169217. ** Code below may link it back in.
  169218. */
  169219. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  169220. int bPkOnly1 = 0;
  169221. int bPkOnly2 = 0;
  169222. if( pIter->bPatchset ){
  169223. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  169224. bPkOnly2 = op==SQLITE_DELETE;
  169225. }
  169226. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  169227. pExist = *pp;
  169228. *pp = (*pp)->pNext;
  169229. pTab->nEntry--;
  169230. break;
  169231. }
  169232. }
  169233. rc = sessionChangeMerge(pTab,
  169234. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  169235. );
  169236. if( rc ) break;
  169237. if( pChange ){
  169238. pChange->pNext = pTab->apChange[iHash];
  169239. pTab->apChange[iHash] = pChange;
  169240. pTab->nEntry++;
  169241. }
  169242. }
  169243. if( rc==SQLITE_OK ) rc = pIter->rc;
  169244. return rc;
  169245. }
  169246. /*
  169247. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  169248. ** added to the changegroup object passed as the first argument.
  169249. **
  169250. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  169251. ** user via one or more calls to xOutput, as with the other streaming
  169252. ** interfaces.
  169253. **
  169254. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  169255. ** buffer containing the output changeset before this function returns. In
  169256. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  169257. ** is the responsibility of the caller to free the output buffer using
  169258. ** sqlite3_free() when it is no longer required.
  169259. **
  169260. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  169261. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  169262. ** are both set to 0 before returning.
  169263. */
  169264. static int sessionChangegroupOutput(
  169265. sqlite3_changegroup *pGrp,
  169266. int (*xOutput)(void *pOut, const void *pData, int nData),
  169267. void *pOut,
  169268. int *pnOut,
  169269. void **ppOut
  169270. ){
  169271. int rc = SQLITE_OK;
  169272. SessionBuffer buf = {0, 0, 0};
  169273. SessionTable *pTab;
  169274. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  169275. /* Create the serialized output changeset based on the contents of the
  169276. ** hash tables attached to the SessionTable objects in list p->pList.
  169277. */
  169278. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  169279. int i;
  169280. if( pTab->nEntry==0 ) continue;
  169281. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  169282. for(i=0; i<pTab->nChange; i++){
  169283. SessionChange *p;
  169284. for(p=pTab->apChange[i]; p; p=p->pNext){
  169285. sessionAppendByte(&buf, p->op, &rc);
  169286. sessionAppendByte(&buf, p->bIndirect, &rc);
  169287. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  169288. }
  169289. }
  169290. if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  169291. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  169292. buf.nBuf = 0;
  169293. }
  169294. }
  169295. if( rc==SQLITE_OK ){
  169296. if( xOutput ){
  169297. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  169298. }else{
  169299. *ppOut = buf.aBuf;
  169300. *pnOut = buf.nBuf;
  169301. buf.aBuf = 0;
  169302. }
  169303. }
  169304. sqlite3_free(buf.aBuf);
  169305. return rc;
  169306. }
  169307. /*
  169308. ** Allocate a new, empty, sqlite3_changegroup.
  169309. */
  169310. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  169311. int rc = SQLITE_OK; /* Return code */
  169312. sqlite3_changegroup *p; /* New object */
  169313. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  169314. if( p==0 ){
  169315. rc = SQLITE_NOMEM;
  169316. }else{
  169317. memset(p, 0, sizeof(sqlite3_changegroup));
  169318. }
  169319. *pp = p;
  169320. return rc;
  169321. }
  169322. /*
  169323. ** Add the changeset currently stored in buffer pData, size nData bytes,
  169324. ** to changeset-group p.
  169325. */
  169326. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  169327. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  169328. int rc; /* Return code */
  169329. rc = sqlite3changeset_start(&pIter, nData, pData);
  169330. if( rc==SQLITE_OK ){
  169331. rc = sessionChangesetToHash(pIter, pGrp);
  169332. }
  169333. sqlite3changeset_finalize(pIter);
  169334. return rc;
  169335. }
  169336. /*
  169337. ** Obtain a buffer containing a changeset representing the concatenation
  169338. ** of all changesets added to the group so far.
  169339. */
  169340. SQLITE_API int sqlite3changegroup_output(
  169341. sqlite3_changegroup *pGrp,
  169342. int *pnData,
  169343. void **ppData
  169344. ){
  169345. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  169346. }
  169347. /*
  169348. ** Streaming versions of changegroup_add().
  169349. */
  169350. SQLITE_API int sqlite3changegroup_add_strm(
  169351. sqlite3_changegroup *pGrp,
  169352. int (*xInput)(void *pIn, void *pData, int *pnData),
  169353. void *pIn
  169354. ){
  169355. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  169356. int rc; /* Return code */
  169357. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  169358. if( rc==SQLITE_OK ){
  169359. rc = sessionChangesetToHash(pIter, pGrp);
  169360. }
  169361. sqlite3changeset_finalize(pIter);
  169362. return rc;
  169363. }
  169364. /*
  169365. ** Streaming versions of changegroup_output().
  169366. */
  169367. SQLITE_API int sqlite3changegroup_output_strm(
  169368. sqlite3_changegroup *pGrp,
  169369. int (*xOutput)(void *pOut, const void *pData, int nData),
  169370. void *pOut
  169371. ){
  169372. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  169373. }
  169374. /*
  169375. ** Delete a changegroup object.
  169376. */
  169377. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  169378. if( pGrp ){
  169379. sessionDeleteTable(pGrp->pList);
  169380. sqlite3_free(pGrp);
  169381. }
  169382. }
  169383. /*
  169384. ** Combine two changesets together.
  169385. */
  169386. SQLITE_API int sqlite3changeset_concat(
  169387. int nLeft, /* Number of bytes in lhs input */
  169388. void *pLeft, /* Lhs input changeset */
  169389. int nRight /* Number of bytes in rhs input */,
  169390. void *pRight, /* Rhs input changeset */
  169391. int *pnOut, /* OUT: Number of bytes in output changeset */
  169392. void **ppOut /* OUT: changeset (left <concat> right) */
  169393. ){
  169394. sqlite3_changegroup *pGrp;
  169395. int rc;
  169396. rc = sqlite3changegroup_new(&pGrp);
  169397. if( rc==SQLITE_OK ){
  169398. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  169399. }
  169400. if( rc==SQLITE_OK ){
  169401. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  169402. }
  169403. if( rc==SQLITE_OK ){
  169404. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  169405. }
  169406. sqlite3changegroup_delete(pGrp);
  169407. return rc;
  169408. }
  169409. /*
  169410. ** Streaming version of sqlite3changeset_concat().
  169411. */
  169412. SQLITE_API int sqlite3changeset_concat_strm(
  169413. int (*xInputA)(void *pIn, void *pData, int *pnData),
  169414. void *pInA,
  169415. int (*xInputB)(void *pIn, void *pData, int *pnData),
  169416. void *pInB,
  169417. int (*xOutput)(void *pOut, const void *pData, int nData),
  169418. void *pOut
  169419. ){
  169420. sqlite3_changegroup *pGrp;
  169421. int rc;
  169422. rc = sqlite3changegroup_new(&pGrp);
  169423. if( rc==SQLITE_OK ){
  169424. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  169425. }
  169426. if( rc==SQLITE_OK ){
  169427. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  169428. }
  169429. if( rc==SQLITE_OK ){
  169430. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  169431. }
  169432. sqlite3changegroup_delete(pGrp);
  169433. return rc;
  169434. }
  169435. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  169436. /************** End of sqlite3session.c **************************************/
  169437. /************** Begin file json1.c *******************************************/
  169438. /*
  169439. ** 2015-08-12
  169440. **
  169441. ** The author disclaims copyright to this source code. In place of
  169442. ** a legal notice, here is a blessing:
  169443. **
  169444. ** May you do good and not evil.
  169445. ** May you find forgiveness for yourself and forgive others.
  169446. ** May you share freely, never taking more than you give.
  169447. **
  169448. ******************************************************************************
  169449. **
  169450. ** This SQLite extension implements JSON functions. The interface is
  169451. ** modeled after MySQL JSON functions:
  169452. **
  169453. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  169454. **
  169455. ** For the time being, all JSON is stored as pure text. (We might add
  169456. ** a JSONB type in the future which stores a binary encoding of JSON in
  169457. ** a BLOB, but there is no support for JSONB in the current implementation.
  169458. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  169459. ** how JSONB might improve on that.)
  169460. */
  169461. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  169462. #if !defined(SQLITEINT_H)
  169463. /* #include "sqlite3ext.h" */
  169464. #endif
  169465. SQLITE_EXTENSION_INIT1
  169466. /* #include <assert.h> */
  169467. /* #include <string.h> */
  169468. /* #include <stdlib.h> */
  169469. /* #include <stdarg.h> */
  169470. /* Mark a function parameter as unused, to suppress nuisance compiler
  169471. ** warnings. */
  169472. #ifndef UNUSED_PARAM
  169473. # define UNUSED_PARAM(X) (void)(X)
  169474. #endif
  169475. #ifndef LARGEST_INT64
  169476. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  169477. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  169478. #endif
  169479. /*
  169480. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  169481. ** to pass signed char values.
  169482. */
  169483. #ifdef sqlite3Isdigit
  169484. /* Use the SQLite core versions if this routine is part of the
  169485. ** SQLite amalgamation */
  169486. # define safe_isdigit(x) sqlite3Isdigit(x)
  169487. # define safe_isalnum(x) sqlite3Isalnum(x)
  169488. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  169489. #else
  169490. /* Use the standard library for separate compilation */
  169491. #include <ctype.h> /* amalgamator: keep */
  169492. # define safe_isdigit(x) isdigit((unsigned char)(x))
  169493. # define safe_isalnum(x) isalnum((unsigned char)(x))
  169494. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  169495. #endif
  169496. /*
  169497. ** Growing our own isspace() routine this way is twice as fast as
  169498. ** the library isspace() function, resulting in a 7% overall performance
  169499. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  169500. */
  169501. static const char jsonIsSpace[] = {
  169502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  169503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169504. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  169518. };
  169519. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  169520. #ifndef SQLITE_AMALGAMATION
  169521. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  169522. ** but the definitions need to be repeated for separate compilation. */
  169523. typedef sqlite3_uint64 u64;
  169524. typedef unsigned int u32;
  169525. typedef unsigned short int u16;
  169526. typedef unsigned char u8;
  169527. #endif
  169528. /* Objects */
  169529. typedef struct JsonString JsonString;
  169530. typedef struct JsonNode JsonNode;
  169531. typedef struct JsonParse JsonParse;
  169532. /* An instance of this object represents a JSON string
  169533. ** under construction. Really, this is a generic string accumulator
  169534. ** that can be and is used to create strings other than JSON.
  169535. */
  169536. struct JsonString {
  169537. sqlite3_context *pCtx; /* Function context - put error messages here */
  169538. char *zBuf; /* Append JSON content here */
  169539. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  169540. u64 nUsed; /* Bytes of zBuf[] currently used */
  169541. u8 bStatic; /* True if zBuf is static space */
  169542. u8 bErr; /* True if an error has been encountered */
  169543. char zSpace[100]; /* Initial static space */
  169544. };
  169545. /* JSON type values
  169546. */
  169547. #define JSON_NULL 0
  169548. #define JSON_TRUE 1
  169549. #define JSON_FALSE 2
  169550. #define JSON_INT 3
  169551. #define JSON_REAL 4
  169552. #define JSON_STRING 5
  169553. #define JSON_ARRAY 6
  169554. #define JSON_OBJECT 7
  169555. /* The "subtype" set for JSON values */
  169556. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  169557. /*
  169558. ** Names of the various JSON types:
  169559. */
  169560. static const char * const jsonType[] = {
  169561. "null", "true", "false", "integer", "real", "text", "array", "object"
  169562. };
  169563. /* Bit values for the JsonNode.jnFlag field
  169564. */
  169565. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  169566. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  169567. #define JNODE_REMOVE 0x04 /* Do not output */
  169568. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  169569. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  169570. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  169571. #define JNODE_LABEL 0x40 /* Is a label of an object */
  169572. /* A single node of parsed JSON
  169573. */
  169574. struct JsonNode {
  169575. u8 eType; /* One of the JSON_ type values */
  169576. u8 jnFlags; /* JNODE flags */
  169577. u32 n; /* Bytes of content, or number of sub-nodes */
  169578. union {
  169579. const char *zJContent; /* Content for INT, REAL, and STRING */
  169580. u32 iAppend; /* More terms for ARRAY and OBJECT */
  169581. u32 iKey; /* Key for ARRAY objects in json_tree() */
  169582. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  169583. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  169584. } u;
  169585. };
  169586. /* A completely parsed JSON string
  169587. */
  169588. struct JsonParse {
  169589. u32 nNode; /* Number of slots of aNode[] used */
  169590. u32 nAlloc; /* Number of slots of aNode[] allocated */
  169591. JsonNode *aNode; /* Array of nodes containing the parse */
  169592. const char *zJson; /* Original JSON string */
  169593. u32 *aUp; /* Index of parent of each node */
  169594. u8 oom; /* Set to true if out of memory */
  169595. u8 nErr; /* Number of errors seen */
  169596. u16 iDepth; /* Nesting depth */
  169597. int nJson; /* Length of the zJson string in bytes */
  169598. };
  169599. /*
  169600. ** Maximum nesting depth of JSON for this implementation.
  169601. **
  169602. ** This limit is needed to avoid a stack overflow in the recursive
  169603. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  169604. ** should go.
  169605. */
  169606. #define JSON_MAX_DEPTH 2000
  169607. /**************************************************************************
  169608. ** Utility routines for dealing with JsonString objects
  169609. **************************************************************************/
  169610. /* Set the JsonString object to an empty string
  169611. */
  169612. static void jsonZero(JsonString *p){
  169613. p->zBuf = p->zSpace;
  169614. p->nAlloc = sizeof(p->zSpace);
  169615. p->nUsed = 0;
  169616. p->bStatic = 1;
  169617. }
  169618. /* Initialize the JsonString object
  169619. */
  169620. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  169621. p->pCtx = pCtx;
  169622. p->bErr = 0;
  169623. jsonZero(p);
  169624. }
  169625. /* Free all allocated memory and reset the JsonString object back to its
  169626. ** initial state.
  169627. */
  169628. static void jsonReset(JsonString *p){
  169629. if( !p->bStatic ) sqlite3_free(p->zBuf);
  169630. jsonZero(p);
  169631. }
  169632. /* Report an out-of-memory (OOM) condition
  169633. */
  169634. static void jsonOom(JsonString *p){
  169635. p->bErr = 1;
  169636. sqlite3_result_error_nomem(p->pCtx);
  169637. jsonReset(p);
  169638. }
  169639. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  169640. ** Return zero on success. Return non-zero on an OOM error
  169641. */
  169642. static int jsonGrow(JsonString *p, u32 N){
  169643. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  169644. char *zNew;
  169645. if( p->bStatic ){
  169646. if( p->bErr ) return 1;
  169647. zNew = sqlite3_malloc64(nTotal);
  169648. if( zNew==0 ){
  169649. jsonOom(p);
  169650. return SQLITE_NOMEM;
  169651. }
  169652. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  169653. p->zBuf = zNew;
  169654. p->bStatic = 0;
  169655. }else{
  169656. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  169657. if( zNew==0 ){
  169658. jsonOom(p);
  169659. return SQLITE_NOMEM;
  169660. }
  169661. p->zBuf = zNew;
  169662. }
  169663. p->nAlloc = nTotal;
  169664. return SQLITE_OK;
  169665. }
  169666. /* Append N bytes from zIn onto the end of the JsonString string.
  169667. */
  169668. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  169669. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  169670. memcpy(p->zBuf+p->nUsed, zIn, N);
  169671. p->nUsed += N;
  169672. }
  169673. /* Append formatted text (not to exceed N bytes) to the JsonString.
  169674. */
  169675. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  169676. va_list ap;
  169677. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  169678. va_start(ap, zFormat);
  169679. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  169680. va_end(ap);
  169681. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  169682. }
  169683. /* Append a single character
  169684. */
  169685. static void jsonAppendChar(JsonString *p, char c){
  169686. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  169687. p->zBuf[p->nUsed++] = c;
  169688. }
  169689. /* Append a comma separator to the output buffer, if the previous
  169690. ** character is not '[' or '{'.
  169691. */
  169692. static void jsonAppendSeparator(JsonString *p){
  169693. char c;
  169694. if( p->nUsed==0 ) return;
  169695. c = p->zBuf[p->nUsed-1];
  169696. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  169697. }
  169698. /* Append the N-byte string in zIn to the end of the JsonString string
  169699. ** under construction. Enclose the string in "..." and escape
  169700. ** any double-quotes or backslash characters contained within the
  169701. ** string.
  169702. */
  169703. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  169704. u32 i;
  169705. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  169706. p->zBuf[p->nUsed++] = '"';
  169707. for(i=0; i<N; i++){
  169708. unsigned char c = ((unsigned const char*)zIn)[i];
  169709. if( c=='"' || c=='\\' ){
  169710. json_simple_escape:
  169711. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  169712. p->zBuf[p->nUsed++] = '\\';
  169713. }else if( c<=0x1f ){
  169714. static const char aSpecial[] = {
  169715. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  169716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  169717. };
  169718. assert( sizeof(aSpecial)==32 );
  169719. assert( aSpecial['\b']=='b' );
  169720. assert( aSpecial['\f']=='f' );
  169721. assert( aSpecial['\n']=='n' );
  169722. assert( aSpecial['\r']=='r' );
  169723. assert( aSpecial['\t']=='t' );
  169724. if( aSpecial[c] ){
  169725. c = aSpecial[c];
  169726. goto json_simple_escape;
  169727. }
  169728. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  169729. p->zBuf[p->nUsed++] = '\\';
  169730. p->zBuf[p->nUsed++] = 'u';
  169731. p->zBuf[p->nUsed++] = '0';
  169732. p->zBuf[p->nUsed++] = '0';
  169733. p->zBuf[p->nUsed++] = '0' + (c>>4);
  169734. c = "0123456789abcdef"[c&0xf];
  169735. }
  169736. p->zBuf[p->nUsed++] = c;
  169737. }
  169738. p->zBuf[p->nUsed++] = '"';
  169739. assert( p->nUsed<p->nAlloc );
  169740. }
  169741. /*
  169742. ** Append a function parameter value to the JSON string under
  169743. ** construction.
  169744. */
  169745. static void jsonAppendValue(
  169746. JsonString *p, /* Append to this JSON string */
  169747. sqlite3_value *pValue /* Value to append */
  169748. ){
  169749. switch( sqlite3_value_type(pValue) ){
  169750. case SQLITE_NULL: {
  169751. jsonAppendRaw(p, "null", 4);
  169752. break;
  169753. }
  169754. case SQLITE_INTEGER:
  169755. case SQLITE_FLOAT: {
  169756. const char *z = (const char*)sqlite3_value_text(pValue);
  169757. u32 n = (u32)sqlite3_value_bytes(pValue);
  169758. jsonAppendRaw(p, z, n);
  169759. break;
  169760. }
  169761. case SQLITE_TEXT: {
  169762. const char *z = (const char*)sqlite3_value_text(pValue);
  169763. u32 n = (u32)sqlite3_value_bytes(pValue);
  169764. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  169765. jsonAppendRaw(p, z, n);
  169766. }else{
  169767. jsonAppendString(p, z, n);
  169768. }
  169769. break;
  169770. }
  169771. default: {
  169772. if( p->bErr==0 ){
  169773. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  169774. p->bErr = 2;
  169775. jsonReset(p);
  169776. }
  169777. break;
  169778. }
  169779. }
  169780. }
  169781. /* Make the JSON in p the result of the SQL function.
  169782. */
  169783. static void jsonResult(JsonString *p){
  169784. if( p->bErr==0 ){
  169785. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  169786. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  169787. SQLITE_UTF8);
  169788. jsonZero(p);
  169789. }
  169790. assert( p->bStatic );
  169791. }
  169792. /**************************************************************************
  169793. ** Utility routines for dealing with JsonNode and JsonParse objects
  169794. **************************************************************************/
  169795. /*
  169796. ** Return the number of consecutive JsonNode slots need to represent
  169797. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  169798. ** OBJECT types, the number might be larger.
  169799. **
  169800. ** Appended elements are not counted. The value returned is the number
  169801. ** by which the JsonNode counter should increment in order to go to the
  169802. ** next peer value.
  169803. */
  169804. static u32 jsonNodeSize(JsonNode *pNode){
  169805. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  169806. }
  169807. /*
  169808. ** Reclaim all memory allocated by a JsonParse object. But do not
  169809. ** delete the JsonParse object itself.
  169810. */
  169811. static void jsonParseReset(JsonParse *pParse){
  169812. sqlite3_free(pParse->aNode);
  169813. pParse->aNode = 0;
  169814. pParse->nNode = 0;
  169815. pParse->nAlloc = 0;
  169816. sqlite3_free(pParse->aUp);
  169817. pParse->aUp = 0;
  169818. }
  169819. /*
  169820. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  169821. */
  169822. static void jsonParseFree(JsonParse *pParse){
  169823. jsonParseReset(pParse);
  169824. sqlite3_free(pParse);
  169825. }
  169826. /*
  169827. ** Convert the JsonNode pNode into a pure JSON string and
  169828. ** append to pOut. Subsubstructure is also included. Return
  169829. ** the number of JsonNode objects that are encoded.
  169830. */
  169831. static void jsonRenderNode(
  169832. JsonNode *pNode, /* The node to render */
  169833. JsonString *pOut, /* Write JSON here */
  169834. sqlite3_value **aReplace /* Replacement values */
  169835. ){
  169836. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  169837. if( pNode->jnFlags & JNODE_REPLACE ){
  169838. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  169839. return;
  169840. }
  169841. pNode = pNode->u.pPatch;
  169842. }
  169843. switch( pNode->eType ){
  169844. default: {
  169845. assert( pNode->eType==JSON_NULL );
  169846. jsonAppendRaw(pOut, "null", 4);
  169847. break;
  169848. }
  169849. case JSON_TRUE: {
  169850. jsonAppendRaw(pOut, "true", 4);
  169851. break;
  169852. }
  169853. case JSON_FALSE: {
  169854. jsonAppendRaw(pOut, "false", 5);
  169855. break;
  169856. }
  169857. case JSON_STRING: {
  169858. if( pNode->jnFlags & JNODE_RAW ){
  169859. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  169860. break;
  169861. }
  169862. /* Fall through into the next case */
  169863. }
  169864. case JSON_REAL:
  169865. case JSON_INT: {
  169866. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  169867. break;
  169868. }
  169869. case JSON_ARRAY: {
  169870. u32 j = 1;
  169871. jsonAppendChar(pOut, '[');
  169872. for(;;){
  169873. while( j<=pNode->n ){
  169874. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  169875. jsonAppendSeparator(pOut);
  169876. jsonRenderNode(&pNode[j], pOut, aReplace);
  169877. }
  169878. j += jsonNodeSize(&pNode[j]);
  169879. }
  169880. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  169881. pNode = &pNode[pNode->u.iAppend];
  169882. j = 1;
  169883. }
  169884. jsonAppendChar(pOut, ']');
  169885. break;
  169886. }
  169887. case JSON_OBJECT: {
  169888. u32 j = 1;
  169889. jsonAppendChar(pOut, '{');
  169890. for(;;){
  169891. while( j<=pNode->n ){
  169892. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  169893. jsonAppendSeparator(pOut);
  169894. jsonRenderNode(&pNode[j], pOut, aReplace);
  169895. jsonAppendChar(pOut, ':');
  169896. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  169897. }
  169898. j += 1 + jsonNodeSize(&pNode[j+1]);
  169899. }
  169900. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  169901. pNode = &pNode[pNode->u.iAppend];
  169902. j = 1;
  169903. }
  169904. jsonAppendChar(pOut, '}');
  169905. break;
  169906. }
  169907. }
  169908. }
  169909. /*
  169910. ** Return a JsonNode and all its descendents as a JSON string.
  169911. */
  169912. static void jsonReturnJson(
  169913. JsonNode *pNode, /* Node to return */
  169914. sqlite3_context *pCtx, /* Return value for this function */
  169915. sqlite3_value **aReplace /* Array of replacement values */
  169916. ){
  169917. JsonString s;
  169918. jsonInit(&s, pCtx);
  169919. jsonRenderNode(pNode, &s, aReplace);
  169920. jsonResult(&s);
  169921. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  169922. }
  169923. /*
  169924. ** Make the JsonNode the return value of the function.
  169925. */
  169926. static void jsonReturn(
  169927. JsonNode *pNode, /* Node to return */
  169928. sqlite3_context *pCtx, /* Return value for this function */
  169929. sqlite3_value **aReplace /* Array of replacement values */
  169930. ){
  169931. switch( pNode->eType ){
  169932. default: {
  169933. assert( pNode->eType==JSON_NULL );
  169934. sqlite3_result_null(pCtx);
  169935. break;
  169936. }
  169937. case JSON_TRUE: {
  169938. sqlite3_result_int(pCtx, 1);
  169939. break;
  169940. }
  169941. case JSON_FALSE: {
  169942. sqlite3_result_int(pCtx, 0);
  169943. break;
  169944. }
  169945. case JSON_INT: {
  169946. sqlite3_int64 i = 0;
  169947. const char *z = pNode->u.zJContent;
  169948. if( z[0]=='-' ){ z++; }
  169949. while( z[0]>='0' && z[0]<='9' ){
  169950. unsigned v = *(z++) - '0';
  169951. if( i>=LARGEST_INT64/10 ){
  169952. if( i>LARGEST_INT64/10 ) goto int_as_real;
  169953. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  169954. if( v==9 ) goto int_as_real;
  169955. if( v==8 ){
  169956. if( pNode->u.zJContent[0]=='-' ){
  169957. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  169958. goto int_done;
  169959. }else{
  169960. goto int_as_real;
  169961. }
  169962. }
  169963. }
  169964. i = i*10 + v;
  169965. }
  169966. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  169967. sqlite3_result_int64(pCtx, i);
  169968. int_done:
  169969. break;
  169970. int_as_real: /* fall through to real */;
  169971. }
  169972. case JSON_REAL: {
  169973. double r;
  169974. #ifdef SQLITE_AMALGAMATION
  169975. const char *z = pNode->u.zJContent;
  169976. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  169977. #else
  169978. r = strtod(pNode->u.zJContent, 0);
  169979. #endif
  169980. sqlite3_result_double(pCtx, r);
  169981. break;
  169982. }
  169983. case JSON_STRING: {
  169984. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  169985. ** json_insert() and json_replace() and those routines do not
  169986. ** call jsonReturn() */
  169987. if( pNode->jnFlags & JNODE_RAW ){
  169988. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  169989. SQLITE_TRANSIENT);
  169990. }else
  169991. #endif
  169992. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  169993. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  169994. /* JSON formatted without any backslash-escapes */
  169995. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  169996. SQLITE_TRANSIENT);
  169997. }else{
  169998. /* Translate JSON formatted string into raw text */
  169999. u32 i;
  170000. u32 n = pNode->n;
  170001. const char *z = pNode->u.zJContent;
  170002. char *zOut;
  170003. u32 j;
  170004. zOut = sqlite3_malloc( n+1 );
  170005. if( zOut==0 ){
  170006. sqlite3_result_error_nomem(pCtx);
  170007. break;
  170008. }
  170009. for(i=1, j=0; i<n-1; i++){
  170010. char c = z[i];
  170011. if( c!='\\' ){
  170012. zOut[j++] = c;
  170013. }else{
  170014. c = z[++i];
  170015. if( c=='u' ){
  170016. u32 v = 0, k;
  170017. for(k=0; k<4; i++, k++){
  170018. assert( i<n-2 );
  170019. c = z[i+1];
  170020. assert( safe_isxdigit(c) );
  170021. if( c<='9' ) v = v*16 + c - '0';
  170022. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  170023. else v = v*16 + c - 'a' + 10;
  170024. }
  170025. if( v==0 ) break;
  170026. if( v<=0x7f ){
  170027. zOut[j++] = (char)v;
  170028. }else if( v<=0x7ff ){
  170029. zOut[j++] = (char)(0xc0 | (v>>6));
  170030. zOut[j++] = 0x80 | (v&0x3f);
  170031. }else{
  170032. zOut[j++] = (char)(0xe0 | (v>>12));
  170033. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  170034. zOut[j++] = 0x80 | (v&0x3f);
  170035. }
  170036. }else{
  170037. if( c=='b' ){
  170038. c = '\b';
  170039. }else if( c=='f' ){
  170040. c = '\f';
  170041. }else if( c=='n' ){
  170042. c = '\n';
  170043. }else if( c=='r' ){
  170044. c = '\r';
  170045. }else if( c=='t' ){
  170046. c = '\t';
  170047. }
  170048. zOut[j++] = c;
  170049. }
  170050. }
  170051. }
  170052. zOut[j] = 0;
  170053. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  170054. }
  170055. break;
  170056. }
  170057. case JSON_ARRAY:
  170058. case JSON_OBJECT: {
  170059. jsonReturnJson(pNode, pCtx, aReplace);
  170060. break;
  170061. }
  170062. }
  170063. }
  170064. /* Forward reference */
  170065. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  170066. /*
  170067. ** A macro to hint to the compiler that a function should not be
  170068. ** inlined.
  170069. */
  170070. #if defined(__GNUC__)
  170071. # define JSON_NOINLINE __attribute__((noinline))
  170072. #elif defined(_MSC_VER) && _MSC_VER>=1310
  170073. # define JSON_NOINLINE __declspec(noinline)
  170074. #else
  170075. # define JSON_NOINLINE
  170076. #endif
  170077. static JSON_NOINLINE int jsonParseAddNodeExpand(
  170078. JsonParse *pParse, /* Append the node to this object */
  170079. u32 eType, /* Node type */
  170080. u32 n, /* Content size or sub-node count */
  170081. const char *zContent /* Content */
  170082. ){
  170083. u32 nNew;
  170084. JsonNode *pNew;
  170085. assert( pParse->nNode>=pParse->nAlloc );
  170086. if( pParse->oom ) return -1;
  170087. nNew = pParse->nAlloc*2 + 10;
  170088. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  170089. if( pNew==0 ){
  170090. pParse->oom = 1;
  170091. return -1;
  170092. }
  170093. pParse->nAlloc = nNew;
  170094. pParse->aNode = pNew;
  170095. assert( pParse->nNode<pParse->nAlloc );
  170096. return jsonParseAddNode(pParse, eType, n, zContent);
  170097. }
  170098. /*
  170099. ** Create a new JsonNode instance based on the arguments and append that
  170100. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  170101. ** new node, or -1 if a memory allocation fails.
  170102. */
  170103. static int jsonParseAddNode(
  170104. JsonParse *pParse, /* Append the node to this object */
  170105. u32 eType, /* Node type */
  170106. u32 n, /* Content size or sub-node count */
  170107. const char *zContent /* Content */
  170108. ){
  170109. JsonNode *p;
  170110. if( pParse->nNode>=pParse->nAlloc ){
  170111. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  170112. }
  170113. p = &pParse->aNode[pParse->nNode];
  170114. p->eType = (u8)eType;
  170115. p->jnFlags = 0;
  170116. p->n = n;
  170117. p->u.zJContent = zContent;
  170118. return pParse->nNode++;
  170119. }
  170120. /*
  170121. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  170122. */
  170123. static int jsonIs4Hex(const char *z){
  170124. int i;
  170125. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  170126. return 1;
  170127. }
  170128. /*
  170129. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  170130. ** index of the first character past the end of the value parsed.
  170131. **
  170132. ** Return negative for a syntax error. Special cases: return -2 if the
  170133. ** first non-whitespace character is '}' and return -3 if the first
  170134. ** non-whitespace character is ']'.
  170135. */
  170136. static int jsonParseValue(JsonParse *pParse, u32 i){
  170137. char c;
  170138. u32 j;
  170139. int iThis;
  170140. int x;
  170141. JsonNode *pNode;
  170142. const char *z = pParse->zJson;
  170143. while( safe_isspace(z[i]) ){ i++; }
  170144. if( (c = z[i])=='{' ){
  170145. /* Parse object */
  170146. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  170147. if( iThis<0 ) return -1;
  170148. for(j=i+1;;j++){
  170149. while( safe_isspace(z[j]) ){ j++; }
  170150. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  170151. x = jsonParseValue(pParse, j);
  170152. if( x<0 ){
  170153. pParse->iDepth--;
  170154. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  170155. return -1;
  170156. }
  170157. if( pParse->oom ) return -1;
  170158. pNode = &pParse->aNode[pParse->nNode-1];
  170159. if( pNode->eType!=JSON_STRING ) return -1;
  170160. pNode->jnFlags |= JNODE_LABEL;
  170161. j = x;
  170162. while( safe_isspace(z[j]) ){ j++; }
  170163. if( z[j]!=':' ) return -1;
  170164. j++;
  170165. x = jsonParseValue(pParse, j);
  170166. pParse->iDepth--;
  170167. if( x<0 ) return -1;
  170168. j = x;
  170169. while( safe_isspace(z[j]) ){ j++; }
  170170. c = z[j];
  170171. if( c==',' ) continue;
  170172. if( c!='}' ) return -1;
  170173. break;
  170174. }
  170175. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  170176. return j+1;
  170177. }else if( c=='[' ){
  170178. /* Parse array */
  170179. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  170180. if( iThis<0 ) return -1;
  170181. for(j=i+1;;j++){
  170182. while( safe_isspace(z[j]) ){ j++; }
  170183. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  170184. x = jsonParseValue(pParse, j);
  170185. pParse->iDepth--;
  170186. if( x<0 ){
  170187. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  170188. return -1;
  170189. }
  170190. j = x;
  170191. while( safe_isspace(z[j]) ){ j++; }
  170192. c = z[j];
  170193. if( c==',' ) continue;
  170194. if( c!=']' ) return -1;
  170195. break;
  170196. }
  170197. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  170198. return j+1;
  170199. }else if( c=='"' ){
  170200. /* Parse string */
  170201. u8 jnFlags = 0;
  170202. j = i+1;
  170203. for(;;){
  170204. c = z[j];
  170205. if( (c & ~0x1f)==0 ){
  170206. /* Control characters are not allowed in strings */
  170207. return -1;
  170208. }
  170209. if( c=='\\' ){
  170210. c = z[++j];
  170211. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  170212. || c=='n' || c=='r' || c=='t'
  170213. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  170214. jnFlags = JNODE_ESCAPE;
  170215. }else{
  170216. return -1;
  170217. }
  170218. }else if( c=='"' ){
  170219. break;
  170220. }
  170221. j++;
  170222. }
  170223. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  170224. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  170225. return j+1;
  170226. }else if( c=='n'
  170227. && strncmp(z+i,"null",4)==0
  170228. && !safe_isalnum(z[i+4]) ){
  170229. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  170230. return i+4;
  170231. }else if( c=='t'
  170232. && strncmp(z+i,"true",4)==0
  170233. && !safe_isalnum(z[i+4]) ){
  170234. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  170235. return i+4;
  170236. }else if( c=='f'
  170237. && strncmp(z+i,"false",5)==0
  170238. && !safe_isalnum(z[i+5]) ){
  170239. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  170240. return i+5;
  170241. }else if( c=='-' || (c>='0' && c<='9') ){
  170242. /* Parse number */
  170243. u8 seenDP = 0;
  170244. u8 seenE = 0;
  170245. assert( '-' < '0' );
  170246. if( c<='0' ){
  170247. j = c=='-' ? i+1 : i;
  170248. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  170249. }
  170250. j = i+1;
  170251. for(;; j++){
  170252. c = z[j];
  170253. if( c>='0' && c<='9' ) continue;
  170254. if( c=='.' ){
  170255. if( z[j-1]=='-' ) return -1;
  170256. if( seenDP ) return -1;
  170257. seenDP = 1;
  170258. continue;
  170259. }
  170260. if( c=='e' || c=='E' ){
  170261. if( z[j-1]<'0' ) return -1;
  170262. if( seenE ) return -1;
  170263. seenDP = seenE = 1;
  170264. c = z[j+1];
  170265. if( c=='+' || c=='-' ){
  170266. j++;
  170267. c = z[j+1];
  170268. }
  170269. if( c<'0' || c>'9' ) return -1;
  170270. continue;
  170271. }
  170272. break;
  170273. }
  170274. if( z[j-1]<'0' ) return -1;
  170275. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  170276. j - i, &z[i]);
  170277. return j;
  170278. }else if( c=='}' ){
  170279. return -2; /* End of {...} */
  170280. }else if( c==']' ){
  170281. return -3; /* End of [...] */
  170282. }else if( c==0 ){
  170283. return 0; /* End of file */
  170284. }else{
  170285. return -1; /* Syntax error */
  170286. }
  170287. }
  170288. /*
  170289. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  170290. ** are any errors. If an error occurs, free all memory associated with
  170291. ** pParse.
  170292. **
  170293. ** pParse is uninitialized when this routine is called.
  170294. */
  170295. static int jsonParse(
  170296. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  170297. sqlite3_context *pCtx, /* Report errors here */
  170298. const char *zJson /* Input JSON text to be parsed */
  170299. ){
  170300. int i;
  170301. memset(pParse, 0, sizeof(*pParse));
  170302. if( zJson==0 ) return 1;
  170303. pParse->zJson = zJson;
  170304. i = jsonParseValue(pParse, 0);
  170305. if( pParse->oom ) i = -1;
  170306. if( i>0 ){
  170307. assert( pParse->iDepth==0 );
  170308. while( safe_isspace(zJson[i]) ) i++;
  170309. if( zJson[i] ) i = -1;
  170310. }
  170311. if( i<=0 ){
  170312. if( pCtx!=0 ){
  170313. if( pParse->oom ){
  170314. sqlite3_result_error_nomem(pCtx);
  170315. }else{
  170316. sqlite3_result_error(pCtx, "malformed JSON", -1);
  170317. }
  170318. }
  170319. jsonParseReset(pParse);
  170320. return 1;
  170321. }
  170322. return 0;
  170323. }
  170324. /* Mark node i of pParse as being a child of iParent. Call recursively
  170325. ** to fill in all the descendants of node i.
  170326. */
  170327. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  170328. JsonNode *pNode = &pParse->aNode[i];
  170329. u32 j;
  170330. pParse->aUp[i] = iParent;
  170331. switch( pNode->eType ){
  170332. case JSON_ARRAY: {
  170333. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  170334. jsonParseFillInParentage(pParse, i+j, i);
  170335. }
  170336. break;
  170337. }
  170338. case JSON_OBJECT: {
  170339. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  170340. pParse->aUp[i+j] = i;
  170341. jsonParseFillInParentage(pParse, i+j+1, i);
  170342. }
  170343. break;
  170344. }
  170345. default: {
  170346. break;
  170347. }
  170348. }
  170349. }
  170350. /*
  170351. ** Compute the parentage of all nodes in a completed parse.
  170352. */
  170353. static int jsonParseFindParents(JsonParse *pParse){
  170354. u32 *aUp;
  170355. assert( pParse->aUp==0 );
  170356. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  170357. if( aUp==0 ){
  170358. pParse->oom = 1;
  170359. return SQLITE_NOMEM;
  170360. }
  170361. jsonParseFillInParentage(pParse, 0, 0);
  170362. return SQLITE_OK;
  170363. }
  170364. /*
  170365. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  170366. */
  170367. #define JSON_CACHE_ID (-429938)
  170368. /*
  170369. ** Obtain a complete parse of the JSON found in the first argument
  170370. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  170371. ** parse if it is available. If the cache is not available or if it
  170372. ** is no longer valid, parse the JSON again and return the new parse,
  170373. ** and also register the new parse so that it will be available for
  170374. ** future sqlite3_get_auxdata() calls.
  170375. */
  170376. static JsonParse *jsonParseCached(
  170377. sqlite3_context *pCtx,
  170378. sqlite3_value **argv
  170379. ){
  170380. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  170381. int nJson = sqlite3_value_bytes(argv[0]);
  170382. JsonParse *p;
  170383. if( zJson==0 ) return 0;
  170384. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  170385. if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
  170386. p->nErr = 0;
  170387. return p; /* The cached entry matches, so return it */
  170388. }
  170389. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  170390. if( p==0 ){
  170391. sqlite3_result_error_nomem(pCtx);
  170392. return 0;
  170393. }
  170394. memset(p, 0, sizeof(*p));
  170395. p->zJson = (char*)&p[1];
  170396. memcpy((char*)p->zJson, zJson, nJson+1);
  170397. if( jsonParse(p, pCtx, p->zJson) ){
  170398. sqlite3_free(p);
  170399. return 0;
  170400. }
  170401. p->nJson = nJson;
  170402. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  170403. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  170404. }
  170405. /*
  170406. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  170407. ** a match.
  170408. */
  170409. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  170410. if( pNode->jnFlags & JNODE_RAW ){
  170411. if( pNode->n!=nKey ) return 0;
  170412. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  170413. }else{
  170414. if( pNode->n!=nKey+2 ) return 0;
  170415. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  170416. }
  170417. }
  170418. /* forward declaration */
  170419. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  170420. /*
  170421. ** Search along zPath to find the node specified. Return a pointer
  170422. ** to that node, or NULL if zPath is malformed or if there is no such
  170423. ** node.
  170424. **
  170425. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  170426. ** possible to do so and if no existing node corresponds to zPath. If
  170427. ** new nodes are appended *pApnd is set to 1.
  170428. */
  170429. static JsonNode *jsonLookupStep(
  170430. JsonParse *pParse, /* The JSON to search */
  170431. u32 iRoot, /* Begin the search at this node */
  170432. const char *zPath, /* The path to search */
  170433. int *pApnd, /* Append nodes to complete path if not NULL */
  170434. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  170435. ){
  170436. u32 i, j, nKey;
  170437. const char *zKey;
  170438. JsonNode *pRoot = &pParse->aNode[iRoot];
  170439. if( zPath[0]==0 ) return pRoot;
  170440. if( zPath[0]=='.' ){
  170441. if( pRoot->eType!=JSON_OBJECT ) return 0;
  170442. zPath++;
  170443. if( zPath[0]=='"' ){
  170444. zKey = zPath + 1;
  170445. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  170446. nKey = i-1;
  170447. if( zPath[i] ){
  170448. i++;
  170449. }else{
  170450. *pzErr = zPath;
  170451. return 0;
  170452. }
  170453. }else{
  170454. zKey = zPath;
  170455. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  170456. nKey = i;
  170457. }
  170458. if( nKey==0 ){
  170459. *pzErr = zPath;
  170460. return 0;
  170461. }
  170462. j = 1;
  170463. for(;;){
  170464. while( j<=pRoot->n ){
  170465. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  170466. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  170467. }
  170468. j++;
  170469. j += jsonNodeSize(&pRoot[j]);
  170470. }
  170471. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  170472. iRoot += pRoot->u.iAppend;
  170473. pRoot = &pParse->aNode[iRoot];
  170474. j = 1;
  170475. }
  170476. if( pApnd ){
  170477. u32 iStart, iLabel;
  170478. JsonNode *pNode;
  170479. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  170480. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  170481. zPath += i;
  170482. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  170483. if( pParse->oom ) return 0;
  170484. if( pNode ){
  170485. pRoot = &pParse->aNode[iRoot];
  170486. pRoot->u.iAppend = iStart - iRoot;
  170487. pRoot->jnFlags |= JNODE_APPEND;
  170488. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  170489. }
  170490. return pNode;
  170491. }
  170492. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  170493. if( pRoot->eType!=JSON_ARRAY ) return 0;
  170494. i = 0;
  170495. j = 1;
  170496. while( safe_isdigit(zPath[j]) ){
  170497. i = i*10 + zPath[j] - '0';
  170498. j++;
  170499. }
  170500. if( zPath[j]!=']' ){
  170501. *pzErr = zPath;
  170502. return 0;
  170503. }
  170504. zPath += j + 1;
  170505. j = 1;
  170506. for(;;){
  170507. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  170508. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  170509. j += jsonNodeSize(&pRoot[j]);
  170510. }
  170511. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  170512. iRoot += pRoot->u.iAppend;
  170513. pRoot = &pParse->aNode[iRoot];
  170514. j = 1;
  170515. }
  170516. if( j<=pRoot->n ){
  170517. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  170518. }
  170519. if( i==0 && pApnd ){
  170520. u32 iStart;
  170521. JsonNode *pNode;
  170522. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  170523. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  170524. if( pParse->oom ) return 0;
  170525. if( pNode ){
  170526. pRoot = &pParse->aNode[iRoot];
  170527. pRoot->u.iAppend = iStart - iRoot;
  170528. pRoot->jnFlags |= JNODE_APPEND;
  170529. }
  170530. return pNode;
  170531. }
  170532. }else{
  170533. *pzErr = zPath;
  170534. }
  170535. return 0;
  170536. }
  170537. /*
  170538. ** Append content to pParse that will complete zPath. Return a pointer
  170539. ** to the inserted node, or return NULL if the append fails.
  170540. */
  170541. static JsonNode *jsonLookupAppend(
  170542. JsonParse *pParse, /* Append content to the JSON parse */
  170543. const char *zPath, /* Description of content to append */
  170544. int *pApnd, /* Set this flag to 1 */
  170545. const char **pzErr /* Make this point to any syntax error */
  170546. ){
  170547. *pApnd = 1;
  170548. if( zPath[0]==0 ){
  170549. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  170550. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  170551. }
  170552. if( zPath[0]=='.' ){
  170553. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  170554. }else if( strncmp(zPath,"[0]",3)==0 ){
  170555. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  170556. }else{
  170557. return 0;
  170558. }
  170559. if( pParse->oom ) return 0;
  170560. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  170561. }
  170562. /*
  170563. ** Return the text of a syntax error message on a JSON path. Space is
  170564. ** obtained from sqlite3_malloc().
  170565. */
  170566. static char *jsonPathSyntaxError(const char *zErr){
  170567. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  170568. }
  170569. /*
  170570. ** Do a node lookup using zPath. Return a pointer to the node on success.
  170571. ** Return NULL if not found or if there is an error.
  170572. **
  170573. ** On an error, write an error message into pCtx and increment the
  170574. ** pParse->nErr counter.
  170575. **
  170576. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  170577. ** nodes are appended.
  170578. */
  170579. static JsonNode *jsonLookup(
  170580. JsonParse *pParse, /* The JSON to search */
  170581. const char *zPath, /* The path to search */
  170582. int *pApnd, /* Append nodes to complete path if not NULL */
  170583. sqlite3_context *pCtx /* Report errors here, if not NULL */
  170584. ){
  170585. const char *zErr = 0;
  170586. JsonNode *pNode = 0;
  170587. char *zMsg;
  170588. if( zPath==0 ) return 0;
  170589. if( zPath[0]!='$' ){
  170590. zErr = zPath;
  170591. goto lookup_err;
  170592. }
  170593. zPath++;
  170594. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  170595. if( zErr==0 ) return pNode;
  170596. lookup_err:
  170597. pParse->nErr++;
  170598. assert( zErr!=0 && pCtx!=0 );
  170599. zMsg = jsonPathSyntaxError(zErr);
  170600. if( zMsg ){
  170601. sqlite3_result_error(pCtx, zMsg, -1);
  170602. sqlite3_free(zMsg);
  170603. }else{
  170604. sqlite3_result_error_nomem(pCtx);
  170605. }
  170606. return 0;
  170607. }
  170608. /*
  170609. ** Report the wrong number of arguments for json_insert(), json_replace()
  170610. ** or json_set().
  170611. */
  170612. static void jsonWrongNumArgs(
  170613. sqlite3_context *pCtx,
  170614. const char *zFuncName
  170615. ){
  170616. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  170617. zFuncName);
  170618. sqlite3_result_error(pCtx, zMsg, -1);
  170619. sqlite3_free(zMsg);
  170620. }
  170621. /*
  170622. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  170623. */
  170624. static void jsonRemoveAllNulls(JsonNode *pNode){
  170625. int i, n;
  170626. assert( pNode->eType==JSON_OBJECT );
  170627. n = pNode->n;
  170628. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  170629. switch( pNode[i].eType ){
  170630. case JSON_NULL:
  170631. pNode[i].jnFlags |= JNODE_REMOVE;
  170632. break;
  170633. case JSON_OBJECT:
  170634. jsonRemoveAllNulls(&pNode[i]);
  170635. break;
  170636. }
  170637. }
  170638. }
  170639. /****************************************************************************
  170640. ** SQL functions used for testing and debugging
  170641. ****************************************************************************/
  170642. #ifdef SQLITE_DEBUG
  170643. /*
  170644. ** The json_parse(JSON) function returns a string which describes
  170645. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  170646. ** well-formed.
  170647. */
  170648. static void jsonParseFunc(
  170649. sqlite3_context *ctx,
  170650. int argc,
  170651. sqlite3_value **argv
  170652. ){
  170653. JsonString s; /* Output string - not real JSON */
  170654. JsonParse x; /* The parse */
  170655. u32 i;
  170656. assert( argc==1 );
  170657. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  170658. jsonParseFindParents(&x);
  170659. jsonInit(&s, ctx);
  170660. for(i=0; i<x.nNode; i++){
  170661. const char *zType;
  170662. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  170663. assert( x.aNode[i].eType==JSON_STRING );
  170664. zType = "label";
  170665. }else{
  170666. zType = jsonType[x.aNode[i].eType];
  170667. }
  170668. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  170669. i, zType, x.aNode[i].n, x.aUp[i]);
  170670. if( x.aNode[i].u.zJContent!=0 ){
  170671. jsonAppendRaw(&s, " ", 1);
  170672. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  170673. }
  170674. jsonAppendRaw(&s, "\n", 1);
  170675. }
  170676. jsonParseReset(&x);
  170677. jsonResult(&s);
  170678. }
  170679. /*
  170680. ** The json_test1(JSON) function return true (1) if the input is JSON
  170681. ** text generated by another json function. It returns (0) if the input
  170682. ** is not known to be JSON.
  170683. */
  170684. static void jsonTest1Func(
  170685. sqlite3_context *ctx,
  170686. int argc,
  170687. sqlite3_value **argv
  170688. ){
  170689. UNUSED_PARAM(argc);
  170690. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  170691. }
  170692. #endif /* SQLITE_DEBUG */
  170693. /****************************************************************************
  170694. ** Scalar SQL function implementations
  170695. ****************************************************************************/
  170696. /*
  170697. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  170698. ** corresponding to the SQL value input. Mostly this means putting
  170699. ** double-quotes around strings and returning the unquoted string "null"
  170700. ** when given a NULL input.
  170701. */
  170702. static void jsonQuoteFunc(
  170703. sqlite3_context *ctx,
  170704. int argc,
  170705. sqlite3_value **argv
  170706. ){
  170707. JsonString jx;
  170708. UNUSED_PARAM(argc);
  170709. jsonInit(&jx, ctx);
  170710. jsonAppendValue(&jx, argv[0]);
  170711. jsonResult(&jx);
  170712. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  170713. }
  170714. /*
  170715. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  170716. ** array that contains all values given in arguments. Or if any argument
  170717. ** is a BLOB, throw an error.
  170718. */
  170719. static void jsonArrayFunc(
  170720. sqlite3_context *ctx,
  170721. int argc,
  170722. sqlite3_value **argv
  170723. ){
  170724. int i;
  170725. JsonString jx;
  170726. jsonInit(&jx, ctx);
  170727. jsonAppendChar(&jx, '[');
  170728. for(i=0; i<argc; i++){
  170729. jsonAppendSeparator(&jx);
  170730. jsonAppendValue(&jx, argv[i]);
  170731. }
  170732. jsonAppendChar(&jx, ']');
  170733. jsonResult(&jx);
  170734. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  170735. }
  170736. /*
  170737. ** json_array_length(JSON)
  170738. ** json_array_length(JSON, PATH)
  170739. **
  170740. ** Return the number of elements in the top-level JSON array.
  170741. ** Return 0 if the input is not a well-formed JSON array.
  170742. */
  170743. static void jsonArrayLengthFunc(
  170744. sqlite3_context *ctx,
  170745. int argc,
  170746. sqlite3_value **argv
  170747. ){
  170748. JsonParse *p; /* The parse */
  170749. sqlite3_int64 n = 0;
  170750. u32 i;
  170751. JsonNode *pNode;
  170752. p = jsonParseCached(ctx, argv);
  170753. if( p==0 ) return;
  170754. assert( p->nNode );
  170755. if( argc==2 ){
  170756. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  170757. pNode = jsonLookup(p, zPath, 0, ctx);
  170758. }else{
  170759. pNode = p->aNode;
  170760. }
  170761. if( pNode==0 ){
  170762. return;
  170763. }
  170764. if( pNode->eType==JSON_ARRAY ){
  170765. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  170766. for(i=1; i<=pNode->n; n++){
  170767. i += jsonNodeSize(&pNode[i]);
  170768. }
  170769. }
  170770. sqlite3_result_int64(ctx, n);
  170771. }
  170772. /*
  170773. ** json_extract(JSON, PATH, ...)
  170774. **
  170775. ** Return the element described by PATH. Return NULL if there is no
  170776. ** PATH element. If there are multiple PATHs, then return a JSON array
  170777. ** with the result from each path. Throw an error if the JSON or any PATH
  170778. ** is malformed.
  170779. */
  170780. static void jsonExtractFunc(
  170781. sqlite3_context *ctx,
  170782. int argc,
  170783. sqlite3_value **argv
  170784. ){
  170785. JsonParse *p; /* The parse */
  170786. JsonNode *pNode;
  170787. const char *zPath;
  170788. JsonString jx;
  170789. int i;
  170790. if( argc<2 ) return;
  170791. p = jsonParseCached(ctx, argv);
  170792. if( p==0 ) return;
  170793. jsonInit(&jx, ctx);
  170794. jsonAppendChar(&jx, '[');
  170795. for(i=1; i<argc; i++){
  170796. zPath = (const char*)sqlite3_value_text(argv[i]);
  170797. pNode = jsonLookup(p, zPath, 0, ctx);
  170798. if( p->nErr ) break;
  170799. if( argc>2 ){
  170800. jsonAppendSeparator(&jx);
  170801. if( pNode ){
  170802. jsonRenderNode(pNode, &jx, 0);
  170803. }else{
  170804. jsonAppendRaw(&jx, "null", 4);
  170805. }
  170806. }else if( pNode ){
  170807. jsonReturn(pNode, ctx, 0);
  170808. }
  170809. }
  170810. if( argc>2 && i==argc ){
  170811. jsonAppendChar(&jx, ']');
  170812. jsonResult(&jx);
  170813. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  170814. }
  170815. jsonReset(&jx);
  170816. }
  170817. /* This is the RFC 7396 MergePatch algorithm.
  170818. */
  170819. static JsonNode *jsonMergePatch(
  170820. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  170821. u32 iTarget, /* Node of the TARGET in pParse */
  170822. JsonNode *pPatch /* The PATCH */
  170823. ){
  170824. u32 i, j;
  170825. u32 iRoot;
  170826. JsonNode *pTarget;
  170827. if( pPatch->eType!=JSON_OBJECT ){
  170828. return pPatch;
  170829. }
  170830. assert( iTarget>=0 && iTarget<pParse->nNode );
  170831. pTarget = &pParse->aNode[iTarget];
  170832. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  170833. if( pTarget->eType!=JSON_OBJECT ){
  170834. jsonRemoveAllNulls(pPatch);
  170835. return pPatch;
  170836. }
  170837. iRoot = iTarget;
  170838. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  170839. u32 nKey;
  170840. const char *zKey;
  170841. assert( pPatch[i].eType==JSON_STRING );
  170842. assert( pPatch[i].jnFlags & JNODE_LABEL );
  170843. nKey = pPatch[i].n;
  170844. zKey = pPatch[i].u.zJContent;
  170845. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  170846. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  170847. assert( pTarget[j].eType==JSON_STRING );
  170848. assert( pTarget[j].jnFlags & JNODE_LABEL );
  170849. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  170850. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  170851. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  170852. if( pPatch[i+1].eType==JSON_NULL ){
  170853. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  170854. }else{
  170855. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  170856. if( pNew==0 ) return 0;
  170857. pTarget = &pParse->aNode[iTarget];
  170858. if( pNew!=&pTarget[j+1] ){
  170859. pTarget[j+1].u.pPatch = pNew;
  170860. pTarget[j+1].jnFlags |= JNODE_PATCH;
  170861. }
  170862. }
  170863. break;
  170864. }
  170865. }
  170866. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  170867. int iStart, iPatch;
  170868. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  170869. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  170870. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  170871. if( pParse->oom ) return 0;
  170872. jsonRemoveAllNulls(pPatch);
  170873. pTarget = &pParse->aNode[iTarget];
  170874. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  170875. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  170876. iRoot = iStart;
  170877. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  170878. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  170879. }
  170880. }
  170881. return pTarget;
  170882. }
  170883. /*
  170884. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  170885. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  170886. ** on the two arguments.
  170887. */
  170888. static void jsonPatchFunc(
  170889. sqlite3_context *ctx,
  170890. int argc,
  170891. sqlite3_value **argv
  170892. ){
  170893. JsonParse x; /* The JSON that is being patched */
  170894. JsonParse y; /* The patch */
  170895. JsonNode *pResult; /* The result of the merge */
  170896. UNUSED_PARAM(argc);
  170897. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  170898. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  170899. jsonParseReset(&x);
  170900. return;
  170901. }
  170902. pResult = jsonMergePatch(&x, 0, y.aNode);
  170903. assert( pResult!=0 || x.oom );
  170904. if( pResult ){
  170905. jsonReturnJson(pResult, ctx, 0);
  170906. }else{
  170907. sqlite3_result_error_nomem(ctx);
  170908. }
  170909. jsonParseReset(&x);
  170910. jsonParseReset(&y);
  170911. }
  170912. /*
  170913. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  170914. ** object that contains all name/value given in arguments. Or if any name
  170915. ** is not a string or if any value is a BLOB, throw an error.
  170916. */
  170917. static void jsonObjectFunc(
  170918. sqlite3_context *ctx,
  170919. int argc,
  170920. sqlite3_value **argv
  170921. ){
  170922. int i;
  170923. JsonString jx;
  170924. const char *z;
  170925. u32 n;
  170926. if( argc&1 ){
  170927. sqlite3_result_error(ctx, "json_object() requires an even number "
  170928. "of arguments", -1);
  170929. return;
  170930. }
  170931. jsonInit(&jx, ctx);
  170932. jsonAppendChar(&jx, '{');
  170933. for(i=0; i<argc; i+=2){
  170934. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  170935. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  170936. jsonReset(&jx);
  170937. return;
  170938. }
  170939. jsonAppendSeparator(&jx);
  170940. z = (const char*)sqlite3_value_text(argv[i]);
  170941. n = (u32)sqlite3_value_bytes(argv[i]);
  170942. jsonAppendString(&jx, z, n);
  170943. jsonAppendChar(&jx, ':');
  170944. jsonAppendValue(&jx, argv[i+1]);
  170945. }
  170946. jsonAppendChar(&jx, '}');
  170947. jsonResult(&jx);
  170948. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  170949. }
  170950. /*
  170951. ** json_remove(JSON, PATH, ...)
  170952. **
  170953. ** Remove the named elements from JSON and return the result. malformed
  170954. ** JSON or PATH arguments result in an error.
  170955. */
  170956. static void jsonRemoveFunc(
  170957. sqlite3_context *ctx,
  170958. int argc,
  170959. sqlite3_value **argv
  170960. ){
  170961. JsonParse x; /* The parse */
  170962. JsonNode *pNode;
  170963. const char *zPath;
  170964. u32 i;
  170965. if( argc<1 ) return;
  170966. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  170967. assert( x.nNode );
  170968. for(i=1; i<(u32)argc; i++){
  170969. zPath = (const char*)sqlite3_value_text(argv[i]);
  170970. if( zPath==0 ) goto remove_done;
  170971. pNode = jsonLookup(&x, zPath, 0, ctx);
  170972. if( x.nErr ) goto remove_done;
  170973. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  170974. }
  170975. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  170976. jsonReturnJson(x.aNode, ctx, 0);
  170977. }
  170978. remove_done:
  170979. jsonParseReset(&x);
  170980. }
  170981. /*
  170982. ** json_replace(JSON, PATH, VALUE, ...)
  170983. **
  170984. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  170985. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  170986. */
  170987. static void jsonReplaceFunc(
  170988. sqlite3_context *ctx,
  170989. int argc,
  170990. sqlite3_value **argv
  170991. ){
  170992. JsonParse x; /* The parse */
  170993. JsonNode *pNode;
  170994. const char *zPath;
  170995. u32 i;
  170996. if( argc<1 ) return;
  170997. if( (argc&1)==0 ) {
  170998. jsonWrongNumArgs(ctx, "replace");
  170999. return;
  171000. }
  171001. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  171002. assert( x.nNode );
  171003. for(i=1; i<(u32)argc; i+=2){
  171004. zPath = (const char*)sqlite3_value_text(argv[i]);
  171005. pNode = jsonLookup(&x, zPath, 0, ctx);
  171006. if( x.nErr ) goto replace_err;
  171007. if( pNode ){
  171008. pNode->jnFlags |= (u8)JNODE_REPLACE;
  171009. pNode->u.iReplace = i + 1;
  171010. }
  171011. }
  171012. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  171013. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  171014. }else{
  171015. jsonReturnJson(x.aNode, ctx, argv);
  171016. }
  171017. replace_err:
  171018. jsonParseReset(&x);
  171019. }
  171020. /*
  171021. ** json_set(JSON, PATH, VALUE, ...)
  171022. **
  171023. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  171024. ** exist. Overwrite existing values that do exist.
  171025. ** If JSON or PATH is malformed, throw an error.
  171026. **
  171027. ** json_insert(JSON, PATH, VALUE, ...)
  171028. **
  171029. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  171030. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  171031. */
  171032. static void jsonSetFunc(
  171033. sqlite3_context *ctx,
  171034. int argc,
  171035. sqlite3_value **argv
  171036. ){
  171037. JsonParse x; /* The parse */
  171038. JsonNode *pNode;
  171039. const char *zPath;
  171040. u32 i;
  171041. int bApnd;
  171042. int bIsSet = *(int*)sqlite3_user_data(ctx);
  171043. if( argc<1 ) return;
  171044. if( (argc&1)==0 ) {
  171045. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  171046. return;
  171047. }
  171048. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  171049. assert( x.nNode );
  171050. for(i=1; i<(u32)argc; i+=2){
  171051. zPath = (const char*)sqlite3_value_text(argv[i]);
  171052. bApnd = 0;
  171053. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  171054. if( x.oom ){
  171055. sqlite3_result_error_nomem(ctx);
  171056. goto jsonSetDone;
  171057. }else if( x.nErr ){
  171058. goto jsonSetDone;
  171059. }else if( pNode && (bApnd || bIsSet) ){
  171060. pNode->jnFlags |= (u8)JNODE_REPLACE;
  171061. pNode->u.iReplace = i + 1;
  171062. }
  171063. }
  171064. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  171065. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  171066. }else{
  171067. jsonReturnJson(x.aNode, ctx, argv);
  171068. }
  171069. jsonSetDone:
  171070. jsonParseReset(&x);
  171071. }
  171072. /*
  171073. ** json_type(JSON)
  171074. ** json_type(JSON, PATH)
  171075. **
  171076. ** Return the top-level "type" of a JSON string. Throw an error if
  171077. ** either the JSON or PATH inputs are not well-formed.
  171078. */
  171079. static void jsonTypeFunc(
  171080. sqlite3_context *ctx,
  171081. int argc,
  171082. sqlite3_value **argv
  171083. ){
  171084. JsonParse x; /* The parse */
  171085. const char *zPath;
  171086. JsonNode *pNode;
  171087. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  171088. assert( x.nNode );
  171089. if( argc==2 ){
  171090. zPath = (const char*)sqlite3_value_text(argv[1]);
  171091. pNode = jsonLookup(&x, zPath, 0, ctx);
  171092. }else{
  171093. pNode = x.aNode;
  171094. }
  171095. if( pNode ){
  171096. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  171097. }
  171098. jsonParseReset(&x);
  171099. }
  171100. /*
  171101. ** json_valid(JSON)
  171102. **
  171103. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  171104. ** Return 0 otherwise.
  171105. */
  171106. static void jsonValidFunc(
  171107. sqlite3_context *ctx,
  171108. int argc,
  171109. sqlite3_value **argv
  171110. ){
  171111. JsonParse x; /* The parse */
  171112. int rc = 0;
  171113. UNUSED_PARAM(argc);
  171114. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  171115. rc = 1;
  171116. }
  171117. jsonParseReset(&x);
  171118. sqlite3_result_int(ctx, rc);
  171119. }
  171120. /****************************************************************************
  171121. ** Aggregate SQL function implementations
  171122. ****************************************************************************/
  171123. /*
  171124. ** json_group_array(VALUE)
  171125. **
  171126. ** Return a JSON array composed of all values in the aggregate.
  171127. */
  171128. static void jsonArrayStep(
  171129. sqlite3_context *ctx,
  171130. int argc,
  171131. sqlite3_value **argv
  171132. ){
  171133. JsonString *pStr;
  171134. UNUSED_PARAM(argc);
  171135. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  171136. if( pStr ){
  171137. if( pStr->zBuf==0 ){
  171138. jsonInit(pStr, ctx);
  171139. jsonAppendChar(pStr, '[');
  171140. }else{
  171141. jsonAppendChar(pStr, ',');
  171142. pStr->pCtx = ctx;
  171143. }
  171144. jsonAppendValue(pStr, argv[0]);
  171145. }
  171146. }
  171147. static void jsonArrayFinal(sqlite3_context *ctx){
  171148. JsonString *pStr;
  171149. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  171150. if( pStr ){
  171151. pStr->pCtx = ctx;
  171152. jsonAppendChar(pStr, ']');
  171153. if( pStr->bErr ){
  171154. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  171155. assert( pStr->bStatic );
  171156. }else{
  171157. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  171158. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  171159. pStr->bStatic = 1;
  171160. }
  171161. }else{
  171162. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  171163. }
  171164. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  171165. }
  171166. /*
  171167. ** json_group_obj(NAME,VALUE)
  171168. **
  171169. ** Return a JSON object composed of all names and values in the aggregate.
  171170. */
  171171. static void jsonObjectStep(
  171172. sqlite3_context *ctx,
  171173. int argc,
  171174. sqlite3_value **argv
  171175. ){
  171176. JsonString *pStr;
  171177. const char *z;
  171178. u32 n;
  171179. UNUSED_PARAM(argc);
  171180. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  171181. if( pStr ){
  171182. if( pStr->zBuf==0 ){
  171183. jsonInit(pStr, ctx);
  171184. jsonAppendChar(pStr, '{');
  171185. }else{
  171186. jsonAppendChar(pStr, ',');
  171187. pStr->pCtx = ctx;
  171188. }
  171189. z = (const char*)sqlite3_value_text(argv[0]);
  171190. n = (u32)sqlite3_value_bytes(argv[0]);
  171191. jsonAppendString(pStr, z, n);
  171192. jsonAppendChar(pStr, ':');
  171193. jsonAppendValue(pStr, argv[1]);
  171194. }
  171195. }
  171196. static void jsonObjectFinal(sqlite3_context *ctx){
  171197. JsonString *pStr;
  171198. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  171199. if( pStr ){
  171200. jsonAppendChar(pStr, '}');
  171201. if( pStr->bErr ){
  171202. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  171203. assert( pStr->bStatic );
  171204. }else{
  171205. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  171206. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  171207. pStr->bStatic = 1;
  171208. }
  171209. }else{
  171210. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  171211. }
  171212. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  171213. }
  171214. #ifndef SQLITE_OMIT_VIRTUALTABLE
  171215. /****************************************************************************
  171216. ** The json_each virtual table
  171217. ****************************************************************************/
  171218. typedef struct JsonEachCursor JsonEachCursor;
  171219. struct JsonEachCursor {
  171220. sqlite3_vtab_cursor base; /* Base class - must be first */
  171221. u32 iRowid; /* The rowid */
  171222. u32 iBegin; /* The first node of the scan */
  171223. u32 i; /* Index in sParse.aNode[] of current row */
  171224. u32 iEnd; /* EOF when i equals or exceeds this value */
  171225. u8 eType; /* Type of top-level element */
  171226. u8 bRecursive; /* True for json_tree(). False for json_each() */
  171227. char *zJson; /* Input JSON */
  171228. char *zRoot; /* Path by which to filter zJson */
  171229. JsonParse sParse; /* Parse of the input JSON */
  171230. };
  171231. /* Constructor for the json_each virtual table */
  171232. static int jsonEachConnect(
  171233. sqlite3 *db,
  171234. void *pAux,
  171235. int argc, const char *const*argv,
  171236. sqlite3_vtab **ppVtab,
  171237. char **pzErr
  171238. ){
  171239. sqlite3_vtab *pNew;
  171240. int rc;
  171241. /* Column numbers */
  171242. #define JEACH_KEY 0
  171243. #define JEACH_VALUE 1
  171244. #define JEACH_TYPE 2
  171245. #define JEACH_ATOM 3
  171246. #define JEACH_ID 4
  171247. #define JEACH_PARENT 5
  171248. #define JEACH_FULLKEY 6
  171249. #define JEACH_PATH 7
  171250. #define JEACH_JSON 8
  171251. #define JEACH_ROOT 9
  171252. UNUSED_PARAM(pzErr);
  171253. UNUSED_PARAM(argv);
  171254. UNUSED_PARAM(argc);
  171255. UNUSED_PARAM(pAux);
  171256. rc = sqlite3_declare_vtab(db,
  171257. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  171258. "json HIDDEN,root HIDDEN)");
  171259. if( rc==SQLITE_OK ){
  171260. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  171261. if( pNew==0 ) return SQLITE_NOMEM;
  171262. memset(pNew, 0, sizeof(*pNew));
  171263. }
  171264. return rc;
  171265. }
  171266. /* destructor for json_each virtual table */
  171267. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  171268. sqlite3_free(pVtab);
  171269. return SQLITE_OK;
  171270. }
  171271. /* constructor for a JsonEachCursor object for json_each(). */
  171272. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  171273. JsonEachCursor *pCur;
  171274. UNUSED_PARAM(p);
  171275. pCur = sqlite3_malloc( sizeof(*pCur) );
  171276. if( pCur==0 ) return SQLITE_NOMEM;
  171277. memset(pCur, 0, sizeof(*pCur));
  171278. *ppCursor = &pCur->base;
  171279. return SQLITE_OK;
  171280. }
  171281. /* constructor for a JsonEachCursor object for json_tree(). */
  171282. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  171283. int rc = jsonEachOpenEach(p, ppCursor);
  171284. if( rc==SQLITE_OK ){
  171285. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  171286. pCur->bRecursive = 1;
  171287. }
  171288. return rc;
  171289. }
  171290. /* Reset a JsonEachCursor back to its original state. Free any memory
  171291. ** held. */
  171292. static void jsonEachCursorReset(JsonEachCursor *p){
  171293. sqlite3_free(p->zJson);
  171294. sqlite3_free(p->zRoot);
  171295. jsonParseReset(&p->sParse);
  171296. p->iRowid = 0;
  171297. p->i = 0;
  171298. p->iEnd = 0;
  171299. p->eType = 0;
  171300. p->zJson = 0;
  171301. p->zRoot = 0;
  171302. }
  171303. /* Destructor for a jsonEachCursor object */
  171304. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  171305. JsonEachCursor *p = (JsonEachCursor*)cur;
  171306. jsonEachCursorReset(p);
  171307. sqlite3_free(cur);
  171308. return SQLITE_OK;
  171309. }
  171310. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  171311. ** of the JSON object */
  171312. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  171313. JsonEachCursor *p = (JsonEachCursor*)cur;
  171314. return p->i >= p->iEnd;
  171315. }
  171316. /* Advance the cursor to the next element for json_tree() */
  171317. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  171318. JsonEachCursor *p = (JsonEachCursor*)cur;
  171319. if( p->bRecursive ){
  171320. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  171321. p->i++;
  171322. p->iRowid++;
  171323. if( p->i<p->iEnd ){
  171324. u32 iUp = p->sParse.aUp[p->i];
  171325. JsonNode *pUp = &p->sParse.aNode[iUp];
  171326. p->eType = pUp->eType;
  171327. if( pUp->eType==JSON_ARRAY ){
  171328. if( iUp==p->i-1 ){
  171329. pUp->u.iKey = 0;
  171330. }else{
  171331. pUp->u.iKey++;
  171332. }
  171333. }
  171334. }
  171335. }else{
  171336. switch( p->eType ){
  171337. case JSON_ARRAY: {
  171338. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  171339. p->iRowid++;
  171340. break;
  171341. }
  171342. case JSON_OBJECT: {
  171343. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  171344. p->iRowid++;
  171345. break;
  171346. }
  171347. default: {
  171348. p->i = p->iEnd;
  171349. break;
  171350. }
  171351. }
  171352. }
  171353. return SQLITE_OK;
  171354. }
  171355. /* Append the name of the path for element i to pStr
  171356. */
  171357. static void jsonEachComputePath(
  171358. JsonEachCursor *p, /* The cursor */
  171359. JsonString *pStr, /* Write the path here */
  171360. u32 i /* Path to this element */
  171361. ){
  171362. JsonNode *pNode, *pUp;
  171363. u32 iUp;
  171364. if( i==0 ){
  171365. jsonAppendChar(pStr, '$');
  171366. return;
  171367. }
  171368. iUp = p->sParse.aUp[i];
  171369. jsonEachComputePath(p, pStr, iUp);
  171370. pNode = &p->sParse.aNode[i];
  171371. pUp = &p->sParse.aNode[iUp];
  171372. if( pUp->eType==JSON_ARRAY ){
  171373. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  171374. }else{
  171375. assert( pUp->eType==JSON_OBJECT );
  171376. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  171377. assert( pNode->eType==JSON_STRING );
  171378. assert( pNode->jnFlags & JNODE_LABEL );
  171379. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  171380. }
  171381. }
  171382. /* Return the value of a column */
  171383. static int jsonEachColumn(
  171384. sqlite3_vtab_cursor *cur, /* The cursor */
  171385. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  171386. int i /* Which column to return */
  171387. ){
  171388. JsonEachCursor *p = (JsonEachCursor*)cur;
  171389. JsonNode *pThis = &p->sParse.aNode[p->i];
  171390. switch( i ){
  171391. case JEACH_KEY: {
  171392. if( p->i==0 ) break;
  171393. if( p->eType==JSON_OBJECT ){
  171394. jsonReturn(pThis, ctx, 0);
  171395. }else if( p->eType==JSON_ARRAY ){
  171396. u32 iKey;
  171397. if( p->bRecursive ){
  171398. if( p->iRowid==0 ) break;
  171399. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  171400. }else{
  171401. iKey = p->iRowid;
  171402. }
  171403. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  171404. }
  171405. break;
  171406. }
  171407. case JEACH_VALUE: {
  171408. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  171409. jsonReturn(pThis, ctx, 0);
  171410. break;
  171411. }
  171412. case JEACH_TYPE: {
  171413. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  171414. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  171415. break;
  171416. }
  171417. case JEACH_ATOM: {
  171418. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  171419. if( pThis->eType>=JSON_ARRAY ) break;
  171420. jsonReturn(pThis, ctx, 0);
  171421. break;
  171422. }
  171423. case JEACH_ID: {
  171424. sqlite3_result_int64(ctx,
  171425. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  171426. break;
  171427. }
  171428. case JEACH_PARENT: {
  171429. if( p->i>p->iBegin && p->bRecursive ){
  171430. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  171431. }
  171432. break;
  171433. }
  171434. case JEACH_FULLKEY: {
  171435. JsonString x;
  171436. jsonInit(&x, ctx);
  171437. if( p->bRecursive ){
  171438. jsonEachComputePath(p, &x, p->i);
  171439. }else{
  171440. if( p->zRoot ){
  171441. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  171442. }else{
  171443. jsonAppendChar(&x, '$');
  171444. }
  171445. if( p->eType==JSON_ARRAY ){
  171446. jsonPrintf(30, &x, "[%d]", p->iRowid);
  171447. }else{
  171448. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  171449. }
  171450. }
  171451. jsonResult(&x);
  171452. break;
  171453. }
  171454. case JEACH_PATH: {
  171455. if( p->bRecursive ){
  171456. JsonString x;
  171457. jsonInit(&x, ctx);
  171458. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  171459. jsonResult(&x);
  171460. break;
  171461. }
  171462. /* For json_each() path and root are the same so fall through
  171463. ** into the root case */
  171464. }
  171465. default: {
  171466. const char *zRoot = p->zRoot;
  171467. if( zRoot==0 ) zRoot = "$";
  171468. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  171469. break;
  171470. }
  171471. case JEACH_JSON: {
  171472. assert( i==JEACH_JSON );
  171473. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  171474. break;
  171475. }
  171476. }
  171477. return SQLITE_OK;
  171478. }
  171479. /* Return the current rowid value */
  171480. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  171481. JsonEachCursor *p = (JsonEachCursor*)cur;
  171482. *pRowid = p->iRowid;
  171483. return SQLITE_OK;
  171484. }
  171485. /* The query strategy is to look for an equality constraint on the json
  171486. ** column. Without such a constraint, the table cannot operate. idxNum is
  171487. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  171488. ** and 0 otherwise.
  171489. */
  171490. static int jsonEachBestIndex(
  171491. sqlite3_vtab *tab,
  171492. sqlite3_index_info *pIdxInfo
  171493. ){
  171494. int i;
  171495. int jsonIdx = -1;
  171496. int rootIdx = -1;
  171497. const struct sqlite3_index_constraint *pConstraint;
  171498. UNUSED_PARAM(tab);
  171499. pConstraint = pIdxInfo->aConstraint;
  171500. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  171501. if( pConstraint->usable==0 ) continue;
  171502. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  171503. switch( pConstraint->iColumn ){
  171504. case JEACH_JSON: jsonIdx = i; break;
  171505. case JEACH_ROOT: rootIdx = i; break;
  171506. default: /* no-op */ break;
  171507. }
  171508. }
  171509. if( jsonIdx<0 ){
  171510. pIdxInfo->idxNum = 0;
  171511. pIdxInfo->estimatedCost = 1e99;
  171512. }else{
  171513. pIdxInfo->estimatedCost = 1.0;
  171514. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  171515. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  171516. if( rootIdx<0 ){
  171517. pIdxInfo->idxNum = 1;
  171518. }else{
  171519. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  171520. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  171521. pIdxInfo->idxNum = 3;
  171522. }
  171523. }
  171524. return SQLITE_OK;
  171525. }
  171526. /* Start a search on a new JSON string */
  171527. static int jsonEachFilter(
  171528. sqlite3_vtab_cursor *cur,
  171529. int idxNum, const char *idxStr,
  171530. int argc, sqlite3_value **argv
  171531. ){
  171532. JsonEachCursor *p = (JsonEachCursor*)cur;
  171533. const char *z;
  171534. const char *zRoot = 0;
  171535. sqlite3_int64 n;
  171536. UNUSED_PARAM(idxStr);
  171537. UNUSED_PARAM(argc);
  171538. jsonEachCursorReset(p);
  171539. if( idxNum==0 ) return SQLITE_OK;
  171540. z = (const char*)sqlite3_value_text(argv[0]);
  171541. if( z==0 ) return SQLITE_OK;
  171542. n = sqlite3_value_bytes(argv[0]);
  171543. p->zJson = sqlite3_malloc64( n+1 );
  171544. if( p->zJson==0 ) return SQLITE_NOMEM;
  171545. memcpy(p->zJson, z, (size_t)n+1);
  171546. if( jsonParse(&p->sParse, 0, p->zJson) ){
  171547. int rc = SQLITE_NOMEM;
  171548. if( p->sParse.oom==0 ){
  171549. sqlite3_free(cur->pVtab->zErrMsg);
  171550. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  171551. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  171552. }
  171553. jsonEachCursorReset(p);
  171554. return rc;
  171555. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  171556. jsonEachCursorReset(p);
  171557. return SQLITE_NOMEM;
  171558. }else{
  171559. JsonNode *pNode = 0;
  171560. if( idxNum==3 ){
  171561. const char *zErr = 0;
  171562. zRoot = (const char*)sqlite3_value_text(argv[1]);
  171563. if( zRoot==0 ) return SQLITE_OK;
  171564. n = sqlite3_value_bytes(argv[1]);
  171565. p->zRoot = sqlite3_malloc64( n+1 );
  171566. if( p->zRoot==0 ) return SQLITE_NOMEM;
  171567. memcpy(p->zRoot, zRoot, (size_t)n+1);
  171568. if( zRoot[0]!='$' ){
  171569. zErr = zRoot;
  171570. }else{
  171571. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  171572. }
  171573. if( zErr ){
  171574. sqlite3_free(cur->pVtab->zErrMsg);
  171575. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  171576. jsonEachCursorReset(p);
  171577. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  171578. }else if( pNode==0 ){
  171579. return SQLITE_OK;
  171580. }
  171581. }else{
  171582. pNode = p->sParse.aNode;
  171583. }
  171584. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  171585. p->eType = pNode->eType;
  171586. if( p->eType>=JSON_ARRAY ){
  171587. pNode->u.iKey = 0;
  171588. p->iEnd = p->i + pNode->n + 1;
  171589. if( p->bRecursive ){
  171590. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  171591. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  171592. p->i--;
  171593. }
  171594. }else{
  171595. p->i++;
  171596. }
  171597. }else{
  171598. p->iEnd = p->i+1;
  171599. }
  171600. }
  171601. return SQLITE_OK;
  171602. }
  171603. /* The methods of the json_each virtual table */
  171604. static sqlite3_module jsonEachModule = {
  171605. 0, /* iVersion */
  171606. 0, /* xCreate */
  171607. jsonEachConnect, /* xConnect */
  171608. jsonEachBestIndex, /* xBestIndex */
  171609. jsonEachDisconnect, /* xDisconnect */
  171610. 0, /* xDestroy */
  171611. jsonEachOpenEach, /* xOpen - open a cursor */
  171612. jsonEachClose, /* xClose - close a cursor */
  171613. jsonEachFilter, /* xFilter - configure scan constraints */
  171614. jsonEachNext, /* xNext - advance a cursor */
  171615. jsonEachEof, /* xEof - check for end of scan */
  171616. jsonEachColumn, /* xColumn - read data */
  171617. jsonEachRowid, /* xRowid - read data */
  171618. 0, /* xUpdate */
  171619. 0, /* xBegin */
  171620. 0, /* xSync */
  171621. 0, /* xCommit */
  171622. 0, /* xRollback */
  171623. 0, /* xFindMethod */
  171624. 0, /* xRename */
  171625. 0, /* xSavepoint */
  171626. 0, /* xRelease */
  171627. 0 /* xRollbackTo */
  171628. };
  171629. /* The methods of the json_tree virtual table. */
  171630. static sqlite3_module jsonTreeModule = {
  171631. 0, /* iVersion */
  171632. 0, /* xCreate */
  171633. jsonEachConnect, /* xConnect */
  171634. jsonEachBestIndex, /* xBestIndex */
  171635. jsonEachDisconnect, /* xDisconnect */
  171636. 0, /* xDestroy */
  171637. jsonEachOpenTree, /* xOpen - open a cursor */
  171638. jsonEachClose, /* xClose - close a cursor */
  171639. jsonEachFilter, /* xFilter - configure scan constraints */
  171640. jsonEachNext, /* xNext - advance a cursor */
  171641. jsonEachEof, /* xEof - check for end of scan */
  171642. jsonEachColumn, /* xColumn - read data */
  171643. jsonEachRowid, /* xRowid - read data */
  171644. 0, /* xUpdate */
  171645. 0, /* xBegin */
  171646. 0, /* xSync */
  171647. 0, /* xCommit */
  171648. 0, /* xRollback */
  171649. 0, /* xFindMethod */
  171650. 0, /* xRename */
  171651. 0, /* xSavepoint */
  171652. 0, /* xRelease */
  171653. 0 /* xRollbackTo */
  171654. };
  171655. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  171656. /****************************************************************************
  171657. ** The following routines are the only publically visible identifiers in this
  171658. ** file. Call the following routines in order to register the various SQL
  171659. ** functions and the virtual table implemented by this file.
  171660. ****************************************************************************/
  171661. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  171662. int rc = SQLITE_OK;
  171663. unsigned int i;
  171664. static const struct {
  171665. const char *zName;
  171666. int nArg;
  171667. int flag;
  171668. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  171669. } aFunc[] = {
  171670. { "json", 1, 0, jsonRemoveFunc },
  171671. { "json_array", -1, 0, jsonArrayFunc },
  171672. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  171673. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  171674. { "json_extract", -1, 0, jsonExtractFunc },
  171675. { "json_insert", -1, 0, jsonSetFunc },
  171676. { "json_object", -1, 0, jsonObjectFunc },
  171677. { "json_patch", 2, 0, jsonPatchFunc },
  171678. { "json_quote", 1, 0, jsonQuoteFunc },
  171679. { "json_remove", -1, 0, jsonRemoveFunc },
  171680. { "json_replace", -1, 0, jsonReplaceFunc },
  171681. { "json_set", -1, 1, jsonSetFunc },
  171682. { "json_type", 1, 0, jsonTypeFunc },
  171683. { "json_type", 2, 0, jsonTypeFunc },
  171684. { "json_valid", 1, 0, jsonValidFunc },
  171685. #if SQLITE_DEBUG
  171686. /* DEBUG and TESTING functions */
  171687. { "json_parse", 1, 0, jsonParseFunc },
  171688. { "json_test1", 1, 0, jsonTest1Func },
  171689. #endif
  171690. };
  171691. static const struct {
  171692. const char *zName;
  171693. int nArg;
  171694. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  171695. void (*xFinal)(sqlite3_context*);
  171696. } aAgg[] = {
  171697. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  171698. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  171699. };
  171700. #ifndef SQLITE_OMIT_VIRTUALTABLE
  171701. static const struct {
  171702. const char *zName;
  171703. sqlite3_module *pModule;
  171704. } aMod[] = {
  171705. { "json_each", &jsonEachModule },
  171706. { "json_tree", &jsonTreeModule },
  171707. };
  171708. #endif
  171709. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  171710. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  171711. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  171712. (void*)&aFunc[i].flag,
  171713. aFunc[i].xFunc, 0, 0);
  171714. }
  171715. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  171716. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  171717. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  171718. 0, aAgg[i].xStep, aAgg[i].xFinal);
  171719. }
  171720. #ifndef SQLITE_OMIT_VIRTUALTABLE
  171721. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  171722. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  171723. }
  171724. #endif
  171725. return rc;
  171726. }
  171727. #ifndef SQLITE_CORE
  171728. #ifdef _WIN32
  171729. __declspec(dllexport)
  171730. #endif
  171731. SQLITE_API int sqlite3_json_init(
  171732. sqlite3 *db,
  171733. char **pzErrMsg,
  171734. const sqlite3_api_routines *pApi
  171735. ){
  171736. SQLITE_EXTENSION_INIT2(pApi);
  171737. (void)pzErrMsg; /* Unused parameter */
  171738. return sqlite3Json1Init(db);
  171739. }
  171740. #endif
  171741. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  171742. /************** End of json1.c ***********************************************/
  171743. /************** Begin file fts5.c ********************************************/
  171744. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  171745. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  171746. # define NDEBUG 1
  171747. #endif
  171748. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  171749. # undef NDEBUG
  171750. #endif
  171751. /*
  171752. ** 2014 May 31
  171753. **
  171754. ** The author disclaims copyright to this source code. In place of
  171755. ** a legal notice, here is a blessing:
  171756. **
  171757. ** May you do good and not evil.
  171758. ** May you find forgiveness for yourself and forgive others.
  171759. ** May you share freely, never taking more than you give.
  171760. **
  171761. ******************************************************************************
  171762. **
  171763. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  171764. ** FTS5 may be extended with:
  171765. **
  171766. ** * custom tokenizers, and
  171767. ** * custom auxiliary functions.
  171768. */
  171769. #ifndef _FTS5_H
  171770. #define _FTS5_H
  171771. /* #include "sqlite3.h" */
  171772. #if 0
  171773. extern "C" {
  171774. #endif
  171775. /*************************************************************************
  171776. ** CUSTOM AUXILIARY FUNCTIONS
  171777. **
  171778. ** Virtual table implementations may overload SQL functions by implementing
  171779. ** the sqlite3_module.xFindFunction() method.
  171780. */
  171781. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  171782. typedef struct Fts5Context Fts5Context;
  171783. typedef struct Fts5PhraseIter Fts5PhraseIter;
  171784. typedef void (*fts5_extension_function)(
  171785. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  171786. Fts5Context *pFts, /* First arg to pass to pApi functions */
  171787. sqlite3_context *pCtx, /* Context for returning result/error */
  171788. int nVal, /* Number of values in apVal[] array */
  171789. sqlite3_value **apVal /* Array of trailing arguments */
  171790. );
  171791. struct Fts5PhraseIter {
  171792. const unsigned char *a;
  171793. const unsigned char *b;
  171794. };
  171795. /*
  171796. ** EXTENSION API FUNCTIONS
  171797. **
  171798. ** xUserData(pFts):
  171799. ** Return a copy of the context pointer the extension function was
  171800. ** registered with.
  171801. **
  171802. ** xColumnTotalSize(pFts, iCol, pnToken):
  171803. ** If parameter iCol is less than zero, set output variable *pnToken
  171804. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  171805. ** non-negative but less than the number of columns in the table, return
  171806. ** the total number of tokens in column iCol, considering all rows in
  171807. ** the FTS5 table.
  171808. **
  171809. ** If parameter iCol is greater than or equal to the number of columns
  171810. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  171811. ** an OOM condition or IO error), an appropriate SQLite error code is
  171812. ** returned.
  171813. **
  171814. ** xColumnCount(pFts):
  171815. ** Return the number of columns in the table.
  171816. **
  171817. ** xColumnSize(pFts, iCol, pnToken):
  171818. ** If parameter iCol is less than zero, set output variable *pnToken
  171819. ** to the total number of tokens in the current row. Or, if iCol is
  171820. ** non-negative but less than the number of columns in the table, set
  171821. ** *pnToken to the number of tokens in column iCol of the current row.
  171822. **
  171823. ** If parameter iCol is greater than or equal to the number of columns
  171824. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  171825. ** an OOM condition or IO error), an appropriate SQLite error code is
  171826. ** returned.
  171827. **
  171828. ** This function may be quite inefficient if used with an FTS5 table
  171829. ** created with the "columnsize=0" option.
  171830. **
  171831. ** xColumnText:
  171832. ** This function attempts to retrieve the text of column iCol of the
  171833. ** current document. If successful, (*pz) is set to point to a buffer
  171834. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  171835. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  171836. ** if an error occurs, an SQLite error code is returned and the final values
  171837. ** of (*pz) and (*pn) are undefined.
  171838. **
  171839. ** xPhraseCount:
  171840. ** Returns the number of phrases in the current query expression.
  171841. **
  171842. ** xPhraseSize:
  171843. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  171844. ** are numbered starting from zero.
  171845. **
  171846. ** xInstCount:
  171847. ** Set *pnInst to the total number of occurrences of all phrases within
  171848. ** the query within the current row. Return SQLITE_OK if successful, or
  171849. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  171850. **
  171851. ** This API can be quite slow if used with an FTS5 table created with the
  171852. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  171853. ** with either "detail=none" or "detail=column" and "content=" option
  171854. ** (i.e. if it is a contentless table), then this API always returns 0.
  171855. **
  171856. ** xInst:
  171857. ** Query for the details of phrase match iIdx within the current row.
  171858. ** Phrase matches are numbered starting from zero, so the iIdx argument
  171859. ** should be greater than or equal to zero and smaller than the value
  171860. ** output by xInstCount().
  171861. **
  171862. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  171863. ** to the column in which it occurs and *piOff the token offset of the
  171864. ** first token of the phrase. The exception is if the table was created
  171865. ** with the offsets=0 option specified. In this case *piOff is always
  171866. ** set to -1.
  171867. **
  171868. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  171869. ** if an error occurs.
  171870. **
  171871. ** This API can be quite slow if used with an FTS5 table created with the
  171872. ** "detail=none" or "detail=column" option.
  171873. **
  171874. ** xRowid:
  171875. ** Returns the rowid of the current row.
  171876. **
  171877. ** xTokenize:
  171878. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  171879. **
  171880. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  171881. ** This API function is used to query the FTS table for phrase iPhrase
  171882. ** of the current query. Specifically, a query equivalent to:
  171883. **
  171884. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  171885. **
  171886. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  171887. ** current query is executed. Any column filter that applies to
  171888. ** phrase iPhrase of the current query is included in $p. For each
  171889. ** row visited, the callback function passed as the fourth argument
  171890. ** is invoked. The context and API objects passed to the callback
  171891. ** function may be used to access the properties of each matched row.
  171892. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  171893. ** the third argument to pUserData.
  171894. **
  171895. ** If the callback function returns any value other than SQLITE_OK, the
  171896. ** query is abandoned and the xQueryPhrase function returns immediately.
  171897. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  171898. ** Otherwise, the error code is propagated upwards.
  171899. **
  171900. ** If the query runs to completion without incident, SQLITE_OK is returned.
  171901. ** Or, if some error occurs before the query completes or is aborted by
  171902. ** the callback, an SQLite error code is returned.
  171903. **
  171904. **
  171905. ** xSetAuxdata(pFts5, pAux, xDelete)
  171906. **
  171907. ** Save the pointer passed as the second argument as the extension functions
  171908. ** "auxiliary data". The pointer may then be retrieved by the current or any
  171909. ** future invocation of the same fts5 extension function made as part of
  171910. ** of the same MATCH query using the xGetAuxdata() API.
  171911. **
  171912. ** Each extension function is allocated a single auxiliary data slot for
  171913. ** each FTS query (MATCH expression). If the extension function is invoked
  171914. ** more than once for a single FTS query, then all invocations share a
  171915. ** single auxiliary data context.
  171916. **
  171917. ** If there is already an auxiliary data pointer when this function is
  171918. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  171919. ** was specified along with the original pointer, it is invoked at this
  171920. ** point.
  171921. **
  171922. ** The xDelete callback, if one is specified, is also invoked on the
  171923. ** auxiliary data pointer after the FTS5 query has finished.
  171924. **
  171925. ** If an error (e.g. an OOM condition) occurs within this function, an
  171926. ** the auxiliary data is set to NULL and an error code returned. If the
  171927. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  171928. ** pointer before returning.
  171929. **
  171930. **
  171931. ** xGetAuxdata(pFts5, bClear)
  171932. **
  171933. ** Returns the current auxiliary data pointer for the fts5 extension
  171934. ** function. See the xSetAuxdata() method for details.
  171935. **
  171936. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  171937. ** (set to NULL) before this function returns. In this case the xDelete,
  171938. ** if any, is not invoked.
  171939. **
  171940. **
  171941. ** xRowCount(pFts5, pnRow)
  171942. **
  171943. ** This function is used to retrieve the total number of rows in the table.
  171944. ** In other words, the same value that would be returned by:
  171945. **
  171946. ** SELECT count(*) FROM ftstable;
  171947. **
  171948. ** xPhraseFirst()
  171949. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  171950. ** method, to iterate through all instances of a single query phrase within
  171951. ** the current row. This is the same information as is accessible via the
  171952. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  171953. ** to use, this API may be faster under some circumstances. To iterate
  171954. ** through instances of phrase iPhrase, use the following code:
  171955. **
  171956. ** Fts5PhraseIter iter;
  171957. ** int iCol, iOff;
  171958. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  171959. ** iCol>=0;
  171960. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  171961. ** ){
  171962. ** // An instance of phrase iPhrase at offset iOff of column iCol
  171963. ** }
  171964. **
  171965. ** The Fts5PhraseIter structure is defined above. Applications should not
  171966. ** modify this structure directly - it should only be used as shown above
  171967. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  171968. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  171969. **
  171970. ** This API can be quite slow if used with an FTS5 table created with the
  171971. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  171972. ** with either "detail=none" or "detail=column" and "content=" option
  171973. ** (i.e. if it is a contentless table), then this API always iterates
  171974. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  171975. **
  171976. ** xPhraseNext()
  171977. ** See xPhraseFirst above.
  171978. **
  171979. ** xPhraseFirstColumn()
  171980. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  171981. ** and xPhraseNext() APIs described above. The difference is that instead
  171982. ** of iterating through all instances of a phrase in the current row, these
  171983. ** APIs are used to iterate through the set of columns in the current row
  171984. ** that contain one or more instances of a specified phrase. For example:
  171985. **
  171986. ** Fts5PhraseIter iter;
  171987. ** int iCol;
  171988. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  171989. ** iCol>=0;
  171990. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  171991. ** ){
  171992. ** // Column iCol contains at least one instance of phrase iPhrase
  171993. ** }
  171994. **
  171995. ** This API can be quite slow if used with an FTS5 table created with the
  171996. ** "detail=none" option. If the FTS5 table is created with either
  171997. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  171998. ** then this API always iterates through an empty set (all calls to
  171999. ** xPhraseFirstColumn() set iCol to -1).
  172000. **
  172001. ** The information accessed using this API and its companion
  172002. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  172003. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  172004. ** significantly more efficient than those alternatives when used with
  172005. ** "detail=column" tables.
  172006. **
  172007. ** xPhraseNextColumn()
  172008. ** See xPhraseFirstColumn above.
  172009. */
  172010. struct Fts5ExtensionApi {
  172011. int iVersion; /* Currently always set to 3 */
  172012. void *(*xUserData)(Fts5Context*);
  172013. int (*xColumnCount)(Fts5Context*);
  172014. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  172015. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  172016. int (*xTokenize)(Fts5Context*,
  172017. const char *pText, int nText, /* Text to tokenize */
  172018. void *pCtx, /* Context passed to xToken() */
  172019. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  172020. );
  172021. int (*xPhraseCount)(Fts5Context*);
  172022. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  172023. int (*xInstCount)(Fts5Context*, int *pnInst);
  172024. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  172025. sqlite3_int64 (*xRowid)(Fts5Context*);
  172026. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  172027. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  172028. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  172029. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  172030. );
  172031. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  172032. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  172033. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  172034. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  172035. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  172036. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  172037. };
  172038. /*
  172039. ** CUSTOM AUXILIARY FUNCTIONS
  172040. *************************************************************************/
  172041. /*************************************************************************
  172042. ** CUSTOM TOKENIZERS
  172043. **
  172044. ** Applications may also register custom tokenizer types. A tokenizer
  172045. ** is registered by providing fts5 with a populated instance of the
  172046. ** following structure. All structure methods must be defined, setting
  172047. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  172048. ** behaviour. The structure methods are expected to function as follows:
  172049. **
  172050. ** xCreate:
  172051. ** This function is used to allocate and initialize a tokenizer instance.
  172052. ** A tokenizer instance is required to actually tokenize text.
  172053. **
  172054. ** The first argument passed to this function is a copy of the (void*)
  172055. ** pointer provided by the application when the fts5_tokenizer object
  172056. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  172057. ** The second and third arguments are an array of nul-terminated strings
  172058. ** containing the tokenizer arguments, if any, specified following the
  172059. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  172060. ** to create the FTS5 table.
  172061. **
  172062. ** The final argument is an output variable. If successful, (*ppOut)
  172063. ** should be set to point to the new tokenizer handle and SQLITE_OK
  172064. ** returned. If an error occurs, some value other than SQLITE_OK should
  172065. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  172066. ** is undefined.
  172067. **
  172068. ** xDelete:
  172069. ** This function is invoked to delete a tokenizer handle previously
  172070. ** allocated using xCreate(). Fts5 guarantees that this function will
  172071. ** be invoked exactly once for each successful call to xCreate().
  172072. **
  172073. ** xTokenize:
  172074. ** This function is expected to tokenize the nText byte string indicated
  172075. ** by argument pText. pText may or may not be nul-terminated. The first
  172076. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  172077. ** returned by an earlier call to xCreate().
  172078. **
  172079. ** The second argument indicates the reason that FTS5 is requesting
  172080. ** tokenization of the supplied text. This is always one of the following
  172081. ** four values:
  172082. **
  172083. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  172084. ** or removed from the FTS table. The tokenizer is being invoked to
  172085. ** determine the set of tokens to add to (or delete from) the
  172086. ** FTS index.
  172087. **
  172088. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  172089. ** against the FTS index. The tokenizer is being called to tokenize
  172090. ** a bareword or quoted string specified as part of the query.
  172091. **
  172092. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  172093. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  172094. ** followed by a "*" character, indicating that the last token
  172095. ** returned by the tokenizer will be treated as a token prefix.
  172096. **
  172097. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  172098. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  172099. ** function. Or an fts5_api.xColumnSize() request made by the same
  172100. ** on a columnsize=0 database.
  172101. ** </ul>
  172102. **
  172103. ** For each token in the input string, the supplied callback xToken() must
  172104. ** be invoked. The first argument to it should be a copy of the pointer
  172105. ** passed as the second argument to xTokenize(). The third and fourth
  172106. ** arguments are a pointer to a buffer containing the token text, and the
  172107. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  172108. ** of the first byte of and first byte immediately following the text from
  172109. ** which the token is derived within the input.
  172110. **
  172111. ** The second argument passed to the xToken() callback ("tflags") should
  172112. ** normally be set to 0. The exception is if the tokenizer supports
  172113. ** synonyms. In this case see the discussion below for details.
  172114. **
  172115. ** FTS5 assumes the xToken() callback is invoked for each token in the
  172116. ** order that they occur within the input text.
  172117. **
  172118. ** If an xToken() callback returns any value other than SQLITE_OK, then
  172119. ** the tokenization should be abandoned and the xTokenize() method should
  172120. ** immediately return a copy of the xToken() return value. Or, if the
  172121. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  172122. ** if an error occurs with the xTokenize() implementation itself, it
  172123. ** may abandon the tokenization and return any error code other than
  172124. ** SQLITE_OK or SQLITE_DONE.
  172125. **
  172126. ** SYNONYM SUPPORT
  172127. **
  172128. ** Custom tokenizers may also support synonyms. Consider a case in which a
  172129. ** user wishes to query for a phrase such as "first place". Using the
  172130. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  172131. ** of "first place" within the document set, but not alternative forms
  172132. ** such as "1st place". In some applications, it would be better to match
  172133. ** all instances of "first place" or "1st place" regardless of which form
  172134. ** the user specified in the MATCH query text.
  172135. **
  172136. ** There are several ways to approach this in FTS5:
  172137. **
  172138. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  172139. ** In the above example, this means that the tokenizer returns the
  172140. ** same token for inputs "first" and "1st". Say that token is in
  172141. ** fact "first", so that when the user inserts the document "I won
  172142. ** 1st place" entries are added to the index for tokens "i", "won",
  172143. ** "first" and "place". If the user then queries for '1st + place',
  172144. ** the tokenizer substitutes "first" for "1st" and the query works
  172145. ** as expected.
  172146. **
  172147. ** <li> By adding multiple synonyms for a single term to the FTS index.
  172148. ** In this case, when tokenizing query text, the tokenizer may
  172149. ** provide multiple synonyms for a single term within the document.
  172150. ** FTS5 then queries the index for each synonym individually. For
  172151. ** example, faced with the query:
  172152. **
  172153. ** <codeblock>
  172154. ** ... MATCH 'first place'</codeblock>
  172155. **
  172156. ** the tokenizer offers both "1st" and "first" as synonyms for the
  172157. ** first token in the MATCH query and FTS5 effectively runs a query
  172158. ** similar to:
  172159. **
  172160. ** <codeblock>
  172161. ** ... MATCH '(first OR 1st) place'</codeblock>
  172162. **
  172163. ** except that, for the purposes of auxiliary functions, the query
  172164. ** still appears to contain just two phrases - "(first OR 1st)"
  172165. ** being treated as a single phrase.
  172166. **
  172167. ** <li> By adding multiple synonyms for a single term to the FTS index.
  172168. ** Using this method, when tokenizing document text, the tokenizer
  172169. ** provides multiple synonyms for each token. So that when a
  172170. ** document such as "I won first place" is tokenized, entries are
  172171. ** added to the FTS index for "i", "won", "first", "1st" and
  172172. ** "place".
  172173. **
  172174. ** This way, even if the tokenizer does not provide synonyms
  172175. ** when tokenizing query text (it should not - to do would be
  172176. ** inefficient), it doesn't matter if the user queries for
  172177. ** 'first + place' or '1st + place', as there are entires in the
  172178. ** FTS index corresponding to both forms of the first token.
  172179. ** </ol>
  172180. **
  172181. ** Whether it is parsing document or query text, any call to xToken that
  172182. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  172183. ** is considered to supply a synonym for the previous token. For example,
  172184. ** when parsing the document "I won first place", a tokenizer that supports
  172185. ** synonyms would call xToken() 5 times, as follows:
  172186. **
  172187. ** <codeblock>
  172188. ** xToken(pCtx, 0, "i", 1, 0, 1);
  172189. ** xToken(pCtx, 0, "won", 3, 2, 5);
  172190. ** xToken(pCtx, 0, "first", 5, 6, 11);
  172191. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  172192. ** xToken(pCtx, 0, "place", 5, 12, 17);
  172193. **</codeblock>
  172194. **
  172195. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  172196. ** xToken() is called. Multiple synonyms may be specified for a single token
  172197. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  172198. ** There is no limit to the number of synonyms that may be provided for a
  172199. ** single token.
  172200. **
  172201. ** In many cases, method (1) above is the best approach. It does not add
  172202. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  172203. ** so it is efficient in terms of disk space and query speed. However, it
  172204. ** does not support prefix queries very well. If, as suggested above, the
  172205. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  172206. **
  172207. ** <codeblock>
  172208. ** ... MATCH '1s*'</codeblock>
  172209. **
  172210. ** will not match documents that contain the token "1st" (as the tokenizer
  172211. ** will probably not map "1s" to any prefix of "first").
  172212. **
  172213. ** For full prefix support, method (3) may be preferred. In this case,
  172214. ** because the index contains entries for both "first" and "1st", prefix
  172215. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  172216. ** extra entries are added to the FTS index, this method uses more space
  172217. ** within the database.
  172218. **
  172219. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  172220. ** a query such as '1s*' will match documents that contain the literal
  172221. ** token "1st", but not "first" (assuming the tokenizer is not able to
  172222. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  172223. ** will match against "1st" and "first". This method does not require
  172224. ** extra disk space, as no extra entries are added to the FTS index.
  172225. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  172226. ** as separate queries of the FTS index are required for each synonym.
  172227. **
  172228. ** When using methods (2) or (3), it is important that the tokenizer only
  172229. ** provide synonyms when tokenizing document text (method (2)) or query
  172230. ** text (method (3)), not both. Doing so will not cause any errors, but is
  172231. ** inefficient.
  172232. */
  172233. typedef struct Fts5Tokenizer Fts5Tokenizer;
  172234. typedef struct fts5_tokenizer fts5_tokenizer;
  172235. struct fts5_tokenizer {
  172236. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  172237. void (*xDelete)(Fts5Tokenizer*);
  172238. int (*xTokenize)(Fts5Tokenizer*,
  172239. void *pCtx,
  172240. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  172241. const char *pText, int nText,
  172242. int (*xToken)(
  172243. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  172244. int tflags, /* Mask of FTS5_TOKEN_* flags */
  172245. const char *pToken, /* Pointer to buffer containing token */
  172246. int nToken, /* Size of token in bytes */
  172247. int iStart, /* Byte offset of token within input text */
  172248. int iEnd /* Byte offset of end of token within input text */
  172249. )
  172250. );
  172251. };
  172252. /* Flags that may be passed as the third argument to xTokenize() */
  172253. #define FTS5_TOKENIZE_QUERY 0x0001
  172254. #define FTS5_TOKENIZE_PREFIX 0x0002
  172255. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  172256. #define FTS5_TOKENIZE_AUX 0x0008
  172257. /* Flags that may be passed by the tokenizer implementation back to FTS5
  172258. ** as the third argument to the supplied xToken callback. */
  172259. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  172260. /*
  172261. ** END OF CUSTOM TOKENIZERS
  172262. *************************************************************************/
  172263. /*************************************************************************
  172264. ** FTS5 EXTENSION REGISTRATION API
  172265. */
  172266. typedef struct fts5_api fts5_api;
  172267. struct fts5_api {
  172268. int iVersion; /* Currently always set to 2 */
  172269. /* Create a new tokenizer */
  172270. int (*xCreateTokenizer)(
  172271. fts5_api *pApi,
  172272. const char *zName,
  172273. void *pContext,
  172274. fts5_tokenizer *pTokenizer,
  172275. void (*xDestroy)(void*)
  172276. );
  172277. /* Find an existing tokenizer */
  172278. int (*xFindTokenizer)(
  172279. fts5_api *pApi,
  172280. const char *zName,
  172281. void **ppContext,
  172282. fts5_tokenizer *pTokenizer
  172283. );
  172284. /* Create a new auxiliary function */
  172285. int (*xCreateFunction)(
  172286. fts5_api *pApi,
  172287. const char *zName,
  172288. void *pContext,
  172289. fts5_extension_function xFunction,
  172290. void (*xDestroy)(void*)
  172291. );
  172292. };
  172293. /*
  172294. ** END OF REGISTRATION API
  172295. *************************************************************************/
  172296. #if 0
  172297. } /* end of the 'extern "C"' block */
  172298. #endif
  172299. #endif /* _FTS5_H */
  172300. /*
  172301. ** 2014 May 31
  172302. **
  172303. ** The author disclaims copyright to this source code. In place of
  172304. ** a legal notice, here is a blessing:
  172305. **
  172306. ** May you do good and not evil.
  172307. ** May you find forgiveness for yourself and forgive others.
  172308. ** May you share freely, never taking more than you give.
  172309. **
  172310. ******************************************************************************
  172311. **
  172312. */
  172313. #ifndef _FTS5INT_H
  172314. #define _FTS5INT_H
  172315. /* #include "fts5.h" */
  172316. /* #include "sqlite3ext.h" */
  172317. SQLITE_EXTENSION_INIT1
  172318. /* #include <string.h> */
  172319. /* #include <assert.h> */
  172320. #ifndef SQLITE_AMALGAMATION
  172321. typedef unsigned char u8;
  172322. typedef unsigned int u32;
  172323. typedef unsigned short u16;
  172324. typedef short i16;
  172325. typedef sqlite3_int64 i64;
  172326. typedef sqlite3_uint64 u64;
  172327. #ifndef ArraySize
  172328. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  172329. #endif
  172330. #define testcase(x)
  172331. #define ALWAYS(x) 1
  172332. #define NEVER(x) 0
  172333. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  172334. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  172335. /*
  172336. ** Constants for the largest and smallest possible 64-bit signed integers.
  172337. */
  172338. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  172339. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  172340. #endif
  172341. /* Truncate very long tokens to this many bytes. Hard limit is
  172342. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  172343. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  172344. #define FTS5_MAX_TOKEN_SIZE 32768
  172345. /*
  172346. ** Maximum number of prefix indexes on single FTS5 table. This must be
  172347. ** less than 32. If it is set to anything large than that, an #error
  172348. ** directive in fts5_index.c will cause the build to fail.
  172349. */
  172350. #define FTS5_MAX_PREFIX_INDEXES 31
  172351. #define FTS5_DEFAULT_NEARDIST 10
  172352. #define FTS5_DEFAULT_RANK "bm25"
  172353. /* Name of rank and rowid columns */
  172354. #define FTS5_RANK_NAME "rank"
  172355. #define FTS5_ROWID_NAME "rowid"
  172356. #ifdef SQLITE_DEBUG
  172357. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  172358. static int sqlite3Fts5Corrupt(void);
  172359. #else
  172360. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  172361. #endif
  172362. /*
  172363. ** The assert_nc() macro is similar to the assert() macro, except that it
  172364. ** is used for assert() conditions that are true only if it can be
  172365. ** guranteed that the database is not corrupt.
  172366. */
  172367. #ifdef SQLITE_DEBUG
  172368. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  172369. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  172370. #else
  172371. # define assert_nc(x) assert(x)
  172372. #endif
  172373. /* Mark a function parameter as unused, to suppress nuisance compiler
  172374. ** warnings. */
  172375. #ifndef UNUSED_PARAM
  172376. # define UNUSED_PARAM(X) (void)(X)
  172377. #endif
  172378. #ifndef UNUSED_PARAM2
  172379. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  172380. #endif
  172381. typedef struct Fts5Global Fts5Global;
  172382. typedef struct Fts5Colset Fts5Colset;
  172383. /* If a NEAR() clump or phrase may only match a specific set of columns,
  172384. ** then an object of the following type is used to record the set of columns.
  172385. ** Each entry in the aiCol[] array is a column that may be matched.
  172386. **
  172387. ** This object is used by fts5_expr.c and fts5_index.c.
  172388. */
  172389. struct Fts5Colset {
  172390. int nCol;
  172391. int aiCol[1];
  172392. };
  172393. /**************************************************************************
  172394. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  172395. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  172396. */
  172397. typedef struct Fts5Config Fts5Config;
  172398. /*
  172399. ** An instance of the following structure encodes all information that can
  172400. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  172401. **
  172402. ** And all information loaded from the %_config table.
  172403. **
  172404. ** nAutomerge:
  172405. ** The minimum number of segments that an auto-merge operation should
  172406. ** attempt to merge together. A value of 1 sets the object to use the
  172407. ** compile time default. Zero disables auto-merge altogether.
  172408. **
  172409. ** zContent:
  172410. **
  172411. ** zContentRowid:
  172412. ** The value of the content_rowid= option, if one was specified. Or
  172413. ** the string "rowid" otherwise. This text is not quoted - if it is
  172414. ** used as part of an SQL statement it needs to be quoted appropriately.
  172415. **
  172416. ** zContentExprlist:
  172417. **
  172418. ** pzErrmsg:
  172419. ** This exists in order to allow the fts5_index.c module to return a
  172420. ** decent error message if it encounters a file-format version it does
  172421. ** not understand.
  172422. **
  172423. ** bColumnsize:
  172424. ** True if the %_docsize table is created.
  172425. **
  172426. ** bPrefixIndex:
  172427. ** This is only used for debugging. If set to false, any prefix indexes
  172428. ** are ignored. This value is configured using:
  172429. **
  172430. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  172431. **
  172432. */
  172433. struct Fts5Config {
  172434. sqlite3 *db; /* Database handle */
  172435. char *zDb; /* Database holding FTS index (e.g. "main") */
  172436. char *zName; /* Name of FTS index */
  172437. int nCol; /* Number of columns */
  172438. char **azCol; /* Column names */
  172439. u8 *abUnindexed; /* True for unindexed columns */
  172440. int nPrefix; /* Number of prefix indexes */
  172441. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  172442. int eContent; /* An FTS5_CONTENT value */
  172443. char *zContent; /* content table */
  172444. char *zContentRowid; /* "content_rowid=" option value */
  172445. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  172446. int eDetail; /* FTS5_DETAIL_XXX value */
  172447. char *zContentExprlist;
  172448. Fts5Tokenizer *pTok;
  172449. fts5_tokenizer *pTokApi;
  172450. /* Values loaded from the %_config table */
  172451. int iCookie; /* Incremented when %_config is modified */
  172452. int pgsz; /* Approximate page size used in %_data */
  172453. int nAutomerge; /* 'automerge' setting */
  172454. int nCrisisMerge; /* Maximum allowed segments per level */
  172455. int nUsermerge; /* 'usermerge' setting */
  172456. int nHashSize; /* Bytes of memory for in-memory hash */
  172457. char *zRank; /* Name of rank function */
  172458. char *zRankArgs; /* Arguments to rank function */
  172459. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  172460. char **pzErrmsg;
  172461. #ifdef SQLITE_DEBUG
  172462. int bPrefixIndex; /* True to use prefix-indexes */
  172463. #endif
  172464. };
  172465. /* Current expected value of %_config table 'version' field */
  172466. #define FTS5_CURRENT_VERSION 4
  172467. #define FTS5_CONTENT_NORMAL 0
  172468. #define FTS5_CONTENT_NONE 1
  172469. #define FTS5_CONTENT_EXTERNAL 2
  172470. #define FTS5_DETAIL_FULL 0
  172471. #define FTS5_DETAIL_NONE 1
  172472. #define FTS5_DETAIL_COLUMNS 2
  172473. static int sqlite3Fts5ConfigParse(
  172474. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  172475. );
  172476. static void sqlite3Fts5ConfigFree(Fts5Config*);
  172477. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  172478. static int sqlite3Fts5Tokenize(
  172479. Fts5Config *pConfig, /* FTS5 Configuration object */
  172480. int flags, /* FTS5_TOKENIZE_* flags */
  172481. const char *pText, int nText, /* Text to tokenize */
  172482. void *pCtx, /* Context passed to xToken() */
  172483. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  172484. );
  172485. static void sqlite3Fts5Dequote(char *z);
  172486. /* Load the contents of the %_config table */
  172487. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  172488. /* Set the value of a single config attribute */
  172489. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  172490. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  172491. /*
  172492. ** End of interface to code in fts5_config.c.
  172493. **************************************************************************/
  172494. /**************************************************************************
  172495. ** Interface to code in fts5_buffer.c.
  172496. */
  172497. /*
  172498. ** Buffer object for the incremental building of string data.
  172499. */
  172500. typedef struct Fts5Buffer Fts5Buffer;
  172501. struct Fts5Buffer {
  172502. u8 *p;
  172503. int n;
  172504. int nSpace;
  172505. };
  172506. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  172507. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  172508. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  172509. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  172510. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  172511. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  172512. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  172513. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  172514. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  172515. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  172516. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  172517. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  172518. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  172519. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  172520. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  172521. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  172522. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  172523. )
  172524. /* Write and decode big-endian 32-bit integer values */
  172525. static void sqlite3Fts5Put32(u8*, int);
  172526. static int sqlite3Fts5Get32(const u8*);
  172527. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  172528. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  172529. typedef struct Fts5PoslistReader Fts5PoslistReader;
  172530. struct Fts5PoslistReader {
  172531. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  172532. const u8 *a; /* Position list to iterate through */
  172533. int n; /* Size of buffer at a[] in bytes */
  172534. int i; /* Current offset in a[] */
  172535. u8 bFlag; /* For client use (any custom purpose) */
  172536. /* Output variables */
  172537. u8 bEof; /* Set to true at EOF */
  172538. i64 iPos; /* (iCol<<32) + iPos */
  172539. };
  172540. static int sqlite3Fts5PoslistReaderInit(
  172541. const u8 *a, int n, /* Poslist buffer to iterate through */
  172542. Fts5PoslistReader *pIter /* Iterator object to initialize */
  172543. );
  172544. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  172545. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  172546. struct Fts5PoslistWriter {
  172547. i64 iPrev;
  172548. };
  172549. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  172550. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  172551. static int sqlite3Fts5PoslistNext64(
  172552. const u8 *a, int n, /* Buffer containing poslist */
  172553. int *pi, /* IN/OUT: Offset within a[] */
  172554. i64 *piOff /* IN/OUT: Current offset */
  172555. );
  172556. /* Malloc utility */
  172557. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  172558. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  172559. /* Character set tests (like isspace(), isalpha() etc.) */
  172560. static int sqlite3Fts5IsBareword(char t);
  172561. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  172562. typedef struct Fts5Termset Fts5Termset;
  172563. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  172564. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  172565. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  172566. /*
  172567. ** End of interface to code in fts5_buffer.c.
  172568. **************************************************************************/
  172569. /**************************************************************************
  172570. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  172571. ** to access the data stored in the %_data table.
  172572. */
  172573. typedef struct Fts5Index Fts5Index;
  172574. typedef struct Fts5IndexIter Fts5IndexIter;
  172575. struct Fts5IndexIter {
  172576. i64 iRowid;
  172577. const u8 *pData;
  172578. int nData;
  172579. u8 bEof;
  172580. };
  172581. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  172582. /*
  172583. ** Values used as part of the flags argument passed to IndexQuery().
  172584. */
  172585. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  172586. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  172587. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  172588. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  172589. /* The following are used internally by the fts5_index.c module. They are
  172590. ** defined here only to make it easier to avoid clashes with the flags
  172591. ** above. */
  172592. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  172593. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  172594. /*
  172595. ** Create/destroy an Fts5Index object.
  172596. */
  172597. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  172598. static int sqlite3Fts5IndexClose(Fts5Index *p);
  172599. /*
  172600. ** Return a simple checksum value based on the arguments.
  172601. */
  172602. static u64 sqlite3Fts5IndexEntryCksum(
  172603. i64 iRowid,
  172604. int iCol,
  172605. int iPos,
  172606. int iIdx,
  172607. const char *pTerm,
  172608. int nTerm
  172609. );
  172610. /*
  172611. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  172612. ** size. Return the number of bytes in the nChar character prefix of the
  172613. ** buffer, or 0 if there are less than nChar characters in total.
  172614. */
  172615. static int sqlite3Fts5IndexCharlenToBytelen(
  172616. const char *p,
  172617. int nByte,
  172618. int nChar
  172619. );
  172620. /*
  172621. ** Open a new iterator to iterate though all rowids that match the
  172622. ** specified token or token prefix.
  172623. */
  172624. static int sqlite3Fts5IndexQuery(
  172625. Fts5Index *p, /* FTS index to query */
  172626. const char *pToken, int nToken, /* Token (or prefix) to query for */
  172627. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  172628. Fts5Colset *pColset, /* Match these columns only */
  172629. Fts5IndexIter **ppIter /* OUT: New iterator object */
  172630. );
  172631. /*
  172632. ** The various operations on open token or token prefix iterators opened
  172633. ** using sqlite3Fts5IndexQuery().
  172634. */
  172635. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  172636. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  172637. /*
  172638. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  172639. */
  172640. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  172641. /*
  172642. ** This interface is used by the fts5vocab module.
  172643. */
  172644. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  172645. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  172646. /*
  172647. ** Insert or remove data to or from the index. Each time a document is
  172648. ** added to or removed from the index, this function is called one or more
  172649. ** times.
  172650. **
  172651. ** For an insert, it must be called once for each token in the new document.
  172652. ** If the operation is a delete, it must be called (at least) once for each
  172653. ** unique token in the document with an iCol value less than zero. The iPos
  172654. ** argument is ignored for a delete.
  172655. */
  172656. static int sqlite3Fts5IndexWrite(
  172657. Fts5Index *p, /* Index to write to */
  172658. int iCol, /* Column token appears in (-ve -> delete) */
  172659. int iPos, /* Position of token within column */
  172660. const char *pToken, int nToken /* Token to add or remove to or from index */
  172661. );
  172662. /*
  172663. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  172664. ** document iDocid.
  172665. */
  172666. static int sqlite3Fts5IndexBeginWrite(
  172667. Fts5Index *p, /* Index to write to */
  172668. int bDelete, /* True if current operation is a delete */
  172669. i64 iDocid /* Docid to add or remove data from */
  172670. );
  172671. /*
  172672. ** Flush any data stored in the in-memory hash tables to the database.
  172673. ** Also close any open blob handles.
  172674. */
  172675. static int sqlite3Fts5IndexSync(Fts5Index *p);
  172676. /*
  172677. ** Discard any data stored in the in-memory hash tables. Do not write it
  172678. ** to the database. Additionally, assume that the contents of the %_data
  172679. ** table may have changed on disk. So any in-memory caches of %_data
  172680. ** records must be invalidated.
  172681. */
  172682. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  172683. /*
  172684. ** Get or set the "averages" values.
  172685. */
  172686. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  172687. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  172688. /*
  172689. ** Functions called by the storage module as part of integrity-check.
  172690. */
  172691. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  172692. /*
  172693. ** Called during virtual module initialization to register UDF
  172694. ** fts5_decode() with SQLite
  172695. */
  172696. static int sqlite3Fts5IndexInit(sqlite3*);
  172697. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  172698. /*
  172699. ** Return the total number of entries read from the %_data table by
  172700. ** this connection since it was created.
  172701. */
  172702. static int sqlite3Fts5IndexReads(Fts5Index *p);
  172703. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  172704. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  172705. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  172706. static int sqlite3Fts5IndexReset(Fts5Index *p);
  172707. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  172708. /*
  172709. ** End of interface to code in fts5_index.c.
  172710. **************************************************************************/
  172711. /**************************************************************************
  172712. ** Interface to code in fts5_varint.c.
  172713. */
  172714. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  172715. static int sqlite3Fts5GetVarintLen(u32 iVal);
  172716. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  172717. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  172718. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  172719. #define fts5GetVarint sqlite3Fts5GetVarint
  172720. #define fts5FastGetVarint32(a, iOff, nVal) { \
  172721. nVal = (a)[iOff++]; \
  172722. if( nVal & 0x80 ){ \
  172723. iOff--; \
  172724. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  172725. } \
  172726. }
  172727. /*
  172728. ** End of interface to code in fts5_varint.c.
  172729. **************************************************************************/
  172730. /**************************************************************************
  172731. ** Interface to code in fts5.c.
  172732. */
  172733. static int sqlite3Fts5GetTokenizer(
  172734. Fts5Global*,
  172735. const char **azArg,
  172736. int nArg,
  172737. Fts5Tokenizer**,
  172738. fts5_tokenizer**,
  172739. char **pzErr
  172740. );
  172741. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  172742. /*
  172743. ** End of interface to code in fts5.c.
  172744. **************************************************************************/
  172745. /**************************************************************************
  172746. ** Interface to code in fts5_hash.c.
  172747. */
  172748. typedef struct Fts5Hash Fts5Hash;
  172749. /*
  172750. ** Create a hash table, free a hash table.
  172751. */
  172752. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  172753. static void sqlite3Fts5HashFree(Fts5Hash*);
  172754. static int sqlite3Fts5HashWrite(
  172755. Fts5Hash*,
  172756. i64 iRowid, /* Rowid for this entry */
  172757. int iCol, /* Column token appears in (-ve -> delete) */
  172758. int iPos, /* Position of token within column */
  172759. char bByte,
  172760. const char *pToken, int nToken /* Token to add or remove to or from index */
  172761. );
  172762. /*
  172763. ** Empty (but do not delete) a hash table.
  172764. */
  172765. static void sqlite3Fts5HashClear(Fts5Hash*);
  172766. static int sqlite3Fts5HashQuery(
  172767. Fts5Hash*, /* Hash table to query */
  172768. const char *pTerm, int nTerm, /* Query term */
  172769. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  172770. int *pnDoclist /* OUT: Size of doclist in bytes */
  172771. );
  172772. static int sqlite3Fts5HashScanInit(
  172773. Fts5Hash*, /* Hash table to query */
  172774. const char *pTerm, int nTerm /* Query prefix */
  172775. );
  172776. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  172777. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  172778. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  172779. const char **pzTerm, /* OUT: term (nul-terminated) */
  172780. const u8 **ppDoclist, /* OUT: pointer to doclist */
  172781. int *pnDoclist /* OUT: size of doclist in bytes */
  172782. );
  172783. /*
  172784. ** End of interface to code in fts5_hash.c.
  172785. **************************************************************************/
  172786. /**************************************************************************
  172787. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  172788. ** code to access the data stored in the %_content and %_docsize tables.
  172789. */
  172790. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  172791. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  172792. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  172793. typedef struct Fts5Storage Fts5Storage;
  172794. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  172795. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  172796. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  172797. static int sqlite3Fts5DropAll(Fts5Config*);
  172798. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  172799. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  172800. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  172801. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  172802. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  172803. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  172804. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  172805. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  172806. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  172807. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  172808. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  172809. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  172810. static int sqlite3Fts5StorageConfigValue(
  172811. Fts5Storage *p, const char*, sqlite3_value*, int
  172812. );
  172813. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  172814. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  172815. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  172816. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  172817. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  172818. /*
  172819. ** End of interface to code in fts5_storage.c.
  172820. **************************************************************************/
  172821. /**************************************************************************
  172822. ** Interface to code in fts5_expr.c.
  172823. */
  172824. typedef struct Fts5Expr Fts5Expr;
  172825. typedef struct Fts5ExprNode Fts5ExprNode;
  172826. typedef struct Fts5Parse Fts5Parse;
  172827. typedef struct Fts5Token Fts5Token;
  172828. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  172829. typedef struct Fts5ExprNearset Fts5ExprNearset;
  172830. struct Fts5Token {
  172831. const char *p; /* Token text (not NULL terminated) */
  172832. int n; /* Size of buffer p in bytes */
  172833. };
  172834. /* Parse a MATCH expression. */
  172835. static int sqlite3Fts5ExprNew(
  172836. Fts5Config *pConfig,
  172837. int iCol, /* Column on LHS of MATCH operator */
  172838. const char *zExpr,
  172839. Fts5Expr **ppNew,
  172840. char **pzErr
  172841. );
  172842. /*
  172843. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  172844. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  172845. ** rc = sqlite3Fts5ExprNext(pExpr)
  172846. ** ){
  172847. ** // The document with rowid iRowid matches the expression!
  172848. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  172849. ** }
  172850. */
  172851. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  172852. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  172853. static int sqlite3Fts5ExprEof(Fts5Expr*);
  172854. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  172855. static void sqlite3Fts5ExprFree(Fts5Expr*);
  172856. /* Called during startup to register a UDF with SQLite */
  172857. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  172858. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  172859. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  172860. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  172861. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  172862. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  172863. static int sqlite3Fts5ExprPopulatePoslists(
  172864. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  172865. );
  172866. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  172867. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  172868. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  172869. /*******************************************
  172870. ** The fts5_expr.c API above this point is used by the other hand-written
  172871. ** C code in this module. The interfaces below this point are called by
  172872. ** the parser code in fts5parse.y. */
  172873. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  172874. static Fts5ExprNode *sqlite3Fts5ParseNode(
  172875. Fts5Parse *pParse,
  172876. int eType,
  172877. Fts5ExprNode *pLeft,
  172878. Fts5ExprNode *pRight,
  172879. Fts5ExprNearset *pNear
  172880. );
  172881. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  172882. Fts5Parse *pParse,
  172883. Fts5ExprNode *pLeft,
  172884. Fts5ExprNode *pRight
  172885. );
  172886. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  172887. Fts5Parse *pParse,
  172888. Fts5ExprPhrase *pPhrase,
  172889. Fts5Token *pToken,
  172890. int bPrefix
  172891. );
  172892. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  172893. Fts5Parse*,
  172894. Fts5ExprNearset*,
  172895. Fts5ExprPhrase*
  172896. );
  172897. static Fts5Colset *sqlite3Fts5ParseColset(
  172898. Fts5Parse*,
  172899. Fts5Colset*,
  172900. Fts5Token *
  172901. );
  172902. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  172903. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  172904. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  172905. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  172906. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  172907. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  172908. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  172909. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  172910. /*
  172911. ** End of interface to code in fts5_expr.c.
  172912. **************************************************************************/
  172913. /**************************************************************************
  172914. ** Interface to code in fts5_aux.c.
  172915. */
  172916. static int sqlite3Fts5AuxInit(fts5_api*);
  172917. /*
  172918. ** End of interface to code in fts5_aux.c.
  172919. **************************************************************************/
  172920. /**************************************************************************
  172921. ** Interface to code in fts5_tokenizer.c.
  172922. */
  172923. static int sqlite3Fts5TokenizerInit(fts5_api*);
  172924. /*
  172925. ** End of interface to code in fts5_tokenizer.c.
  172926. **************************************************************************/
  172927. /**************************************************************************
  172928. ** Interface to code in fts5_vocab.c.
  172929. */
  172930. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  172931. /*
  172932. ** End of interface to code in fts5_vocab.c.
  172933. **************************************************************************/
  172934. /**************************************************************************
  172935. ** Interface to automatically generated code in fts5_unicode2.c.
  172936. */
  172937. static int sqlite3Fts5UnicodeIsalnum(int c);
  172938. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  172939. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  172940. /*
  172941. ** End of interface to code in fts5_unicode2.c.
  172942. **************************************************************************/
  172943. #endif
  172944. #define FTS5_OR 1
  172945. #define FTS5_AND 2
  172946. #define FTS5_NOT 3
  172947. #define FTS5_TERM 4
  172948. #define FTS5_COLON 5
  172949. #define FTS5_MINUS 6
  172950. #define FTS5_LCP 7
  172951. #define FTS5_RCP 8
  172952. #define FTS5_STRING 9
  172953. #define FTS5_LP 10
  172954. #define FTS5_RP 11
  172955. #define FTS5_COMMA 12
  172956. #define FTS5_PLUS 13
  172957. #define FTS5_STAR 14
  172958. /*
  172959. ** 2000-05-29
  172960. **
  172961. ** The author disclaims copyright to this source code. In place of
  172962. ** a legal notice, here is a blessing:
  172963. **
  172964. ** May you do good and not evil.
  172965. ** May you find forgiveness for yourself and forgive others.
  172966. ** May you share freely, never taking more than you give.
  172967. **
  172968. *************************************************************************
  172969. ** Driver template for the LEMON parser generator.
  172970. **
  172971. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  172972. ** this template to construct a parser. The "lemon" program inserts text
  172973. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  172974. ** interstitial "-" characters) contained in this template is changed into
  172975. ** the value of the %name directive from the grammar. Otherwise, the content
  172976. ** of this template is copied straight through into the generate parser
  172977. ** source file.
  172978. **
  172979. ** The following is the concatenation of all %include directives from the
  172980. ** input grammar file:
  172981. */
  172982. /* #include <stdio.h> */
  172983. /************ Begin %include sections from the grammar ************************/
  172984. /* #include "fts5Int.h" */
  172985. /* #include "fts5parse.h" */
  172986. /*
  172987. ** Disable all error recovery processing in the parser push-down
  172988. ** automaton.
  172989. */
  172990. #define fts5YYNOERRORRECOVERY 1
  172991. /*
  172992. ** Make fts5yytestcase() the same as testcase()
  172993. */
  172994. #define fts5yytestcase(X) testcase(X)
  172995. /*
  172996. ** Indicate that sqlite3ParserFree() will never be called with a null
  172997. ** pointer.
  172998. */
  172999. #define fts5YYPARSEFREENOTNULL 1
  173000. /*
  173001. ** Alternative datatype for the argument to the malloc() routine passed
  173002. ** into sqlite3ParserAlloc(). The default is size_t.
  173003. */
  173004. #define fts5YYMALLOCARGTYPE u64
  173005. /**************** End of %include directives **********************************/
  173006. /* These constants specify the various numeric values for terminal symbols
  173007. ** in a format understandable to "makeheaders". This section is blank unless
  173008. ** "lemon" is run with the "-m" command-line option.
  173009. ***************** Begin makeheaders token definitions *************************/
  173010. /**************** End makeheaders token definitions ***************************/
  173011. /* The next sections is a series of control #defines.
  173012. ** various aspects of the generated parser.
  173013. ** fts5YYCODETYPE is the data type used to store the integer codes
  173014. ** that represent terminal and non-terminal symbols.
  173015. ** "unsigned char" is used if there are fewer than
  173016. ** 256 symbols. Larger types otherwise.
  173017. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  173018. ** any terminal or nonterminal symbol.
  173019. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  173020. ** (also known as: "terminal symbols") have fall-back
  173021. ** values which should be used if the original symbol
  173022. ** would not parse. This permits keywords to sometimes
  173023. ** be used as identifiers, for example.
  173024. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  173025. ** that indicate what to do in response to the next
  173026. ** token.
  173027. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  173028. ** symbols. Background: A "minor type" is a semantic
  173029. ** value associated with a terminal or non-terminal
  173030. ** symbols. For example, for an "ID" terminal symbol,
  173031. ** the minor type might be the name of the identifier.
  173032. ** Each non-terminal can have a different minor type.
  173033. ** Terminal symbols all have the same minor type, though.
  173034. ** This macros defines the minor type for terminal
  173035. ** symbols.
  173036. ** fts5YYMINORTYPE is the data type used for all minor types.
  173037. ** This is typically a union of many types, one of
  173038. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  173039. ** for terminal symbols is called "fts5yy0".
  173040. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  173041. ** zero the stack is dynamically sized using realloc()
  173042. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  173043. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  173044. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  173045. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  173046. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  173047. ** defined, then do no error processing.
  173048. ** fts5YYNSTATE the combined number of states.
  173049. ** fts5YYNRULE the number of rules in the grammar
  173050. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  173051. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  173052. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  173053. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  173054. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  173055. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  173056. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  173057. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  173058. */
  173059. #ifndef INTERFACE
  173060. # define INTERFACE 1
  173061. #endif
  173062. /************* Begin control #defines *****************************************/
  173063. #define fts5YYCODETYPE unsigned char
  173064. #define fts5YYNOCODE 28
  173065. #define fts5YYACTIONTYPE unsigned char
  173066. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  173067. typedef union {
  173068. int fts5yyinit;
  173069. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  173070. int fts5yy4;
  173071. Fts5Colset* fts5yy11;
  173072. Fts5ExprNode* fts5yy24;
  173073. Fts5ExprNearset* fts5yy46;
  173074. Fts5ExprPhrase* fts5yy53;
  173075. } fts5YYMINORTYPE;
  173076. #ifndef fts5YYSTACKDEPTH
  173077. #define fts5YYSTACKDEPTH 100
  173078. #endif
  173079. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  173080. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  173081. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  173082. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  173083. #define fts5YYNSTATE 33
  173084. #define fts5YYNRULE 27
  173085. #define fts5YY_MAX_SHIFT 32
  173086. #define fts5YY_MIN_SHIFTREDUCE 50
  173087. #define fts5YY_MAX_SHIFTREDUCE 76
  173088. #define fts5YY_MIN_REDUCE 77
  173089. #define fts5YY_MAX_REDUCE 103
  173090. #define fts5YY_ERROR_ACTION 104
  173091. #define fts5YY_ACCEPT_ACTION 105
  173092. #define fts5YY_NO_ACTION 106
  173093. /************* End control #defines *******************************************/
  173094. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  173095. ** otherwise.
  173096. **
  173097. ** Applications can choose to define fts5yytestcase() in the %include section
  173098. ** to a macro that can assist in verifying code coverage. For production
  173099. ** code the fts5yytestcase() macro should be turned off. But it is useful
  173100. ** for testing.
  173101. */
  173102. #ifndef fts5yytestcase
  173103. # define fts5yytestcase(X)
  173104. #endif
  173105. /* Next are the tables used to determine what action to take based on the
  173106. ** current state and lookahead token. These tables are used to implement
  173107. ** functions that take a state number and lookahead value and return an
  173108. ** action integer.
  173109. **
  173110. ** Suppose the action integer is N. Then the action is determined as
  173111. ** follows
  173112. **
  173113. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  173114. ** token onto the stack and goto state N.
  173115. **
  173116. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  173117. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  173118. **
  173119. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  173120. ** and fts5YY_MAX_REDUCE
  173121. **
  173122. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  173123. **
  173124. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  173125. **
  173126. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  173127. ** slots in the fts5yy_action[] table.
  173128. **
  173129. ** The action table is constructed as a single large table named fts5yy_action[].
  173130. ** Given state S and lookahead X, the action is computed as either:
  173131. **
  173132. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  173133. ** (B) N = fts5yy_default[S]
  173134. **
  173135. ** The (A) formula is preferred. The B formula is used instead if:
  173136. ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
  173137. ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
  173138. ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
  173139. ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
  173140. ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  173141. ** Hence only tests (1) and (2) need to be evaluated.)
  173142. **
  173143. ** The formulas above are for computing the action when the lookahead is
  173144. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  173145. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  173146. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  173147. ** fts5YY_SHIFT_USE_DFLT.
  173148. **
  173149. ** The following are the tables generated in this section:
  173150. **
  173151. ** fts5yy_action[] A single table containing all actions.
  173152. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  173153. ** fts5yy_action. Used to detect hash collisions.
  173154. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  173155. ** shifting terminals.
  173156. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  173157. ** shifting non-terminals after a reduce.
  173158. ** fts5yy_default[] Default action for each state.
  173159. **
  173160. *********** Begin parsing tables **********************************************/
  173161. #define fts5YY_ACTTAB_COUNT (98)
  173162. static const fts5YYACTIONTYPE fts5yy_action[] = {
  173163. /* 0 */ 105, 19, 90, 6, 26, 93, 92, 24, 24, 17,
  173164. /* 10 */ 90, 6, 26, 16, 92, 54, 24, 18, 90, 6,
  173165. /* 20 */ 26, 10, 92, 12, 24, 75, 86, 90, 6, 26,
  173166. /* 30 */ 13, 92, 75, 24, 20, 90, 6, 26, 101, 92,
  173167. /* 40 */ 56, 24, 27, 90, 6, 26, 100, 92, 21, 24,
  173168. /* 50 */ 23, 15, 30, 11, 1, 91, 22, 25, 9, 92,
  173169. /* 60 */ 7, 24, 3, 4, 5, 3, 4, 5, 3, 77,
  173170. /* 70 */ 4, 5, 3, 61, 23, 15, 60, 11, 80, 12,
  173171. /* 80 */ 2, 13, 68, 10, 29, 52, 55, 75, 31, 32,
  173172. /* 90 */ 8, 28, 5, 3, 51, 55, 72, 14,
  173173. };
  173174. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  173175. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  173176. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  173177. /* 20 */ 20, 10, 22, 9, 24, 14, 17, 18, 19, 20,
  173178. /* 30 */ 9, 22, 14, 24, 17, 18, 19, 20, 26, 22,
  173179. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  173180. /* 50 */ 6, 7, 13, 9, 10, 18, 21, 20, 5, 22,
  173181. /* 60 */ 5, 24, 3, 1, 2, 3, 1, 2, 3, 0,
  173182. /* 70 */ 1, 2, 3, 11, 6, 7, 11, 9, 5, 9,
  173183. /* 80 */ 10, 9, 11, 10, 12, 8, 9, 14, 24, 25,
  173184. /* 90 */ 23, 24, 2, 3, 8, 9, 9, 9,
  173185. };
  173186. #define fts5YY_SHIFT_USE_DFLT (98)
  173187. #define fts5YY_SHIFT_COUNT (32)
  173188. #define fts5YY_SHIFT_MIN (0)
  173189. #define fts5YY_SHIFT_MAX (90)
  173190. static const unsigned char fts5yy_shift_ofst[] = {
  173191. /* 0 */ 44, 44, 44, 44, 44, 44, 68, 70, 72, 14,
  173192. /* 10 */ 21, 73, 11, 18, 18, 31, 31, 62, 65, 69,
  173193. /* 20 */ 90, 77, 86, 6, 39, 53, 55, 59, 39, 87,
  173194. /* 30 */ 88, 39, 71,
  173195. };
  173196. #define fts5YY_REDUCE_USE_DFLT (-18)
  173197. #define fts5YY_REDUCE_COUNT (16)
  173198. #define fts5YY_REDUCE_MIN (-17)
  173199. #define fts5YY_REDUCE_MAX (67)
  173200. static const signed char fts5yy_reduce_ofst[] = {
  173201. /* 0 */ -16, -8, 0, 9, 17, 25, 37, -17, 64, -17,
  173202. /* 10 */ 67, 12, 12, 12, 20, 27, 35,
  173203. };
  173204. static const fts5YYACTIONTYPE fts5yy_default[] = {
  173205. /* 0 */ 104, 104, 104, 104, 104, 104, 89, 104, 98, 104,
  173206. /* 10 */ 104, 103, 103, 103, 103, 104, 104, 104, 104, 104,
  173207. /* 20 */ 85, 104, 104, 104, 94, 104, 104, 84, 96, 104,
  173208. /* 30 */ 104, 97, 104,
  173209. };
  173210. /********** End of lemon-generated parsing tables *****************************/
  173211. /* The next table maps tokens (terminal symbols) into fallback tokens.
  173212. ** If a construct like the following:
  173213. **
  173214. ** %fallback ID X Y Z.
  173215. **
  173216. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  173217. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  173218. ** but it does not parse, the type of the token is changed to ID and
  173219. ** the parse is retried before an error is thrown.
  173220. **
  173221. ** This feature can be used, for example, to cause some keywords in a language
  173222. ** to revert to identifiers if they keyword does not apply in the context where
  173223. ** it appears.
  173224. */
  173225. #ifdef fts5YYFALLBACK
  173226. static const fts5YYCODETYPE fts5yyFallback[] = {
  173227. };
  173228. #endif /* fts5YYFALLBACK */
  173229. /* The following structure represents a single element of the
  173230. ** parser's stack. Information stored includes:
  173231. **
  173232. ** + The state number for the parser at this level of the stack.
  173233. **
  173234. ** + The value of the token stored at this level of the stack.
  173235. ** (In other words, the "major" token.)
  173236. **
  173237. ** + The semantic value stored at this level of the stack. This is
  173238. ** the information used by the action routines in the grammar.
  173239. ** It is sometimes called the "minor" token.
  173240. **
  173241. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  173242. ** actually contains the reduce action for the second half of the
  173243. ** SHIFTREDUCE.
  173244. */
  173245. struct fts5yyStackEntry {
  173246. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  173247. fts5YYCODETYPE major; /* The major token value. This is the code
  173248. ** number for the token at this stack level */
  173249. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  173250. ** is the value of the token */
  173251. };
  173252. typedef struct fts5yyStackEntry fts5yyStackEntry;
  173253. /* The state of the parser is completely contained in an instance of
  173254. ** the following structure */
  173255. struct fts5yyParser {
  173256. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  173257. #ifdef fts5YYTRACKMAXSTACKDEPTH
  173258. int fts5yyhwm; /* High-water mark of the stack */
  173259. #endif
  173260. #ifndef fts5YYNOERRORRECOVERY
  173261. int fts5yyerrcnt; /* Shifts left before out of the error */
  173262. #endif
  173263. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  173264. #if fts5YYSTACKDEPTH<=0
  173265. int fts5yystksz; /* Current side of the stack */
  173266. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  173267. fts5yyStackEntry fts5yystk0; /* First stack entry */
  173268. #else
  173269. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  173270. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  173271. #endif
  173272. };
  173273. typedef struct fts5yyParser fts5yyParser;
  173274. #ifndef NDEBUG
  173275. /* #include <stdio.h> */
  173276. static FILE *fts5yyTraceFILE = 0;
  173277. static char *fts5yyTracePrompt = 0;
  173278. #endif /* NDEBUG */
  173279. #ifndef NDEBUG
  173280. /*
  173281. ** Turn parser tracing on by giving a stream to which to write the trace
  173282. ** and a prompt to preface each trace message. Tracing is turned off
  173283. ** by making either argument NULL
  173284. **
  173285. ** Inputs:
  173286. ** <ul>
  173287. ** <li> A FILE* to which trace output should be written.
  173288. ** If NULL, then tracing is turned off.
  173289. ** <li> A prefix string written at the beginning of every
  173290. ** line of trace output. If NULL, then tracing is
  173291. ** turned off.
  173292. ** </ul>
  173293. **
  173294. ** Outputs:
  173295. ** None.
  173296. */
  173297. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  173298. fts5yyTraceFILE = TraceFILE;
  173299. fts5yyTracePrompt = zTracePrompt;
  173300. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  173301. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  173302. }
  173303. #endif /* NDEBUG */
  173304. #ifndef NDEBUG
  173305. /* For tracing shifts, the names of all terminals and nonterminals
  173306. ** are required. The following table supplies these names */
  173307. static const char *const fts5yyTokenName[] = {
  173308. "$", "OR", "AND", "NOT",
  173309. "TERM", "COLON", "MINUS", "LCP",
  173310. "RCP", "STRING", "LP", "RP",
  173311. "COMMA", "PLUS", "STAR", "error",
  173312. "input", "expr", "cnearset", "exprlist",
  173313. "colset", "colsetlist", "nearset", "nearphrases",
  173314. "phrase", "neardist_opt", "star_opt",
  173315. };
  173316. #endif /* NDEBUG */
  173317. #ifndef NDEBUG
  173318. /* For tracing reduce actions, the names of all rules are required.
  173319. */
  173320. static const char *const fts5yyRuleName[] = {
  173321. /* 0 */ "input ::= expr",
  173322. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  173323. /* 2 */ "colset ::= LCP colsetlist RCP",
  173324. /* 3 */ "colset ::= STRING",
  173325. /* 4 */ "colset ::= MINUS STRING",
  173326. /* 5 */ "colsetlist ::= colsetlist STRING",
  173327. /* 6 */ "colsetlist ::= STRING",
  173328. /* 7 */ "expr ::= expr AND expr",
  173329. /* 8 */ "expr ::= expr OR expr",
  173330. /* 9 */ "expr ::= expr NOT expr",
  173331. /* 10 */ "expr ::= colset COLON LP expr RP",
  173332. /* 11 */ "expr ::= LP expr RP",
  173333. /* 12 */ "expr ::= exprlist",
  173334. /* 13 */ "exprlist ::= cnearset",
  173335. /* 14 */ "exprlist ::= exprlist cnearset",
  173336. /* 15 */ "cnearset ::= nearset",
  173337. /* 16 */ "cnearset ::= colset COLON nearset",
  173338. /* 17 */ "nearset ::= phrase",
  173339. /* 18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  173340. /* 19 */ "nearphrases ::= phrase",
  173341. /* 20 */ "nearphrases ::= nearphrases phrase",
  173342. /* 21 */ "neardist_opt ::=",
  173343. /* 22 */ "neardist_opt ::= COMMA STRING",
  173344. /* 23 */ "phrase ::= phrase PLUS STRING star_opt",
  173345. /* 24 */ "phrase ::= STRING star_opt",
  173346. /* 25 */ "star_opt ::= STAR",
  173347. /* 26 */ "star_opt ::=",
  173348. };
  173349. #endif /* NDEBUG */
  173350. #if fts5YYSTACKDEPTH<=0
  173351. /*
  173352. ** Try to increase the size of the parser stack. Return the number
  173353. ** of errors. Return 0 on success.
  173354. */
  173355. static int fts5yyGrowStack(fts5yyParser *p){
  173356. int newSize;
  173357. int idx;
  173358. fts5yyStackEntry *pNew;
  173359. newSize = p->fts5yystksz*2 + 100;
  173360. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  173361. if( p->fts5yystack==&p->fts5yystk0 ){
  173362. pNew = malloc(newSize*sizeof(pNew[0]));
  173363. if( pNew ) pNew[0] = p->fts5yystk0;
  173364. }else{
  173365. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  173366. }
  173367. if( pNew ){
  173368. p->fts5yystack = pNew;
  173369. p->fts5yytos = &p->fts5yystack[idx];
  173370. #ifndef NDEBUG
  173371. if( fts5yyTraceFILE ){
  173372. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  173373. fts5yyTracePrompt, p->fts5yystksz, newSize);
  173374. }
  173375. #endif
  173376. p->fts5yystksz = newSize;
  173377. }
  173378. return pNew==0;
  173379. }
  173380. #endif
  173381. /* Datatype of the argument to the memory allocated passed as the
  173382. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  173383. ** putting an appropriate #define in the %include section of the input
  173384. ** grammar.
  173385. */
  173386. #ifndef fts5YYMALLOCARGTYPE
  173387. # define fts5YYMALLOCARGTYPE size_t
  173388. #endif
  173389. /* Initialize a new parser that has already been allocated.
  173390. */
  173391. static void sqlite3Fts5ParserInit(void *fts5yypParser){
  173392. fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
  173393. #ifdef fts5YYTRACKMAXSTACKDEPTH
  173394. pParser->fts5yyhwm = 0;
  173395. #endif
  173396. #if fts5YYSTACKDEPTH<=0
  173397. pParser->fts5yytos = NULL;
  173398. pParser->fts5yystack = NULL;
  173399. pParser->fts5yystksz = 0;
  173400. if( fts5yyGrowStack(pParser) ){
  173401. pParser->fts5yystack = &pParser->fts5yystk0;
  173402. pParser->fts5yystksz = 1;
  173403. }
  173404. #endif
  173405. #ifndef fts5YYNOERRORRECOVERY
  173406. pParser->fts5yyerrcnt = -1;
  173407. #endif
  173408. pParser->fts5yytos = pParser->fts5yystack;
  173409. pParser->fts5yystack[0].stateno = 0;
  173410. pParser->fts5yystack[0].major = 0;
  173411. #if fts5YYSTACKDEPTH>0
  173412. pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
  173413. #endif
  173414. }
  173415. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  173416. /*
  173417. ** This function allocates a new parser.
  173418. ** The only argument is a pointer to a function which works like
  173419. ** malloc.
  173420. **
  173421. ** Inputs:
  173422. ** A pointer to the function used to allocate memory.
  173423. **
  173424. ** Outputs:
  173425. ** A pointer to a parser. This pointer is used in subsequent calls
  173426. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  173427. */
  173428. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  173429. fts5yyParser *pParser;
  173430. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  173431. if( pParser ) sqlite3Fts5ParserInit(pParser);
  173432. return pParser;
  173433. }
  173434. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  173435. /* The following function deletes the "minor type" or semantic value
  173436. ** associated with a symbol. The symbol can be either a terminal
  173437. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  173438. ** a pointer to the value to be deleted. The code used to do the
  173439. ** deletions is derived from the %destructor and/or %token_destructor
  173440. ** directives of the input grammar.
  173441. */
  173442. static void fts5yy_destructor(
  173443. fts5yyParser *fts5yypParser, /* The parser */
  173444. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  173445. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  173446. ){
  173447. sqlite3Fts5ParserARG_FETCH;
  173448. switch( fts5yymajor ){
  173449. /* Here is inserted the actions which take place when a
  173450. ** terminal or non-terminal is destroyed. This can happen
  173451. ** when the symbol is popped from the stack during a
  173452. ** reduce or during error processing or when a parser is
  173453. ** being destroyed before it is finished parsing.
  173454. **
  173455. ** Note: during a reduce, the only symbols destroyed are those
  173456. ** which appear on the RHS of the rule, but which are *not* used
  173457. ** inside the C code.
  173458. */
  173459. /********* Begin destructor definitions ***************************************/
  173460. case 16: /* input */
  173461. {
  173462. (void)pParse;
  173463. }
  173464. break;
  173465. case 17: /* expr */
  173466. case 18: /* cnearset */
  173467. case 19: /* exprlist */
  173468. {
  173469. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  173470. }
  173471. break;
  173472. case 20: /* colset */
  173473. case 21: /* colsetlist */
  173474. {
  173475. sqlite3_free((fts5yypminor->fts5yy11));
  173476. }
  173477. break;
  173478. case 22: /* nearset */
  173479. case 23: /* nearphrases */
  173480. {
  173481. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  173482. }
  173483. break;
  173484. case 24: /* phrase */
  173485. {
  173486. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  173487. }
  173488. break;
  173489. /********* End destructor definitions *****************************************/
  173490. default: break; /* If no destructor action specified: do nothing */
  173491. }
  173492. }
  173493. /*
  173494. ** Pop the parser's stack once.
  173495. **
  173496. ** If there is a destructor routine associated with the token which
  173497. ** is popped from the stack, then call it.
  173498. */
  173499. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  173500. fts5yyStackEntry *fts5yytos;
  173501. assert( pParser->fts5yytos!=0 );
  173502. assert( pParser->fts5yytos > pParser->fts5yystack );
  173503. fts5yytos = pParser->fts5yytos--;
  173504. #ifndef NDEBUG
  173505. if( fts5yyTraceFILE ){
  173506. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  173507. fts5yyTracePrompt,
  173508. fts5yyTokenName[fts5yytos->major]);
  173509. }
  173510. #endif
  173511. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  173512. }
  173513. /*
  173514. ** Clear all secondary memory allocations from the parser
  173515. */
  173516. static void sqlite3Fts5ParserFinalize(void *p){
  173517. fts5yyParser *pParser = (fts5yyParser*)p;
  173518. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  173519. #if fts5YYSTACKDEPTH<=0
  173520. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  173521. #endif
  173522. }
  173523. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  173524. /*
  173525. ** Deallocate and destroy a parser. Destructors are called for
  173526. ** all stack elements before shutting the parser down.
  173527. **
  173528. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  173529. ** is defined in a %include section of the input grammar) then it is
  173530. ** assumed that the input pointer is never NULL.
  173531. */
  173532. static void sqlite3Fts5ParserFree(
  173533. void *p, /* The parser to be deleted */
  173534. void (*freeProc)(void*) /* Function used to reclaim memory */
  173535. ){
  173536. #ifndef fts5YYPARSEFREENEVERNULL
  173537. if( p==0 ) return;
  173538. #endif
  173539. sqlite3Fts5ParserFinalize(p);
  173540. (*freeProc)(p);
  173541. }
  173542. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  173543. /*
  173544. ** Return the peak depth of the stack for a parser.
  173545. */
  173546. #ifdef fts5YYTRACKMAXSTACKDEPTH
  173547. static int sqlite3Fts5ParserStackPeak(void *p){
  173548. fts5yyParser *pParser = (fts5yyParser*)p;
  173549. return pParser->fts5yyhwm;
  173550. }
  173551. #endif
  173552. /*
  173553. ** Find the appropriate action for a parser given the terminal
  173554. ** look-ahead token iLookAhead.
  173555. */
  173556. static unsigned int fts5yy_find_shift_action(
  173557. fts5yyParser *pParser, /* The parser */
  173558. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  173559. ){
  173560. int i;
  173561. int stateno = pParser->fts5yytos->stateno;
  173562. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  173563. assert( stateno <= fts5YY_SHIFT_COUNT );
  173564. do{
  173565. i = fts5yy_shift_ofst[stateno];
  173566. assert( iLookAhead!=fts5YYNOCODE );
  173567. i += iLookAhead;
  173568. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  173569. #ifdef fts5YYFALLBACK
  173570. fts5YYCODETYPE iFallback; /* Fallback token */
  173571. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  173572. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  173573. #ifndef NDEBUG
  173574. if( fts5yyTraceFILE ){
  173575. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  173576. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  173577. }
  173578. #endif
  173579. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  173580. iLookAhead = iFallback;
  173581. continue;
  173582. }
  173583. #endif
  173584. #ifdef fts5YYWILDCARD
  173585. {
  173586. int j = i - iLookAhead + fts5YYWILDCARD;
  173587. if(
  173588. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  173589. j>=0 &&
  173590. #endif
  173591. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  173592. j<fts5YY_ACTTAB_COUNT &&
  173593. #endif
  173594. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  173595. ){
  173596. #ifndef NDEBUG
  173597. if( fts5yyTraceFILE ){
  173598. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  173599. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  173600. fts5yyTokenName[fts5YYWILDCARD]);
  173601. }
  173602. #endif /* NDEBUG */
  173603. return fts5yy_action[j];
  173604. }
  173605. }
  173606. #endif /* fts5YYWILDCARD */
  173607. return fts5yy_default[stateno];
  173608. }else{
  173609. return fts5yy_action[i];
  173610. }
  173611. }while(1);
  173612. }
  173613. /*
  173614. ** Find the appropriate action for a parser given the non-terminal
  173615. ** look-ahead token iLookAhead.
  173616. */
  173617. static int fts5yy_find_reduce_action(
  173618. int stateno, /* Current state number */
  173619. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  173620. ){
  173621. int i;
  173622. #ifdef fts5YYERRORSYMBOL
  173623. if( stateno>fts5YY_REDUCE_COUNT ){
  173624. return fts5yy_default[stateno];
  173625. }
  173626. #else
  173627. assert( stateno<=fts5YY_REDUCE_COUNT );
  173628. #endif
  173629. i = fts5yy_reduce_ofst[stateno];
  173630. assert( i!=fts5YY_REDUCE_USE_DFLT );
  173631. assert( iLookAhead!=fts5YYNOCODE );
  173632. i += iLookAhead;
  173633. #ifdef fts5YYERRORSYMBOL
  173634. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  173635. return fts5yy_default[stateno];
  173636. }
  173637. #else
  173638. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  173639. assert( fts5yy_lookahead[i]==iLookAhead );
  173640. #endif
  173641. return fts5yy_action[i];
  173642. }
  173643. /*
  173644. ** The following routine is called if the stack overflows.
  173645. */
  173646. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  173647. sqlite3Fts5ParserARG_FETCH;
  173648. #ifndef NDEBUG
  173649. if( fts5yyTraceFILE ){
  173650. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  173651. }
  173652. #endif
  173653. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  173654. /* Here code is inserted which will execute if the parser
  173655. ** stack every overflows */
  173656. /******** Begin %stack_overflow code ******************************************/
  173657. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  173658. /******** End %stack_overflow code ********************************************/
  173659. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  173660. }
  173661. /*
  173662. ** Print tracing information for a SHIFT action
  173663. */
  173664. #ifndef NDEBUG
  173665. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  173666. if( fts5yyTraceFILE ){
  173667. if( fts5yyNewState<fts5YYNSTATE ){
  173668. fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
  173669. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
  173670. fts5yyNewState);
  173671. }else{
  173672. fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
  173673. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
  173674. }
  173675. }
  173676. }
  173677. #else
  173678. # define fts5yyTraceShift(X,Y)
  173679. #endif
  173680. /*
  173681. ** Perform a shift action.
  173682. */
  173683. static void fts5yy_shift(
  173684. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  173685. int fts5yyNewState, /* The new state to shift in */
  173686. int fts5yyMajor, /* The major token to shift in */
  173687. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  173688. ){
  173689. fts5yyStackEntry *fts5yytos;
  173690. fts5yypParser->fts5yytos++;
  173691. #ifdef fts5YYTRACKMAXSTACKDEPTH
  173692. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  173693. fts5yypParser->fts5yyhwm++;
  173694. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  173695. }
  173696. #endif
  173697. #if fts5YYSTACKDEPTH>0
  173698. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  173699. fts5yypParser->fts5yytos--;
  173700. fts5yyStackOverflow(fts5yypParser);
  173701. return;
  173702. }
  173703. #else
  173704. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  173705. if( fts5yyGrowStack(fts5yypParser) ){
  173706. fts5yypParser->fts5yytos--;
  173707. fts5yyStackOverflow(fts5yypParser);
  173708. return;
  173709. }
  173710. }
  173711. #endif
  173712. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  173713. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  173714. }
  173715. fts5yytos = fts5yypParser->fts5yytos;
  173716. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  173717. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  173718. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  173719. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  173720. }
  173721. /* The following table contains information about every rule that
  173722. ** is used during the reduce.
  173723. */
  173724. static const struct {
  173725. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  173726. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  173727. } fts5yyRuleInfo[] = {
  173728. { 16, -1 },
  173729. { 20, -4 },
  173730. { 20, -3 },
  173731. { 20, -1 },
  173732. { 20, -2 },
  173733. { 21, -2 },
  173734. { 21, -1 },
  173735. { 17, -3 },
  173736. { 17, -3 },
  173737. { 17, -3 },
  173738. { 17, -5 },
  173739. { 17, -3 },
  173740. { 17, -1 },
  173741. { 19, -1 },
  173742. { 19, -2 },
  173743. { 18, -1 },
  173744. { 18, -3 },
  173745. { 22, -1 },
  173746. { 22, -5 },
  173747. { 23, -1 },
  173748. { 23, -2 },
  173749. { 25, 0 },
  173750. { 25, -2 },
  173751. { 24, -4 },
  173752. { 24, -2 },
  173753. { 26, -1 },
  173754. { 26, 0 },
  173755. };
  173756. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  173757. /*
  173758. ** Perform a reduce action and the shift that must immediately
  173759. ** follow the reduce.
  173760. */
  173761. static void fts5yy_reduce(
  173762. fts5yyParser *fts5yypParser, /* The parser */
  173763. unsigned int fts5yyruleno /* Number of the rule by which to reduce */
  173764. ){
  173765. int fts5yygoto; /* The next state */
  173766. int fts5yyact; /* The next action */
  173767. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  173768. int fts5yysize; /* Amount to pop the stack */
  173769. sqlite3Fts5ParserARG_FETCH;
  173770. fts5yymsp = fts5yypParser->fts5yytos;
  173771. #ifndef NDEBUG
  173772. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  173773. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  173774. fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
  173775. fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  173776. }
  173777. #endif /* NDEBUG */
  173778. /* Check that the stack is large enough to grow by a single entry
  173779. ** if the RHS of the rule is empty. This ensures that there is room
  173780. ** enough on the stack to push the LHS value */
  173781. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  173782. #ifdef fts5YYTRACKMAXSTACKDEPTH
  173783. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  173784. fts5yypParser->fts5yyhwm++;
  173785. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  173786. }
  173787. #endif
  173788. #if fts5YYSTACKDEPTH>0
  173789. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  173790. fts5yyStackOverflow(fts5yypParser);
  173791. return;
  173792. }
  173793. #else
  173794. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  173795. if( fts5yyGrowStack(fts5yypParser) ){
  173796. fts5yyStackOverflow(fts5yypParser);
  173797. return;
  173798. }
  173799. fts5yymsp = fts5yypParser->fts5yytos;
  173800. }
  173801. #endif
  173802. }
  173803. switch( fts5yyruleno ){
  173804. /* Beginning here are the reduction cases. A typical example
  173805. ** follows:
  173806. ** case 0:
  173807. ** #line <lineno> <grammarfile>
  173808. ** { ... } // User supplied code
  173809. ** #line <lineno> <thisfile>
  173810. ** break;
  173811. */
  173812. /********** Begin reduce actions **********************************************/
  173813. fts5YYMINORTYPE fts5yylhsminor;
  173814. case 0: /* input ::= expr */
  173815. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  173816. break;
  173817. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  173818. {
  173819. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  173820. }
  173821. break;
  173822. case 2: /* colset ::= LCP colsetlist RCP */
  173823. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  173824. break;
  173825. case 3: /* colset ::= STRING */
  173826. {
  173827. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  173828. }
  173829. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  173830. break;
  173831. case 4: /* colset ::= MINUS STRING */
  173832. {
  173833. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  173834. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  173835. }
  173836. break;
  173837. case 5: /* colsetlist ::= colsetlist STRING */
  173838. {
  173839. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  173840. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  173841. break;
  173842. case 6: /* colsetlist ::= STRING */
  173843. {
  173844. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  173845. }
  173846. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  173847. break;
  173848. case 7: /* expr ::= expr AND expr */
  173849. {
  173850. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  173851. }
  173852. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173853. break;
  173854. case 8: /* expr ::= expr OR expr */
  173855. {
  173856. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  173857. }
  173858. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173859. break;
  173860. case 9: /* expr ::= expr NOT expr */
  173861. {
  173862. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  173863. }
  173864. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173865. break;
  173866. case 10: /* expr ::= colset COLON LP expr RP */
  173867. {
  173868. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  173869. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  173870. }
  173871. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173872. break;
  173873. case 11: /* expr ::= LP expr RP */
  173874. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  173875. break;
  173876. case 12: /* expr ::= exprlist */
  173877. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  173878. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  173879. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173880. break;
  173881. case 14: /* exprlist ::= exprlist cnearset */
  173882. {
  173883. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  173884. }
  173885. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173886. break;
  173887. case 15: /* cnearset ::= nearset */
  173888. {
  173889. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  173890. }
  173891. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173892. break;
  173893. case 16: /* cnearset ::= colset COLON nearset */
  173894. {
  173895. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  173896. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  173897. }
  173898. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  173899. break;
  173900. case 17: /* nearset ::= phrase */
  173901. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  173902. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  173903. break;
  173904. case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  173905. {
  173906. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  173907. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  173908. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  173909. }
  173910. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  173911. break;
  173912. case 19: /* nearphrases ::= phrase */
  173913. {
  173914. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  173915. }
  173916. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  173917. break;
  173918. case 20: /* nearphrases ::= nearphrases phrase */
  173919. {
  173920. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  173921. }
  173922. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  173923. break;
  173924. case 21: /* neardist_opt ::= */
  173925. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  173926. break;
  173927. case 22: /* neardist_opt ::= COMMA STRING */
  173928. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  173929. break;
  173930. case 23: /* phrase ::= phrase PLUS STRING star_opt */
  173931. {
  173932. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  173933. }
  173934. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  173935. break;
  173936. case 24: /* phrase ::= STRING star_opt */
  173937. {
  173938. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  173939. }
  173940. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  173941. break;
  173942. case 25: /* star_opt ::= STAR */
  173943. { fts5yymsp[0].minor.fts5yy4 = 1; }
  173944. break;
  173945. case 26: /* star_opt ::= */
  173946. { fts5yymsp[1].minor.fts5yy4 = 0; }
  173947. break;
  173948. default:
  173949. break;
  173950. /********** End reduce actions ************************************************/
  173951. };
  173952. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  173953. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  173954. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  173955. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  173956. /* There are no SHIFTREDUCE actions on nonterminals because the table
  173957. ** generator has simplified them to pure REDUCE actions. */
  173958. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  173959. /* It is not possible for a REDUCE to be followed by an error */
  173960. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  173961. if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  173962. fts5yypParser->fts5yytos += fts5yysize;
  173963. fts5yy_accept(fts5yypParser);
  173964. }else{
  173965. fts5yymsp += fts5yysize+1;
  173966. fts5yypParser->fts5yytos = fts5yymsp;
  173967. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  173968. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  173969. fts5yyTraceShift(fts5yypParser, fts5yyact);
  173970. }
  173971. }
  173972. /*
  173973. ** The following code executes when the parse fails
  173974. */
  173975. #ifndef fts5YYNOERRORRECOVERY
  173976. static void fts5yy_parse_failed(
  173977. fts5yyParser *fts5yypParser /* The parser */
  173978. ){
  173979. sqlite3Fts5ParserARG_FETCH;
  173980. #ifndef NDEBUG
  173981. if( fts5yyTraceFILE ){
  173982. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  173983. }
  173984. #endif
  173985. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  173986. /* Here code is inserted which will be executed whenever the
  173987. ** parser fails */
  173988. /************ Begin %parse_failure code ***************************************/
  173989. /************ End %parse_failure code *****************************************/
  173990. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  173991. }
  173992. #endif /* fts5YYNOERRORRECOVERY */
  173993. /*
  173994. ** The following code executes when a syntax error first occurs.
  173995. */
  173996. static void fts5yy_syntax_error(
  173997. fts5yyParser *fts5yypParser, /* The parser */
  173998. int fts5yymajor, /* The major type of the error token */
  173999. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  174000. ){
  174001. sqlite3Fts5ParserARG_FETCH;
  174002. #define FTS5TOKEN fts5yyminor
  174003. /************ Begin %syntax_error code ****************************************/
  174004. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  174005. sqlite3Fts5ParseError(
  174006. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  174007. );
  174008. /************ End %syntax_error code ******************************************/
  174009. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  174010. }
  174011. /*
  174012. ** The following is executed when the parser accepts
  174013. */
  174014. static void fts5yy_accept(
  174015. fts5yyParser *fts5yypParser /* The parser */
  174016. ){
  174017. sqlite3Fts5ParserARG_FETCH;
  174018. #ifndef NDEBUG
  174019. if( fts5yyTraceFILE ){
  174020. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  174021. }
  174022. #endif
  174023. #ifndef fts5YYNOERRORRECOVERY
  174024. fts5yypParser->fts5yyerrcnt = -1;
  174025. #endif
  174026. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  174027. /* Here code is inserted which will be executed whenever the
  174028. ** parser accepts */
  174029. /*********** Begin %parse_accept code *****************************************/
  174030. /*********** End %parse_accept code *******************************************/
  174031. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  174032. }
  174033. /* The main parser program.
  174034. ** The first argument is a pointer to a structure obtained from
  174035. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  174036. ** The second argument is the major token number. The third is
  174037. ** the minor token. The fourth optional argument is whatever the
  174038. ** user wants (and specified in the grammar) and is available for
  174039. ** use by the action routines.
  174040. **
  174041. ** Inputs:
  174042. ** <ul>
  174043. ** <li> A pointer to the parser (an opaque structure.)
  174044. ** <li> The major token number.
  174045. ** <li> The minor token number.
  174046. ** <li> An option argument of a grammar-specified type.
  174047. ** </ul>
  174048. **
  174049. ** Outputs:
  174050. ** None.
  174051. */
  174052. static void sqlite3Fts5Parser(
  174053. void *fts5yyp, /* The parser */
  174054. int fts5yymajor, /* The major token code number */
  174055. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  174056. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  174057. ){
  174058. fts5YYMINORTYPE fts5yyminorunion;
  174059. unsigned int fts5yyact; /* The parser action. */
  174060. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  174061. int fts5yyendofinput; /* True if we are at the end of input */
  174062. #endif
  174063. #ifdef fts5YYERRORSYMBOL
  174064. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  174065. #endif
  174066. fts5yyParser *fts5yypParser; /* The parser */
  174067. fts5yypParser = (fts5yyParser*)fts5yyp;
  174068. assert( fts5yypParser->fts5yytos!=0 );
  174069. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  174070. fts5yyendofinput = (fts5yymajor==0);
  174071. #endif
  174072. sqlite3Fts5ParserARG_STORE;
  174073. #ifndef NDEBUG
  174074. if( fts5yyTraceFILE ){
  174075. fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  174076. }
  174077. #endif
  174078. do{
  174079. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  174080. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  174081. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  174082. #ifndef fts5YYNOERRORRECOVERY
  174083. fts5yypParser->fts5yyerrcnt--;
  174084. #endif
  174085. fts5yymajor = fts5YYNOCODE;
  174086. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  174087. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  174088. }else{
  174089. assert( fts5yyact == fts5YY_ERROR_ACTION );
  174090. fts5yyminorunion.fts5yy0 = fts5yyminor;
  174091. #ifdef fts5YYERRORSYMBOL
  174092. int fts5yymx;
  174093. #endif
  174094. #ifndef NDEBUG
  174095. if( fts5yyTraceFILE ){
  174096. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  174097. }
  174098. #endif
  174099. #ifdef fts5YYERRORSYMBOL
  174100. /* A syntax error has occurred.
  174101. ** The response to an error depends upon whether or not the
  174102. ** grammar defines an error token "ERROR".
  174103. **
  174104. ** This is what we do if the grammar does define ERROR:
  174105. **
  174106. ** * Call the %syntax_error function.
  174107. **
  174108. ** * Begin popping the stack until we enter a state where
  174109. ** it is legal to shift the error symbol, then shift
  174110. ** the error symbol.
  174111. **
  174112. ** * Set the error count to three.
  174113. **
  174114. ** * Begin accepting and shifting new tokens. No new error
  174115. ** processing will occur until three tokens have been
  174116. ** shifted successfully.
  174117. **
  174118. */
  174119. if( fts5yypParser->fts5yyerrcnt<0 ){
  174120. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  174121. }
  174122. fts5yymx = fts5yypParser->fts5yytos->major;
  174123. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  174124. #ifndef NDEBUG
  174125. if( fts5yyTraceFILE ){
  174126. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  174127. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  174128. }
  174129. #endif
  174130. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  174131. fts5yymajor = fts5YYNOCODE;
  174132. }else{
  174133. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  174134. && fts5yymx != fts5YYERRORSYMBOL
  174135. && (fts5yyact = fts5yy_find_reduce_action(
  174136. fts5yypParser->fts5yytos->stateno,
  174137. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  174138. ){
  174139. fts5yy_pop_parser_stack(fts5yypParser);
  174140. }
  174141. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  174142. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  174143. fts5yy_parse_failed(fts5yypParser);
  174144. #ifndef fts5YYNOERRORRECOVERY
  174145. fts5yypParser->fts5yyerrcnt = -1;
  174146. #endif
  174147. fts5yymajor = fts5YYNOCODE;
  174148. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  174149. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  174150. }
  174151. }
  174152. fts5yypParser->fts5yyerrcnt = 3;
  174153. fts5yyerrorhit = 1;
  174154. #elif defined(fts5YYNOERRORRECOVERY)
  174155. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  174156. ** do any kind of error recovery. Instead, simply invoke the syntax
  174157. ** error routine and continue going as if nothing had happened.
  174158. **
  174159. ** Applications can set this macro (for example inside %include) if
  174160. ** they intend to abandon the parse upon the first syntax error seen.
  174161. */
  174162. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  174163. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  174164. fts5yymajor = fts5YYNOCODE;
  174165. #else /* fts5YYERRORSYMBOL is not defined */
  174166. /* This is what we do if the grammar does not define ERROR:
  174167. **
  174168. ** * Report an error message, and throw away the input token.
  174169. **
  174170. ** * If the input token is $, then fail the parse.
  174171. **
  174172. ** As before, subsequent error messages are suppressed until
  174173. ** three input tokens have been successfully shifted.
  174174. */
  174175. if( fts5yypParser->fts5yyerrcnt<=0 ){
  174176. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  174177. }
  174178. fts5yypParser->fts5yyerrcnt = 3;
  174179. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  174180. if( fts5yyendofinput ){
  174181. fts5yy_parse_failed(fts5yypParser);
  174182. #ifndef fts5YYNOERRORRECOVERY
  174183. fts5yypParser->fts5yyerrcnt = -1;
  174184. #endif
  174185. }
  174186. fts5yymajor = fts5YYNOCODE;
  174187. #endif
  174188. }
  174189. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  174190. #ifndef NDEBUG
  174191. if( fts5yyTraceFILE ){
  174192. fts5yyStackEntry *i;
  174193. char cDiv = '[';
  174194. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  174195. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  174196. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  174197. cDiv = ' ';
  174198. }
  174199. fprintf(fts5yyTraceFILE,"]\n");
  174200. }
  174201. #endif
  174202. return;
  174203. }
  174204. /*
  174205. ** 2014 May 31
  174206. **
  174207. ** The author disclaims copyright to this source code. In place of
  174208. ** a legal notice, here is a blessing:
  174209. **
  174210. ** May you do good and not evil.
  174211. ** May you find forgiveness for yourself and forgive others.
  174212. ** May you share freely, never taking more than you give.
  174213. **
  174214. ******************************************************************************
  174215. */
  174216. /* #include "fts5Int.h" */
  174217. #include <math.h> /* amalgamator: keep */
  174218. /*
  174219. ** Object used to iterate through all "coalesced phrase instances" in
  174220. ** a single column of the current row. If the phrase instances in the
  174221. ** column being considered do not overlap, this object simply iterates
  174222. ** through them. Or, if they do overlap (share one or more tokens in
  174223. ** common), each set of overlapping instances is treated as a single
  174224. ** match. See documentation for the highlight() auxiliary function for
  174225. ** details.
  174226. **
  174227. ** Usage is:
  174228. **
  174229. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  174230. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  174231. ** rc = fts5CInstIterNext(&iter)
  174232. ** ){
  174233. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  174234. ** }
  174235. **
  174236. */
  174237. typedef struct CInstIter CInstIter;
  174238. struct CInstIter {
  174239. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  174240. Fts5Context *pFts; /* First arg to pass to pApi functions */
  174241. int iCol; /* Column to search */
  174242. int iInst; /* Next phrase instance index */
  174243. int nInst; /* Total number of phrase instances */
  174244. /* Output variables */
  174245. int iStart; /* First token in coalesced phrase instance */
  174246. int iEnd; /* Last token in coalesced phrase instance */
  174247. };
  174248. /*
  174249. ** Advance the iterator to the next coalesced phrase instance. Return
  174250. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  174251. */
  174252. static int fts5CInstIterNext(CInstIter *pIter){
  174253. int rc = SQLITE_OK;
  174254. pIter->iStart = -1;
  174255. pIter->iEnd = -1;
  174256. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  174257. int ip; int ic; int io;
  174258. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  174259. if( rc==SQLITE_OK ){
  174260. if( ic==pIter->iCol ){
  174261. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  174262. if( pIter->iStart<0 ){
  174263. pIter->iStart = io;
  174264. pIter->iEnd = iEnd;
  174265. }else if( io<=pIter->iEnd ){
  174266. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  174267. }else{
  174268. break;
  174269. }
  174270. }
  174271. pIter->iInst++;
  174272. }
  174273. }
  174274. return rc;
  174275. }
  174276. /*
  174277. ** Initialize the iterator object indicated by the final parameter to
  174278. ** iterate through coalesced phrase instances in column iCol.
  174279. */
  174280. static int fts5CInstIterInit(
  174281. const Fts5ExtensionApi *pApi,
  174282. Fts5Context *pFts,
  174283. int iCol,
  174284. CInstIter *pIter
  174285. ){
  174286. int rc;
  174287. memset(pIter, 0, sizeof(CInstIter));
  174288. pIter->pApi = pApi;
  174289. pIter->pFts = pFts;
  174290. pIter->iCol = iCol;
  174291. rc = pApi->xInstCount(pFts, &pIter->nInst);
  174292. if( rc==SQLITE_OK ){
  174293. rc = fts5CInstIterNext(pIter);
  174294. }
  174295. return rc;
  174296. }
  174297. /*************************************************************************
  174298. ** Start of highlight() implementation.
  174299. */
  174300. typedef struct HighlightContext HighlightContext;
  174301. struct HighlightContext {
  174302. CInstIter iter; /* Coalesced Instance Iterator */
  174303. int iPos; /* Current token offset in zIn[] */
  174304. int iRangeStart; /* First token to include */
  174305. int iRangeEnd; /* If non-zero, last token to include */
  174306. const char *zOpen; /* Opening highlight */
  174307. const char *zClose; /* Closing highlight */
  174308. const char *zIn; /* Input text */
  174309. int nIn; /* Size of input text in bytes */
  174310. int iOff; /* Current offset within zIn[] */
  174311. char *zOut; /* Output value */
  174312. };
  174313. /*
  174314. ** Append text to the HighlightContext output string - p->zOut. Argument
  174315. ** z points to a buffer containing n bytes of text to append. If n is
  174316. ** negative, everything up until the first '\0' is appended to the output.
  174317. **
  174318. ** If *pRc is set to any value other than SQLITE_OK when this function is
  174319. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  174320. ** *pRc is set to an error code before returning.
  174321. */
  174322. static void fts5HighlightAppend(
  174323. int *pRc,
  174324. HighlightContext *p,
  174325. const char *z, int n
  174326. ){
  174327. if( *pRc==SQLITE_OK ){
  174328. if( n<0 ) n = (int)strlen(z);
  174329. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  174330. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  174331. }
  174332. }
  174333. /*
  174334. ** Tokenizer callback used by implementation of highlight() function.
  174335. */
  174336. static int fts5HighlightCb(
  174337. void *pContext, /* Pointer to HighlightContext object */
  174338. int tflags, /* Mask of FTS5_TOKEN_* flags */
  174339. const char *pToken, /* Buffer containing token */
  174340. int nToken, /* Size of token in bytes */
  174341. int iStartOff, /* Start offset of token */
  174342. int iEndOff /* End offset of token */
  174343. ){
  174344. HighlightContext *p = (HighlightContext*)pContext;
  174345. int rc = SQLITE_OK;
  174346. int iPos;
  174347. UNUSED_PARAM2(pToken, nToken);
  174348. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  174349. iPos = p->iPos++;
  174350. if( p->iRangeEnd>0 ){
  174351. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  174352. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  174353. }
  174354. if( iPos==p->iter.iStart ){
  174355. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  174356. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  174357. p->iOff = iStartOff;
  174358. }
  174359. if( iPos==p->iter.iEnd ){
  174360. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  174361. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  174362. }
  174363. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  174364. fts5HighlightAppend(&rc, p, p->zClose, -1);
  174365. p->iOff = iEndOff;
  174366. if( rc==SQLITE_OK ){
  174367. rc = fts5CInstIterNext(&p->iter);
  174368. }
  174369. }
  174370. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  174371. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  174372. p->iOff = iEndOff;
  174373. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  174374. fts5HighlightAppend(&rc, p, p->zClose, -1);
  174375. }
  174376. }
  174377. return rc;
  174378. }
  174379. /*
  174380. ** Implementation of highlight() function.
  174381. */
  174382. static void fts5HighlightFunction(
  174383. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  174384. Fts5Context *pFts, /* First arg to pass to pApi functions */
  174385. sqlite3_context *pCtx, /* Context for returning result/error */
  174386. int nVal, /* Number of values in apVal[] array */
  174387. sqlite3_value **apVal /* Array of trailing arguments */
  174388. ){
  174389. HighlightContext ctx;
  174390. int rc;
  174391. int iCol;
  174392. if( nVal!=3 ){
  174393. const char *zErr = "wrong number of arguments to function highlight()";
  174394. sqlite3_result_error(pCtx, zErr, -1);
  174395. return;
  174396. }
  174397. iCol = sqlite3_value_int(apVal[0]);
  174398. memset(&ctx, 0, sizeof(HighlightContext));
  174399. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  174400. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  174401. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  174402. if( ctx.zIn ){
  174403. if( rc==SQLITE_OK ){
  174404. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  174405. }
  174406. if( rc==SQLITE_OK ){
  174407. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  174408. }
  174409. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  174410. if( rc==SQLITE_OK ){
  174411. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  174412. }
  174413. sqlite3_free(ctx.zOut);
  174414. }
  174415. if( rc!=SQLITE_OK ){
  174416. sqlite3_result_error_code(pCtx, rc);
  174417. }
  174418. }
  174419. /*
  174420. ** End of highlight() implementation.
  174421. **************************************************************************/
  174422. /*
  174423. ** Context object passed to the fts5SentenceFinderCb() function.
  174424. */
  174425. typedef struct Fts5SFinder Fts5SFinder;
  174426. struct Fts5SFinder {
  174427. int iPos; /* Current token position */
  174428. int nFirstAlloc; /* Allocated size of aFirst[] */
  174429. int nFirst; /* Number of entries in aFirst[] */
  174430. int *aFirst; /* Array of first token in each sentence */
  174431. const char *zDoc; /* Document being tokenized */
  174432. };
  174433. /*
  174434. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  174435. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  174436. ** error occurs.
  174437. */
  174438. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  174439. if( p->nFirstAlloc==p->nFirst ){
  174440. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  174441. int *aNew;
  174442. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  174443. if( aNew==0 ) return SQLITE_NOMEM;
  174444. p->aFirst = aNew;
  174445. p->nFirstAlloc = nNew;
  174446. }
  174447. p->aFirst[p->nFirst++] = iAdd;
  174448. return SQLITE_OK;
  174449. }
  174450. /*
  174451. ** This function is an xTokenize() callback used by the auxiliary snippet()
  174452. ** function. Its job is to identify tokens that are the first in a sentence.
  174453. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  174454. */
  174455. static int fts5SentenceFinderCb(
  174456. void *pContext, /* Pointer to HighlightContext object */
  174457. int tflags, /* Mask of FTS5_TOKEN_* flags */
  174458. const char *pToken, /* Buffer containing token */
  174459. int nToken, /* Size of token in bytes */
  174460. int iStartOff, /* Start offset of token */
  174461. int iEndOff /* End offset of token */
  174462. ){
  174463. int rc = SQLITE_OK;
  174464. UNUSED_PARAM2(pToken, nToken);
  174465. UNUSED_PARAM(iEndOff);
  174466. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  174467. Fts5SFinder *p = (Fts5SFinder*)pContext;
  174468. if( p->iPos>0 ){
  174469. int i;
  174470. char c = 0;
  174471. for(i=iStartOff-1; i>=0; i--){
  174472. c = p->zDoc[i];
  174473. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  174474. }
  174475. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  174476. rc = fts5SentenceFinderAdd(p, p->iPos);
  174477. }
  174478. }else{
  174479. rc = fts5SentenceFinderAdd(p, 0);
  174480. }
  174481. p->iPos++;
  174482. }
  174483. return rc;
  174484. }
  174485. static int fts5SnippetScore(
  174486. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  174487. Fts5Context *pFts, /* First arg to pass to pApi functions */
  174488. int nDocsize, /* Size of column in tokens */
  174489. unsigned char *aSeen, /* Array with one element per query phrase */
  174490. int iCol, /* Column to score */
  174491. int iPos, /* Starting offset to score */
  174492. int nToken, /* Max tokens per snippet */
  174493. int *pnScore, /* OUT: Score */
  174494. int *piPos /* OUT: Adjusted offset */
  174495. ){
  174496. int rc;
  174497. int i;
  174498. int ip = 0;
  174499. int ic = 0;
  174500. int iOff = 0;
  174501. int iFirst = -1;
  174502. int nInst;
  174503. int nScore = 0;
  174504. int iLast = 0;
  174505. rc = pApi->xInstCount(pFts, &nInst);
  174506. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  174507. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  174508. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  174509. nScore += (aSeen[ip] ? 1 : 1000);
  174510. aSeen[ip] = 1;
  174511. if( iFirst<0 ) iFirst = iOff;
  174512. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  174513. }
  174514. }
  174515. *pnScore = nScore;
  174516. if( piPos ){
  174517. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  174518. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  174519. if( iAdj<0 ) iAdj = 0;
  174520. *piPos = iAdj;
  174521. }
  174522. return rc;
  174523. }
  174524. /*
  174525. ** Implementation of snippet() function.
  174526. */
  174527. static void fts5SnippetFunction(
  174528. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  174529. Fts5Context *pFts, /* First arg to pass to pApi functions */
  174530. sqlite3_context *pCtx, /* Context for returning result/error */
  174531. int nVal, /* Number of values in apVal[] array */
  174532. sqlite3_value **apVal /* Array of trailing arguments */
  174533. ){
  174534. HighlightContext ctx;
  174535. int rc = SQLITE_OK; /* Return code */
  174536. int iCol; /* 1st argument to snippet() */
  174537. const char *zEllips; /* 4th argument to snippet() */
  174538. int nToken; /* 5th argument to snippet() */
  174539. int nInst = 0; /* Number of instance matches this row */
  174540. int i; /* Used to iterate through instances */
  174541. int nPhrase; /* Number of phrases in query */
  174542. unsigned char *aSeen; /* Array of "seen instance" flags */
  174543. int iBestCol; /* Column containing best snippet */
  174544. int iBestStart = 0; /* First token of best snippet */
  174545. int nBestScore = 0; /* Score of best snippet */
  174546. int nColSize = 0; /* Total size of iBestCol in tokens */
  174547. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  174548. int nCol;
  174549. if( nVal!=5 ){
  174550. const char *zErr = "wrong number of arguments to function snippet()";
  174551. sqlite3_result_error(pCtx, zErr, -1);
  174552. return;
  174553. }
  174554. nCol = pApi->xColumnCount(pFts);
  174555. memset(&ctx, 0, sizeof(HighlightContext));
  174556. iCol = sqlite3_value_int(apVal[0]);
  174557. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  174558. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  174559. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  174560. nToken = sqlite3_value_int(apVal[4]);
  174561. iBestCol = (iCol>=0 ? iCol : 0);
  174562. nPhrase = pApi->xPhraseCount(pFts);
  174563. aSeen = sqlite3_malloc(nPhrase);
  174564. if( aSeen==0 ){
  174565. rc = SQLITE_NOMEM;
  174566. }
  174567. if( rc==SQLITE_OK ){
  174568. rc = pApi->xInstCount(pFts, &nInst);
  174569. }
  174570. memset(&sFinder, 0, sizeof(Fts5SFinder));
  174571. for(i=0; i<nCol; i++){
  174572. if( iCol<0 || iCol==i ){
  174573. int nDoc;
  174574. int nDocsize;
  174575. int ii;
  174576. sFinder.iPos = 0;
  174577. sFinder.nFirst = 0;
  174578. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  174579. if( rc!=SQLITE_OK ) break;
  174580. rc = pApi->xTokenize(pFts,
  174581. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  174582. );
  174583. if( rc!=SQLITE_OK ) break;
  174584. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  174585. if( rc!=SQLITE_OK ) break;
  174586. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  174587. int ip, ic, io;
  174588. int iAdj;
  174589. int nScore;
  174590. int jj;
  174591. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  174592. if( ic!=i || rc!=SQLITE_OK ) continue;
  174593. memset(aSeen, 0, nPhrase);
  174594. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  174595. io, nToken, &nScore, &iAdj
  174596. );
  174597. if( rc==SQLITE_OK && nScore>nBestScore ){
  174598. nBestScore = nScore;
  174599. iBestCol = i;
  174600. iBestStart = iAdj;
  174601. nColSize = nDocsize;
  174602. }
  174603. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  174604. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  174605. if( sFinder.aFirst[jj+1]>io ) break;
  174606. }
  174607. if( sFinder.aFirst[jj]<io ){
  174608. memset(aSeen, 0, nPhrase);
  174609. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  174610. sFinder.aFirst[jj], nToken, &nScore, 0
  174611. );
  174612. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  174613. if( rc==SQLITE_OK && nScore>nBestScore ){
  174614. nBestScore = nScore;
  174615. iBestCol = i;
  174616. iBestStart = sFinder.aFirst[jj];
  174617. nColSize = nDocsize;
  174618. }
  174619. }
  174620. }
  174621. }
  174622. }
  174623. }
  174624. if( rc==SQLITE_OK ){
  174625. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  174626. }
  174627. if( rc==SQLITE_OK && nColSize==0 ){
  174628. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  174629. }
  174630. if( ctx.zIn ){
  174631. if( rc==SQLITE_OK ){
  174632. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  174633. }
  174634. ctx.iRangeStart = iBestStart;
  174635. ctx.iRangeEnd = iBestStart + nToken - 1;
  174636. if( iBestStart>0 ){
  174637. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  174638. }
  174639. /* Advance iterator ctx.iter so that it points to the first coalesced
  174640. ** phrase instance at or following position iBestStart. */
  174641. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  174642. rc = fts5CInstIterNext(&ctx.iter);
  174643. }
  174644. if( rc==SQLITE_OK ){
  174645. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  174646. }
  174647. if( ctx.iRangeEnd>=(nColSize-1) ){
  174648. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  174649. }else{
  174650. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  174651. }
  174652. }
  174653. if( rc==SQLITE_OK ){
  174654. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  174655. }else{
  174656. sqlite3_result_error_code(pCtx, rc);
  174657. }
  174658. sqlite3_free(ctx.zOut);
  174659. sqlite3_free(aSeen);
  174660. sqlite3_free(sFinder.aFirst);
  174661. }
  174662. /************************************************************************/
  174663. /*
  174664. ** The first time the bm25() function is called for a query, an instance
  174665. ** of the following structure is allocated and populated.
  174666. */
  174667. typedef struct Fts5Bm25Data Fts5Bm25Data;
  174668. struct Fts5Bm25Data {
  174669. int nPhrase; /* Number of phrases in query */
  174670. double avgdl; /* Average number of tokens in each row */
  174671. double *aIDF; /* IDF for each phrase */
  174672. double *aFreq; /* Array used to calculate phrase freq. */
  174673. };
  174674. /*
  174675. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  174676. ** table matched by each individual phrase within the query.
  174677. */
  174678. static int fts5CountCb(
  174679. const Fts5ExtensionApi *pApi,
  174680. Fts5Context *pFts,
  174681. void *pUserData /* Pointer to sqlite3_int64 variable */
  174682. ){
  174683. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  174684. UNUSED_PARAM2(pApi, pFts);
  174685. (*pn)++;
  174686. return SQLITE_OK;
  174687. }
  174688. /*
  174689. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  174690. ** If the object has not already been allocated, allocate and populate it
  174691. ** now.
  174692. */
  174693. static int fts5Bm25GetData(
  174694. const Fts5ExtensionApi *pApi,
  174695. Fts5Context *pFts,
  174696. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  174697. ){
  174698. int rc = SQLITE_OK; /* Return code */
  174699. Fts5Bm25Data *p; /* Object to return */
  174700. p = pApi->xGetAuxdata(pFts, 0);
  174701. if( p==0 ){
  174702. int nPhrase; /* Number of phrases in query */
  174703. sqlite3_int64 nRow = 0; /* Number of rows in table */
  174704. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  174705. int nByte; /* Bytes of space to allocate */
  174706. int i;
  174707. /* Allocate the Fts5Bm25Data object */
  174708. nPhrase = pApi->xPhraseCount(pFts);
  174709. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  174710. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  174711. if( p==0 ){
  174712. rc = SQLITE_NOMEM;
  174713. }else{
  174714. memset(p, 0, nByte);
  174715. p->nPhrase = nPhrase;
  174716. p->aIDF = (double*)&p[1];
  174717. p->aFreq = &p->aIDF[nPhrase];
  174718. }
  174719. /* Calculate the average document length for this FTS5 table */
  174720. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  174721. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  174722. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  174723. /* Calculate an IDF for each phrase in the query */
  174724. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  174725. sqlite3_int64 nHit = 0;
  174726. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  174727. if( rc==SQLITE_OK ){
  174728. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  174729. ** This is done using the standard BM25 formula as found on wikipedia:
  174730. **
  174731. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  174732. **
  174733. ** where "N" is the total number of documents in the set and nHit
  174734. ** is the number that contain at least one instance of the phrase
  174735. ** under consideration.
  174736. **
  174737. ** The problem with this is that if (N < 2*nHit), the IDF is
  174738. ** negative. Which is undesirable. So the mimimum allowable IDF is
  174739. ** (1e-6) - roughly the same as a term that appears in just over
  174740. ** half of set of 5,000,000 documents. */
  174741. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  174742. if( idf<=0.0 ) idf = 1e-6;
  174743. p->aIDF[i] = idf;
  174744. }
  174745. }
  174746. if( rc!=SQLITE_OK ){
  174747. sqlite3_free(p);
  174748. }else{
  174749. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  174750. }
  174751. if( rc!=SQLITE_OK ) p = 0;
  174752. }
  174753. *ppData = p;
  174754. return rc;
  174755. }
  174756. /*
  174757. ** Implementation of bm25() function.
  174758. */
  174759. static void fts5Bm25Function(
  174760. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  174761. Fts5Context *pFts, /* First arg to pass to pApi functions */
  174762. sqlite3_context *pCtx, /* Context for returning result/error */
  174763. int nVal, /* Number of values in apVal[] array */
  174764. sqlite3_value **apVal /* Array of trailing arguments */
  174765. ){
  174766. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  174767. const double b = 0.75; /* Constant "b" from BM25 formula */
  174768. int rc = SQLITE_OK; /* Error code */
  174769. double score = 0.0; /* SQL function return value */
  174770. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  174771. int i; /* Iterator variable */
  174772. int nInst = 0; /* Value returned by xInstCount() */
  174773. double D = 0.0; /* Total number of tokens in row */
  174774. double *aFreq = 0; /* Array of phrase freq. for current row */
  174775. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  174776. ** for each phrase in the query for the current row. */
  174777. rc = fts5Bm25GetData(pApi, pFts, &pData);
  174778. if( rc==SQLITE_OK ){
  174779. aFreq = pData->aFreq;
  174780. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  174781. rc = pApi->xInstCount(pFts, &nInst);
  174782. }
  174783. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  174784. int ip; int ic; int io;
  174785. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  174786. if( rc==SQLITE_OK ){
  174787. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  174788. aFreq[ip] += w;
  174789. }
  174790. }
  174791. /* Figure out the total size of the current row in tokens. */
  174792. if( rc==SQLITE_OK ){
  174793. int nTok;
  174794. rc = pApi->xColumnSize(pFts, -1, &nTok);
  174795. D = (double)nTok;
  174796. }
  174797. /* Determine the BM25 score for the current row. */
  174798. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  174799. score += pData->aIDF[i] * (
  174800. ( aFreq[i] * (k1 + 1.0) ) /
  174801. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  174802. );
  174803. }
  174804. /* If no error has occurred, return the calculated score. Otherwise,
  174805. ** throw an SQL exception. */
  174806. if( rc==SQLITE_OK ){
  174807. sqlite3_result_double(pCtx, -1.0 * score);
  174808. }else{
  174809. sqlite3_result_error_code(pCtx, rc);
  174810. }
  174811. }
  174812. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  174813. struct Builtin {
  174814. const char *zFunc; /* Function name (nul-terminated) */
  174815. void *pUserData; /* User-data pointer */
  174816. fts5_extension_function xFunc;/* Callback function */
  174817. void (*xDestroy)(void*); /* Destructor function */
  174818. } aBuiltin [] = {
  174819. { "snippet", 0, fts5SnippetFunction, 0 },
  174820. { "highlight", 0, fts5HighlightFunction, 0 },
  174821. { "bm25", 0, fts5Bm25Function, 0 },
  174822. };
  174823. int rc = SQLITE_OK; /* Return code */
  174824. int i; /* To iterate through builtin functions */
  174825. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  174826. rc = pApi->xCreateFunction(pApi,
  174827. aBuiltin[i].zFunc,
  174828. aBuiltin[i].pUserData,
  174829. aBuiltin[i].xFunc,
  174830. aBuiltin[i].xDestroy
  174831. );
  174832. }
  174833. return rc;
  174834. }
  174835. /*
  174836. ** 2014 May 31
  174837. **
  174838. ** The author disclaims copyright to this source code. In place of
  174839. ** a legal notice, here is a blessing:
  174840. **
  174841. ** May you do good and not evil.
  174842. ** May you find forgiveness for yourself and forgive others.
  174843. ** May you share freely, never taking more than you give.
  174844. **
  174845. ******************************************************************************
  174846. */
  174847. /* #include "fts5Int.h" */
  174848. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  174849. if( (u32)pBuf->nSpace<nByte ){
  174850. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  174851. u8 *pNew;
  174852. while( nNew<nByte ){
  174853. nNew = nNew * 2;
  174854. }
  174855. pNew = sqlite3_realloc(pBuf->p, nNew);
  174856. if( pNew==0 ){
  174857. *pRc = SQLITE_NOMEM;
  174858. return 1;
  174859. }else{
  174860. pBuf->nSpace = nNew;
  174861. pBuf->p = pNew;
  174862. }
  174863. }
  174864. return 0;
  174865. }
  174866. /*
  174867. ** Encode value iVal as an SQLite varint and append it to the buffer object
  174868. ** pBuf. If an OOM error occurs, set the error code in p.
  174869. */
  174870. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  174871. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  174872. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  174873. }
  174874. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  174875. aBuf[0] = (iVal>>24) & 0x00FF;
  174876. aBuf[1] = (iVal>>16) & 0x00FF;
  174877. aBuf[2] = (iVal>> 8) & 0x00FF;
  174878. aBuf[3] = (iVal>> 0) & 0x00FF;
  174879. }
  174880. static int sqlite3Fts5Get32(const u8 *aBuf){
  174881. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  174882. }
  174883. /*
  174884. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  174885. ** the error code in p. If an error has already occurred when this function
  174886. ** is called, it is a no-op.
  174887. */
  174888. static void sqlite3Fts5BufferAppendBlob(
  174889. int *pRc,
  174890. Fts5Buffer *pBuf,
  174891. u32 nData,
  174892. const u8 *pData
  174893. ){
  174894. assert_nc( *pRc || nData>=0 );
  174895. if( nData ){
  174896. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  174897. memcpy(&pBuf->p[pBuf->n], pData, nData);
  174898. pBuf->n += nData;
  174899. }
  174900. }
  174901. /*
  174902. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  174903. ** ensures that the byte following the buffer data is set to 0x00, even
  174904. ** though this byte is not included in the pBuf->n count.
  174905. */
  174906. static void sqlite3Fts5BufferAppendString(
  174907. int *pRc,
  174908. Fts5Buffer *pBuf,
  174909. const char *zStr
  174910. ){
  174911. int nStr = (int)strlen(zStr);
  174912. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  174913. pBuf->n--;
  174914. }
  174915. /*
  174916. ** Argument zFmt is a printf() style format string. This function performs
  174917. ** the printf() style processing, then appends the results to buffer pBuf.
  174918. **
  174919. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  174920. ** following the buffer data is set to 0x00, even though this byte is not
  174921. ** included in the pBuf->n count.
  174922. */
  174923. static void sqlite3Fts5BufferAppendPrintf(
  174924. int *pRc,
  174925. Fts5Buffer *pBuf,
  174926. char *zFmt, ...
  174927. ){
  174928. if( *pRc==SQLITE_OK ){
  174929. char *zTmp;
  174930. va_list ap;
  174931. va_start(ap, zFmt);
  174932. zTmp = sqlite3_vmprintf(zFmt, ap);
  174933. va_end(ap);
  174934. if( zTmp==0 ){
  174935. *pRc = SQLITE_NOMEM;
  174936. }else{
  174937. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  174938. sqlite3_free(zTmp);
  174939. }
  174940. }
  174941. }
  174942. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  174943. char *zRet = 0;
  174944. if( *pRc==SQLITE_OK ){
  174945. va_list ap;
  174946. va_start(ap, zFmt);
  174947. zRet = sqlite3_vmprintf(zFmt, ap);
  174948. va_end(ap);
  174949. if( zRet==0 ){
  174950. *pRc = SQLITE_NOMEM;
  174951. }
  174952. }
  174953. return zRet;
  174954. }
  174955. /*
  174956. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  174957. */
  174958. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  174959. sqlite3_free(pBuf->p);
  174960. memset(pBuf, 0, sizeof(Fts5Buffer));
  174961. }
  174962. /*
  174963. ** Zero the contents of the buffer object. But do not free the associated
  174964. ** memory allocation.
  174965. */
  174966. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  174967. pBuf->n = 0;
  174968. }
  174969. /*
  174970. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  174971. ** the error code in p. If an error has already occurred when this function
  174972. ** is called, it is a no-op.
  174973. */
  174974. static void sqlite3Fts5BufferSet(
  174975. int *pRc,
  174976. Fts5Buffer *pBuf,
  174977. int nData,
  174978. const u8 *pData
  174979. ){
  174980. pBuf->n = 0;
  174981. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  174982. }
  174983. static int sqlite3Fts5PoslistNext64(
  174984. const u8 *a, int n, /* Buffer containing poslist */
  174985. int *pi, /* IN/OUT: Offset within a[] */
  174986. i64 *piOff /* IN/OUT: Current offset */
  174987. ){
  174988. int i = *pi;
  174989. if( i>=n ){
  174990. /* EOF */
  174991. *piOff = -1;
  174992. return 1;
  174993. }else{
  174994. i64 iOff = *piOff;
  174995. int iVal;
  174996. fts5FastGetVarint32(a, i, iVal);
  174997. if( iVal==1 ){
  174998. fts5FastGetVarint32(a, i, iVal);
  174999. iOff = ((i64)iVal) << 32;
  175000. fts5FastGetVarint32(a, i, iVal);
  175001. }
  175002. *piOff = iOff + (iVal-2);
  175003. *pi = i;
  175004. return 0;
  175005. }
  175006. }
  175007. /*
  175008. ** Advance the iterator object passed as the only argument. Return true
  175009. ** if the iterator reaches EOF, or false otherwise.
  175010. */
  175011. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  175012. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  175013. pIter->bEof = 1;
  175014. }
  175015. return pIter->bEof;
  175016. }
  175017. static int sqlite3Fts5PoslistReaderInit(
  175018. const u8 *a, int n, /* Poslist buffer to iterate through */
  175019. Fts5PoslistReader *pIter /* Iterator object to initialize */
  175020. ){
  175021. memset(pIter, 0, sizeof(*pIter));
  175022. pIter->a = a;
  175023. pIter->n = n;
  175024. sqlite3Fts5PoslistReaderNext(pIter);
  175025. return pIter->bEof;
  175026. }
  175027. /*
  175028. ** Append position iPos to the position list being accumulated in buffer
  175029. ** pBuf, which must be already be large enough to hold the new data.
  175030. ** The previous position written to this list is *piPrev. *piPrev is set
  175031. ** to iPos before returning.
  175032. */
  175033. static void sqlite3Fts5PoslistSafeAppend(
  175034. Fts5Buffer *pBuf,
  175035. i64 *piPrev,
  175036. i64 iPos
  175037. ){
  175038. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  175039. if( (iPos & colmask) != (*piPrev & colmask) ){
  175040. pBuf->p[pBuf->n++] = 1;
  175041. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  175042. *piPrev = (iPos & colmask);
  175043. }
  175044. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  175045. *piPrev = iPos;
  175046. }
  175047. static int sqlite3Fts5PoslistWriterAppend(
  175048. Fts5Buffer *pBuf,
  175049. Fts5PoslistWriter *pWriter,
  175050. i64 iPos
  175051. ){
  175052. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  175053. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  175054. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  175055. return SQLITE_OK;
  175056. }
  175057. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  175058. void *pRet = 0;
  175059. if( *pRc==SQLITE_OK ){
  175060. pRet = sqlite3_malloc(nByte);
  175061. if( pRet==0 ){
  175062. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  175063. }else{
  175064. memset(pRet, 0, nByte);
  175065. }
  175066. }
  175067. return pRet;
  175068. }
  175069. /*
  175070. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  175071. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  175072. ** the length of the string is determined using strlen().
  175073. **
  175074. ** It is the responsibility of the caller to eventually free the returned
  175075. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  175076. */
  175077. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  175078. char *zRet = 0;
  175079. if( *pRc==SQLITE_OK ){
  175080. if( nIn<0 ){
  175081. nIn = (int)strlen(pIn);
  175082. }
  175083. zRet = (char*)sqlite3_malloc(nIn+1);
  175084. if( zRet ){
  175085. memcpy(zRet, pIn, nIn);
  175086. zRet[nIn] = '\0';
  175087. }else{
  175088. *pRc = SQLITE_NOMEM;
  175089. }
  175090. }
  175091. return zRet;
  175092. }
  175093. /*
  175094. ** Return true if character 't' may be part of an FTS5 bareword, or false
  175095. ** otherwise. Characters that may be part of barewords:
  175096. **
  175097. ** * All non-ASCII characters,
  175098. ** * The 52 upper and lower case ASCII characters, and
  175099. ** * The 10 integer ASCII characters.
  175100. ** * The underscore character "_" (0x5F).
  175101. ** * The unicode "subsitute" character (0x1A).
  175102. */
  175103. static int sqlite3Fts5IsBareword(char t){
  175104. u8 aBareword[128] = {
  175105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  175106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  175107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  175108. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  175109. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  175110. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  175111. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  175112. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  175113. };
  175114. return (t & 0x80) || aBareword[(int)t];
  175115. }
  175116. /*************************************************************************
  175117. */
  175118. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  175119. struct Fts5TermsetEntry {
  175120. char *pTerm;
  175121. int nTerm;
  175122. int iIdx; /* Index (main or aPrefix[] entry) */
  175123. Fts5TermsetEntry *pNext;
  175124. };
  175125. struct Fts5Termset {
  175126. Fts5TermsetEntry *apHash[512];
  175127. };
  175128. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  175129. int rc = SQLITE_OK;
  175130. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  175131. return rc;
  175132. }
  175133. static int sqlite3Fts5TermsetAdd(
  175134. Fts5Termset *p,
  175135. int iIdx,
  175136. const char *pTerm, int nTerm,
  175137. int *pbPresent
  175138. ){
  175139. int rc = SQLITE_OK;
  175140. *pbPresent = 0;
  175141. if( p ){
  175142. int i;
  175143. u32 hash = 13;
  175144. Fts5TermsetEntry *pEntry;
  175145. /* Calculate a hash value for this term. This is the same hash checksum
  175146. ** used by the fts5_hash.c module. This is not important for correct
  175147. ** operation of the module, but is necessary to ensure that some tests
  175148. ** designed to produce hash table collisions really do work. */
  175149. for(i=nTerm-1; i>=0; i--){
  175150. hash = (hash << 3) ^ hash ^ pTerm[i];
  175151. }
  175152. hash = (hash << 3) ^ hash ^ iIdx;
  175153. hash = hash % ArraySize(p->apHash);
  175154. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  175155. if( pEntry->iIdx==iIdx
  175156. && pEntry->nTerm==nTerm
  175157. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  175158. ){
  175159. *pbPresent = 1;
  175160. break;
  175161. }
  175162. }
  175163. if( pEntry==0 ){
  175164. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  175165. if( pEntry ){
  175166. pEntry->pTerm = (char*)&pEntry[1];
  175167. pEntry->nTerm = nTerm;
  175168. pEntry->iIdx = iIdx;
  175169. memcpy(pEntry->pTerm, pTerm, nTerm);
  175170. pEntry->pNext = p->apHash[hash];
  175171. p->apHash[hash] = pEntry;
  175172. }
  175173. }
  175174. }
  175175. return rc;
  175176. }
  175177. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  175178. if( p ){
  175179. u32 i;
  175180. for(i=0; i<ArraySize(p->apHash); i++){
  175181. Fts5TermsetEntry *pEntry = p->apHash[i];
  175182. while( pEntry ){
  175183. Fts5TermsetEntry *pDel = pEntry;
  175184. pEntry = pEntry->pNext;
  175185. sqlite3_free(pDel);
  175186. }
  175187. }
  175188. sqlite3_free(p);
  175189. }
  175190. }
  175191. /*
  175192. ** 2014 Jun 09
  175193. **
  175194. ** The author disclaims copyright to this source code. In place of
  175195. ** a legal notice, here is a blessing:
  175196. **
  175197. ** May you do good and not evil.
  175198. ** May you find forgiveness for yourself and forgive others.
  175199. ** May you share freely, never taking more than you give.
  175200. **
  175201. ******************************************************************************
  175202. **
  175203. ** This is an SQLite module implementing full-text search.
  175204. */
  175205. /* #include "fts5Int.h" */
  175206. #define FTS5_DEFAULT_PAGE_SIZE 4050
  175207. #define FTS5_DEFAULT_AUTOMERGE 4
  175208. #define FTS5_DEFAULT_USERMERGE 4
  175209. #define FTS5_DEFAULT_CRISISMERGE 16
  175210. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  175211. /* Maximum allowed page size */
  175212. #define FTS5_MAX_PAGE_SIZE (128*1024)
  175213. static int fts5_iswhitespace(char x){
  175214. return (x==' ');
  175215. }
  175216. static int fts5_isopenquote(char x){
  175217. return (x=='"' || x=='\'' || x=='[' || x=='`');
  175218. }
  175219. /*
  175220. ** Argument pIn points to a character that is part of a nul-terminated
  175221. ** string. Return a pointer to the first character following *pIn in
  175222. ** the string that is not a white-space character.
  175223. */
  175224. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  175225. const char *p = pIn;
  175226. if( p ){
  175227. while( fts5_iswhitespace(*p) ){ p++; }
  175228. }
  175229. return p;
  175230. }
  175231. /*
  175232. ** Argument pIn points to a character that is part of a nul-terminated
  175233. ** string. Return a pointer to the first character following *pIn in
  175234. ** the string that is not a "bareword" character.
  175235. */
  175236. static const char *fts5ConfigSkipBareword(const char *pIn){
  175237. const char *p = pIn;
  175238. while ( sqlite3Fts5IsBareword(*p) ) p++;
  175239. if( p==pIn ) p = 0;
  175240. return p;
  175241. }
  175242. static int fts5_isdigit(char a){
  175243. return (a>='0' && a<='9');
  175244. }
  175245. static const char *fts5ConfigSkipLiteral(const char *pIn){
  175246. const char *p = pIn;
  175247. switch( *p ){
  175248. case 'n': case 'N':
  175249. if( sqlite3_strnicmp("null", p, 4)==0 ){
  175250. p = &p[4];
  175251. }else{
  175252. p = 0;
  175253. }
  175254. break;
  175255. case 'x': case 'X':
  175256. p++;
  175257. if( *p=='\'' ){
  175258. p++;
  175259. while( (*p>='a' && *p<='f')
  175260. || (*p>='A' && *p<='F')
  175261. || (*p>='0' && *p<='9')
  175262. ){
  175263. p++;
  175264. }
  175265. if( *p=='\'' && 0==((p-pIn)%2) ){
  175266. p++;
  175267. }else{
  175268. p = 0;
  175269. }
  175270. }else{
  175271. p = 0;
  175272. }
  175273. break;
  175274. case '\'':
  175275. p++;
  175276. while( p ){
  175277. if( *p=='\'' ){
  175278. p++;
  175279. if( *p!='\'' ) break;
  175280. }
  175281. p++;
  175282. if( *p==0 ) p = 0;
  175283. }
  175284. break;
  175285. default:
  175286. /* maybe a number */
  175287. if( *p=='+' || *p=='-' ) p++;
  175288. while( fts5_isdigit(*p) ) p++;
  175289. /* At this point, if the literal was an integer, the parse is
  175290. ** finished. Or, if it is a floating point value, it may continue
  175291. ** with either a decimal point or an 'E' character. */
  175292. if( *p=='.' && fts5_isdigit(p[1]) ){
  175293. p += 2;
  175294. while( fts5_isdigit(*p) ) p++;
  175295. }
  175296. if( p==pIn ) p = 0;
  175297. break;
  175298. }
  175299. return p;
  175300. }
  175301. /*
  175302. ** The first character of the string pointed to by argument z is guaranteed
  175303. ** to be an open-quote character (see function fts5_isopenquote()).
  175304. **
  175305. ** This function searches for the corresponding close-quote character within
  175306. ** the string and, if found, dequotes the string in place and adds a new
  175307. ** nul-terminator byte.
  175308. **
  175309. ** If the close-quote is found, the value returned is the byte offset of
  175310. ** the character immediately following it. Or, if the close-quote is not
  175311. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  175312. ** undefined state.
  175313. */
  175314. static int fts5Dequote(char *z){
  175315. char q;
  175316. int iIn = 1;
  175317. int iOut = 0;
  175318. q = z[0];
  175319. /* Set stack variable q to the close-quote character */
  175320. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  175321. if( q=='[' ) q = ']';
  175322. while( ALWAYS(z[iIn]) ){
  175323. if( z[iIn]==q ){
  175324. if( z[iIn+1]!=q ){
  175325. /* Character iIn was the close quote. */
  175326. iIn++;
  175327. break;
  175328. }else{
  175329. /* Character iIn and iIn+1 form an escaped quote character. Skip
  175330. ** the input cursor past both and copy a single quote character
  175331. ** to the output buffer. */
  175332. iIn += 2;
  175333. z[iOut++] = q;
  175334. }
  175335. }else{
  175336. z[iOut++] = z[iIn++];
  175337. }
  175338. }
  175339. z[iOut] = '\0';
  175340. return iIn;
  175341. }
  175342. /*
  175343. ** Convert an SQL-style quoted string into a normal string by removing
  175344. ** the quote characters. The conversion is done in-place. If the
  175345. ** input does not begin with a quote character, then this routine
  175346. ** is a no-op.
  175347. **
  175348. ** Examples:
  175349. **
  175350. ** "abc" becomes abc
  175351. ** 'xyz' becomes xyz
  175352. ** [pqr] becomes pqr
  175353. ** `mno` becomes mno
  175354. */
  175355. static void sqlite3Fts5Dequote(char *z){
  175356. char quote; /* Quote character (if any ) */
  175357. assert( 0==fts5_iswhitespace(z[0]) );
  175358. quote = z[0];
  175359. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  175360. fts5Dequote(z);
  175361. }
  175362. }
  175363. struct Fts5Enum {
  175364. const char *zName;
  175365. int eVal;
  175366. };
  175367. typedef struct Fts5Enum Fts5Enum;
  175368. static int fts5ConfigSetEnum(
  175369. const Fts5Enum *aEnum,
  175370. const char *zEnum,
  175371. int *peVal
  175372. ){
  175373. int nEnum = (int)strlen(zEnum);
  175374. int i;
  175375. int iVal = -1;
  175376. for(i=0; aEnum[i].zName; i++){
  175377. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  175378. if( iVal>=0 ) return SQLITE_ERROR;
  175379. iVal = aEnum[i].eVal;
  175380. }
  175381. }
  175382. *peVal = iVal;
  175383. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  175384. }
  175385. /*
  175386. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  175387. ** configuration object pConfig as appropriate.
  175388. **
  175389. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  175390. ** an error occurs, an SQLite error code is returned and an error message
  175391. ** may be left in *pzErr. It is the responsibility of the caller to
  175392. ** eventually free any such error message using sqlite3_free().
  175393. */
  175394. static int fts5ConfigParseSpecial(
  175395. Fts5Global *pGlobal,
  175396. Fts5Config *pConfig, /* Configuration object to update */
  175397. const char *zCmd, /* Special command to parse */
  175398. const char *zArg, /* Argument to parse */
  175399. char **pzErr /* OUT: Error message */
  175400. ){
  175401. int rc = SQLITE_OK;
  175402. int nCmd = (int)strlen(zCmd);
  175403. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  175404. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  175405. const char *p;
  175406. int bFirst = 1;
  175407. if( pConfig->aPrefix==0 ){
  175408. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  175409. if( rc ) return rc;
  175410. }
  175411. p = zArg;
  175412. while( 1 ){
  175413. int nPre = 0;
  175414. while( p[0]==' ' ) p++;
  175415. if( bFirst==0 && p[0]==',' ){
  175416. p++;
  175417. while( p[0]==' ' ) p++;
  175418. }else if( p[0]=='\0' ){
  175419. break;
  175420. }
  175421. if( p[0]<'0' || p[0]>'9' ){
  175422. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  175423. rc = SQLITE_ERROR;
  175424. break;
  175425. }
  175426. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  175427. *pzErr = sqlite3_mprintf(
  175428. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  175429. );
  175430. rc = SQLITE_ERROR;
  175431. break;
  175432. }
  175433. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  175434. nPre = nPre*10 + (p[0] - '0');
  175435. p++;
  175436. }
  175437. if( nPre<=0 || nPre>=1000 ){
  175438. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  175439. rc = SQLITE_ERROR;
  175440. break;
  175441. }
  175442. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  175443. pConfig->nPrefix++;
  175444. bFirst = 0;
  175445. }
  175446. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  175447. return rc;
  175448. }
  175449. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  175450. const char *p = (const char*)zArg;
  175451. int nArg = (int)strlen(zArg) + 1;
  175452. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  175453. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  175454. char *pSpace = pDel;
  175455. if( azArg && pSpace ){
  175456. if( pConfig->pTok ){
  175457. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  175458. rc = SQLITE_ERROR;
  175459. }else{
  175460. for(nArg=0; p && *p; nArg++){
  175461. const char *p2 = fts5ConfigSkipWhitespace(p);
  175462. if( *p2=='\'' ){
  175463. p = fts5ConfigSkipLiteral(p2);
  175464. }else{
  175465. p = fts5ConfigSkipBareword(p2);
  175466. }
  175467. if( p ){
  175468. memcpy(pSpace, p2, p-p2);
  175469. azArg[nArg] = pSpace;
  175470. sqlite3Fts5Dequote(pSpace);
  175471. pSpace += (p - p2) + 1;
  175472. p = fts5ConfigSkipWhitespace(p);
  175473. }
  175474. }
  175475. if( p==0 ){
  175476. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  175477. rc = SQLITE_ERROR;
  175478. }else{
  175479. rc = sqlite3Fts5GetTokenizer(pGlobal,
  175480. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  175481. pzErr
  175482. );
  175483. }
  175484. }
  175485. }
  175486. sqlite3_free(azArg);
  175487. sqlite3_free(pDel);
  175488. return rc;
  175489. }
  175490. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  175491. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  175492. *pzErr = sqlite3_mprintf("multiple content=... directives");
  175493. rc = SQLITE_ERROR;
  175494. }else{
  175495. if( zArg[0] ){
  175496. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  175497. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  175498. }else{
  175499. pConfig->eContent = FTS5_CONTENT_NONE;
  175500. }
  175501. }
  175502. return rc;
  175503. }
  175504. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  175505. if( pConfig->zContentRowid ){
  175506. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  175507. rc = SQLITE_ERROR;
  175508. }else{
  175509. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  175510. }
  175511. return rc;
  175512. }
  175513. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  175514. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  175515. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  175516. rc = SQLITE_ERROR;
  175517. }else{
  175518. pConfig->bColumnsize = (zArg[0]=='1');
  175519. }
  175520. return rc;
  175521. }
  175522. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  175523. const Fts5Enum aDetail[] = {
  175524. { "none", FTS5_DETAIL_NONE },
  175525. { "full", FTS5_DETAIL_FULL },
  175526. { "columns", FTS5_DETAIL_COLUMNS },
  175527. { 0, 0 }
  175528. };
  175529. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  175530. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  175531. }
  175532. return rc;
  175533. }
  175534. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  175535. return SQLITE_ERROR;
  175536. }
  175537. /*
  175538. ** Allocate an instance of the default tokenizer ("simple") at
  175539. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  175540. ** code if an error occurs.
  175541. */
  175542. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  175543. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  175544. return sqlite3Fts5GetTokenizer(
  175545. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  175546. );
  175547. }
  175548. /*
  175549. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  175550. ** Return a pointer to the character immediately following the last in
  175551. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  175552. ** to find close-quote character).
  175553. **
  175554. ** Before returning, set pzOut to point to a new buffer containing a
  175555. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  175556. ** quoted, *pbQuoted is also set to 1 before returning.
  175557. **
  175558. ** If *pRc is other than SQLITE_OK when this function is called, it is
  175559. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  175560. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  175561. ** set if a parse error (failed to find close quote) occurs.
  175562. */
  175563. static const char *fts5ConfigGobbleWord(
  175564. int *pRc, /* IN/OUT: Error code */
  175565. const char *zIn, /* Buffer to gobble string/bareword from */
  175566. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  175567. int *pbQuoted /* OUT: Set to true if dequoting required */
  175568. ){
  175569. const char *zRet = 0;
  175570. int nIn = (int)strlen(zIn);
  175571. char *zOut = sqlite3_malloc(nIn+1);
  175572. assert( *pRc==SQLITE_OK );
  175573. *pbQuoted = 0;
  175574. *pzOut = 0;
  175575. if( zOut==0 ){
  175576. *pRc = SQLITE_NOMEM;
  175577. }else{
  175578. memcpy(zOut, zIn, nIn+1);
  175579. if( fts5_isopenquote(zOut[0]) ){
  175580. int ii = fts5Dequote(zOut);
  175581. zRet = &zIn[ii];
  175582. *pbQuoted = 1;
  175583. }else{
  175584. zRet = fts5ConfigSkipBareword(zIn);
  175585. if( zRet ){
  175586. zOut[zRet-zIn] = '\0';
  175587. }
  175588. }
  175589. }
  175590. if( zRet==0 ){
  175591. sqlite3_free(zOut);
  175592. }else{
  175593. *pzOut = zOut;
  175594. }
  175595. return zRet;
  175596. }
  175597. static int fts5ConfigParseColumn(
  175598. Fts5Config *p,
  175599. char *zCol,
  175600. char *zArg,
  175601. char **pzErr
  175602. ){
  175603. int rc = SQLITE_OK;
  175604. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  175605. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  175606. ){
  175607. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  175608. rc = SQLITE_ERROR;
  175609. }else if( zArg ){
  175610. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  175611. p->abUnindexed[p->nCol] = 1;
  175612. }else{
  175613. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  175614. rc = SQLITE_ERROR;
  175615. }
  175616. }
  175617. p->azCol[p->nCol++] = zCol;
  175618. return rc;
  175619. }
  175620. /*
  175621. ** Populate the Fts5Config.zContentExprlist string.
  175622. */
  175623. static int fts5ConfigMakeExprlist(Fts5Config *p){
  175624. int i;
  175625. int rc = SQLITE_OK;
  175626. Fts5Buffer buf = {0, 0, 0};
  175627. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  175628. if( p->eContent!=FTS5_CONTENT_NONE ){
  175629. for(i=0; i<p->nCol; i++){
  175630. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  175631. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  175632. }else{
  175633. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  175634. }
  175635. }
  175636. }
  175637. assert( p->zContentExprlist==0 );
  175638. p->zContentExprlist = (char*)buf.p;
  175639. return rc;
  175640. }
  175641. /*
  175642. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  175643. ** or xConnect method of the virtual table. This function attempts to
  175644. ** allocate an instance of Fts5Config containing the results of parsing
  175645. ** those arguments.
  175646. **
  175647. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  175648. ** new Fts5Config object. If an error occurs, an SQLite error code is
  175649. ** returned, *ppOut is set to NULL and an error message may be left in
  175650. ** *pzErr. It is the responsibility of the caller to eventually free any
  175651. ** such error message using sqlite3_free().
  175652. */
  175653. static int sqlite3Fts5ConfigParse(
  175654. Fts5Global *pGlobal,
  175655. sqlite3 *db,
  175656. int nArg, /* Number of arguments */
  175657. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  175658. Fts5Config **ppOut, /* OUT: Results of parse */
  175659. char **pzErr /* OUT: Error message */
  175660. ){
  175661. int rc = SQLITE_OK; /* Return code */
  175662. Fts5Config *pRet; /* New object to return */
  175663. int i;
  175664. int nByte;
  175665. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  175666. if( pRet==0 ) return SQLITE_NOMEM;
  175667. memset(pRet, 0, sizeof(Fts5Config));
  175668. pRet->db = db;
  175669. pRet->iCookie = -1;
  175670. nByte = nArg * (sizeof(char*) + sizeof(u8));
  175671. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  175672. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  175673. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  175674. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  175675. pRet->bColumnsize = 1;
  175676. pRet->eDetail = FTS5_DETAIL_FULL;
  175677. #ifdef SQLITE_DEBUG
  175678. pRet->bPrefixIndex = 1;
  175679. #endif
  175680. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  175681. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  175682. rc = SQLITE_ERROR;
  175683. }
  175684. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  175685. const char *zOrig = azArg[i];
  175686. const char *z;
  175687. char *zOne = 0;
  175688. char *zTwo = 0;
  175689. int bOption = 0;
  175690. int bMustBeCol = 0;
  175691. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  175692. z = fts5ConfigSkipWhitespace(z);
  175693. if( z && *z=='=' ){
  175694. bOption = 1;
  175695. z++;
  175696. if( bMustBeCol ) z = 0;
  175697. }
  175698. z = fts5ConfigSkipWhitespace(z);
  175699. if( z && z[0] ){
  175700. int bDummy;
  175701. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  175702. if( z && z[0] ) z = 0;
  175703. }
  175704. if( rc==SQLITE_OK ){
  175705. if( z==0 ){
  175706. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  175707. rc = SQLITE_ERROR;
  175708. }else{
  175709. if( bOption ){
  175710. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  175711. }else{
  175712. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  175713. zOne = 0;
  175714. }
  175715. }
  175716. }
  175717. sqlite3_free(zOne);
  175718. sqlite3_free(zTwo);
  175719. }
  175720. /* If a tokenizer= option was successfully parsed, the tokenizer has
  175721. ** already been allocated. Otherwise, allocate an instance of the default
  175722. ** tokenizer (unicode61) now. */
  175723. if( rc==SQLITE_OK && pRet->pTok==0 ){
  175724. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  175725. }
  175726. /* If no zContent option was specified, fill in the default values. */
  175727. if( rc==SQLITE_OK && pRet->zContent==0 ){
  175728. const char *zTail = 0;
  175729. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  175730. || pRet->eContent==FTS5_CONTENT_NONE
  175731. );
  175732. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  175733. zTail = "content";
  175734. }else if( pRet->bColumnsize ){
  175735. zTail = "docsize";
  175736. }
  175737. if( zTail ){
  175738. pRet->zContent = sqlite3Fts5Mprintf(
  175739. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  175740. );
  175741. }
  175742. }
  175743. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  175744. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  175745. }
  175746. /* Formulate the zContentExprlist text */
  175747. if( rc==SQLITE_OK ){
  175748. rc = fts5ConfigMakeExprlist(pRet);
  175749. }
  175750. if( rc!=SQLITE_OK ){
  175751. sqlite3Fts5ConfigFree(pRet);
  175752. *ppOut = 0;
  175753. }
  175754. return rc;
  175755. }
  175756. /*
  175757. ** Free the configuration object passed as the only argument.
  175758. */
  175759. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  175760. if( pConfig ){
  175761. int i;
  175762. if( pConfig->pTok ){
  175763. pConfig->pTokApi->xDelete(pConfig->pTok);
  175764. }
  175765. sqlite3_free(pConfig->zDb);
  175766. sqlite3_free(pConfig->zName);
  175767. for(i=0; i<pConfig->nCol; i++){
  175768. sqlite3_free(pConfig->azCol[i]);
  175769. }
  175770. sqlite3_free(pConfig->azCol);
  175771. sqlite3_free(pConfig->aPrefix);
  175772. sqlite3_free(pConfig->zRank);
  175773. sqlite3_free(pConfig->zRankArgs);
  175774. sqlite3_free(pConfig->zContent);
  175775. sqlite3_free(pConfig->zContentRowid);
  175776. sqlite3_free(pConfig->zContentExprlist);
  175777. sqlite3_free(pConfig);
  175778. }
  175779. }
  175780. /*
  175781. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  175782. ** object passed as the only argument. Return SQLITE_OK if successful, or
  175783. ** an SQLite error code if an error occurs.
  175784. */
  175785. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  175786. int i;
  175787. int rc = SQLITE_OK;
  175788. char *zSql;
  175789. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  175790. for(i=0; zSql && i<pConfig->nCol; i++){
  175791. const char *zSep = (i==0?"":", ");
  175792. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  175793. }
  175794. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  175795. zSql, pConfig->zName, FTS5_RANK_NAME
  175796. );
  175797. assert( zSql || rc==SQLITE_NOMEM );
  175798. if( zSql ){
  175799. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  175800. sqlite3_free(zSql);
  175801. }
  175802. return rc;
  175803. }
  175804. /*
  175805. ** Tokenize the text passed via the second and third arguments.
  175806. **
  175807. ** The callback is invoked once for each token in the input text. The
  175808. ** arguments passed to it are, in order:
  175809. **
  175810. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  175811. ** const char *pToken // Pointer to buffer containing token
  175812. ** int nToken // Size of token in bytes
  175813. ** int iStart // Byte offset of start of token within input text
  175814. ** int iEnd // Byte offset of end of token within input text
  175815. ** int iPos // Position of token in input (first token is 0)
  175816. **
  175817. ** If the callback returns a non-zero value the tokenization is abandoned
  175818. ** and no further callbacks are issued.
  175819. **
  175820. ** This function returns SQLITE_OK if successful or an SQLite error code
  175821. ** if an error occurs. If the tokenization was abandoned early because
  175822. ** the callback returned SQLITE_DONE, this is not an error and this function
  175823. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  175824. ** because the callback returned another non-zero value, it is assumed
  175825. ** to be an SQLite error code and returned to the caller.
  175826. */
  175827. static int sqlite3Fts5Tokenize(
  175828. Fts5Config *pConfig, /* FTS5 Configuration object */
  175829. int flags, /* FTS5_TOKENIZE_* flags */
  175830. const char *pText, int nText, /* Text to tokenize */
  175831. void *pCtx, /* Context passed to xToken() */
  175832. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  175833. ){
  175834. if( pText==0 ) return SQLITE_OK;
  175835. return pConfig->pTokApi->xTokenize(
  175836. pConfig->pTok, pCtx, flags, pText, nText, xToken
  175837. );
  175838. }
  175839. /*
  175840. ** Argument pIn points to the first character in what is expected to be
  175841. ** a comma-separated list of SQL literals followed by a ')' character.
  175842. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  175843. ** NULL to indicate a parse error.
  175844. */
  175845. static const char *fts5ConfigSkipArgs(const char *pIn){
  175846. const char *p = pIn;
  175847. while( 1 ){
  175848. p = fts5ConfigSkipWhitespace(p);
  175849. p = fts5ConfigSkipLiteral(p);
  175850. p = fts5ConfigSkipWhitespace(p);
  175851. if( p==0 || *p==')' ) break;
  175852. if( *p!=',' ){
  175853. p = 0;
  175854. break;
  175855. }
  175856. p++;
  175857. }
  175858. return p;
  175859. }
  175860. /*
  175861. ** Parameter zIn contains a rank() function specification. The format of
  175862. ** this is:
  175863. **
  175864. ** + Bareword (function name)
  175865. ** + Open parenthesis - "("
  175866. ** + Zero or more SQL literals in a comma separated list
  175867. ** + Close parenthesis - ")"
  175868. */
  175869. static int sqlite3Fts5ConfigParseRank(
  175870. const char *zIn, /* Input string */
  175871. char **pzRank, /* OUT: Rank function name */
  175872. char **pzRankArgs /* OUT: Rank function arguments */
  175873. ){
  175874. const char *p = zIn;
  175875. const char *pRank;
  175876. char *zRank = 0;
  175877. char *zRankArgs = 0;
  175878. int rc = SQLITE_OK;
  175879. *pzRank = 0;
  175880. *pzRankArgs = 0;
  175881. if( p==0 ){
  175882. rc = SQLITE_ERROR;
  175883. }else{
  175884. p = fts5ConfigSkipWhitespace(p);
  175885. pRank = p;
  175886. p = fts5ConfigSkipBareword(p);
  175887. if( p ){
  175888. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  175889. if( zRank ) memcpy(zRank, pRank, p-pRank);
  175890. }else{
  175891. rc = SQLITE_ERROR;
  175892. }
  175893. if( rc==SQLITE_OK ){
  175894. p = fts5ConfigSkipWhitespace(p);
  175895. if( *p!='(' ) rc = SQLITE_ERROR;
  175896. p++;
  175897. }
  175898. if( rc==SQLITE_OK ){
  175899. const char *pArgs;
  175900. p = fts5ConfigSkipWhitespace(p);
  175901. pArgs = p;
  175902. if( *p!=')' ){
  175903. p = fts5ConfigSkipArgs(p);
  175904. if( p==0 ){
  175905. rc = SQLITE_ERROR;
  175906. }else{
  175907. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  175908. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  175909. }
  175910. }
  175911. }
  175912. }
  175913. if( rc!=SQLITE_OK ){
  175914. sqlite3_free(zRank);
  175915. assert( zRankArgs==0 );
  175916. }else{
  175917. *pzRank = zRank;
  175918. *pzRankArgs = zRankArgs;
  175919. }
  175920. return rc;
  175921. }
  175922. static int sqlite3Fts5ConfigSetValue(
  175923. Fts5Config *pConfig,
  175924. const char *zKey,
  175925. sqlite3_value *pVal,
  175926. int *pbBadkey
  175927. ){
  175928. int rc = SQLITE_OK;
  175929. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  175930. int pgsz = 0;
  175931. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  175932. pgsz = sqlite3_value_int(pVal);
  175933. }
  175934. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  175935. *pbBadkey = 1;
  175936. }else{
  175937. pConfig->pgsz = pgsz;
  175938. }
  175939. }
  175940. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  175941. int nHashSize = -1;
  175942. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  175943. nHashSize = sqlite3_value_int(pVal);
  175944. }
  175945. if( nHashSize<=0 ){
  175946. *pbBadkey = 1;
  175947. }else{
  175948. pConfig->nHashSize = nHashSize;
  175949. }
  175950. }
  175951. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  175952. int nAutomerge = -1;
  175953. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  175954. nAutomerge = sqlite3_value_int(pVal);
  175955. }
  175956. if( nAutomerge<0 || nAutomerge>64 ){
  175957. *pbBadkey = 1;
  175958. }else{
  175959. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  175960. pConfig->nAutomerge = nAutomerge;
  175961. }
  175962. }
  175963. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  175964. int nUsermerge = -1;
  175965. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  175966. nUsermerge = sqlite3_value_int(pVal);
  175967. }
  175968. if( nUsermerge<2 || nUsermerge>16 ){
  175969. *pbBadkey = 1;
  175970. }else{
  175971. pConfig->nUsermerge = nUsermerge;
  175972. }
  175973. }
  175974. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  175975. int nCrisisMerge = -1;
  175976. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  175977. nCrisisMerge = sqlite3_value_int(pVal);
  175978. }
  175979. if( nCrisisMerge<0 ){
  175980. *pbBadkey = 1;
  175981. }else{
  175982. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  175983. pConfig->nCrisisMerge = nCrisisMerge;
  175984. }
  175985. }
  175986. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  175987. const char *zIn = (const char*)sqlite3_value_text(pVal);
  175988. char *zRank;
  175989. char *zRankArgs;
  175990. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  175991. if( rc==SQLITE_OK ){
  175992. sqlite3_free(pConfig->zRank);
  175993. sqlite3_free(pConfig->zRankArgs);
  175994. pConfig->zRank = zRank;
  175995. pConfig->zRankArgs = zRankArgs;
  175996. }else if( rc==SQLITE_ERROR ){
  175997. rc = SQLITE_OK;
  175998. *pbBadkey = 1;
  175999. }
  176000. }else{
  176001. *pbBadkey = 1;
  176002. }
  176003. return rc;
  176004. }
  176005. /*
  176006. ** Load the contents of the %_config table into memory.
  176007. */
  176008. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  176009. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  176010. char *zSql;
  176011. sqlite3_stmt *p = 0;
  176012. int rc = SQLITE_OK;
  176013. int iVersion = 0;
  176014. /* Set default values */
  176015. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  176016. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  176017. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  176018. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  176019. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  176020. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  176021. if( zSql ){
  176022. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  176023. sqlite3_free(zSql);
  176024. }
  176025. assert( rc==SQLITE_OK || p==0 );
  176026. if( rc==SQLITE_OK ){
  176027. while( SQLITE_ROW==sqlite3_step(p) ){
  176028. const char *zK = (const char*)sqlite3_column_text(p, 0);
  176029. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  176030. if( 0==sqlite3_stricmp(zK, "version") ){
  176031. iVersion = sqlite3_value_int(pVal);
  176032. }else{
  176033. int bDummy = 0;
  176034. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  176035. }
  176036. }
  176037. rc = sqlite3_finalize(p);
  176038. }
  176039. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  176040. rc = SQLITE_ERROR;
  176041. if( pConfig->pzErrmsg ){
  176042. assert( 0==*pConfig->pzErrmsg );
  176043. *pConfig->pzErrmsg = sqlite3_mprintf(
  176044. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  176045. iVersion, FTS5_CURRENT_VERSION
  176046. );
  176047. }
  176048. }
  176049. if( rc==SQLITE_OK ){
  176050. pConfig->iCookie = iCookie;
  176051. }
  176052. return rc;
  176053. }
  176054. /*
  176055. ** 2014 May 31
  176056. **
  176057. ** The author disclaims copyright to this source code. In place of
  176058. ** a legal notice, here is a blessing:
  176059. **
  176060. ** May you do good and not evil.
  176061. ** May you find forgiveness for yourself and forgive others.
  176062. ** May you share freely, never taking more than you give.
  176063. **
  176064. ******************************************************************************
  176065. **
  176066. */
  176067. /* #include "fts5Int.h" */
  176068. /* #include "fts5parse.h" */
  176069. /*
  176070. ** All token types in the generated fts5parse.h file are greater than 0.
  176071. */
  176072. #define FTS5_EOF 0
  176073. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  176074. typedef struct Fts5ExprTerm Fts5ExprTerm;
  176075. /*
  176076. ** Functions generated by lemon from fts5parse.y.
  176077. */
  176078. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  176079. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  176080. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  176081. #ifndef NDEBUG
  176082. /* #include <stdio.h> */
  176083. static void sqlite3Fts5ParserTrace(FILE*, char*);
  176084. #endif
  176085. struct Fts5Expr {
  176086. Fts5Index *pIndex;
  176087. Fts5Config *pConfig;
  176088. Fts5ExprNode *pRoot;
  176089. int bDesc; /* Iterate in descending rowid order */
  176090. int nPhrase; /* Number of phrases in expression */
  176091. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  176092. };
  176093. /*
  176094. ** eType:
  176095. ** Expression node type. Always one of:
  176096. **
  176097. ** FTS5_AND (nChild, apChild valid)
  176098. ** FTS5_OR (nChild, apChild valid)
  176099. ** FTS5_NOT (nChild, apChild valid)
  176100. ** FTS5_STRING (pNear valid)
  176101. ** FTS5_TERM (pNear valid)
  176102. */
  176103. struct Fts5ExprNode {
  176104. int eType; /* Node type */
  176105. int bEof; /* True at EOF */
  176106. int bNomatch; /* True if entry is not a match */
  176107. /* Next method for this node. */
  176108. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  176109. i64 iRowid; /* Current rowid */
  176110. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  176111. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  176112. ** AND or OR nodes, it contains 2 or more entries. */
  176113. int nChild; /* Number of child nodes */
  176114. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  176115. };
  176116. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  176117. /*
  176118. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  176119. ** used as if it has the same signature as the xNext() methods themselves.
  176120. */
  176121. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  176122. /*
  176123. ** An instance of the following structure represents a single search term
  176124. ** or term prefix.
  176125. */
  176126. struct Fts5ExprTerm {
  176127. int bPrefix; /* True for a prefix term */
  176128. char *zTerm; /* nul-terminated term */
  176129. Fts5IndexIter *pIter; /* Iterator for this term */
  176130. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  176131. };
  176132. /*
  176133. ** A phrase. One or more terms that must appear in a contiguous sequence
  176134. ** within a document for it to match.
  176135. */
  176136. struct Fts5ExprPhrase {
  176137. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  176138. Fts5Buffer poslist; /* Current position list */
  176139. int nTerm; /* Number of entries in aTerm[] */
  176140. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  176141. };
  176142. /*
  176143. ** One or more phrases that must appear within a certain token distance of
  176144. ** each other within each matching document.
  176145. */
  176146. struct Fts5ExprNearset {
  176147. int nNear; /* NEAR parameter */
  176148. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  176149. int nPhrase; /* Number of entries in aPhrase[] array */
  176150. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  176151. };
  176152. /*
  176153. ** Parse context.
  176154. */
  176155. struct Fts5Parse {
  176156. Fts5Config *pConfig;
  176157. char *zErr;
  176158. int rc;
  176159. int nPhrase; /* Size of apPhrase array */
  176160. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  176161. Fts5ExprNode *pExpr; /* Result of a successful parse */
  176162. };
  176163. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  176164. va_list ap;
  176165. va_start(ap, zFmt);
  176166. if( pParse->rc==SQLITE_OK ){
  176167. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  176168. pParse->rc = SQLITE_ERROR;
  176169. }
  176170. va_end(ap);
  176171. }
  176172. static int fts5ExprIsspace(char t){
  176173. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  176174. }
  176175. /*
  176176. ** Read the first token from the nul-terminated string at *pz.
  176177. */
  176178. static int fts5ExprGetToken(
  176179. Fts5Parse *pParse,
  176180. const char **pz, /* IN/OUT: Pointer into buffer */
  176181. Fts5Token *pToken
  176182. ){
  176183. const char *z = *pz;
  176184. int tok;
  176185. /* Skip past any whitespace */
  176186. while( fts5ExprIsspace(*z) ) z++;
  176187. pToken->p = z;
  176188. pToken->n = 1;
  176189. switch( *z ){
  176190. case '(': tok = FTS5_LP; break;
  176191. case ')': tok = FTS5_RP; break;
  176192. case '{': tok = FTS5_LCP; break;
  176193. case '}': tok = FTS5_RCP; break;
  176194. case ':': tok = FTS5_COLON; break;
  176195. case ',': tok = FTS5_COMMA; break;
  176196. case '+': tok = FTS5_PLUS; break;
  176197. case '*': tok = FTS5_STAR; break;
  176198. case '-': tok = FTS5_MINUS; break;
  176199. case '\0': tok = FTS5_EOF; break;
  176200. case '"': {
  176201. const char *z2;
  176202. tok = FTS5_STRING;
  176203. for(z2=&z[1]; 1; z2++){
  176204. if( z2[0]=='"' ){
  176205. z2++;
  176206. if( z2[0]!='"' ) break;
  176207. }
  176208. if( z2[0]=='\0' ){
  176209. sqlite3Fts5ParseError(pParse, "unterminated string");
  176210. return FTS5_EOF;
  176211. }
  176212. }
  176213. pToken->n = (z2 - z);
  176214. break;
  176215. }
  176216. default: {
  176217. const char *z2;
  176218. if( sqlite3Fts5IsBareword(z[0])==0 ){
  176219. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  176220. return FTS5_EOF;
  176221. }
  176222. tok = FTS5_STRING;
  176223. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  176224. pToken->n = (z2 - z);
  176225. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  176226. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  176227. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  176228. break;
  176229. }
  176230. }
  176231. *pz = &pToken->p[pToken->n];
  176232. return tok;
  176233. }
  176234. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  176235. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  176236. static int sqlite3Fts5ExprNew(
  176237. Fts5Config *pConfig, /* FTS5 Configuration */
  176238. int iCol,
  176239. const char *zExpr, /* Expression text */
  176240. Fts5Expr **ppNew,
  176241. char **pzErr
  176242. ){
  176243. Fts5Parse sParse;
  176244. Fts5Token token;
  176245. const char *z = zExpr;
  176246. int t; /* Next token type */
  176247. void *pEngine;
  176248. Fts5Expr *pNew;
  176249. *ppNew = 0;
  176250. *pzErr = 0;
  176251. memset(&sParse, 0, sizeof(sParse));
  176252. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  176253. if( pEngine==0 ){ return SQLITE_NOMEM; }
  176254. sParse.pConfig = pConfig;
  176255. do {
  176256. t = fts5ExprGetToken(&sParse, &z, &token);
  176257. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  176258. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  176259. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  176260. /* If the LHS of the MATCH expression was a user column, apply the
  176261. ** implicit column-filter. */
  176262. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  176263. int n = sizeof(Fts5Colset);
  176264. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  176265. if( pColset ){
  176266. pColset->nCol = 1;
  176267. pColset->aiCol[0] = iCol;
  176268. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  176269. }
  176270. }
  176271. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  176272. if( sParse.rc==SQLITE_OK ){
  176273. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  176274. if( pNew==0 ){
  176275. sParse.rc = SQLITE_NOMEM;
  176276. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  176277. }else{
  176278. if( !sParse.pExpr ){
  176279. const int nByte = sizeof(Fts5ExprNode);
  176280. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  176281. if( pNew->pRoot ){
  176282. pNew->pRoot->bEof = 1;
  176283. }
  176284. }else{
  176285. pNew->pRoot = sParse.pExpr;
  176286. }
  176287. pNew->pIndex = 0;
  176288. pNew->pConfig = pConfig;
  176289. pNew->apExprPhrase = sParse.apPhrase;
  176290. pNew->nPhrase = sParse.nPhrase;
  176291. sParse.apPhrase = 0;
  176292. }
  176293. }else{
  176294. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  176295. }
  176296. sqlite3_free(sParse.apPhrase);
  176297. *pzErr = sParse.zErr;
  176298. return sParse.rc;
  176299. }
  176300. /*
  176301. ** Free the expression node object passed as the only argument.
  176302. */
  176303. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  176304. if( p ){
  176305. int i;
  176306. for(i=0; i<p->nChild; i++){
  176307. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  176308. }
  176309. sqlite3Fts5ParseNearsetFree(p->pNear);
  176310. sqlite3_free(p);
  176311. }
  176312. }
  176313. /*
  176314. ** Free the expression object passed as the only argument.
  176315. */
  176316. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  176317. if( p ){
  176318. sqlite3Fts5ParseNodeFree(p->pRoot);
  176319. sqlite3_free(p->apExprPhrase);
  176320. sqlite3_free(p);
  176321. }
  176322. }
  176323. /*
  176324. ** Argument pTerm must be a synonym iterator. Return the current rowid
  176325. ** that it points to.
  176326. */
  176327. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  176328. i64 iRet = 0;
  176329. int bRetValid = 0;
  176330. Fts5ExprTerm *p;
  176331. assert( pTerm->pSynonym );
  176332. assert( bDesc==0 || bDesc==1 );
  176333. for(p=pTerm; p; p=p->pSynonym){
  176334. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  176335. i64 iRowid = p->pIter->iRowid;
  176336. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  176337. iRet = iRowid;
  176338. bRetValid = 1;
  176339. }
  176340. }
  176341. }
  176342. if( pbEof && bRetValid==0 ) *pbEof = 1;
  176343. return iRet;
  176344. }
  176345. /*
  176346. ** Argument pTerm must be a synonym iterator.
  176347. */
  176348. static int fts5ExprSynonymList(
  176349. Fts5ExprTerm *pTerm,
  176350. i64 iRowid,
  176351. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  176352. u8 **pa, int *pn
  176353. ){
  176354. Fts5PoslistReader aStatic[4];
  176355. Fts5PoslistReader *aIter = aStatic;
  176356. int nIter = 0;
  176357. int nAlloc = 4;
  176358. int rc = SQLITE_OK;
  176359. Fts5ExprTerm *p;
  176360. assert( pTerm->pSynonym );
  176361. for(p=pTerm; p; p=p->pSynonym){
  176362. Fts5IndexIter *pIter = p->pIter;
  176363. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  176364. if( pIter->nData==0 ) continue;
  176365. if( nIter==nAlloc ){
  176366. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  176367. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  176368. if( aNew==0 ){
  176369. rc = SQLITE_NOMEM;
  176370. goto synonym_poslist_out;
  176371. }
  176372. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  176373. nAlloc = nAlloc*2;
  176374. if( aIter!=aStatic ) sqlite3_free(aIter);
  176375. aIter = aNew;
  176376. }
  176377. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  176378. assert( aIter[nIter].bEof==0 );
  176379. nIter++;
  176380. }
  176381. }
  176382. if( nIter==1 ){
  176383. *pa = (u8*)aIter[0].a;
  176384. *pn = aIter[0].n;
  176385. }else{
  176386. Fts5PoslistWriter writer = {0};
  176387. i64 iPrev = -1;
  176388. fts5BufferZero(pBuf);
  176389. while( 1 ){
  176390. int i;
  176391. i64 iMin = FTS5_LARGEST_INT64;
  176392. for(i=0; i<nIter; i++){
  176393. if( aIter[i].bEof==0 ){
  176394. if( aIter[i].iPos==iPrev ){
  176395. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  176396. }
  176397. if( aIter[i].iPos<iMin ){
  176398. iMin = aIter[i].iPos;
  176399. }
  176400. }
  176401. }
  176402. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  176403. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  176404. iPrev = iMin;
  176405. }
  176406. if( rc==SQLITE_OK ){
  176407. *pa = pBuf->p;
  176408. *pn = pBuf->n;
  176409. }
  176410. }
  176411. synonym_poslist_out:
  176412. if( aIter!=aStatic ) sqlite3_free(aIter);
  176413. return rc;
  176414. }
  176415. /*
  176416. ** All individual term iterators in pPhrase are guaranteed to be valid and
  176417. ** pointing to the same rowid when this function is called. This function
  176418. ** checks if the current rowid really is a match, and if so populates
  176419. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  176420. ** is set to true if this is really a match, or false otherwise.
  176421. **
  176422. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  176423. ** otherwise. It is not considered an error code if the current rowid is
  176424. ** not a match.
  176425. */
  176426. static int fts5ExprPhraseIsMatch(
  176427. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  176428. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  176429. int *pbMatch /* OUT: Set to true if really a match */
  176430. ){
  176431. Fts5PoslistWriter writer = {0};
  176432. Fts5PoslistReader aStatic[4];
  176433. Fts5PoslistReader *aIter = aStatic;
  176434. int i;
  176435. int rc = SQLITE_OK;
  176436. fts5BufferZero(&pPhrase->poslist);
  176437. /* If the aStatic[] array is not large enough, allocate a large array
  176438. ** using sqlite3_malloc(). This approach could be improved upon. */
  176439. if( pPhrase->nTerm>ArraySize(aStatic) ){
  176440. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  176441. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  176442. if( !aIter ) return SQLITE_NOMEM;
  176443. }
  176444. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  176445. /* Initialize a term iterator for each term in the phrase */
  176446. for(i=0; i<pPhrase->nTerm; i++){
  176447. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  176448. int n = 0;
  176449. int bFlag = 0;
  176450. u8 *a = 0;
  176451. if( pTerm->pSynonym ){
  176452. Fts5Buffer buf = {0, 0, 0};
  176453. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  176454. if( rc ){
  176455. sqlite3_free(a);
  176456. goto ismatch_out;
  176457. }
  176458. if( a==buf.p ) bFlag = 1;
  176459. }else{
  176460. a = (u8*)pTerm->pIter->pData;
  176461. n = pTerm->pIter->nData;
  176462. }
  176463. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  176464. aIter[i].bFlag = (u8)bFlag;
  176465. if( aIter[i].bEof ) goto ismatch_out;
  176466. }
  176467. while( 1 ){
  176468. int bMatch;
  176469. i64 iPos = aIter[0].iPos;
  176470. do {
  176471. bMatch = 1;
  176472. for(i=0; i<pPhrase->nTerm; i++){
  176473. Fts5PoslistReader *pPos = &aIter[i];
  176474. i64 iAdj = iPos + i;
  176475. if( pPos->iPos!=iAdj ){
  176476. bMatch = 0;
  176477. while( pPos->iPos<iAdj ){
  176478. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  176479. }
  176480. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  176481. }
  176482. }
  176483. }while( bMatch==0 );
  176484. /* Append position iPos to the output */
  176485. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  176486. if( rc!=SQLITE_OK ) goto ismatch_out;
  176487. for(i=0; i<pPhrase->nTerm; i++){
  176488. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  176489. }
  176490. }
  176491. ismatch_out:
  176492. *pbMatch = (pPhrase->poslist.n>0);
  176493. for(i=0; i<pPhrase->nTerm; i++){
  176494. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  176495. }
  176496. if( aIter!=aStatic ) sqlite3_free(aIter);
  176497. return rc;
  176498. }
  176499. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  176500. struct Fts5LookaheadReader {
  176501. const u8 *a; /* Buffer containing position list */
  176502. int n; /* Size of buffer a[] in bytes */
  176503. int i; /* Current offset in position list */
  176504. i64 iPos; /* Current position */
  176505. i64 iLookahead; /* Next position */
  176506. };
  176507. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  176508. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  176509. p->iPos = p->iLookahead;
  176510. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  176511. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  176512. }
  176513. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  176514. }
  176515. static int fts5LookaheadReaderInit(
  176516. const u8 *a, int n, /* Buffer to read position list from */
  176517. Fts5LookaheadReader *p /* Iterator object to initialize */
  176518. ){
  176519. memset(p, 0, sizeof(Fts5LookaheadReader));
  176520. p->a = a;
  176521. p->n = n;
  176522. fts5LookaheadReaderNext(p);
  176523. return fts5LookaheadReaderNext(p);
  176524. }
  176525. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  176526. struct Fts5NearTrimmer {
  176527. Fts5LookaheadReader reader; /* Input iterator */
  176528. Fts5PoslistWriter writer; /* Writer context */
  176529. Fts5Buffer *pOut; /* Output poslist */
  176530. };
  176531. /*
  176532. ** The near-set object passed as the first argument contains more than
  176533. ** one phrase. All phrases currently point to the same row. The
  176534. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  176535. ** tests if the current row contains instances of each phrase sufficiently
  176536. ** close together to meet the NEAR constraint. Non-zero is returned if it
  176537. ** does, or zero otherwise.
  176538. **
  176539. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  176540. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  176541. ** occurs within this function (*pRc) is set accordingly before returning.
  176542. ** The return value is undefined in both these cases.
  176543. **
  176544. ** If no error occurs and non-zero (a match) is returned, the position-list
  176545. ** of each phrase object is edited to contain only those entries that
  176546. ** meet the constraint before returning.
  176547. */
  176548. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  176549. Fts5NearTrimmer aStatic[4];
  176550. Fts5NearTrimmer *a = aStatic;
  176551. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  176552. int i;
  176553. int rc = *pRc;
  176554. int bMatch;
  176555. assert( pNear->nPhrase>1 );
  176556. /* If the aStatic[] array is not large enough, allocate a large array
  176557. ** using sqlite3_malloc(). This approach could be improved upon. */
  176558. if( pNear->nPhrase>ArraySize(aStatic) ){
  176559. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  176560. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  176561. }else{
  176562. memset(aStatic, 0, sizeof(aStatic));
  176563. }
  176564. if( rc!=SQLITE_OK ){
  176565. *pRc = rc;
  176566. return 0;
  176567. }
  176568. /* Initialize a lookahead iterator for each phrase. After passing the
  176569. ** buffer and buffer size to the lookaside-reader init function, zero
  176570. ** the phrase poslist buffer. The new poslist for the phrase (containing
  176571. ** the same entries as the original with some entries removed on account
  176572. ** of the NEAR constraint) is written over the original even as it is
  176573. ** being read. This is safe as the entries for the new poslist are a
  176574. ** subset of the old, so it is not possible for data yet to be read to
  176575. ** be overwritten. */
  176576. for(i=0; i<pNear->nPhrase; i++){
  176577. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  176578. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  176579. pPoslist->n = 0;
  176580. a[i].pOut = pPoslist;
  176581. }
  176582. while( 1 ){
  176583. int iAdv;
  176584. i64 iMin;
  176585. i64 iMax;
  176586. /* This block advances the phrase iterators until they point to a set of
  176587. ** entries that together comprise a match. */
  176588. iMax = a[0].reader.iPos;
  176589. do {
  176590. bMatch = 1;
  176591. for(i=0; i<pNear->nPhrase; i++){
  176592. Fts5LookaheadReader *pPos = &a[i].reader;
  176593. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  176594. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  176595. bMatch = 0;
  176596. while( pPos->iPos<iMin ){
  176597. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  176598. }
  176599. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  176600. }
  176601. }
  176602. }while( bMatch==0 );
  176603. /* Add an entry to each output position list */
  176604. for(i=0; i<pNear->nPhrase; i++){
  176605. i64 iPos = a[i].reader.iPos;
  176606. Fts5PoslistWriter *pWriter = &a[i].writer;
  176607. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  176608. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  176609. }
  176610. }
  176611. iAdv = 0;
  176612. iMin = a[0].reader.iLookahead;
  176613. for(i=0; i<pNear->nPhrase; i++){
  176614. if( a[i].reader.iLookahead < iMin ){
  176615. iMin = a[i].reader.iLookahead;
  176616. iAdv = i;
  176617. }
  176618. }
  176619. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  176620. }
  176621. ismatch_out: {
  176622. int bRet = a[0].pOut->n>0;
  176623. *pRc = rc;
  176624. if( a!=aStatic ) sqlite3_free(a);
  176625. return bRet;
  176626. }
  176627. }
  176628. /*
  176629. ** Advance iterator pIter until it points to a value equal to or laster
  176630. ** than the initial value of *piLast. If this means the iterator points
  176631. ** to a value laster than *piLast, update *piLast to the new lastest value.
  176632. **
  176633. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  176634. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  176635. ** are set, return a non-zero value. Otherwise, return zero.
  176636. */
  176637. static int fts5ExprAdvanceto(
  176638. Fts5IndexIter *pIter, /* Iterator to advance */
  176639. int bDesc, /* True if iterator is "rowid DESC" */
  176640. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  176641. int *pRc, /* OUT: Error code */
  176642. int *pbEof /* OUT: Set to true if EOF */
  176643. ){
  176644. i64 iLast = *piLast;
  176645. i64 iRowid;
  176646. iRowid = pIter->iRowid;
  176647. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  176648. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  176649. if( rc || sqlite3Fts5IterEof(pIter) ){
  176650. *pRc = rc;
  176651. *pbEof = 1;
  176652. return 1;
  176653. }
  176654. iRowid = pIter->iRowid;
  176655. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  176656. }
  176657. *piLast = iRowid;
  176658. return 0;
  176659. }
  176660. static int fts5ExprSynonymAdvanceto(
  176661. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  176662. int bDesc, /* True if iterator is "rowid DESC" */
  176663. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  176664. int *pRc /* OUT: Error code */
  176665. ){
  176666. int rc = SQLITE_OK;
  176667. i64 iLast = *piLast;
  176668. Fts5ExprTerm *p;
  176669. int bEof = 0;
  176670. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  176671. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  176672. i64 iRowid = p->pIter->iRowid;
  176673. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  176674. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  176675. }
  176676. }
  176677. }
  176678. if( rc!=SQLITE_OK ){
  176679. *pRc = rc;
  176680. bEof = 1;
  176681. }else{
  176682. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  176683. }
  176684. return bEof;
  176685. }
  176686. static int fts5ExprNearTest(
  176687. int *pRc,
  176688. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  176689. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  176690. ){
  176691. Fts5ExprNearset *pNear = pNode->pNear;
  176692. int rc = *pRc;
  176693. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  176694. Fts5ExprTerm *pTerm;
  176695. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  176696. pPhrase->poslist.n = 0;
  176697. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  176698. Fts5IndexIter *pIter = pTerm->pIter;
  176699. if( sqlite3Fts5IterEof(pIter)==0 ){
  176700. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  176701. pPhrase->poslist.n = 1;
  176702. }
  176703. }
  176704. }
  176705. return pPhrase->poslist.n;
  176706. }else{
  176707. int i;
  176708. /* Check that each phrase in the nearset matches the current row.
  176709. ** Populate the pPhrase->poslist buffers at the same time. If any
  176710. ** phrase is not a match, break out of the loop early. */
  176711. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  176712. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176713. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  176714. int bMatch = 0;
  176715. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  176716. if( bMatch==0 ) break;
  176717. }else{
  176718. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  176719. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  176720. }
  176721. }
  176722. *pRc = rc;
  176723. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  176724. return 1;
  176725. }
  176726. return 0;
  176727. }
  176728. }
  176729. /*
  176730. ** Initialize all term iterators in the pNear object. If any term is found
  176731. ** to match no documents at all, return immediately without initializing any
  176732. ** further iterators.
  176733. **
  176734. ** If an error occurs, return an SQLite error code. Otherwise, return
  176735. ** SQLITE_OK. It is not considered an error if some term matches zero
  176736. ** documents.
  176737. */
  176738. static int fts5ExprNearInitAll(
  176739. Fts5Expr *pExpr,
  176740. Fts5ExprNode *pNode
  176741. ){
  176742. Fts5ExprNearset *pNear = pNode->pNear;
  176743. int i;
  176744. assert( pNode->bNomatch==0 );
  176745. for(i=0; i<pNear->nPhrase; i++){
  176746. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176747. if( pPhrase->nTerm==0 ){
  176748. pNode->bEof = 1;
  176749. return SQLITE_OK;
  176750. }else{
  176751. int j;
  176752. for(j=0; j<pPhrase->nTerm; j++){
  176753. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  176754. Fts5ExprTerm *p;
  176755. int bHit = 0;
  176756. for(p=pTerm; p; p=p->pSynonym){
  176757. int rc;
  176758. if( p->pIter ){
  176759. sqlite3Fts5IterClose(p->pIter);
  176760. p->pIter = 0;
  176761. }
  176762. rc = sqlite3Fts5IndexQuery(
  176763. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  176764. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  176765. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  176766. pNear->pColset,
  176767. &p->pIter
  176768. );
  176769. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  176770. if( rc!=SQLITE_OK ) return rc;
  176771. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  176772. bHit = 1;
  176773. }
  176774. }
  176775. if( bHit==0 ){
  176776. pNode->bEof = 1;
  176777. return SQLITE_OK;
  176778. }
  176779. }
  176780. }
  176781. }
  176782. pNode->bEof = 0;
  176783. return SQLITE_OK;
  176784. }
  176785. /*
  176786. ** If pExpr is an ASC iterator, this function returns a value with the
  176787. ** same sign as:
  176788. **
  176789. ** (iLhs - iRhs)
  176790. **
  176791. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  176792. **
  176793. ** (iRhs - iLhs)
  176794. */
  176795. static int fts5RowidCmp(
  176796. Fts5Expr *pExpr,
  176797. i64 iLhs,
  176798. i64 iRhs
  176799. ){
  176800. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  176801. if( pExpr->bDesc==0 ){
  176802. if( iLhs<iRhs ) return -1;
  176803. return (iLhs > iRhs);
  176804. }else{
  176805. if( iLhs>iRhs ) return -1;
  176806. return (iLhs < iRhs);
  176807. }
  176808. }
  176809. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  176810. int i;
  176811. pNode->bEof = 1;
  176812. pNode->bNomatch = 0;
  176813. for(i=0; i<pNode->nChild; i++){
  176814. fts5ExprSetEof(pNode->apChild[i]);
  176815. }
  176816. }
  176817. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  176818. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  176819. Fts5ExprNearset *pNear = pNode->pNear;
  176820. int i;
  176821. for(i=0; i<pNear->nPhrase; i++){
  176822. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176823. pPhrase->poslist.n = 0;
  176824. }
  176825. }else{
  176826. int i;
  176827. for(i=0; i<pNode->nChild; i++){
  176828. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  176829. }
  176830. }
  176831. }
  176832. /*
  176833. ** Compare the values currently indicated by the two nodes as follows:
  176834. **
  176835. ** res = (*p1) - (*p2)
  176836. **
  176837. ** Nodes that point to values that come later in the iteration order are
  176838. ** considered to be larger. Nodes at EOF are the largest of all.
  176839. **
  176840. ** This means that if the iteration order is ASC, then numerically larger
  176841. ** rowids are considered larger. Or if it is the default DESC, numerically
  176842. ** smaller rowids are larger.
  176843. */
  176844. static int fts5NodeCompare(
  176845. Fts5Expr *pExpr,
  176846. Fts5ExprNode *p1,
  176847. Fts5ExprNode *p2
  176848. ){
  176849. if( p2->bEof ) return -1;
  176850. if( p1->bEof ) return +1;
  176851. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  176852. }
  176853. /*
  176854. ** All individual term iterators in pNear are guaranteed to be valid when
  176855. ** this function is called. This function checks if all term iterators
  176856. ** point to the same rowid, and if not, advances them until they do.
  176857. ** If an EOF is reached before this happens, *pbEof is set to true before
  176858. ** returning.
  176859. **
  176860. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  176861. ** otherwise. It is not considered an error code if an iterator reaches
  176862. ** EOF.
  176863. */
  176864. static int fts5ExprNodeTest_STRING(
  176865. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  176866. Fts5ExprNode *pNode
  176867. ){
  176868. Fts5ExprNearset *pNear = pNode->pNear;
  176869. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  176870. int rc = SQLITE_OK;
  176871. i64 iLast; /* Lastest rowid any iterator points to */
  176872. int i, j; /* Phrase and token index, respectively */
  176873. int bMatch; /* True if all terms are at the same rowid */
  176874. const int bDesc = pExpr->bDesc;
  176875. /* Check that this node should not be FTS5_TERM */
  176876. assert( pNear->nPhrase>1
  176877. || pNear->apPhrase[0]->nTerm>1
  176878. || pNear->apPhrase[0]->aTerm[0].pSynonym
  176879. );
  176880. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  176881. ** iterator skips through rowids in the default ascending order, this means
  176882. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  176883. ** means the minimum rowid. */
  176884. if( pLeft->aTerm[0].pSynonym ){
  176885. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  176886. }else{
  176887. iLast = pLeft->aTerm[0].pIter->iRowid;
  176888. }
  176889. do {
  176890. bMatch = 1;
  176891. for(i=0; i<pNear->nPhrase; i++){
  176892. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176893. for(j=0; j<pPhrase->nTerm; j++){
  176894. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  176895. if( pTerm->pSynonym ){
  176896. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  176897. if( iRowid==iLast ) continue;
  176898. bMatch = 0;
  176899. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  176900. pNode->bNomatch = 0;
  176901. pNode->bEof = 1;
  176902. return rc;
  176903. }
  176904. }else{
  176905. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  176906. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  176907. bMatch = 0;
  176908. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  176909. return rc;
  176910. }
  176911. }
  176912. }
  176913. }
  176914. }while( bMatch==0 );
  176915. pNode->iRowid = iLast;
  176916. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  176917. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  176918. return rc;
  176919. }
  176920. /*
  176921. ** Advance the first term iterator in the first phrase of pNear. Set output
  176922. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  176923. **
  176924. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  176925. ** occurs.
  176926. */
  176927. static int fts5ExprNodeNext_STRING(
  176928. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  176929. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  176930. int bFromValid,
  176931. i64 iFrom
  176932. ){
  176933. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  176934. int rc = SQLITE_OK;
  176935. pNode->bNomatch = 0;
  176936. if( pTerm->pSynonym ){
  176937. int bEof = 1;
  176938. Fts5ExprTerm *p;
  176939. /* Find the firstest rowid any synonym points to. */
  176940. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  176941. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  176942. ** is valid - each iterator that points to a rowid before iFrom. */
  176943. for(p=pTerm; p; p=p->pSynonym){
  176944. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  176945. i64 ii = p->pIter->iRowid;
  176946. if( ii==iRowid
  176947. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  176948. ){
  176949. if( bFromValid ){
  176950. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  176951. }else{
  176952. rc = sqlite3Fts5IterNext(p->pIter);
  176953. }
  176954. if( rc!=SQLITE_OK ) break;
  176955. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  176956. bEof = 0;
  176957. }
  176958. }else{
  176959. bEof = 0;
  176960. }
  176961. }
  176962. }
  176963. /* Set the EOF flag if either all synonym iterators are at EOF or an
  176964. ** error has occurred. */
  176965. pNode->bEof = (rc || bEof);
  176966. }else{
  176967. Fts5IndexIter *pIter = pTerm->pIter;
  176968. assert( Fts5NodeIsString(pNode) );
  176969. if( bFromValid ){
  176970. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  176971. }else{
  176972. rc = sqlite3Fts5IterNext(pIter);
  176973. }
  176974. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  176975. }
  176976. if( pNode->bEof==0 ){
  176977. assert( rc==SQLITE_OK );
  176978. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  176979. }
  176980. return rc;
  176981. }
  176982. static int fts5ExprNodeTest_TERM(
  176983. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  176984. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  176985. ){
  176986. /* As this "NEAR" object is actually a single phrase that consists
  176987. ** of a single term only, grab pointers into the poslist managed by the
  176988. ** fts5_index.c iterator object. This is much faster than synthesizing
  176989. ** a new poslist the way we have to for more complicated phrase or NEAR
  176990. ** expressions. */
  176991. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  176992. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  176993. assert( pNode->eType==FTS5_TERM );
  176994. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  176995. assert( pPhrase->aTerm[0].pSynonym==0 );
  176996. pPhrase->poslist.n = pIter->nData;
  176997. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  176998. pPhrase->poslist.p = (u8*)pIter->pData;
  176999. }
  177000. pNode->iRowid = pIter->iRowid;
  177001. pNode->bNomatch = (pPhrase->poslist.n==0);
  177002. return SQLITE_OK;
  177003. }
  177004. /*
  177005. ** xNext() method for a node of type FTS5_TERM.
  177006. */
  177007. static int fts5ExprNodeNext_TERM(
  177008. Fts5Expr *pExpr,
  177009. Fts5ExprNode *pNode,
  177010. int bFromValid,
  177011. i64 iFrom
  177012. ){
  177013. int rc;
  177014. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  177015. assert( pNode->bEof==0 );
  177016. if( bFromValid ){
  177017. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  177018. }else{
  177019. rc = sqlite3Fts5IterNext(pIter);
  177020. }
  177021. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  177022. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  177023. }else{
  177024. pNode->bEof = 1;
  177025. pNode->bNomatch = 0;
  177026. }
  177027. return rc;
  177028. }
  177029. static void fts5ExprNodeTest_OR(
  177030. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  177031. Fts5ExprNode *pNode /* Expression node to test */
  177032. ){
  177033. Fts5ExprNode *pNext = pNode->apChild[0];
  177034. int i;
  177035. for(i=1; i<pNode->nChild; i++){
  177036. Fts5ExprNode *pChild = pNode->apChild[i];
  177037. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  177038. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  177039. pNext = pChild;
  177040. }
  177041. }
  177042. pNode->iRowid = pNext->iRowid;
  177043. pNode->bEof = pNext->bEof;
  177044. pNode->bNomatch = pNext->bNomatch;
  177045. }
  177046. static int fts5ExprNodeNext_OR(
  177047. Fts5Expr *pExpr,
  177048. Fts5ExprNode *pNode,
  177049. int bFromValid,
  177050. i64 iFrom
  177051. ){
  177052. int i;
  177053. i64 iLast = pNode->iRowid;
  177054. for(i=0; i<pNode->nChild; i++){
  177055. Fts5ExprNode *p1 = pNode->apChild[i];
  177056. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  177057. if( p1->bEof==0 ){
  177058. if( (p1->iRowid==iLast)
  177059. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  177060. ){
  177061. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  177062. if( rc!=SQLITE_OK ){
  177063. pNode->bNomatch = 0;
  177064. return rc;
  177065. }
  177066. }
  177067. }
  177068. }
  177069. fts5ExprNodeTest_OR(pExpr, pNode);
  177070. return SQLITE_OK;
  177071. }
  177072. /*
  177073. ** Argument pNode is an FTS5_AND node.
  177074. */
  177075. static int fts5ExprNodeTest_AND(
  177076. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  177077. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  177078. ){
  177079. int iChild;
  177080. i64 iLast = pAnd->iRowid;
  177081. int rc = SQLITE_OK;
  177082. int bMatch;
  177083. assert( pAnd->bEof==0 );
  177084. do {
  177085. pAnd->bNomatch = 0;
  177086. bMatch = 1;
  177087. for(iChild=0; iChild<pAnd->nChild; iChild++){
  177088. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  177089. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  177090. if( cmp>0 ){
  177091. /* Advance pChild until it points to iLast or laster */
  177092. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  177093. if( rc!=SQLITE_OK ){
  177094. pAnd->bNomatch = 0;
  177095. return rc;
  177096. }
  177097. }
  177098. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  177099. ** the child node is guaranteed to have advanced at least as far as
  177100. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  177101. ** new lastest rowid seen so far. */
  177102. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  177103. if( pChild->bEof ){
  177104. fts5ExprSetEof(pAnd);
  177105. bMatch = 1;
  177106. break;
  177107. }else if( iLast!=pChild->iRowid ){
  177108. bMatch = 0;
  177109. iLast = pChild->iRowid;
  177110. }
  177111. if( pChild->bNomatch ){
  177112. pAnd->bNomatch = 1;
  177113. }
  177114. }
  177115. }while( bMatch==0 );
  177116. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  177117. fts5ExprNodeZeroPoslist(pAnd);
  177118. }
  177119. pAnd->iRowid = iLast;
  177120. return SQLITE_OK;
  177121. }
  177122. static int fts5ExprNodeNext_AND(
  177123. Fts5Expr *pExpr,
  177124. Fts5ExprNode *pNode,
  177125. int bFromValid,
  177126. i64 iFrom
  177127. ){
  177128. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  177129. if( rc==SQLITE_OK ){
  177130. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  177131. }else{
  177132. pNode->bNomatch = 0;
  177133. }
  177134. return rc;
  177135. }
  177136. static int fts5ExprNodeTest_NOT(
  177137. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  177138. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  177139. ){
  177140. int rc = SQLITE_OK;
  177141. Fts5ExprNode *p1 = pNode->apChild[0];
  177142. Fts5ExprNode *p2 = pNode->apChild[1];
  177143. assert( pNode->nChild==2 );
  177144. while( rc==SQLITE_OK && p1->bEof==0 ){
  177145. int cmp = fts5NodeCompare(pExpr, p1, p2);
  177146. if( cmp>0 ){
  177147. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  177148. cmp = fts5NodeCompare(pExpr, p1, p2);
  177149. }
  177150. assert( rc!=SQLITE_OK || cmp<=0 );
  177151. if( cmp || p2->bNomatch ) break;
  177152. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  177153. }
  177154. pNode->bEof = p1->bEof;
  177155. pNode->bNomatch = p1->bNomatch;
  177156. pNode->iRowid = p1->iRowid;
  177157. if( p1->bEof ){
  177158. fts5ExprNodeZeroPoslist(p2);
  177159. }
  177160. return rc;
  177161. }
  177162. static int fts5ExprNodeNext_NOT(
  177163. Fts5Expr *pExpr,
  177164. Fts5ExprNode *pNode,
  177165. int bFromValid,
  177166. i64 iFrom
  177167. ){
  177168. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  177169. if( rc==SQLITE_OK ){
  177170. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  177171. }
  177172. if( rc!=SQLITE_OK ){
  177173. pNode->bNomatch = 0;
  177174. }
  177175. return rc;
  177176. }
  177177. /*
  177178. ** If pNode currently points to a match, this function returns SQLITE_OK
  177179. ** without modifying it. Otherwise, pNode is advanced until it does point
  177180. ** to a match or EOF is reached.
  177181. */
  177182. static int fts5ExprNodeTest(
  177183. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  177184. Fts5ExprNode *pNode /* Expression node to test */
  177185. ){
  177186. int rc = SQLITE_OK;
  177187. if( pNode->bEof==0 ){
  177188. switch( pNode->eType ){
  177189. case FTS5_STRING: {
  177190. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  177191. break;
  177192. }
  177193. case FTS5_TERM: {
  177194. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  177195. break;
  177196. }
  177197. case FTS5_AND: {
  177198. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  177199. break;
  177200. }
  177201. case FTS5_OR: {
  177202. fts5ExprNodeTest_OR(pExpr, pNode);
  177203. break;
  177204. }
  177205. default: assert( pNode->eType==FTS5_NOT ); {
  177206. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  177207. break;
  177208. }
  177209. }
  177210. }
  177211. return rc;
  177212. }
  177213. /*
  177214. ** Set node pNode, which is part of expression pExpr, to point to the first
  177215. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  177216. **
  177217. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  177218. ** It is not an error if there are no matches.
  177219. */
  177220. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  177221. int rc = SQLITE_OK;
  177222. pNode->bEof = 0;
  177223. pNode->bNomatch = 0;
  177224. if( Fts5NodeIsString(pNode) ){
  177225. /* Initialize all term iterators in the NEAR object. */
  177226. rc = fts5ExprNearInitAll(pExpr, pNode);
  177227. }else if( pNode->xNext==0 ){
  177228. pNode->bEof = 1;
  177229. }else{
  177230. int i;
  177231. int nEof = 0;
  177232. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  177233. Fts5ExprNode *pChild = pNode->apChild[i];
  177234. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  177235. assert( pChild->bEof==0 || pChild->bEof==1 );
  177236. nEof += pChild->bEof;
  177237. }
  177238. pNode->iRowid = pNode->apChild[0]->iRowid;
  177239. switch( pNode->eType ){
  177240. case FTS5_AND:
  177241. if( nEof>0 ) fts5ExprSetEof(pNode);
  177242. break;
  177243. case FTS5_OR:
  177244. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  177245. break;
  177246. default:
  177247. assert( pNode->eType==FTS5_NOT );
  177248. pNode->bEof = pNode->apChild[0]->bEof;
  177249. break;
  177250. }
  177251. }
  177252. if( rc==SQLITE_OK ){
  177253. rc = fts5ExprNodeTest(pExpr, pNode);
  177254. }
  177255. return rc;
  177256. }
  177257. /*
  177258. ** Begin iterating through the set of documents in index pIdx matched by
  177259. ** the MATCH expression passed as the first argument. If the "bDesc"
  177260. ** parameter is passed a non-zero value, iteration is in descending rowid
  177261. ** order. Or, if it is zero, in ascending order.
  177262. **
  177263. ** If iterating in ascending rowid order (bDesc==0), the first document
  177264. ** visited is that with the smallest rowid that is larger than or equal
  177265. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  177266. ** then the first document visited must have a rowid smaller than or
  177267. ** equal to iFirst.
  177268. **
  177269. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  177270. ** is not considered an error if the query does not match any documents.
  177271. */
  177272. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  177273. Fts5ExprNode *pRoot = p->pRoot;
  177274. int rc; /* Return code */
  177275. p->pIndex = pIdx;
  177276. p->bDesc = bDesc;
  177277. rc = fts5ExprNodeFirst(p, pRoot);
  177278. /* If not at EOF but the current rowid occurs earlier than iFirst in
  177279. ** the iteration order, move to document iFirst or later. */
  177280. if( rc==SQLITE_OK
  177281. && 0==pRoot->bEof
  177282. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  177283. ){
  177284. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  177285. }
  177286. /* If the iterator is not at a real match, skip forward until it is. */
  177287. while( pRoot->bNomatch ){
  177288. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  177289. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  177290. }
  177291. return rc;
  177292. }
  177293. /*
  177294. ** Move to the next document
  177295. **
  177296. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  177297. ** is not considered an error if the query does not match any documents.
  177298. */
  177299. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  177300. int rc;
  177301. Fts5ExprNode *pRoot = p->pRoot;
  177302. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  177303. do {
  177304. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  177305. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  177306. }while( pRoot->bNomatch );
  177307. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  177308. pRoot->bEof = 1;
  177309. }
  177310. return rc;
  177311. }
  177312. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  177313. return p->pRoot->bEof;
  177314. }
  177315. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  177316. return p->pRoot->iRowid;
  177317. }
  177318. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  177319. int rc = SQLITE_OK;
  177320. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  177321. return rc;
  177322. }
  177323. /*
  177324. ** Free the phrase object passed as the only argument.
  177325. */
  177326. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  177327. if( pPhrase ){
  177328. int i;
  177329. for(i=0; i<pPhrase->nTerm; i++){
  177330. Fts5ExprTerm *pSyn;
  177331. Fts5ExprTerm *pNext;
  177332. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  177333. sqlite3_free(pTerm->zTerm);
  177334. sqlite3Fts5IterClose(pTerm->pIter);
  177335. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  177336. pNext = pSyn->pSynonym;
  177337. sqlite3Fts5IterClose(pSyn->pIter);
  177338. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  177339. sqlite3_free(pSyn);
  177340. }
  177341. }
  177342. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  177343. sqlite3_free(pPhrase);
  177344. }
  177345. }
  177346. /*
  177347. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  177348. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  177349. ** appended to it and the results returned.
  177350. **
  177351. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  177352. ** NULL returned.
  177353. */
  177354. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  177355. Fts5Parse *pParse, /* Parse context */
  177356. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  177357. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  177358. ){
  177359. const int SZALLOC = 8;
  177360. Fts5ExprNearset *pRet = 0;
  177361. if( pParse->rc==SQLITE_OK ){
  177362. if( pPhrase==0 ){
  177363. return pNear;
  177364. }
  177365. if( pNear==0 ){
  177366. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  177367. pRet = sqlite3_malloc(nByte);
  177368. if( pRet==0 ){
  177369. pParse->rc = SQLITE_NOMEM;
  177370. }else{
  177371. memset(pRet, 0, nByte);
  177372. }
  177373. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  177374. int nNew = pNear->nPhrase + SZALLOC;
  177375. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  177376. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  177377. if( pRet==0 ){
  177378. pParse->rc = SQLITE_NOMEM;
  177379. }
  177380. }else{
  177381. pRet = pNear;
  177382. }
  177383. }
  177384. if( pRet==0 ){
  177385. assert( pParse->rc!=SQLITE_OK );
  177386. sqlite3Fts5ParseNearsetFree(pNear);
  177387. sqlite3Fts5ParsePhraseFree(pPhrase);
  177388. }else{
  177389. if( pRet->nPhrase>0 ){
  177390. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  177391. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  177392. if( pPhrase->nTerm==0 ){
  177393. fts5ExprPhraseFree(pPhrase);
  177394. pRet->nPhrase--;
  177395. pParse->nPhrase--;
  177396. pPhrase = pLast;
  177397. }else if( pLast->nTerm==0 ){
  177398. fts5ExprPhraseFree(pLast);
  177399. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  177400. pParse->nPhrase--;
  177401. pRet->nPhrase--;
  177402. }
  177403. }
  177404. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  177405. }
  177406. return pRet;
  177407. }
  177408. typedef struct TokenCtx TokenCtx;
  177409. struct TokenCtx {
  177410. Fts5ExprPhrase *pPhrase;
  177411. int rc;
  177412. };
  177413. /*
  177414. ** Callback for tokenizing terms used by ParseTerm().
  177415. */
  177416. static int fts5ParseTokenize(
  177417. void *pContext, /* Pointer to Fts5InsertCtx object */
  177418. int tflags, /* Mask of FTS5_TOKEN_* flags */
  177419. const char *pToken, /* Buffer containing token */
  177420. int nToken, /* Size of token in bytes */
  177421. int iUnused1, /* Start offset of token */
  177422. int iUnused2 /* End offset of token */
  177423. ){
  177424. int rc = SQLITE_OK;
  177425. const int SZALLOC = 8;
  177426. TokenCtx *pCtx = (TokenCtx*)pContext;
  177427. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  177428. UNUSED_PARAM2(iUnused1, iUnused2);
  177429. /* If an error has already occurred, this is a no-op */
  177430. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  177431. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  177432. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  177433. Fts5ExprTerm *pSyn;
  177434. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  177435. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  177436. if( pSyn==0 ){
  177437. rc = SQLITE_NOMEM;
  177438. }else{
  177439. memset(pSyn, 0, nByte);
  177440. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  177441. memcpy(pSyn->zTerm, pToken, nToken);
  177442. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  177443. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  177444. }
  177445. }else{
  177446. Fts5ExprTerm *pTerm;
  177447. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  177448. Fts5ExprPhrase *pNew;
  177449. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  177450. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  177451. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  177452. );
  177453. if( pNew==0 ){
  177454. rc = SQLITE_NOMEM;
  177455. }else{
  177456. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  177457. pCtx->pPhrase = pPhrase = pNew;
  177458. pNew->nTerm = nNew - SZALLOC;
  177459. }
  177460. }
  177461. if( rc==SQLITE_OK ){
  177462. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  177463. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  177464. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  177465. }
  177466. }
  177467. pCtx->rc = rc;
  177468. return rc;
  177469. }
  177470. /*
  177471. ** Free the phrase object passed as the only argument.
  177472. */
  177473. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  177474. fts5ExprPhraseFree(pPhrase);
  177475. }
  177476. /*
  177477. ** Free the phrase object passed as the second argument.
  177478. */
  177479. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  177480. if( pNear ){
  177481. int i;
  177482. for(i=0; i<pNear->nPhrase; i++){
  177483. fts5ExprPhraseFree(pNear->apPhrase[i]);
  177484. }
  177485. sqlite3_free(pNear->pColset);
  177486. sqlite3_free(pNear);
  177487. }
  177488. }
  177489. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  177490. assert( pParse->pExpr==0 );
  177491. pParse->pExpr = p;
  177492. }
  177493. /*
  177494. ** This function is called by the parser to process a string token. The
  177495. ** string may or may not be quoted. In any case it is tokenized and a
  177496. ** phrase object consisting of all tokens returned.
  177497. */
  177498. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  177499. Fts5Parse *pParse, /* Parse context */
  177500. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  177501. Fts5Token *pToken, /* String to tokenize */
  177502. int bPrefix /* True if there is a trailing "*" */
  177503. ){
  177504. Fts5Config *pConfig = pParse->pConfig;
  177505. TokenCtx sCtx; /* Context object passed to callback */
  177506. int rc; /* Tokenize return code */
  177507. char *z = 0;
  177508. memset(&sCtx, 0, sizeof(TokenCtx));
  177509. sCtx.pPhrase = pAppend;
  177510. rc = fts5ParseStringFromToken(pToken, &z);
  177511. if( rc==SQLITE_OK ){
  177512. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  177513. int n;
  177514. sqlite3Fts5Dequote(z);
  177515. n = (int)strlen(z);
  177516. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  177517. }
  177518. sqlite3_free(z);
  177519. if( rc || (rc = sCtx.rc) ){
  177520. pParse->rc = rc;
  177521. fts5ExprPhraseFree(sCtx.pPhrase);
  177522. sCtx.pPhrase = 0;
  177523. }else{
  177524. if( pAppend==0 ){
  177525. if( (pParse->nPhrase % 8)==0 ){
  177526. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  177527. Fts5ExprPhrase **apNew;
  177528. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  177529. if( apNew==0 ){
  177530. pParse->rc = SQLITE_NOMEM;
  177531. fts5ExprPhraseFree(sCtx.pPhrase);
  177532. return 0;
  177533. }
  177534. pParse->apPhrase = apNew;
  177535. }
  177536. pParse->nPhrase++;
  177537. }
  177538. if( sCtx.pPhrase==0 ){
  177539. /* This happens when parsing a token or quoted phrase that contains
  177540. ** no token characters at all. (e.g ... MATCH '""'). */
  177541. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  177542. }else if( sCtx.pPhrase->nTerm ){
  177543. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  177544. }
  177545. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  177546. }
  177547. return sCtx.pPhrase;
  177548. }
  177549. /*
  177550. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  177551. ** expression passed as the second argument.
  177552. */
  177553. static int sqlite3Fts5ExprClonePhrase(
  177554. Fts5Expr *pExpr,
  177555. int iPhrase,
  177556. Fts5Expr **ppNew
  177557. ){
  177558. int rc = SQLITE_OK; /* Return code */
  177559. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  177560. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  177561. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  177562. pOrig = pExpr->apExprPhrase[iPhrase];
  177563. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  177564. if( rc==SQLITE_OK ){
  177565. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  177566. sizeof(Fts5ExprPhrase*));
  177567. }
  177568. if( rc==SQLITE_OK ){
  177569. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  177570. sizeof(Fts5ExprNode));
  177571. }
  177572. if( rc==SQLITE_OK ){
  177573. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  177574. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  177575. }
  177576. if( rc==SQLITE_OK ){
  177577. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  177578. if( pColsetOrig ){
  177579. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  177580. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  177581. if( pColset ){
  177582. memcpy(pColset, pColsetOrig, nByte);
  177583. }
  177584. pNew->pRoot->pNear->pColset = pColset;
  177585. }
  177586. }
  177587. if( pOrig->nTerm ){
  177588. int i; /* Used to iterate through phrase terms */
  177589. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  177590. int tflags = 0;
  177591. Fts5ExprTerm *p;
  177592. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  177593. const char *zTerm = p->zTerm;
  177594. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  177595. 0, 0);
  177596. tflags = FTS5_TOKEN_COLOCATED;
  177597. }
  177598. if( rc==SQLITE_OK ){
  177599. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  177600. }
  177601. }
  177602. }else{
  177603. /* This happens when parsing a token or quoted phrase that contains
  177604. ** no token characters at all. (e.g ... MATCH '""'). */
  177605. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  177606. }
  177607. if( rc==SQLITE_OK ){
  177608. /* All the allocations succeeded. Put the expression object together. */
  177609. pNew->pIndex = pExpr->pIndex;
  177610. pNew->pConfig = pExpr->pConfig;
  177611. pNew->nPhrase = 1;
  177612. pNew->apExprPhrase[0] = sCtx.pPhrase;
  177613. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  177614. pNew->pRoot->pNear->nPhrase = 1;
  177615. sCtx.pPhrase->pNode = pNew->pRoot;
  177616. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  177617. pNew->pRoot->eType = FTS5_TERM;
  177618. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  177619. }else{
  177620. pNew->pRoot->eType = FTS5_STRING;
  177621. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  177622. }
  177623. }else{
  177624. sqlite3Fts5ExprFree(pNew);
  177625. fts5ExprPhraseFree(sCtx.pPhrase);
  177626. pNew = 0;
  177627. }
  177628. *ppNew = pNew;
  177629. return rc;
  177630. }
  177631. /*
  177632. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  177633. ** is expected. If token pTok does not contain "NEAR", store an error
  177634. ** in the pParse object.
  177635. */
  177636. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  177637. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  177638. sqlite3Fts5ParseError(
  177639. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  177640. );
  177641. }
  177642. }
  177643. static void sqlite3Fts5ParseSetDistance(
  177644. Fts5Parse *pParse,
  177645. Fts5ExprNearset *pNear,
  177646. Fts5Token *p
  177647. ){
  177648. if( pNear ){
  177649. int nNear = 0;
  177650. int i;
  177651. if( p->n ){
  177652. for(i=0; i<p->n; i++){
  177653. char c = (char)p->p[i];
  177654. if( c<'0' || c>'9' ){
  177655. sqlite3Fts5ParseError(
  177656. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  177657. );
  177658. return;
  177659. }
  177660. nNear = nNear * 10 + (p->p[i] - '0');
  177661. }
  177662. }else{
  177663. nNear = FTS5_DEFAULT_NEARDIST;
  177664. }
  177665. pNear->nNear = nNear;
  177666. }
  177667. }
  177668. /*
  177669. ** The second argument passed to this function may be NULL, or it may be
  177670. ** an existing Fts5Colset object. This function returns a pointer to
  177671. ** a new colset object containing the contents of (p) with new value column
  177672. ** number iCol appended.
  177673. **
  177674. ** If an OOM error occurs, store an error code in pParse and return NULL.
  177675. ** The old colset object (if any) is not freed in this case.
  177676. */
  177677. static Fts5Colset *fts5ParseColset(
  177678. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  177679. Fts5Colset *p, /* Existing colset object */
  177680. int iCol /* New column to add to colset object */
  177681. ){
  177682. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  177683. Fts5Colset *pNew; /* New colset object to return */
  177684. assert( pParse->rc==SQLITE_OK );
  177685. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  177686. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  177687. if( pNew==0 ){
  177688. pParse->rc = SQLITE_NOMEM;
  177689. }else{
  177690. int *aiCol = pNew->aiCol;
  177691. int i, j;
  177692. for(i=0; i<nCol; i++){
  177693. if( aiCol[i]==iCol ) return pNew;
  177694. if( aiCol[i]>iCol ) break;
  177695. }
  177696. for(j=nCol; j>i; j--){
  177697. aiCol[j] = aiCol[j-1];
  177698. }
  177699. aiCol[i] = iCol;
  177700. pNew->nCol = nCol+1;
  177701. #ifndef NDEBUG
  177702. /* Check that the array is in order and contains no duplicate entries. */
  177703. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  177704. #endif
  177705. }
  177706. return pNew;
  177707. }
  177708. /*
  177709. ** Allocate and return an Fts5Colset object specifying the inverse of
  177710. ** the colset passed as the second argument. Free the colset passed
  177711. ** as the second argument before returning.
  177712. */
  177713. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  177714. Fts5Colset *pRet;
  177715. int nCol = pParse->pConfig->nCol;
  177716. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  177717. sizeof(Fts5Colset) + sizeof(int)*nCol
  177718. );
  177719. if( pRet ){
  177720. int i;
  177721. int iOld = 0;
  177722. for(i=0; i<nCol; i++){
  177723. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  177724. pRet->aiCol[pRet->nCol++] = i;
  177725. }else{
  177726. iOld++;
  177727. }
  177728. }
  177729. }
  177730. sqlite3_free(p);
  177731. return pRet;
  177732. }
  177733. static Fts5Colset *sqlite3Fts5ParseColset(
  177734. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  177735. Fts5Colset *pColset, /* Existing colset object */
  177736. Fts5Token *p
  177737. ){
  177738. Fts5Colset *pRet = 0;
  177739. int iCol;
  177740. char *z; /* Dequoted copy of token p */
  177741. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  177742. if( pParse->rc==SQLITE_OK ){
  177743. Fts5Config *pConfig = pParse->pConfig;
  177744. sqlite3Fts5Dequote(z);
  177745. for(iCol=0; iCol<pConfig->nCol; iCol++){
  177746. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  177747. }
  177748. if( iCol==pConfig->nCol ){
  177749. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  177750. }else{
  177751. pRet = fts5ParseColset(pParse, pColset, iCol);
  177752. }
  177753. sqlite3_free(z);
  177754. }
  177755. if( pRet==0 ){
  177756. assert( pParse->rc!=SQLITE_OK );
  177757. sqlite3_free(pColset);
  177758. }
  177759. return pRet;
  177760. }
  177761. /*
  177762. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  177763. ** SQLITE_OK when this function is called, NULL is returned.
  177764. **
  177765. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  177766. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  177767. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  177768. */
  177769. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  177770. Fts5Colset *pRet;
  177771. if( pOrig ){
  177772. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  177773. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  177774. if( pRet ){
  177775. memcpy(pRet, pOrig, nByte);
  177776. }
  177777. }else{
  177778. pRet = 0;
  177779. }
  177780. return pRet;
  177781. }
  177782. /*
  177783. ** Remove from colset pColset any columns that are not also in colset pMerge.
  177784. */
  177785. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  177786. int iIn = 0; /* Next input in pColset */
  177787. int iMerge = 0; /* Next input in pMerge */
  177788. int iOut = 0; /* Next output slot in pColset */
  177789. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  177790. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  177791. if( iDiff==0 ){
  177792. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  177793. iMerge++;
  177794. iIn++;
  177795. }else if( iDiff>0 ){
  177796. iMerge++;
  177797. }else{
  177798. iIn++;
  177799. }
  177800. }
  177801. pColset->nCol = iOut;
  177802. }
  177803. /*
  177804. ** Recursively apply colset pColset to expression node pNode and all of
  177805. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  177806. ** of pColset. This function may use the spare copy and set (*ppFree) to
  177807. ** zero, or it may create copies of pColset using fts5CloneColset().
  177808. */
  177809. static void fts5ParseSetColset(
  177810. Fts5Parse *pParse,
  177811. Fts5ExprNode *pNode,
  177812. Fts5Colset *pColset,
  177813. Fts5Colset **ppFree
  177814. ){
  177815. if( pParse->rc==SQLITE_OK ){
  177816. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  177817. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  177818. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  177819. );
  177820. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  177821. Fts5ExprNearset *pNear = pNode->pNear;
  177822. if( pNear->pColset ){
  177823. fts5MergeColset(pNear->pColset, pColset);
  177824. if( pNear->pColset->nCol==0 ){
  177825. pNode->eType = FTS5_EOF;
  177826. pNode->xNext = 0;
  177827. }
  177828. }else if( *ppFree ){
  177829. pNear->pColset = pColset;
  177830. *ppFree = 0;
  177831. }else{
  177832. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  177833. }
  177834. }else{
  177835. int i;
  177836. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  177837. for(i=0; i<pNode->nChild; i++){
  177838. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  177839. }
  177840. }
  177841. }
  177842. }
  177843. /*
  177844. ** Apply colset pColset to expression node pExpr and all of its descendents.
  177845. */
  177846. static void sqlite3Fts5ParseSetColset(
  177847. Fts5Parse *pParse,
  177848. Fts5ExprNode *pExpr,
  177849. Fts5Colset *pColset
  177850. ){
  177851. Fts5Colset *pFree = pColset;
  177852. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  177853. pParse->rc = SQLITE_ERROR;
  177854. pParse->zErr = sqlite3_mprintf(
  177855. "fts5: column queries are not supported (detail=none)"
  177856. );
  177857. }else{
  177858. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  177859. }
  177860. sqlite3_free(pFree);
  177861. }
  177862. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  177863. switch( pNode->eType ){
  177864. case FTS5_STRING: {
  177865. Fts5ExprNearset *pNear = pNode->pNear;
  177866. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  177867. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  177868. ){
  177869. pNode->eType = FTS5_TERM;
  177870. pNode->xNext = fts5ExprNodeNext_TERM;
  177871. }else{
  177872. pNode->xNext = fts5ExprNodeNext_STRING;
  177873. }
  177874. break;
  177875. };
  177876. case FTS5_OR: {
  177877. pNode->xNext = fts5ExprNodeNext_OR;
  177878. break;
  177879. };
  177880. case FTS5_AND: {
  177881. pNode->xNext = fts5ExprNodeNext_AND;
  177882. break;
  177883. };
  177884. default: assert( pNode->eType==FTS5_NOT ); {
  177885. pNode->xNext = fts5ExprNodeNext_NOT;
  177886. break;
  177887. };
  177888. }
  177889. }
  177890. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  177891. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  177892. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  177893. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  177894. p->nChild += pSub->nChild;
  177895. sqlite3_free(pSub);
  177896. }else{
  177897. p->apChild[p->nChild++] = pSub;
  177898. }
  177899. }
  177900. /*
  177901. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  177902. ** OOM error), leave an error code in pParse and return NULL.
  177903. */
  177904. static Fts5ExprNode *sqlite3Fts5ParseNode(
  177905. Fts5Parse *pParse, /* Parse context */
  177906. int eType, /* FTS5_STRING, AND, OR or NOT */
  177907. Fts5ExprNode *pLeft, /* Left hand child expression */
  177908. Fts5ExprNode *pRight, /* Right hand child expression */
  177909. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  177910. ){
  177911. Fts5ExprNode *pRet = 0;
  177912. if( pParse->rc==SQLITE_OK ){
  177913. int nChild = 0; /* Number of children of returned node */
  177914. int nByte; /* Bytes of space to allocate for this node */
  177915. assert( (eType!=FTS5_STRING && !pNear)
  177916. || (eType==FTS5_STRING && !pLeft && !pRight)
  177917. );
  177918. if( eType==FTS5_STRING && pNear==0 ) return 0;
  177919. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  177920. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  177921. if( eType==FTS5_NOT ){
  177922. nChild = 2;
  177923. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  177924. nChild = 2;
  177925. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  177926. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  177927. }
  177928. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  177929. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  177930. if( pRet ){
  177931. pRet->eType = eType;
  177932. pRet->pNear = pNear;
  177933. fts5ExprAssignXNext(pRet);
  177934. if( eType==FTS5_STRING ){
  177935. int iPhrase;
  177936. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  177937. pNear->apPhrase[iPhrase]->pNode = pRet;
  177938. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  177939. pRet->xNext = 0;
  177940. pRet->eType = FTS5_EOF;
  177941. }
  177942. }
  177943. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
  177944. && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
  177945. ){
  177946. assert( pParse->rc==SQLITE_OK );
  177947. pParse->rc = SQLITE_ERROR;
  177948. assert( pParse->zErr==0 );
  177949. pParse->zErr = sqlite3_mprintf(
  177950. "fts5: %s queries are not supported (detail!=full)",
  177951. pNear->nPhrase==1 ? "phrase": "NEAR"
  177952. );
  177953. sqlite3_free(pRet);
  177954. pRet = 0;
  177955. }
  177956. }else{
  177957. fts5ExprAddChildren(pRet, pLeft);
  177958. fts5ExprAddChildren(pRet, pRight);
  177959. }
  177960. }
  177961. }
  177962. if( pRet==0 ){
  177963. assert( pParse->rc!=SQLITE_OK );
  177964. sqlite3Fts5ParseNodeFree(pLeft);
  177965. sqlite3Fts5ParseNodeFree(pRight);
  177966. sqlite3Fts5ParseNearsetFree(pNear);
  177967. }
  177968. return pRet;
  177969. }
  177970. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  177971. Fts5Parse *pParse, /* Parse context */
  177972. Fts5ExprNode *pLeft, /* Left hand child expression */
  177973. Fts5ExprNode *pRight /* Right hand child expression */
  177974. ){
  177975. Fts5ExprNode *pRet = 0;
  177976. Fts5ExprNode *pPrev;
  177977. if( pParse->rc ){
  177978. sqlite3Fts5ParseNodeFree(pLeft);
  177979. sqlite3Fts5ParseNodeFree(pRight);
  177980. }else{
  177981. assert( pLeft->eType==FTS5_STRING
  177982. || pLeft->eType==FTS5_TERM
  177983. || pLeft->eType==FTS5_EOF
  177984. || pLeft->eType==FTS5_AND
  177985. );
  177986. assert( pRight->eType==FTS5_STRING
  177987. || pRight->eType==FTS5_TERM
  177988. || pRight->eType==FTS5_EOF
  177989. );
  177990. if( pLeft->eType==FTS5_AND ){
  177991. pPrev = pLeft->apChild[pLeft->nChild-1];
  177992. }else{
  177993. pPrev = pLeft;
  177994. }
  177995. assert( pPrev->eType==FTS5_STRING
  177996. || pPrev->eType==FTS5_TERM
  177997. || pPrev->eType==FTS5_EOF
  177998. );
  177999. if( pRight->eType==FTS5_EOF ){
  178000. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  178001. sqlite3Fts5ParseNodeFree(pRight);
  178002. pRet = pLeft;
  178003. pParse->nPhrase--;
  178004. }
  178005. else if( pPrev->eType==FTS5_EOF ){
  178006. Fts5ExprPhrase **ap;
  178007. if( pPrev==pLeft ){
  178008. pRet = pRight;
  178009. }else{
  178010. pLeft->apChild[pLeft->nChild-1] = pRight;
  178011. pRet = pLeft;
  178012. }
  178013. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  178014. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  178015. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  178016. pParse->nPhrase--;
  178017. sqlite3Fts5ParseNodeFree(pPrev);
  178018. }
  178019. else{
  178020. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  178021. }
  178022. }
  178023. return pRet;
  178024. }
  178025. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  178026. int nByte = 0;
  178027. Fts5ExprTerm *p;
  178028. char *zQuoted;
  178029. /* Determine the maximum amount of space required. */
  178030. for(p=pTerm; p; p=p->pSynonym){
  178031. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  178032. }
  178033. zQuoted = sqlite3_malloc(nByte);
  178034. if( zQuoted ){
  178035. int i = 0;
  178036. for(p=pTerm; p; p=p->pSynonym){
  178037. char *zIn = p->zTerm;
  178038. zQuoted[i++] = '"';
  178039. while( *zIn ){
  178040. if( *zIn=='"' ) zQuoted[i++] = '"';
  178041. zQuoted[i++] = *zIn++;
  178042. }
  178043. zQuoted[i++] = '"';
  178044. if( p->pSynonym ) zQuoted[i++] = '|';
  178045. }
  178046. if( pTerm->bPrefix ){
  178047. zQuoted[i++] = ' ';
  178048. zQuoted[i++] = '*';
  178049. }
  178050. zQuoted[i++] = '\0';
  178051. }
  178052. return zQuoted;
  178053. }
  178054. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  178055. char *zNew;
  178056. va_list ap;
  178057. va_start(ap, zFmt);
  178058. zNew = sqlite3_vmprintf(zFmt, ap);
  178059. va_end(ap);
  178060. if( zApp && zNew ){
  178061. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  178062. sqlite3_free(zNew);
  178063. zNew = zNew2;
  178064. }
  178065. sqlite3_free(zApp);
  178066. return zNew;
  178067. }
  178068. /*
  178069. ** Compose a tcl-readable representation of expression pExpr. Return a
  178070. ** pointer to a buffer containing that representation. It is the
  178071. ** responsibility of the caller to at some point free the buffer using
  178072. ** sqlite3_free().
  178073. */
  178074. static char *fts5ExprPrintTcl(
  178075. Fts5Config *pConfig,
  178076. const char *zNearsetCmd,
  178077. Fts5ExprNode *pExpr
  178078. ){
  178079. char *zRet = 0;
  178080. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  178081. Fts5ExprNearset *pNear = pExpr->pNear;
  178082. int i;
  178083. int iTerm;
  178084. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  178085. if( zRet==0 ) return 0;
  178086. if( pNear->pColset ){
  178087. int *aiCol = pNear->pColset->aiCol;
  178088. int nCol = pNear->pColset->nCol;
  178089. if( nCol==1 ){
  178090. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  178091. }else{
  178092. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  178093. for(i=1; i<pNear->pColset->nCol; i++){
  178094. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  178095. }
  178096. zRet = fts5PrintfAppend(zRet, "} ");
  178097. }
  178098. if( zRet==0 ) return 0;
  178099. }
  178100. if( pNear->nPhrase>1 ){
  178101. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  178102. if( zRet==0 ) return 0;
  178103. }
  178104. zRet = fts5PrintfAppend(zRet, "--");
  178105. if( zRet==0 ) return 0;
  178106. for(i=0; i<pNear->nPhrase; i++){
  178107. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  178108. zRet = fts5PrintfAppend(zRet, " {");
  178109. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  178110. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  178111. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  178112. if( pPhrase->aTerm[iTerm].bPrefix ){
  178113. zRet = fts5PrintfAppend(zRet, "*");
  178114. }
  178115. }
  178116. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  178117. if( zRet==0 ) return 0;
  178118. }
  178119. }else{
  178120. char const *zOp = 0;
  178121. int i;
  178122. switch( pExpr->eType ){
  178123. case FTS5_AND: zOp = "AND"; break;
  178124. case FTS5_NOT: zOp = "NOT"; break;
  178125. default:
  178126. assert( pExpr->eType==FTS5_OR );
  178127. zOp = "OR";
  178128. break;
  178129. }
  178130. zRet = sqlite3_mprintf("%s", zOp);
  178131. for(i=0; zRet && i<pExpr->nChild; i++){
  178132. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  178133. if( !z ){
  178134. sqlite3_free(zRet);
  178135. zRet = 0;
  178136. }else{
  178137. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  178138. }
  178139. }
  178140. }
  178141. return zRet;
  178142. }
  178143. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  178144. char *zRet = 0;
  178145. if( pExpr->eType==0 ){
  178146. return sqlite3_mprintf("\"\"");
  178147. }else
  178148. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  178149. Fts5ExprNearset *pNear = pExpr->pNear;
  178150. int i;
  178151. int iTerm;
  178152. if( pNear->pColset ){
  178153. int iCol = pNear->pColset->aiCol[0];
  178154. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  178155. if( zRet==0 ) return 0;
  178156. }
  178157. if( pNear->nPhrase>1 ){
  178158. zRet = fts5PrintfAppend(zRet, "NEAR(");
  178159. if( zRet==0 ) return 0;
  178160. }
  178161. for(i=0; i<pNear->nPhrase; i++){
  178162. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  178163. if( i!=0 ){
  178164. zRet = fts5PrintfAppend(zRet, " ");
  178165. if( zRet==0 ) return 0;
  178166. }
  178167. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  178168. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  178169. if( zTerm ){
  178170. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  178171. sqlite3_free(zTerm);
  178172. }
  178173. if( zTerm==0 || zRet==0 ){
  178174. sqlite3_free(zRet);
  178175. return 0;
  178176. }
  178177. }
  178178. }
  178179. if( pNear->nPhrase>1 ){
  178180. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  178181. if( zRet==0 ) return 0;
  178182. }
  178183. }else{
  178184. char const *zOp = 0;
  178185. int i;
  178186. switch( pExpr->eType ){
  178187. case FTS5_AND: zOp = " AND "; break;
  178188. case FTS5_NOT: zOp = " NOT "; break;
  178189. default:
  178190. assert( pExpr->eType==FTS5_OR );
  178191. zOp = " OR ";
  178192. break;
  178193. }
  178194. for(i=0; i<pExpr->nChild; i++){
  178195. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  178196. if( z==0 ){
  178197. sqlite3_free(zRet);
  178198. zRet = 0;
  178199. }else{
  178200. int e = pExpr->apChild[i]->eType;
  178201. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  178202. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  178203. (i==0 ? "" : zOp),
  178204. (b?"(":""), z, (b?")":"")
  178205. );
  178206. }
  178207. if( zRet==0 ) break;
  178208. }
  178209. }
  178210. return zRet;
  178211. }
  178212. /*
  178213. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  178214. ** and fts5_expr_tcl() (bTcl!=0).
  178215. */
  178216. static void fts5ExprFunction(
  178217. sqlite3_context *pCtx, /* Function call context */
  178218. int nArg, /* Number of args */
  178219. sqlite3_value **apVal, /* Function arguments */
  178220. int bTcl
  178221. ){
  178222. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  178223. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  178224. const char *zExpr = 0;
  178225. char *zErr = 0;
  178226. Fts5Expr *pExpr = 0;
  178227. int rc;
  178228. int i;
  178229. const char **azConfig; /* Array of arguments for Fts5Config */
  178230. const char *zNearsetCmd = "nearset";
  178231. int nConfig; /* Size of azConfig[] */
  178232. Fts5Config *pConfig = 0;
  178233. int iArg = 1;
  178234. if( nArg<1 ){
  178235. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  178236. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  178237. );
  178238. sqlite3_result_error(pCtx, zErr, -1);
  178239. sqlite3_free(zErr);
  178240. return;
  178241. }
  178242. if( bTcl && nArg>1 ){
  178243. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  178244. iArg = 2;
  178245. }
  178246. nConfig = 3 + (nArg-iArg);
  178247. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  178248. if( azConfig==0 ){
  178249. sqlite3_result_error_nomem(pCtx);
  178250. return;
  178251. }
  178252. azConfig[0] = 0;
  178253. azConfig[1] = "main";
  178254. azConfig[2] = "tbl";
  178255. for(i=3; iArg<nArg; iArg++){
  178256. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  178257. }
  178258. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  178259. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  178260. if( rc==SQLITE_OK ){
  178261. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  178262. }
  178263. if( rc==SQLITE_OK ){
  178264. char *zText;
  178265. if( pExpr->pRoot->xNext==0 ){
  178266. zText = sqlite3_mprintf("");
  178267. }else if( bTcl ){
  178268. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  178269. }else{
  178270. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  178271. }
  178272. if( zText==0 ){
  178273. rc = SQLITE_NOMEM;
  178274. }else{
  178275. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  178276. sqlite3_free(zText);
  178277. }
  178278. }
  178279. if( rc!=SQLITE_OK ){
  178280. if( zErr ){
  178281. sqlite3_result_error(pCtx, zErr, -1);
  178282. sqlite3_free(zErr);
  178283. }else{
  178284. sqlite3_result_error_code(pCtx, rc);
  178285. }
  178286. }
  178287. sqlite3_free((void *)azConfig);
  178288. sqlite3Fts5ConfigFree(pConfig);
  178289. sqlite3Fts5ExprFree(pExpr);
  178290. }
  178291. static void fts5ExprFunctionHr(
  178292. sqlite3_context *pCtx, /* Function call context */
  178293. int nArg, /* Number of args */
  178294. sqlite3_value **apVal /* Function arguments */
  178295. ){
  178296. fts5ExprFunction(pCtx, nArg, apVal, 0);
  178297. }
  178298. static void fts5ExprFunctionTcl(
  178299. sqlite3_context *pCtx, /* Function call context */
  178300. int nArg, /* Number of args */
  178301. sqlite3_value **apVal /* Function arguments */
  178302. ){
  178303. fts5ExprFunction(pCtx, nArg, apVal, 1);
  178304. }
  178305. /*
  178306. ** The implementation of an SQLite user-defined-function that accepts a
  178307. ** single integer as an argument. If the integer is an alpha-numeric
  178308. ** unicode code point, 1 is returned. Otherwise 0.
  178309. */
  178310. static void fts5ExprIsAlnum(
  178311. sqlite3_context *pCtx, /* Function call context */
  178312. int nArg, /* Number of args */
  178313. sqlite3_value **apVal /* Function arguments */
  178314. ){
  178315. int iCode;
  178316. if( nArg!=1 ){
  178317. sqlite3_result_error(pCtx,
  178318. "wrong number of arguments to function fts5_isalnum", -1
  178319. );
  178320. return;
  178321. }
  178322. iCode = sqlite3_value_int(apVal[0]);
  178323. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  178324. }
  178325. static void fts5ExprFold(
  178326. sqlite3_context *pCtx, /* Function call context */
  178327. int nArg, /* Number of args */
  178328. sqlite3_value **apVal /* Function arguments */
  178329. ){
  178330. if( nArg!=1 && nArg!=2 ){
  178331. sqlite3_result_error(pCtx,
  178332. "wrong number of arguments to function fts5_fold", -1
  178333. );
  178334. }else{
  178335. int iCode;
  178336. int bRemoveDiacritics = 0;
  178337. iCode = sqlite3_value_int(apVal[0]);
  178338. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  178339. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  178340. }
  178341. }
  178342. /*
  178343. ** This is called during initialization to register the fts5_expr() scalar
  178344. ** UDF with the SQLite handle passed as the only argument.
  178345. */
  178346. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  178347. struct Fts5ExprFunc {
  178348. const char *z;
  178349. void (*x)(sqlite3_context*,int,sqlite3_value**);
  178350. } aFunc[] = {
  178351. { "fts5_expr", fts5ExprFunctionHr },
  178352. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  178353. { "fts5_isalnum", fts5ExprIsAlnum },
  178354. { "fts5_fold", fts5ExprFold },
  178355. };
  178356. int i;
  178357. int rc = SQLITE_OK;
  178358. void *pCtx = (void*)pGlobal;
  178359. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  178360. struct Fts5ExprFunc *p = &aFunc[i];
  178361. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  178362. }
  178363. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  178364. #ifndef NDEBUG
  178365. (void)sqlite3Fts5ParserTrace;
  178366. #endif
  178367. return rc;
  178368. }
  178369. /*
  178370. ** Return the number of phrases in expression pExpr.
  178371. */
  178372. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  178373. return (pExpr ? pExpr->nPhrase : 0);
  178374. }
  178375. /*
  178376. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  178377. */
  178378. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  178379. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  178380. return pExpr->apExprPhrase[iPhrase]->nTerm;
  178381. }
  178382. /*
  178383. ** This function is used to access the current position list for phrase
  178384. ** iPhrase.
  178385. */
  178386. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  178387. int nRet;
  178388. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  178389. Fts5ExprNode *pNode = pPhrase->pNode;
  178390. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  178391. *pa = pPhrase->poslist.p;
  178392. nRet = pPhrase->poslist.n;
  178393. }else{
  178394. *pa = 0;
  178395. nRet = 0;
  178396. }
  178397. return nRet;
  178398. }
  178399. struct Fts5PoslistPopulator {
  178400. Fts5PoslistWriter writer;
  178401. int bOk; /* True if ok to populate */
  178402. int bMiss;
  178403. };
  178404. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  178405. Fts5PoslistPopulator *pRet;
  178406. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  178407. if( pRet ){
  178408. int i;
  178409. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  178410. for(i=0; i<pExpr->nPhrase; i++){
  178411. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  178412. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  178413. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  178414. if( bLive &&
  178415. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  178416. ){
  178417. pRet[i].bMiss = 1;
  178418. }else{
  178419. pBuf->n = 0;
  178420. }
  178421. }
  178422. }
  178423. return pRet;
  178424. }
  178425. struct Fts5ExprCtx {
  178426. Fts5Expr *pExpr;
  178427. Fts5PoslistPopulator *aPopulator;
  178428. i64 iOff;
  178429. };
  178430. typedef struct Fts5ExprCtx Fts5ExprCtx;
  178431. /*
  178432. ** TODO: Make this more efficient!
  178433. */
  178434. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  178435. int i;
  178436. for(i=0; i<pColset->nCol; i++){
  178437. if( pColset->aiCol[i]==iCol ) return 1;
  178438. }
  178439. return 0;
  178440. }
  178441. static int fts5ExprPopulatePoslistsCb(
  178442. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  178443. int tflags, /* Mask of FTS5_TOKEN_* flags */
  178444. const char *pToken, /* Pointer to buffer containing token */
  178445. int nToken, /* Size of token in bytes */
  178446. int iUnused1, /* Byte offset of token within input text */
  178447. int iUnused2 /* Byte offset of end of token within input text */
  178448. ){
  178449. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  178450. Fts5Expr *pExpr = p->pExpr;
  178451. int i;
  178452. UNUSED_PARAM2(iUnused1, iUnused2);
  178453. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  178454. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  178455. for(i=0; i<pExpr->nPhrase; i++){
  178456. Fts5ExprTerm *pTerm;
  178457. if( p->aPopulator[i].bOk==0 ) continue;
  178458. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  178459. int nTerm = (int)strlen(pTerm->zTerm);
  178460. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  178461. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  178462. ){
  178463. int rc = sqlite3Fts5PoslistWriterAppend(
  178464. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  178465. );
  178466. if( rc ) return rc;
  178467. break;
  178468. }
  178469. }
  178470. }
  178471. return SQLITE_OK;
  178472. }
  178473. static int sqlite3Fts5ExprPopulatePoslists(
  178474. Fts5Config *pConfig,
  178475. Fts5Expr *pExpr,
  178476. Fts5PoslistPopulator *aPopulator,
  178477. int iCol,
  178478. const char *z, int n
  178479. ){
  178480. int i;
  178481. Fts5ExprCtx sCtx;
  178482. sCtx.pExpr = pExpr;
  178483. sCtx.aPopulator = aPopulator;
  178484. sCtx.iOff = (((i64)iCol) << 32) - 1;
  178485. for(i=0; i<pExpr->nPhrase; i++){
  178486. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  178487. Fts5Colset *pColset = pNode->pNear->pColset;
  178488. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  178489. || aPopulator[i].bMiss
  178490. ){
  178491. aPopulator[i].bOk = 0;
  178492. }else{
  178493. aPopulator[i].bOk = 1;
  178494. }
  178495. }
  178496. return sqlite3Fts5Tokenize(pConfig,
  178497. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  178498. );
  178499. }
  178500. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  178501. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  178502. pNode->pNear->apPhrase[0]->poslist.n = 0;
  178503. }else{
  178504. int i;
  178505. for(i=0; i<pNode->nChild; i++){
  178506. fts5ExprClearPoslists(pNode->apChild[i]);
  178507. }
  178508. }
  178509. }
  178510. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  178511. pNode->iRowid = iRowid;
  178512. pNode->bEof = 0;
  178513. switch( pNode->eType ){
  178514. case FTS5_TERM:
  178515. case FTS5_STRING:
  178516. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  178517. case FTS5_AND: {
  178518. int i;
  178519. for(i=0; i<pNode->nChild; i++){
  178520. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  178521. fts5ExprClearPoslists(pNode);
  178522. return 0;
  178523. }
  178524. }
  178525. break;
  178526. }
  178527. case FTS5_OR: {
  178528. int i;
  178529. int bRet = 0;
  178530. for(i=0; i<pNode->nChild; i++){
  178531. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  178532. bRet = 1;
  178533. }
  178534. }
  178535. return bRet;
  178536. }
  178537. default: {
  178538. assert( pNode->eType==FTS5_NOT );
  178539. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  178540. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  178541. ){
  178542. fts5ExprClearPoslists(pNode);
  178543. return 0;
  178544. }
  178545. break;
  178546. }
  178547. }
  178548. return 1;
  178549. }
  178550. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  178551. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  178552. }
  178553. /*
  178554. ** This function is only called for detail=columns tables.
  178555. */
  178556. static int sqlite3Fts5ExprPhraseCollist(
  178557. Fts5Expr *pExpr,
  178558. int iPhrase,
  178559. const u8 **ppCollist,
  178560. int *pnCollist
  178561. ){
  178562. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  178563. Fts5ExprNode *pNode = pPhrase->pNode;
  178564. int rc = SQLITE_OK;
  178565. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  178566. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  178567. if( pNode->bEof==0
  178568. && pNode->iRowid==pExpr->pRoot->iRowid
  178569. && pPhrase->poslist.n>0
  178570. ){
  178571. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  178572. if( pTerm->pSynonym ){
  178573. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  178574. rc = fts5ExprSynonymList(
  178575. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  178576. );
  178577. }else{
  178578. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  178579. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  178580. }
  178581. }else{
  178582. *ppCollist = 0;
  178583. *pnCollist = 0;
  178584. }
  178585. return rc;
  178586. }
  178587. /*
  178588. ** 2014 August 11
  178589. **
  178590. ** The author disclaims copyright to this source code. In place of
  178591. ** a legal notice, here is a blessing:
  178592. **
  178593. ** May you do good and not evil.
  178594. ** May you find forgiveness for yourself and forgive others.
  178595. ** May you share freely, never taking more than you give.
  178596. **
  178597. ******************************************************************************
  178598. **
  178599. */
  178600. /* #include "fts5Int.h" */
  178601. typedef struct Fts5HashEntry Fts5HashEntry;
  178602. /*
  178603. ** This file contains the implementation of an in-memory hash table used
  178604. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  178605. ** segment.
  178606. */
  178607. struct Fts5Hash {
  178608. int eDetail; /* Copy of Fts5Config.eDetail */
  178609. int *pnByte; /* Pointer to bytes counter */
  178610. int nEntry; /* Number of entries currently in hash */
  178611. int nSlot; /* Size of aSlot[] array */
  178612. Fts5HashEntry *pScan; /* Current ordered scan item */
  178613. Fts5HashEntry **aSlot; /* Array of hash slots */
  178614. };
  178615. /*
  178616. ** Each entry in the hash table is represented by an object of the
  178617. ** following type. Each object, its key (a nul-terminated string) and
  178618. ** its current data are stored in a single memory allocation. The
  178619. ** key immediately follows the object in memory. The position list
  178620. ** data immediately follows the key data in memory.
  178621. **
  178622. ** The data that follows the key is in a similar, but not identical format
  178623. ** to the doclist data stored in the database. It is:
  178624. **
  178625. ** * Rowid, as a varint
  178626. ** * Position list, without 0x00 terminator.
  178627. ** * Size of previous position list and rowid, as a 4 byte
  178628. ** big-endian integer.
  178629. **
  178630. ** iRowidOff:
  178631. ** Offset of last rowid written to data area. Relative to first byte of
  178632. ** structure.
  178633. **
  178634. ** nData:
  178635. ** Bytes of data written since iRowidOff.
  178636. */
  178637. struct Fts5HashEntry {
  178638. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  178639. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  178640. int nAlloc; /* Total size of allocation */
  178641. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  178642. int nData; /* Total bytes of data (incl. structure) */
  178643. int nKey; /* Length of key in bytes */
  178644. u8 bDel; /* Set delete-flag @ iSzPoslist */
  178645. u8 bContent; /* Set content-flag (detail=none mode) */
  178646. i16 iCol; /* Column of last value written */
  178647. int iPos; /* Position of last value written */
  178648. i64 iRowid; /* Rowid of last value written */
  178649. };
  178650. /*
  178651. ** Eqivalent to:
  178652. **
  178653. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  178654. */
  178655. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  178656. /*
  178657. ** Allocate a new hash table.
  178658. */
  178659. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  178660. int rc = SQLITE_OK;
  178661. Fts5Hash *pNew;
  178662. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  178663. if( pNew==0 ){
  178664. rc = SQLITE_NOMEM;
  178665. }else{
  178666. int nByte;
  178667. memset(pNew, 0, sizeof(Fts5Hash));
  178668. pNew->pnByte = pnByte;
  178669. pNew->eDetail = pConfig->eDetail;
  178670. pNew->nSlot = 1024;
  178671. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  178672. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  178673. if( pNew->aSlot==0 ){
  178674. sqlite3_free(pNew);
  178675. *ppNew = 0;
  178676. rc = SQLITE_NOMEM;
  178677. }else{
  178678. memset(pNew->aSlot, 0, nByte);
  178679. }
  178680. }
  178681. return rc;
  178682. }
  178683. /*
  178684. ** Free a hash table object.
  178685. */
  178686. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  178687. if( pHash ){
  178688. sqlite3Fts5HashClear(pHash);
  178689. sqlite3_free(pHash->aSlot);
  178690. sqlite3_free(pHash);
  178691. }
  178692. }
  178693. /*
  178694. ** Empty (but do not delete) a hash table.
  178695. */
  178696. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  178697. int i;
  178698. for(i=0; i<pHash->nSlot; i++){
  178699. Fts5HashEntry *pNext;
  178700. Fts5HashEntry *pSlot;
  178701. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  178702. pNext = pSlot->pHashNext;
  178703. sqlite3_free(pSlot);
  178704. }
  178705. }
  178706. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  178707. pHash->nEntry = 0;
  178708. }
  178709. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  178710. int i;
  178711. unsigned int h = 13;
  178712. for(i=n-1; i>=0; i--){
  178713. h = (h << 3) ^ h ^ p[i];
  178714. }
  178715. return (h % nSlot);
  178716. }
  178717. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  178718. int i;
  178719. unsigned int h = 13;
  178720. for(i=n-1; i>=0; i--){
  178721. h = (h << 3) ^ h ^ p[i];
  178722. }
  178723. h = (h << 3) ^ h ^ b;
  178724. return (h % nSlot);
  178725. }
  178726. /*
  178727. ** Resize the hash table by doubling the number of slots.
  178728. */
  178729. static int fts5HashResize(Fts5Hash *pHash){
  178730. int nNew = pHash->nSlot*2;
  178731. int i;
  178732. Fts5HashEntry **apNew;
  178733. Fts5HashEntry **apOld = pHash->aSlot;
  178734. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  178735. if( !apNew ) return SQLITE_NOMEM;
  178736. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  178737. for(i=0; i<pHash->nSlot; i++){
  178738. while( apOld[i] ){
  178739. unsigned int iHash;
  178740. Fts5HashEntry *p = apOld[i];
  178741. apOld[i] = p->pHashNext;
  178742. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  178743. (int)strlen(fts5EntryKey(p)));
  178744. p->pHashNext = apNew[iHash];
  178745. apNew[iHash] = p;
  178746. }
  178747. }
  178748. sqlite3_free(apOld);
  178749. pHash->nSlot = nNew;
  178750. pHash->aSlot = apNew;
  178751. return SQLITE_OK;
  178752. }
  178753. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  178754. if( p->iSzPoslist ){
  178755. u8 *pPtr = (u8*)p;
  178756. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  178757. assert( p->nData==p->iSzPoslist );
  178758. if( p->bDel ){
  178759. pPtr[p->nData++] = 0x00;
  178760. if( p->bContent ){
  178761. pPtr[p->nData++] = 0x00;
  178762. }
  178763. }
  178764. }else{
  178765. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  178766. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  178767. assert( p->bDel==0 || p->bDel==1 );
  178768. if( nPos<=127 ){
  178769. pPtr[p->iSzPoslist] = (u8)nPos;
  178770. }else{
  178771. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  178772. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  178773. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  178774. p->nData += (nByte-1);
  178775. }
  178776. }
  178777. p->iSzPoslist = 0;
  178778. p->bDel = 0;
  178779. p->bContent = 0;
  178780. }
  178781. }
  178782. /*
  178783. ** Add an entry to the in-memory hash table. The key is the concatenation
  178784. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  178785. **
  178786. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  178787. **
  178788. ** Or, if iCol is negative, then the value is a delete marker.
  178789. */
  178790. static int sqlite3Fts5HashWrite(
  178791. Fts5Hash *pHash,
  178792. i64 iRowid, /* Rowid for this entry */
  178793. int iCol, /* Column token appears in (-ve -> delete) */
  178794. int iPos, /* Position of token within column */
  178795. char bByte, /* First byte of token */
  178796. const char *pToken, int nToken /* Token to add or remove to or from index */
  178797. ){
  178798. unsigned int iHash;
  178799. Fts5HashEntry *p;
  178800. u8 *pPtr;
  178801. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  178802. int bNew; /* If non-delete entry should be written */
  178803. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  178804. /* Attempt to locate an existing hash entry */
  178805. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  178806. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  178807. char *zKey = fts5EntryKey(p);
  178808. if( zKey[0]==bByte
  178809. && p->nKey==nToken
  178810. && memcmp(&zKey[1], pToken, nToken)==0
  178811. ){
  178812. break;
  178813. }
  178814. }
  178815. /* If an existing hash entry cannot be found, create a new one. */
  178816. if( p==0 ){
  178817. /* Figure out how much space to allocate */
  178818. char *zKey;
  178819. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  178820. if( nByte<128 ) nByte = 128;
  178821. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  178822. if( (pHash->nEntry*2)>=pHash->nSlot ){
  178823. int rc = fts5HashResize(pHash);
  178824. if( rc!=SQLITE_OK ) return rc;
  178825. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  178826. }
  178827. /* Allocate new Fts5HashEntry and add it to the hash table. */
  178828. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  178829. if( !p ) return SQLITE_NOMEM;
  178830. memset(p, 0, sizeof(Fts5HashEntry));
  178831. p->nAlloc = nByte;
  178832. zKey = fts5EntryKey(p);
  178833. zKey[0] = bByte;
  178834. memcpy(&zKey[1], pToken, nToken);
  178835. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  178836. p->nKey = nToken;
  178837. zKey[nToken+1] = '\0';
  178838. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  178839. p->pHashNext = pHash->aSlot[iHash];
  178840. pHash->aSlot[iHash] = p;
  178841. pHash->nEntry++;
  178842. /* Add the first rowid field to the hash-entry */
  178843. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  178844. p->iRowid = iRowid;
  178845. p->iSzPoslist = p->nData;
  178846. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  178847. p->nData += 1;
  178848. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  178849. }
  178850. nIncr += p->nData;
  178851. }else{
  178852. /* Appending to an existing hash-entry. Check that there is enough
  178853. ** space to append the largest possible new entry. Worst case scenario
  178854. ** is:
  178855. **
  178856. ** + 9 bytes for a new rowid,
  178857. ** + 4 byte reserved for the "poslist size" varint.
  178858. ** + 1 byte for a "new column" byte,
  178859. ** + 3 bytes for a new column number (16-bit max) as a varint,
  178860. ** + 5 bytes for the new position offset (32-bit max).
  178861. */
  178862. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  178863. int nNew = p->nAlloc * 2;
  178864. Fts5HashEntry *pNew;
  178865. Fts5HashEntry **pp;
  178866. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  178867. if( pNew==0 ) return SQLITE_NOMEM;
  178868. pNew->nAlloc = nNew;
  178869. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  178870. *pp = pNew;
  178871. p = pNew;
  178872. }
  178873. nIncr -= p->nData;
  178874. }
  178875. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  178876. pPtr = (u8*)p;
  178877. /* If this is a new rowid, append the 4-byte size field for the previous
  178878. ** entry, and the new rowid for this entry. */
  178879. if( iRowid!=p->iRowid ){
  178880. fts5HashAddPoslistSize(pHash, p);
  178881. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  178882. p->iRowid = iRowid;
  178883. bNew = 1;
  178884. p->iSzPoslist = p->nData;
  178885. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  178886. p->nData += 1;
  178887. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  178888. p->iPos = 0;
  178889. }
  178890. }
  178891. if( iCol>=0 ){
  178892. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  178893. p->bContent = 1;
  178894. }else{
  178895. /* Append a new column value, if necessary */
  178896. assert( iCol>=p->iCol );
  178897. if( iCol!=p->iCol ){
  178898. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  178899. pPtr[p->nData++] = 0x01;
  178900. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  178901. p->iCol = (i16)iCol;
  178902. p->iPos = 0;
  178903. }else{
  178904. bNew = 1;
  178905. p->iCol = (i16)(iPos = iCol);
  178906. }
  178907. }
  178908. /* Append the new position offset, if necessary */
  178909. if( bNew ){
  178910. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  178911. p->iPos = iPos;
  178912. }
  178913. }
  178914. }else{
  178915. /* This is a delete. Set the delete flag. */
  178916. p->bDel = 1;
  178917. }
  178918. nIncr += p->nData;
  178919. *pHash->pnByte += nIncr;
  178920. return SQLITE_OK;
  178921. }
  178922. /*
  178923. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  178924. ** each sorted in key order. This function merges the two lists into a
  178925. ** single list and returns a pointer to its first element.
  178926. */
  178927. static Fts5HashEntry *fts5HashEntryMerge(
  178928. Fts5HashEntry *pLeft,
  178929. Fts5HashEntry *pRight
  178930. ){
  178931. Fts5HashEntry *p1 = pLeft;
  178932. Fts5HashEntry *p2 = pRight;
  178933. Fts5HashEntry *pRet = 0;
  178934. Fts5HashEntry **ppOut = &pRet;
  178935. while( p1 || p2 ){
  178936. if( p1==0 ){
  178937. *ppOut = p2;
  178938. p2 = 0;
  178939. }else if( p2==0 ){
  178940. *ppOut = p1;
  178941. p1 = 0;
  178942. }else{
  178943. int i = 0;
  178944. char *zKey1 = fts5EntryKey(p1);
  178945. char *zKey2 = fts5EntryKey(p2);
  178946. while( zKey1[i]==zKey2[i] ) i++;
  178947. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  178948. /* p2 is smaller */
  178949. *ppOut = p2;
  178950. ppOut = &p2->pScanNext;
  178951. p2 = p2->pScanNext;
  178952. }else{
  178953. /* p1 is smaller */
  178954. *ppOut = p1;
  178955. ppOut = &p1->pScanNext;
  178956. p1 = p1->pScanNext;
  178957. }
  178958. *ppOut = 0;
  178959. }
  178960. }
  178961. return pRet;
  178962. }
  178963. /*
  178964. ** Extract all tokens from hash table iHash and link them into a list
  178965. ** in sorted order. The hash table is cleared before returning. It is
  178966. ** the responsibility of the caller to free the elements of the returned
  178967. ** list.
  178968. */
  178969. static int fts5HashEntrySort(
  178970. Fts5Hash *pHash,
  178971. const char *pTerm, int nTerm, /* Query prefix, if any */
  178972. Fts5HashEntry **ppSorted
  178973. ){
  178974. const int nMergeSlot = 32;
  178975. Fts5HashEntry **ap;
  178976. Fts5HashEntry *pList;
  178977. int iSlot;
  178978. int i;
  178979. *ppSorted = 0;
  178980. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  178981. if( !ap ) return SQLITE_NOMEM;
  178982. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  178983. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  178984. Fts5HashEntry *pIter;
  178985. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  178986. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  178987. Fts5HashEntry *pEntry = pIter;
  178988. pEntry->pScanNext = 0;
  178989. for(i=0; ap[i]; i++){
  178990. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  178991. ap[i] = 0;
  178992. }
  178993. ap[i] = pEntry;
  178994. }
  178995. }
  178996. }
  178997. pList = 0;
  178998. for(i=0; i<nMergeSlot; i++){
  178999. pList = fts5HashEntryMerge(pList, ap[i]);
  179000. }
  179001. pHash->nEntry = 0;
  179002. sqlite3_free(ap);
  179003. *ppSorted = pList;
  179004. return SQLITE_OK;
  179005. }
  179006. /*
  179007. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  179008. */
  179009. static int sqlite3Fts5HashQuery(
  179010. Fts5Hash *pHash, /* Hash table to query */
  179011. const char *pTerm, int nTerm, /* Query term */
  179012. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  179013. int *pnDoclist /* OUT: Size of doclist in bytes */
  179014. ){
  179015. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  179016. char *zKey = 0;
  179017. Fts5HashEntry *p;
  179018. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  179019. zKey = fts5EntryKey(p);
  179020. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  179021. }
  179022. if( p ){
  179023. fts5HashAddPoslistSize(pHash, p);
  179024. *ppDoclist = (const u8*)&zKey[nTerm+1];
  179025. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  179026. }else{
  179027. *ppDoclist = 0;
  179028. *pnDoclist = 0;
  179029. }
  179030. return SQLITE_OK;
  179031. }
  179032. static int sqlite3Fts5HashScanInit(
  179033. Fts5Hash *p, /* Hash table to query */
  179034. const char *pTerm, int nTerm /* Query prefix */
  179035. ){
  179036. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  179037. }
  179038. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  179039. assert( !sqlite3Fts5HashScanEof(p) );
  179040. p->pScan = p->pScan->pScanNext;
  179041. }
  179042. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  179043. return (p->pScan==0);
  179044. }
  179045. static void sqlite3Fts5HashScanEntry(
  179046. Fts5Hash *pHash,
  179047. const char **pzTerm, /* OUT: term (nul-terminated) */
  179048. const u8 **ppDoclist, /* OUT: pointer to doclist */
  179049. int *pnDoclist /* OUT: size of doclist in bytes */
  179050. ){
  179051. Fts5HashEntry *p;
  179052. if( (p = pHash->pScan) ){
  179053. char *zKey = fts5EntryKey(p);
  179054. int nTerm = (int)strlen(zKey);
  179055. fts5HashAddPoslistSize(pHash, p);
  179056. *pzTerm = zKey;
  179057. *ppDoclist = (const u8*)&zKey[nTerm+1];
  179058. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  179059. }else{
  179060. *pzTerm = 0;
  179061. *ppDoclist = 0;
  179062. *pnDoclist = 0;
  179063. }
  179064. }
  179065. /*
  179066. ** 2014 May 31
  179067. **
  179068. ** The author disclaims copyright to this source code. In place of
  179069. ** a legal notice, here is a blessing:
  179070. **
  179071. ** May you do good and not evil.
  179072. ** May you find forgiveness for yourself and forgive others.
  179073. ** May you share freely, never taking more than you give.
  179074. **
  179075. ******************************************************************************
  179076. **
  179077. ** Low level access to the FTS index stored in the database file. The
  179078. ** routines in this file file implement all read and write access to the
  179079. ** %_data table. Other parts of the system access this functionality via
  179080. ** the interface defined in fts5Int.h.
  179081. */
  179082. /* #include "fts5Int.h" */
  179083. /*
  179084. ** Overview:
  179085. **
  179086. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  179087. ** As well as the main term index, there may be up to 31 prefix indexes.
  179088. ** The format is similar to FTS3/4, except that:
  179089. **
  179090. ** * all segment b-tree leaf data is stored in fixed size page records
  179091. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  179092. ** taken to ensure it is possible to iterate in either direction through
  179093. ** the entries in a doclist, or to seek to a specific entry within a
  179094. ** doclist, without loading it into memory.
  179095. **
  179096. ** * large doclists that span many pages have associated "doclist index"
  179097. ** records that contain a copy of the first rowid on each page spanned by
  179098. ** the doclist. This is used to speed up seek operations, and merges of
  179099. ** large doclists with very small doclists.
  179100. **
  179101. ** * extra fields in the "structure record" record the state of ongoing
  179102. ** incremental merge operations.
  179103. **
  179104. */
  179105. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  179106. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  179107. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  179108. #define FTS5_MAIN_PREFIX '0'
  179109. #if FTS5_MAX_PREFIX_INDEXES > 31
  179110. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  179111. #endif
  179112. /*
  179113. ** Details:
  179114. **
  179115. ** The %_data table managed by this module,
  179116. **
  179117. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  179118. **
  179119. ** , contains the following 5 types of records. See the comments surrounding
  179120. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  179121. ** assigned to each fo them.
  179122. **
  179123. ** 1. Structure Records:
  179124. **
  179125. ** The set of segments that make up an index - the index structure - are
  179126. ** recorded in a single record within the %_data table. The record consists
  179127. ** of a single 32-bit configuration cookie value followed by a list of
  179128. ** SQLite varints. If the FTS table features more than one index (because
  179129. ** there are one or more prefix indexes), it is guaranteed that all share
  179130. ** the same cookie value.
  179131. **
  179132. ** Immediately following the configuration cookie, the record begins with
  179133. ** three varints:
  179134. **
  179135. ** + number of levels,
  179136. ** + total number of segments on all levels,
  179137. ** + value of write counter.
  179138. **
  179139. ** Then, for each level from 0 to nMax:
  179140. **
  179141. ** + number of input segments in ongoing merge.
  179142. ** + total number of segments in level.
  179143. ** + for each segment from oldest to newest:
  179144. ** + segment id (always > 0)
  179145. ** + first leaf page number (often 1, always greater than 0)
  179146. ** + final leaf page number
  179147. **
  179148. ** 2. The Averages Record:
  179149. **
  179150. ** A single record within the %_data table. The data is a list of varints.
  179151. ** The first value is the number of rows in the index. Then, for each column
  179152. ** from left to right, the total number of tokens in the column for all
  179153. ** rows of the table.
  179154. **
  179155. ** 3. Segment leaves:
  179156. **
  179157. ** TERM/DOCLIST FORMAT:
  179158. **
  179159. ** Most of each segment leaf is taken up by term/doclist data. The
  179160. ** general format of term/doclist, starting with the first term
  179161. ** on the leaf page, is:
  179162. **
  179163. ** varint : size of first term
  179164. ** blob: first term data
  179165. ** doclist: first doclist
  179166. ** zero-or-more {
  179167. ** varint: number of bytes in common with previous term
  179168. ** varint: number of bytes of new term data (nNew)
  179169. ** blob: nNew bytes of new term data
  179170. ** doclist: next doclist
  179171. ** }
  179172. **
  179173. ** doclist format:
  179174. **
  179175. ** varint: first rowid
  179176. ** poslist: first poslist
  179177. ** zero-or-more {
  179178. ** varint: rowid delta (always > 0)
  179179. ** poslist: next poslist
  179180. ** }
  179181. **
  179182. ** poslist format:
  179183. **
  179184. ** varint: size of poslist in bytes multiplied by 2, not including
  179185. ** this field. Plus 1 if this entry carries the "delete" flag.
  179186. ** collist: collist for column 0
  179187. ** zero-or-more {
  179188. ** 0x01 byte
  179189. ** varint: column number (I)
  179190. ** collist: collist for column I
  179191. ** }
  179192. **
  179193. ** collist format:
  179194. **
  179195. ** varint: first offset + 2
  179196. ** zero-or-more {
  179197. ** varint: offset delta + 2
  179198. ** }
  179199. **
  179200. ** PAGE FORMAT
  179201. **
  179202. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  179203. ** unsigned integer fields in big-endian format. They are:
  179204. **
  179205. ** * The byte offset of the first rowid on the page, if it exists
  179206. ** and occurs before the first term (otherwise 0).
  179207. **
  179208. ** * The byte offset of the start of the page footer. If the page
  179209. ** footer is 0 bytes in size, then this field is the same as the
  179210. ** size of the leaf page in bytes.
  179211. **
  179212. ** The page footer consists of a single varint for each term located
  179213. ** on the page. Each varint is the byte offset of the current term
  179214. ** within the page, delta-compressed against the previous value. In
  179215. ** other words, the first varint in the footer is the byte offset of
  179216. ** the first term, the second is the byte offset of the second less that
  179217. ** of the first, and so on.
  179218. **
  179219. ** The term/doclist format described above is accurate if the entire
  179220. ** term/doclist data fits on a single leaf page. If this is not the case,
  179221. ** the format is changed in two ways:
  179222. **
  179223. ** + if the first rowid on a page occurs before the first term, it
  179224. ** is stored as a literal value:
  179225. **
  179226. ** varint: first rowid
  179227. **
  179228. ** + the first term on each page is stored in the same way as the
  179229. ** very first term of the segment:
  179230. **
  179231. ** varint : size of first term
  179232. ** blob: first term data
  179233. **
  179234. ** 5. Segment doclist indexes:
  179235. **
  179236. ** Doclist indexes are themselves b-trees, however they usually consist of
  179237. ** a single leaf record only. The format of each doclist index leaf page
  179238. ** is:
  179239. **
  179240. ** * Flags byte. Bits are:
  179241. ** 0x01: Clear if leaf is also the root page, otherwise set.
  179242. **
  179243. ** * Page number of fts index leaf page. As a varint.
  179244. **
  179245. ** * First rowid on page indicated by previous field. As a varint.
  179246. **
  179247. ** * A list of varints, one for each subsequent termless page. A
  179248. ** positive delta if the termless page contains at least one rowid,
  179249. ** or an 0x00 byte otherwise.
  179250. **
  179251. ** Internal doclist index nodes are:
  179252. **
  179253. ** * Flags byte. Bits are:
  179254. ** 0x01: Clear for root page, otherwise set.
  179255. **
  179256. ** * Page number of first child page. As a varint.
  179257. **
  179258. ** * Copy of first rowid on page indicated by previous field. As a varint.
  179259. **
  179260. ** * A list of delta-encoded varints - the first rowid on each subsequent
  179261. ** child page.
  179262. **
  179263. */
  179264. /*
  179265. ** Rowids for the averages and structure records in the %_data table.
  179266. */
  179267. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  179268. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  179269. /*
  179270. ** Macros determining the rowids used by segment leaves and dlidx leaves
  179271. ** and nodes. All nodes and leaves are stored in the %_data table with large
  179272. ** positive rowids.
  179273. **
  179274. ** Each segment has a unique non-zero 16-bit id.
  179275. **
  179276. ** The rowid for each segment leaf is found by passing the segment id and
  179277. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  179278. ** sequentially starting from 1.
  179279. */
  179280. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  179281. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  179282. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  179283. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  179284. #define fts5_dri(segid, dlidx, height, pgno) ( \
  179285. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  179286. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  179287. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  179288. ((i64)(pgno)) \
  179289. )
  179290. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  179291. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  179292. /*
  179293. ** Maximum segments permitted in a single index
  179294. */
  179295. #define FTS5_MAX_SEGMENT 2000
  179296. #ifdef SQLITE_DEBUG
  179297. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  179298. #endif
  179299. /*
  179300. ** Each time a blob is read from the %_data table, it is padded with this
  179301. ** many zero bytes. This makes it easier to decode the various record formats
  179302. ** without overreading if the records are corrupt.
  179303. */
  179304. #define FTS5_DATA_ZERO_PADDING 8
  179305. #define FTS5_DATA_PADDING 20
  179306. typedef struct Fts5Data Fts5Data;
  179307. typedef struct Fts5DlidxIter Fts5DlidxIter;
  179308. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  179309. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  179310. typedef struct Fts5Iter Fts5Iter;
  179311. typedef struct Fts5PageWriter Fts5PageWriter;
  179312. typedef struct Fts5SegIter Fts5SegIter;
  179313. typedef struct Fts5DoclistIter Fts5DoclistIter;
  179314. typedef struct Fts5SegWriter Fts5SegWriter;
  179315. typedef struct Fts5Structure Fts5Structure;
  179316. typedef struct Fts5StructureLevel Fts5StructureLevel;
  179317. typedef struct Fts5StructureSegment Fts5StructureSegment;
  179318. struct Fts5Data {
  179319. u8 *p; /* Pointer to buffer containing record */
  179320. int nn; /* Size of record in bytes */
  179321. int szLeaf; /* Size of leaf without page-index */
  179322. };
  179323. /*
  179324. ** One object per %_data table.
  179325. */
  179326. struct Fts5Index {
  179327. Fts5Config *pConfig; /* Virtual table configuration */
  179328. char *zDataTbl; /* Name of %_data table */
  179329. int nWorkUnit; /* Leaf pages in a "unit" of work */
  179330. /*
  179331. ** Variables related to the accumulation of tokens and doclists within the
  179332. ** in-memory hash tables before they are flushed to disk.
  179333. */
  179334. Fts5Hash *pHash; /* Hash table for in-memory data */
  179335. int nPendingData; /* Current bytes of pending data */
  179336. i64 iWriteRowid; /* Rowid for current doc being written */
  179337. int bDelete; /* Current write is a delete */
  179338. /* Error state. */
  179339. int rc; /* Current error code */
  179340. /* State used by the fts5DataXXX() functions. */
  179341. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  179342. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  179343. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  179344. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  179345. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  179346. sqlite3_stmt *pIdxSelect;
  179347. int nRead; /* Total number of blocks read */
  179348. sqlite3_stmt *pDataVersion;
  179349. i64 iStructVersion; /* data_version when pStruct read */
  179350. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  179351. };
  179352. struct Fts5DoclistIter {
  179353. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  179354. /* Output variables. aPoslist==0 at EOF */
  179355. i64 iRowid;
  179356. u8 *aPoslist;
  179357. int nPoslist;
  179358. int nSize;
  179359. };
  179360. /*
  179361. ** The contents of the "structure" record for each index are represented
  179362. ** using an Fts5Structure record in memory. Which uses instances of the
  179363. ** other Fts5StructureXXX types as components.
  179364. */
  179365. struct Fts5StructureSegment {
  179366. int iSegid; /* Segment id */
  179367. int pgnoFirst; /* First leaf page number in segment */
  179368. int pgnoLast; /* Last leaf page number in segment */
  179369. };
  179370. struct Fts5StructureLevel {
  179371. int nMerge; /* Number of segments in incr-merge */
  179372. int nSeg; /* Total number of segments on level */
  179373. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  179374. };
  179375. struct Fts5Structure {
  179376. int nRef; /* Object reference count */
  179377. u64 nWriteCounter; /* Total leaves written to level 0 */
  179378. int nSegment; /* Total segments in this structure */
  179379. int nLevel; /* Number of levels in this index */
  179380. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  179381. };
  179382. /*
  179383. ** An object of type Fts5SegWriter is used to write to segments.
  179384. */
  179385. struct Fts5PageWriter {
  179386. int pgno; /* Page number for this page */
  179387. int iPrevPgidx; /* Previous value written into pgidx */
  179388. Fts5Buffer buf; /* Buffer containing leaf data */
  179389. Fts5Buffer pgidx; /* Buffer containing page-index */
  179390. Fts5Buffer term; /* Buffer containing previous term on page */
  179391. };
  179392. struct Fts5DlidxWriter {
  179393. int pgno; /* Page number for this page */
  179394. int bPrevValid; /* True if iPrev is valid */
  179395. i64 iPrev; /* Previous rowid value written to page */
  179396. Fts5Buffer buf; /* Buffer containing page data */
  179397. };
  179398. struct Fts5SegWriter {
  179399. int iSegid; /* Segid to write to */
  179400. Fts5PageWriter writer; /* PageWriter object */
  179401. i64 iPrevRowid; /* Previous rowid written to current leaf */
  179402. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  179403. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  179404. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  179405. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  179406. int nLeafWritten; /* Number of leaf pages written */
  179407. int nEmpty; /* Number of contiguous term-less nodes */
  179408. int nDlidx; /* Allocated size of aDlidx[] array */
  179409. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  179410. /* Values to insert into the %_idx table */
  179411. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  179412. int iBtPage; /* Page number corresponding to btterm */
  179413. };
  179414. typedef struct Fts5CResult Fts5CResult;
  179415. struct Fts5CResult {
  179416. u16 iFirst; /* aSeg[] index of firstest iterator */
  179417. u8 bTermEq; /* True if the terms are equal */
  179418. };
  179419. /*
  179420. ** Object for iterating through a single segment, visiting each term/rowid
  179421. ** pair in the segment.
  179422. **
  179423. ** pSeg:
  179424. ** The segment to iterate through.
  179425. **
  179426. ** iLeafPgno:
  179427. ** Current leaf page number within segment.
  179428. **
  179429. ** iLeafOffset:
  179430. ** Byte offset within the current leaf that is the first byte of the
  179431. ** position list data (one byte passed the position-list size field).
  179432. ** rowid field of the current entry. Usually this is the size field of the
  179433. ** position list data. The exception is if the rowid for the current entry
  179434. ** is the last thing on the leaf page.
  179435. **
  179436. ** pLeaf:
  179437. ** Buffer containing current leaf page data. Set to NULL at EOF.
  179438. **
  179439. ** iTermLeafPgno, iTermLeafOffset:
  179440. ** Leaf page number containing the last term read from the segment. And
  179441. ** the offset immediately following the term data.
  179442. **
  179443. ** flags:
  179444. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  179445. **
  179446. ** FTS5_SEGITER_ONETERM:
  179447. ** If set, set the iterator to point to EOF after the current doclist
  179448. ** has been exhausted. Do not proceed to the next term in the segment.
  179449. **
  179450. ** FTS5_SEGITER_REVERSE:
  179451. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  179452. ** it is set, iterate through rowid in descending order instead of the
  179453. ** default ascending order.
  179454. **
  179455. ** iRowidOffset/nRowidOffset/aRowidOffset:
  179456. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  179457. **
  179458. ** For each rowid on the page corresponding to the current term, the
  179459. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  179460. ** start of the "position-list-size" field within the page.
  179461. **
  179462. ** iTermIdx:
  179463. ** Index of current term on iTermLeafPgno.
  179464. */
  179465. struct Fts5SegIter {
  179466. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  179467. int flags; /* Mask of configuration flags */
  179468. int iLeafPgno; /* Current leaf page number */
  179469. Fts5Data *pLeaf; /* Current leaf data */
  179470. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  179471. int iLeafOffset; /* Byte offset within current leaf */
  179472. /* Next method */
  179473. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  179474. /* The page and offset from which the current term was read. The offset
  179475. ** is the offset of the first rowid in the current doclist. */
  179476. int iTermLeafPgno;
  179477. int iTermLeafOffset;
  179478. int iPgidxOff; /* Next offset in pgidx */
  179479. int iEndofDoclist;
  179480. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  179481. int iRowidOffset; /* Current entry in aRowidOffset[] */
  179482. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  179483. int *aRowidOffset; /* Array of offset to rowid fields */
  179484. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  179485. /* Variables populated based on current entry. */
  179486. Fts5Buffer term; /* Current term */
  179487. i64 iRowid; /* Current rowid */
  179488. int nPos; /* Number of bytes in current position list */
  179489. u8 bDel; /* True if the delete flag is set */
  179490. };
  179491. /*
  179492. ** Argument is a pointer to an Fts5Data structure that contains a
  179493. ** leaf page.
  179494. */
  179495. #define ASSERT_SZLEAF_OK(x) assert( \
  179496. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  179497. )
  179498. #define FTS5_SEGITER_ONETERM 0x01
  179499. #define FTS5_SEGITER_REVERSE 0x02
  179500. /*
  179501. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  179502. ** page. This macro evaluates to true if the leaf contains no terms, or
  179503. ** false if it contains at least one term.
  179504. */
  179505. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  179506. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  179507. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  179508. /*
  179509. ** Object for iterating through the merged results of one or more segments,
  179510. ** visiting each term/rowid pair in the merged data.
  179511. **
  179512. ** nSeg is always a power of two greater than or equal to the number of
  179513. ** segments that this object is merging data from. Both the aSeg[] and
  179514. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  179515. ** with zeroed objects - these are handled as if they were iterators opened
  179516. ** on empty segments.
  179517. **
  179518. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  179519. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  179520. ** comparison in this context is the index of the iterator that currently
  179521. ** points to the smaller term/rowid combination. Iterators at EOF are
  179522. ** considered to be greater than all other iterators.
  179523. **
  179524. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  179525. ** the smallest key overall. aFirst[0] is unused.
  179526. **
  179527. ** poslist:
  179528. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  179529. ** There is no way to tell if this is populated or not.
  179530. */
  179531. struct Fts5Iter {
  179532. Fts5IndexIter base; /* Base class containing output vars */
  179533. Fts5Index *pIndex; /* Index that owns this iterator */
  179534. Fts5Structure *pStruct; /* Database structure for this iterator */
  179535. Fts5Buffer poslist; /* Buffer containing current poslist */
  179536. Fts5Colset *pColset; /* Restrict matches to these columns */
  179537. /* Invoked to set output variables. */
  179538. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  179539. int nSeg; /* Size of aSeg[] array */
  179540. int bRev; /* True to iterate in reverse order */
  179541. u8 bSkipEmpty; /* True to skip deleted entries */
  179542. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  179543. Fts5CResult *aFirst; /* Current merge state (see above) */
  179544. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  179545. };
  179546. /*
  179547. ** An instance of the following type is used to iterate through the contents
  179548. ** of a doclist-index record.
  179549. **
  179550. ** pData:
  179551. ** Record containing the doclist-index data.
  179552. **
  179553. ** bEof:
  179554. ** Set to true once iterator has reached EOF.
  179555. **
  179556. ** iOff:
  179557. ** Set to the current offset within record pData.
  179558. */
  179559. struct Fts5DlidxLvl {
  179560. Fts5Data *pData; /* Data for current page of this level */
  179561. int iOff; /* Current offset into pData */
  179562. int bEof; /* At EOF already */
  179563. int iFirstOff; /* Used by reverse iterators */
  179564. /* Output variables */
  179565. int iLeafPgno; /* Page number of current leaf page */
  179566. i64 iRowid; /* First rowid on leaf iLeafPgno */
  179567. };
  179568. struct Fts5DlidxIter {
  179569. int nLvl;
  179570. int iSegid;
  179571. Fts5DlidxLvl aLvl[1];
  179572. };
  179573. static void fts5PutU16(u8 *aOut, u16 iVal){
  179574. aOut[0] = (iVal>>8);
  179575. aOut[1] = (iVal&0xFF);
  179576. }
  179577. static u16 fts5GetU16(const u8 *aIn){
  179578. return ((u16)aIn[0] << 8) + aIn[1];
  179579. }
  179580. /*
  179581. ** Allocate and return a buffer at least nByte bytes in size.
  179582. **
  179583. ** If an OOM error is encountered, return NULL and set the error code in
  179584. ** the Fts5Index handle passed as the first argument.
  179585. */
  179586. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  179587. return sqlite3Fts5MallocZero(&p->rc, nByte);
  179588. }
  179589. /*
  179590. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  179591. **
  179592. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  179593. ** +ve if pRight is smaller than pLeft. In other words:
  179594. **
  179595. ** res = *pLeft - *pRight
  179596. */
  179597. #ifdef SQLITE_DEBUG
  179598. static int fts5BufferCompareBlob(
  179599. Fts5Buffer *pLeft, /* Left hand side of comparison */
  179600. const u8 *pRight, int nRight /* Right hand side of comparison */
  179601. ){
  179602. int nCmp = MIN(pLeft->n, nRight);
  179603. int res = memcmp(pLeft->p, pRight, nCmp);
  179604. return (res==0 ? (pLeft->n - nRight) : res);
  179605. }
  179606. #endif
  179607. /*
  179608. ** Compare the contents of the two buffers using memcmp(). If one buffer
  179609. ** is a prefix of the other, it is considered the lesser.
  179610. **
  179611. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  179612. ** +ve if pRight is smaller than pLeft. In other words:
  179613. **
  179614. ** res = *pLeft - *pRight
  179615. */
  179616. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  179617. int nCmp = MIN(pLeft->n, pRight->n);
  179618. int res = memcmp(pLeft->p, pRight->p, nCmp);
  179619. return (res==0 ? (pLeft->n - pRight->n) : res);
  179620. }
  179621. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  179622. int ret;
  179623. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  179624. return ret;
  179625. }
  179626. /*
  179627. ** Close the read-only blob handle, if it is open.
  179628. */
  179629. static void fts5CloseReader(Fts5Index *p){
  179630. if( p->pReader ){
  179631. sqlite3_blob *pReader = p->pReader;
  179632. p->pReader = 0;
  179633. sqlite3_blob_close(pReader);
  179634. }
  179635. }
  179636. /*
  179637. ** Retrieve a record from the %_data table.
  179638. **
  179639. ** If an error occurs, NULL is returned and an error left in the
  179640. ** Fts5Index object.
  179641. */
  179642. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  179643. Fts5Data *pRet = 0;
  179644. if( p->rc==SQLITE_OK ){
  179645. int rc = SQLITE_OK;
  179646. if( p->pReader ){
  179647. /* This call may return SQLITE_ABORT if there has been a savepoint
  179648. ** rollback since it was last used. In this case a new blob handle
  179649. ** is required. */
  179650. sqlite3_blob *pBlob = p->pReader;
  179651. p->pReader = 0;
  179652. rc = sqlite3_blob_reopen(pBlob, iRowid);
  179653. assert( p->pReader==0 );
  179654. p->pReader = pBlob;
  179655. if( rc!=SQLITE_OK ){
  179656. fts5CloseReader(p);
  179657. }
  179658. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  179659. }
  179660. /* If the blob handle is not open at this point, open it and seek
  179661. ** to the requested entry. */
  179662. if( p->pReader==0 && rc==SQLITE_OK ){
  179663. Fts5Config *pConfig = p->pConfig;
  179664. rc = sqlite3_blob_open(pConfig->db,
  179665. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  179666. );
  179667. }
  179668. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  179669. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  179670. ** All the reasons those functions might return SQLITE_ERROR - missing
  179671. ** table, missing row, non-blob/text in block column - indicate
  179672. ** backing store corruption. */
  179673. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  179674. if( rc==SQLITE_OK ){
  179675. u8 *aOut = 0; /* Read blob data into this buffer */
  179676. int nByte = sqlite3_blob_bytes(p->pReader);
  179677. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  179678. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  179679. if( pRet ){
  179680. pRet->nn = nByte;
  179681. aOut = pRet->p = (u8*)&pRet[1];
  179682. }else{
  179683. rc = SQLITE_NOMEM;
  179684. }
  179685. if( rc==SQLITE_OK ){
  179686. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  179687. }
  179688. if( rc!=SQLITE_OK ){
  179689. sqlite3_free(pRet);
  179690. pRet = 0;
  179691. }else{
  179692. /* TODO1: Fix this */
  179693. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  179694. }
  179695. }
  179696. p->rc = rc;
  179697. p->nRead++;
  179698. }
  179699. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  179700. return pRet;
  179701. }
  179702. /*
  179703. ** Release a reference to data record returned by an earlier call to
  179704. ** fts5DataRead().
  179705. */
  179706. static void fts5DataRelease(Fts5Data *pData){
  179707. sqlite3_free(pData);
  179708. }
  179709. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  179710. Fts5Data *pRet = fts5DataRead(p, iRowid);
  179711. if( pRet ){
  179712. if( pRet->szLeaf>pRet->nn ){
  179713. p->rc = FTS5_CORRUPT;
  179714. fts5DataRelease(pRet);
  179715. pRet = 0;
  179716. }
  179717. }
  179718. return pRet;
  179719. }
  179720. static int fts5IndexPrepareStmt(
  179721. Fts5Index *p,
  179722. sqlite3_stmt **ppStmt,
  179723. char *zSql
  179724. ){
  179725. if( p->rc==SQLITE_OK ){
  179726. if( zSql ){
  179727. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  179728. SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
  179729. }else{
  179730. p->rc = SQLITE_NOMEM;
  179731. }
  179732. }
  179733. sqlite3_free(zSql);
  179734. return p->rc;
  179735. }
  179736. /*
  179737. ** INSERT OR REPLACE a record into the %_data table.
  179738. */
  179739. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  179740. if( p->rc!=SQLITE_OK ) return;
  179741. if( p->pWriter==0 ){
  179742. Fts5Config *pConfig = p->pConfig;
  179743. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  179744. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  179745. pConfig->zDb, pConfig->zName
  179746. ));
  179747. if( p->rc ) return;
  179748. }
  179749. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  179750. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  179751. sqlite3_step(p->pWriter);
  179752. p->rc = sqlite3_reset(p->pWriter);
  179753. }
  179754. /*
  179755. ** Execute the following SQL:
  179756. **
  179757. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  179758. */
  179759. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  179760. if( p->rc!=SQLITE_OK ) return;
  179761. if( p->pDeleter==0 ){
  179762. int rc;
  179763. Fts5Config *pConfig = p->pConfig;
  179764. char *zSql = sqlite3_mprintf(
  179765. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  179766. pConfig->zDb, pConfig->zName
  179767. );
  179768. if( zSql==0 ){
  179769. rc = SQLITE_NOMEM;
  179770. }else{
  179771. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  179772. SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
  179773. sqlite3_free(zSql);
  179774. }
  179775. if( rc!=SQLITE_OK ){
  179776. p->rc = rc;
  179777. return;
  179778. }
  179779. }
  179780. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  179781. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  179782. sqlite3_step(p->pDeleter);
  179783. p->rc = sqlite3_reset(p->pDeleter);
  179784. }
  179785. /*
  179786. ** Remove all records associated with segment iSegid.
  179787. */
  179788. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  179789. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  179790. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  179791. fts5DataDelete(p, iFirst, iLast);
  179792. if( p->pIdxDeleter==0 ){
  179793. Fts5Config *pConfig = p->pConfig;
  179794. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  179795. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  179796. pConfig->zDb, pConfig->zName
  179797. ));
  179798. }
  179799. if( p->rc==SQLITE_OK ){
  179800. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  179801. sqlite3_step(p->pIdxDeleter);
  179802. p->rc = sqlite3_reset(p->pIdxDeleter);
  179803. }
  179804. }
  179805. /*
  179806. ** Release a reference to an Fts5Structure object returned by an earlier
  179807. ** call to fts5StructureRead() or fts5StructureDecode().
  179808. */
  179809. static void fts5StructureRelease(Fts5Structure *pStruct){
  179810. if( pStruct && 0>=(--pStruct->nRef) ){
  179811. int i;
  179812. assert( pStruct->nRef==0 );
  179813. for(i=0; i<pStruct->nLevel; i++){
  179814. sqlite3_free(pStruct->aLevel[i].aSeg);
  179815. }
  179816. sqlite3_free(pStruct);
  179817. }
  179818. }
  179819. static void fts5StructureRef(Fts5Structure *pStruct){
  179820. pStruct->nRef++;
  179821. }
  179822. /*
  179823. ** Deserialize and return the structure record currently stored in serialized
  179824. ** form within buffer pData/nData.
  179825. **
  179826. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  179827. ** are over-allocated by one slot. This allows the structure contents
  179828. ** to be more easily edited.
  179829. **
  179830. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  179831. ** returned. Otherwise, *ppOut is set to point to the new object and
  179832. ** SQLITE_OK returned.
  179833. */
  179834. static int fts5StructureDecode(
  179835. const u8 *pData, /* Buffer containing serialized structure */
  179836. int nData, /* Size of buffer pData in bytes */
  179837. int *piCookie, /* Configuration cookie value */
  179838. Fts5Structure **ppOut /* OUT: Deserialized object */
  179839. ){
  179840. int rc = SQLITE_OK;
  179841. int i = 0;
  179842. int iLvl;
  179843. int nLevel = 0;
  179844. int nSegment = 0;
  179845. int nByte; /* Bytes of space to allocate at pRet */
  179846. Fts5Structure *pRet = 0; /* Structure object to return */
  179847. /* Grab the cookie value */
  179848. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  179849. i = 4;
  179850. /* Read the total number of levels and segments from the start of the
  179851. ** structure record. */
  179852. i += fts5GetVarint32(&pData[i], nLevel);
  179853. i += fts5GetVarint32(&pData[i], nSegment);
  179854. nByte = (
  179855. sizeof(Fts5Structure) + /* Main structure */
  179856. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  179857. );
  179858. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  179859. if( pRet ){
  179860. pRet->nRef = 1;
  179861. pRet->nLevel = nLevel;
  179862. pRet->nSegment = nSegment;
  179863. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  179864. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  179865. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  179866. int nTotal = 0;
  179867. int iSeg;
  179868. if( i>=nData ){
  179869. rc = FTS5_CORRUPT;
  179870. }else{
  179871. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  179872. i += fts5GetVarint32(&pData[i], nTotal);
  179873. assert( nTotal>=pLvl->nMerge );
  179874. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  179875. nTotal * sizeof(Fts5StructureSegment)
  179876. );
  179877. }
  179878. if( rc==SQLITE_OK ){
  179879. pLvl->nSeg = nTotal;
  179880. for(iSeg=0; iSeg<nTotal; iSeg++){
  179881. if( i>=nData ){
  179882. rc = FTS5_CORRUPT;
  179883. break;
  179884. }
  179885. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  179886. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  179887. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  179888. }
  179889. }
  179890. }
  179891. if( rc!=SQLITE_OK ){
  179892. fts5StructureRelease(pRet);
  179893. pRet = 0;
  179894. }
  179895. }
  179896. *ppOut = pRet;
  179897. return rc;
  179898. }
  179899. /*
  179900. **
  179901. */
  179902. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  179903. if( *pRc==SQLITE_OK ){
  179904. Fts5Structure *pStruct = *ppStruct;
  179905. int nLevel = pStruct->nLevel;
  179906. int nByte = (
  179907. sizeof(Fts5Structure) + /* Main structure */
  179908. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  179909. );
  179910. pStruct = sqlite3_realloc(pStruct, nByte);
  179911. if( pStruct ){
  179912. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  179913. pStruct->nLevel++;
  179914. *ppStruct = pStruct;
  179915. }else{
  179916. *pRc = SQLITE_NOMEM;
  179917. }
  179918. }
  179919. }
  179920. /*
  179921. ** Extend level iLvl so that there is room for at least nExtra more
  179922. ** segments.
  179923. */
  179924. static void fts5StructureExtendLevel(
  179925. int *pRc,
  179926. Fts5Structure *pStruct,
  179927. int iLvl,
  179928. int nExtra,
  179929. int bInsert
  179930. ){
  179931. if( *pRc==SQLITE_OK ){
  179932. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  179933. Fts5StructureSegment *aNew;
  179934. int nByte;
  179935. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  179936. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  179937. if( aNew ){
  179938. if( bInsert==0 ){
  179939. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  179940. }else{
  179941. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  179942. memmove(&aNew[nExtra], aNew, nMove);
  179943. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  179944. }
  179945. pLvl->aSeg = aNew;
  179946. }else{
  179947. *pRc = SQLITE_NOMEM;
  179948. }
  179949. }
  179950. }
  179951. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  179952. Fts5Structure *pRet = 0;
  179953. Fts5Config *pConfig = p->pConfig;
  179954. int iCookie; /* Configuration cookie */
  179955. Fts5Data *pData;
  179956. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  179957. if( p->rc==SQLITE_OK ){
  179958. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  179959. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  179960. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  179961. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  179962. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  179963. }
  179964. fts5DataRelease(pData);
  179965. if( p->rc!=SQLITE_OK ){
  179966. fts5StructureRelease(pRet);
  179967. pRet = 0;
  179968. }
  179969. }
  179970. return pRet;
  179971. }
  179972. static i64 fts5IndexDataVersion(Fts5Index *p){
  179973. i64 iVersion = 0;
  179974. if( p->rc==SQLITE_OK ){
  179975. if( p->pDataVersion==0 ){
  179976. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  179977. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  179978. );
  179979. if( p->rc ) return 0;
  179980. }
  179981. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  179982. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  179983. }
  179984. p->rc = sqlite3_reset(p->pDataVersion);
  179985. }
  179986. return iVersion;
  179987. }
  179988. /*
  179989. ** Read, deserialize and return the structure record.
  179990. **
  179991. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  179992. ** are over-allocated as described for function fts5StructureDecode()
  179993. ** above.
  179994. **
  179995. ** If an error occurs, NULL is returned and an error code left in the
  179996. ** Fts5Index handle. If an error has already occurred when this function
  179997. ** is called, it is a no-op.
  179998. */
  179999. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  180000. if( p->pStruct==0 ){
  180001. p->iStructVersion = fts5IndexDataVersion(p);
  180002. if( p->rc==SQLITE_OK ){
  180003. p->pStruct = fts5StructureReadUncached(p);
  180004. }
  180005. }
  180006. #if 0
  180007. else{
  180008. Fts5Structure *pTest = fts5StructureReadUncached(p);
  180009. if( pTest ){
  180010. int i, j;
  180011. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  180012. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  180013. for(i=0; i<pTest->nLevel; i++){
  180014. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  180015. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  180016. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  180017. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  180018. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  180019. assert_nc( p1->iSegid==p2->iSegid );
  180020. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  180021. assert_nc( p1->pgnoLast==p2->pgnoLast );
  180022. }
  180023. }
  180024. fts5StructureRelease(pTest);
  180025. }
  180026. }
  180027. #endif
  180028. if( p->rc!=SQLITE_OK ) return 0;
  180029. assert( p->iStructVersion!=0 );
  180030. assert( p->pStruct!=0 );
  180031. fts5StructureRef(p->pStruct);
  180032. return p->pStruct;
  180033. }
  180034. static void fts5StructureInvalidate(Fts5Index *p){
  180035. if( p->pStruct ){
  180036. fts5StructureRelease(p->pStruct);
  180037. p->pStruct = 0;
  180038. }
  180039. }
  180040. /*
  180041. ** Return the total number of segments in index structure pStruct. This
  180042. ** function is only ever used as part of assert() conditions.
  180043. */
  180044. #ifdef SQLITE_DEBUG
  180045. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  180046. int nSegment = 0; /* Total number of segments */
  180047. if( pStruct ){
  180048. int iLvl; /* Used to iterate through levels */
  180049. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180050. nSegment += pStruct->aLevel[iLvl].nSeg;
  180051. }
  180052. }
  180053. return nSegment;
  180054. }
  180055. #endif
  180056. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  180057. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  180058. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  180059. (pBuf)->n += nBlob; \
  180060. }
  180061. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  180062. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  180063. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  180064. }
  180065. /*
  180066. ** Serialize and store the "structure" record.
  180067. **
  180068. ** If an error occurs, leave an error code in the Fts5Index object. If an
  180069. ** error has already occurred, this function is a no-op.
  180070. */
  180071. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  180072. if( p->rc==SQLITE_OK ){
  180073. Fts5Buffer buf; /* Buffer to serialize record into */
  180074. int iLvl; /* Used to iterate through levels */
  180075. int iCookie; /* Cookie value to store */
  180076. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  180077. memset(&buf, 0, sizeof(Fts5Buffer));
  180078. /* Append the current configuration cookie */
  180079. iCookie = p->pConfig->iCookie;
  180080. if( iCookie<0 ) iCookie = 0;
  180081. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  180082. sqlite3Fts5Put32(buf.p, iCookie);
  180083. buf.n = 4;
  180084. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  180085. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  180086. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  180087. }
  180088. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180089. int iSeg; /* Used to iterate through segments */
  180090. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  180091. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  180092. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  180093. assert( pLvl->nMerge<=pLvl->nSeg );
  180094. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  180095. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  180096. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  180097. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  180098. }
  180099. }
  180100. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  180101. fts5BufferFree(&buf);
  180102. }
  180103. }
  180104. #if 0
  180105. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  180106. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  180107. int rc = SQLITE_OK;
  180108. Fts5Buffer buf;
  180109. memset(&buf, 0, sizeof(buf));
  180110. fts5DebugStructure(&rc, &buf, pStruct);
  180111. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  180112. fflush(stdout);
  180113. fts5BufferFree(&buf);
  180114. }
  180115. #else
  180116. # define fts5PrintStructure(x,y)
  180117. #endif
  180118. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  180119. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  180120. }
  180121. /*
  180122. ** Return a copy of index structure pStruct. Except, promote as many
  180123. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  180124. ** returned.
  180125. */
  180126. static void fts5StructurePromoteTo(
  180127. Fts5Index *p,
  180128. int iPromote,
  180129. int szPromote,
  180130. Fts5Structure *pStruct
  180131. ){
  180132. int il, is;
  180133. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  180134. if( pOut->nMerge==0 ){
  180135. for(il=iPromote+1; il<pStruct->nLevel; il++){
  180136. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  180137. if( pLvl->nMerge ) return;
  180138. for(is=pLvl->nSeg-1; is>=0; is--){
  180139. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  180140. if( sz>szPromote ) return;
  180141. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  180142. if( p->rc ) return;
  180143. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  180144. pOut->nSeg++;
  180145. pLvl->nSeg--;
  180146. }
  180147. }
  180148. }
  180149. }
  180150. /*
  180151. ** A new segment has just been written to level iLvl of index structure
  180152. ** pStruct. This function determines if any segments should be promoted
  180153. ** as a result. Segments are promoted in two scenarios:
  180154. **
  180155. ** a) If the segment just written is smaller than one or more segments
  180156. ** within the previous populated level, it is promoted to the previous
  180157. ** populated level.
  180158. **
  180159. ** b) If the segment just written is larger than the newest segment on
  180160. ** the next populated level, then that segment, and any other adjacent
  180161. ** segments that are also smaller than the one just written, are
  180162. ** promoted.
  180163. **
  180164. ** If one or more segments are promoted, the structure object is updated
  180165. ** to reflect this.
  180166. */
  180167. static void fts5StructurePromote(
  180168. Fts5Index *p, /* FTS5 backend object */
  180169. int iLvl, /* Index level just updated */
  180170. Fts5Structure *pStruct /* Index structure */
  180171. ){
  180172. if( p->rc==SQLITE_OK ){
  180173. int iTst;
  180174. int iPromote = -1;
  180175. int szPromote = 0; /* Promote anything this size or smaller */
  180176. Fts5StructureSegment *pSeg; /* Segment just written */
  180177. int szSeg; /* Size of segment just written */
  180178. int nSeg = pStruct->aLevel[iLvl].nSeg;
  180179. if( nSeg==0 ) return;
  180180. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  180181. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  180182. /* Check for condition (a) */
  180183. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  180184. if( iTst>=0 ){
  180185. int i;
  180186. int szMax = 0;
  180187. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  180188. assert( pTst->nMerge==0 );
  180189. for(i=0; i<pTst->nSeg; i++){
  180190. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  180191. if( sz>szMax ) szMax = sz;
  180192. }
  180193. if( szMax>=szSeg ){
  180194. /* Condition (a) is true. Promote the newest segment on level
  180195. ** iLvl to level iTst. */
  180196. iPromote = iTst;
  180197. szPromote = szMax;
  180198. }
  180199. }
  180200. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  180201. ** is a no-op if it is not. */
  180202. if( iPromote<0 ){
  180203. iPromote = iLvl;
  180204. szPromote = szSeg;
  180205. }
  180206. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  180207. }
  180208. }
  180209. /*
  180210. ** Advance the iterator passed as the only argument. If the end of the
  180211. ** doclist-index page is reached, return non-zero.
  180212. */
  180213. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  180214. Fts5Data *pData = pLvl->pData;
  180215. if( pLvl->iOff==0 ){
  180216. assert( pLvl->bEof==0 );
  180217. pLvl->iOff = 1;
  180218. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  180219. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  180220. pLvl->iFirstOff = pLvl->iOff;
  180221. }else{
  180222. int iOff;
  180223. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  180224. if( pData->p[iOff] ) break;
  180225. }
  180226. if( iOff<pData->nn ){
  180227. i64 iVal;
  180228. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  180229. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  180230. pLvl->iRowid += iVal;
  180231. pLvl->iOff = iOff;
  180232. }else{
  180233. pLvl->bEof = 1;
  180234. }
  180235. }
  180236. return pLvl->bEof;
  180237. }
  180238. /*
  180239. ** Advance the iterator passed as the only argument.
  180240. */
  180241. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  180242. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  180243. assert( iLvl<pIter->nLvl );
  180244. if( fts5DlidxLvlNext(pLvl) ){
  180245. if( (iLvl+1) < pIter->nLvl ){
  180246. fts5DlidxIterNextR(p, pIter, iLvl+1);
  180247. if( pLvl[1].bEof==0 ){
  180248. fts5DataRelease(pLvl->pData);
  180249. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  180250. pLvl->pData = fts5DataRead(p,
  180251. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  180252. );
  180253. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  180254. }
  180255. }
  180256. }
  180257. return pIter->aLvl[0].bEof;
  180258. }
  180259. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  180260. return fts5DlidxIterNextR(p, pIter, 0);
  180261. }
  180262. /*
  180263. ** The iterator passed as the first argument has the following fields set
  180264. ** as follows. This function sets up the rest of the iterator so that it
  180265. ** points to the first rowid in the doclist-index.
  180266. **
  180267. ** pData:
  180268. ** pointer to doclist-index record,
  180269. **
  180270. ** When this function is called pIter->iLeafPgno is the page number the
  180271. ** doclist is associated with (the one featuring the term).
  180272. */
  180273. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  180274. int i;
  180275. for(i=0; i<pIter->nLvl; i++){
  180276. fts5DlidxLvlNext(&pIter->aLvl[i]);
  180277. }
  180278. return pIter->aLvl[0].bEof;
  180279. }
  180280. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  180281. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  180282. }
  180283. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  180284. int i;
  180285. /* Advance each level to the last entry on the last page */
  180286. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  180287. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  180288. while( fts5DlidxLvlNext(pLvl)==0 );
  180289. pLvl->bEof = 0;
  180290. if( i>0 ){
  180291. Fts5DlidxLvl *pChild = &pLvl[-1];
  180292. fts5DataRelease(pChild->pData);
  180293. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  180294. pChild->pData = fts5DataRead(p,
  180295. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  180296. );
  180297. }
  180298. }
  180299. }
  180300. /*
  180301. ** Move the iterator passed as the only argument to the previous entry.
  180302. */
  180303. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  180304. int iOff = pLvl->iOff;
  180305. assert( pLvl->bEof==0 );
  180306. if( iOff<=pLvl->iFirstOff ){
  180307. pLvl->bEof = 1;
  180308. }else{
  180309. u8 *a = pLvl->pData->p;
  180310. i64 iVal;
  180311. int iLimit;
  180312. int ii;
  180313. int nZero = 0;
  180314. /* Currently iOff points to the first byte of a varint. This block
  180315. ** decrements iOff until it points to the first byte of the previous
  180316. ** varint. Taking care not to read any memory locations that occur
  180317. ** before the buffer in memory. */
  180318. iLimit = (iOff>9 ? iOff-9 : 0);
  180319. for(iOff--; iOff>iLimit; iOff--){
  180320. if( (a[iOff-1] & 0x80)==0 ) break;
  180321. }
  180322. fts5GetVarint(&a[iOff], (u64*)&iVal);
  180323. pLvl->iRowid -= iVal;
  180324. pLvl->iLeafPgno--;
  180325. /* Skip backwards past any 0x00 varints. */
  180326. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  180327. nZero++;
  180328. }
  180329. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  180330. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  180331. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  180332. ** bytes before a[ii]. */
  180333. int bZero = 0; /* True if last 0x00 counts */
  180334. if( (ii-8)>=pLvl->iFirstOff ){
  180335. int j;
  180336. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  180337. bZero = (j>8);
  180338. }
  180339. if( bZero==0 ) nZero--;
  180340. }
  180341. pLvl->iLeafPgno -= nZero;
  180342. pLvl->iOff = iOff - nZero;
  180343. }
  180344. return pLvl->bEof;
  180345. }
  180346. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  180347. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  180348. assert( iLvl<pIter->nLvl );
  180349. if( fts5DlidxLvlPrev(pLvl) ){
  180350. if( (iLvl+1) < pIter->nLvl ){
  180351. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  180352. if( pLvl[1].bEof==0 ){
  180353. fts5DataRelease(pLvl->pData);
  180354. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  180355. pLvl->pData = fts5DataRead(p,
  180356. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  180357. );
  180358. if( pLvl->pData ){
  180359. while( fts5DlidxLvlNext(pLvl)==0 );
  180360. pLvl->bEof = 0;
  180361. }
  180362. }
  180363. }
  180364. }
  180365. return pIter->aLvl[0].bEof;
  180366. }
  180367. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  180368. return fts5DlidxIterPrevR(p, pIter, 0);
  180369. }
  180370. /*
  180371. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  180372. */
  180373. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  180374. if( pIter ){
  180375. int i;
  180376. for(i=0; i<pIter->nLvl; i++){
  180377. fts5DataRelease(pIter->aLvl[i].pData);
  180378. }
  180379. sqlite3_free(pIter);
  180380. }
  180381. }
  180382. static Fts5DlidxIter *fts5DlidxIterInit(
  180383. Fts5Index *p, /* Fts5 Backend to iterate within */
  180384. int bRev, /* True for ORDER BY ASC */
  180385. int iSegid, /* Segment id */
  180386. int iLeafPg /* Leaf page number to load dlidx for */
  180387. ){
  180388. Fts5DlidxIter *pIter = 0;
  180389. int i;
  180390. int bDone = 0;
  180391. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  180392. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  180393. Fts5DlidxIter *pNew;
  180394. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  180395. if( pNew==0 ){
  180396. p->rc = SQLITE_NOMEM;
  180397. }else{
  180398. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  180399. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  180400. pIter = pNew;
  180401. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  180402. pLvl->pData = fts5DataRead(p, iRowid);
  180403. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  180404. bDone = 1;
  180405. }
  180406. pIter->nLvl = i+1;
  180407. }
  180408. }
  180409. if( p->rc==SQLITE_OK ){
  180410. pIter->iSegid = iSegid;
  180411. if( bRev==0 ){
  180412. fts5DlidxIterFirst(pIter);
  180413. }else{
  180414. fts5DlidxIterLast(p, pIter);
  180415. }
  180416. }
  180417. if( p->rc!=SQLITE_OK ){
  180418. fts5DlidxIterFree(pIter);
  180419. pIter = 0;
  180420. }
  180421. return pIter;
  180422. }
  180423. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  180424. return pIter->aLvl[0].iRowid;
  180425. }
  180426. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  180427. return pIter->aLvl[0].iLeafPgno;
  180428. }
  180429. /*
  180430. ** Load the next leaf page into the segment iterator.
  180431. */
  180432. static void fts5SegIterNextPage(
  180433. Fts5Index *p, /* FTS5 backend object */
  180434. Fts5SegIter *pIter /* Iterator to advance to next page */
  180435. ){
  180436. Fts5Data *pLeaf;
  180437. Fts5StructureSegment *pSeg = pIter->pSeg;
  180438. fts5DataRelease(pIter->pLeaf);
  180439. pIter->iLeafPgno++;
  180440. if( pIter->pNextLeaf ){
  180441. pIter->pLeaf = pIter->pNextLeaf;
  180442. pIter->pNextLeaf = 0;
  180443. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  180444. pIter->pLeaf = fts5LeafRead(p,
  180445. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  180446. );
  180447. }else{
  180448. pIter->pLeaf = 0;
  180449. }
  180450. pLeaf = pIter->pLeaf;
  180451. if( pLeaf ){
  180452. pIter->iPgidxOff = pLeaf->szLeaf;
  180453. if( fts5LeafIsTermless(pLeaf) ){
  180454. pIter->iEndofDoclist = pLeaf->nn+1;
  180455. }else{
  180456. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  180457. pIter->iEndofDoclist
  180458. );
  180459. }
  180460. }
  180461. }
  180462. /*
  180463. ** Argument p points to a buffer containing a varint to be interpreted as a
  180464. ** position list size field. Read the varint and return the number of bytes
  180465. ** read. Before returning, set *pnSz to the number of bytes in the position
  180466. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  180467. */
  180468. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  180469. int nSz;
  180470. int n = 0;
  180471. fts5FastGetVarint32(p, n, nSz);
  180472. assert_nc( nSz>=0 );
  180473. *pnSz = nSz/2;
  180474. *pbDel = nSz & 0x0001;
  180475. return n;
  180476. }
  180477. /*
  180478. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  180479. ** position-list size field. Read the value of the field and store it
  180480. ** in the following variables:
  180481. **
  180482. ** Fts5SegIter.nPos
  180483. ** Fts5SegIter.bDel
  180484. **
  180485. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  180486. ** position list content (if any).
  180487. */
  180488. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  180489. if( p->rc==SQLITE_OK ){
  180490. int iOff = pIter->iLeafOffset; /* Offset to read at */
  180491. ASSERT_SZLEAF_OK(pIter->pLeaf);
  180492. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  180493. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  180494. pIter->bDel = 0;
  180495. pIter->nPos = 1;
  180496. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  180497. pIter->bDel = 1;
  180498. iOff++;
  180499. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  180500. pIter->nPos = 1;
  180501. iOff++;
  180502. }else{
  180503. pIter->nPos = 0;
  180504. }
  180505. }
  180506. }else{
  180507. int nSz;
  180508. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  180509. pIter->bDel = (nSz & 0x0001);
  180510. pIter->nPos = nSz>>1;
  180511. assert_nc( pIter->nPos>=0 );
  180512. }
  180513. pIter->iLeafOffset = iOff;
  180514. }
  180515. }
  180516. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  180517. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  180518. int iOff = pIter->iLeafOffset;
  180519. ASSERT_SZLEAF_OK(pIter->pLeaf);
  180520. if( iOff>=pIter->pLeaf->szLeaf ){
  180521. fts5SegIterNextPage(p, pIter);
  180522. if( pIter->pLeaf==0 ){
  180523. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  180524. return;
  180525. }
  180526. iOff = 4;
  180527. a = pIter->pLeaf->p;
  180528. }
  180529. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  180530. pIter->iLeafOffset = iOff;
  180531. }
  180532. /*
  180533. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  180534. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  180535. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  180536. ** the first term in the segment).
  180537. **
  180538. ** This function populates:
  180539. **
  180540. ** Fts5SegIter.term
  180541. ** Fts5SegIter.rowid
  180542. **
  180543. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  180544. ** the first position list. The position list belonging to document
  180545. ** (Fts5SegIter.iRowid).
  180546. */
  180547. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  180548. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  180549. int iOff = pIter->iLeafOffset; /* Offset to read at */
  180550. int nNew; /* Bytes of new data */
  180551. iOff += fts5GetVarint32(&a[iOff], nNew);
  180552. if( iOff+nNew>pIter->pLeaf->nn ){
  180553. p->rc = FTS5_CORRUPT;
  180554. return;
  180555. }
  180556. pIter->term.n = nKeep;
  180557. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  180558. iOff += nNew;
  180559. pIter->iTermLeafOffset = iOff;
  180560. pIter->iTermLeafPgno = pIter->iLeafPgno;
  180561. pIter->iLeafOffset = iOff;
  180562. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  180563. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  180564. }else{
  180565. int nExtra;
  180566. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  180567. pIter->iEndofDoclist += nExtra;
  180568. }
  180569. fts5SegIterLoadRowid(p, pIter);
  180570. }
  180571. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  180572. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  180573. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  180574. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  180575. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  180576. pIter->xNext = fts5SegIterNext_Reverse;
  180577. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  180578. pIter->xNext = fts5SegIterNext_None;
  180579. }else{
  180580. pIter->xNext = fts5SegIterNext;
  180581. }
  180582. }
  180583. /*
  180584. ** Initialize the iterator object pIter to iterate through the entries in
  180585. ** segment pSeg. The iterator is left pointing to the first entry when
  180586. ** this function returns.
  180587. **
  180588. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  180589. ** an error has already occurred when this function is called, it is a no-op.
  180590. */
  180591. static void fts5SegIterInit(
  180592. Fts5Index *p, /* FTS index object */
  180593. Fts5StructureSegment *pSeg, /* Description of segment */
  180594. Fts5SegIter *pIter /* Object to populate */
  180595. ){
  180596. if( pSeg->pgnoFirst==0 ){
  180597. /* This happens if the segment is being used as an input to an incremental
  180598. ** merge and all data has already been "trimmed". See function
  180599. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  180600. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  180601. ** at EOF already. */
  180602. assert( pIter->pLeaf==0 );
  180603. return;
  180604. }
  180605. if( p->rc==SQLITE_OK ){
  180606. memset(pIter, 0, sizeof(*pIter));
  180607. fts5SegIterSetNext(p, pIter);
  180608. pIter->pSeg = pSeg;
  180609. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  180610. fts5SegIterNextPage(p, pIter);
  180611. }
  180612. if( p->rc==SQLITE_OK ){
  180613. pIter->iLeafOffset = 4;
  180614. assert_nc( pIter->pLeaf->nn>4 );
  180615. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  180616. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  180617. fts5SegIterLoadTerm(p, pIter, 0);
  180618. fts5SegIterLoadNPos(p, pIter);
  180619. }
  180620. }
  180621. /*
  180622. ** This function is only ever called on iterators created by calls to
  180623. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  180624. **
  180625. ** The iterator is in an unusual state when this function is called: the
  180626. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  180627. ** the position-list size field for the first relevant rowid on the page.
  180628. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  180629. **
  180630. ** This function advances the iterator so that it points to the last
  180631. ** relevant rowid on the page and, if necessary, initializes the
  180632. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  180633. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  180634. ** byte of the position list content associated with said rowid.
  180635. */
  180636. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  180637. int eDetail = p->pConfig->eDetail;
  180638. int n = pIter->pLeaf->szLeaf;
  180639. int i = pIter->iLeafOffset;
  180640. u8 *a = pIter->pLeaf->p;
  180641. int iRowidOffset = 0;
  180642. if( n>pIter->iEndofDoclist ){
  180643. n = pIter->iEndofDoclist;
  180644. }
  180645. ASSERT_SZLEAF_OK(pIter->pLeaf);
  180646. while( 1 ){
  180647. i64 iDelta = 0;
  180648. if( eDetail==FTS5_DETAIL_NONE ){
  180649. /* todo */
  180650. if( i<n && a[i]==0 ){
  180651. i++;
  180652. if( i<n && a[i]==0 ) i++;
  180653. }
  180654. }else{
  180655. int nPos;
  180656. int bDummy;
  180657. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  180658. i += nPos;
  180659. }
  180660. if( i>=n ) break;
  180661. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  180662. pIter->iRowid += iDelta;
  180663. /* If necessary, grow the pIter->aRowidOffset[] array. */
  180664. if( iRowidOffset>=pIter->nRowidOffset ){
  180665. int nNew = pIter->nRowidOffset + 8;
  180666. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  180667. if( aNew==0 ){
  180668. p->rc = SQLITE_NOMEM;
  180669. break;
  180670. }
  180671. pIter->aRowidOffset = aNew;
  180672. pIter->nRowidOffset = nNew;
  180673. }
  180674. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  180675. pIter->iLeafOffset = i;
  180676. }
  180677. pIter->iRowidOffset = iRowidOffset;
  180678. fts5SegIterLoadNPos(p, pIter);
  180679. }
  180680. /*
  180681. **
  180682. */
  180683. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  180684. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  180685. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  180686. fts5DataRelease(pIter->pLeaf);
  180687. pIter->pLeaf = 0;
  180688. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  180689. Fts5Data *pNew;
  180690. pIter->iLeafPgno--;
  180691. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  180692. pIter->pSeg->iSegid, pIter->iLeafPgno
  180693. ));
  180694. if( pNew ){
  180695. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  180696. ** thing on the page - i.e. the first rowid is on the following page.
  180697. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  180698. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  180699. assert( pIter->pLeaf==0 );
  180700. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  180701. pIter->pLeaf = pNew;
  180702. pIter->iLeafOffset = pIter->iTermLeafOffset;
  180703. }
  180704. }else{
  180705. int iRowidOff;
  180706. iRowidOff = fts5LeafFirstRowidOff(pNew);
  180707. if( iRowidOff ){
  180708. pIter->pLeaf = pNew;
  180709. pIter->iLeafOffset = iRowidOff;
  180710. }
  180711. }
  180712. if( pIter->pLeaf ){
  180713. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  180714. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  180715. break;
  180716. }else{
  180717. fts5DataRelease(pNew);
  180718. }
  180719. }
  180720. }
  180721. if( pIter->pLeaf ){
  180722. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  180723. fts5SegIterReverseInitPage(p, pIter);
  180724. }
  180725. }
  180726. /*
  180727. ** Return true if the iterator passed as the second argument currently
  180728. ** points to a delete marker. A delete marker is an entry with a 0 byte
  180729. ** position-list.
  180730. */
  180731. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  180732. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  180733. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  180734. }
  180735. /*
  180736. ** Advance iterator pIter to the next entry.
  180737. **
  180738. ** This version of fts5SegIterNext() is only used by reverse iterators.
  180739. */
  180740. static void fts5SegIterNext_Reverse(
  180741. Fts5Index *p, /* FTS5 backend object */
  180742. Fts5SegIter *pIter, /* Iterator to advance */
  180743. int *pbUnused /* Unused */
  180744. ){
  180745. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  180746. assert( pIter->pNextLeaf==0 );
  180747. UNUSED_PARAM(pbUnused);
  180748. if( pIter->iRowidOffset>0 ){
  180749. u8 *a = pIter->pLeaf->p;
  180750. int iOff;
  180751. i64 iDelta;
  180752. pIter->iRowidOffset--;
  180753. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  180754. fts5SegIterLoadNPos(p, pIter);
  180755. iOff = pIter->iLeafOffset;
  180756. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  180757. iOff += pIter->nPos;
  180758. }
  180759. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  180760. pIter->iRowid -= iDelta;
  180761. }else{
  180762. fts5SegIterReverseNewPage(p, pIter);
  180763. }
  180764. }
  180765. /*
  180766. ** Advance iterator pIter to the next entry.
  180767. **
  180768. ** This version of fts5SegIterNext() is only used if detail=none and the
  180769. ** iterator is not a reverse direction iterator.
  180770. */
  180771. static void fts5SegIterNext_None(
  180772. Fts5Index *p, /* FTS5 backend object */
  180773. Fts5SegIter *pIter, /* Iterator to advance */
  180774. int *pbNewTerm /* OUT: Set for new term */
  180775. ){
  180776. int iOff;
  180777. assert( p->rc==SQLITE_OK );
  180778. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  180779. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  180780. ASSERT_SZLEAF_OK(pIter->pLeaf);
  180781. iOff = pIter->iLeafOffset;
  180782. /* Next entry is on the next page */
  180783. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  180784. fts5SegIterNextPage(p, pIter);
  180785. if( p->rc || pIter->pLeaf==0 ) return;
  180786. pIter->iRowid = 0;
  180787. iOff = 4;
  180788. }
  180789. if( iOff<pIter->iEndofDoclist ){
  180790. /* Next entry is on the current page */
  180791. i64 iDelta;
  180792. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  180793. pIter->iLeafOffset = iOff;
  180794. pIter->iRowid += iDelta;
  180795. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  180796. if( pIter->pSeg ){
  180797. int nKeep = 0;
  180798. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  180799. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  180800. }
  180801. pIter->iLeafOffset = iOff;
  180802. fts5SegIterLoadTerm(p, pIter, nKeep);
  180803. }else{
  180804. const u8 *pList = 0;
  180805. const char *zTerm = 0;
  180806. int nList;
  180807. sqlite3Fts5HashScanNext(p->pHash);
  180808. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  180809. if( pList==0 ) goto next_none_eof;
  180810. pIter->pLeaf->p = (u8*)pList;
  180811. pIter->pLeaf->nn = nList;
  180812. pIter->pLeaf->szLeaf = nList;
  180813. pIter->iEndofDoclist = nList;
  180814. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  180815. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  180816. }
  180817. if( pbNewTerm ) *pbNewTerm = 1;
  180818. }else{
  180819. goto next_none_eof;
  180820. }
  180821. fts5SegIterLoadNPos(p, pIter);
  180822. return;
  180823. next_none_eof:
  180824. fts5DataRelease(pIter->pLeaf);
  180825. pIter->pLeaf = 0;
  180826. }
  180827. /*
  180828. ** Advance iterator pIter to the next entry.
  180829. **
  180830. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  180831. ** is not considered an error if the iterator reaches EOF. If an error has
  180832. ** already occurred when this function is called, it is a no-op.
  180833. */
  180834. static void fts5SegIterNext(
  180835. Fts5Index *p, /* FTS5 backend object */
  180836. Fts5SegIter *pIter, /* Iterator to advance */
  180837. int *pbNewTerm /* OUT: Set for new term */
  180838. ){
  180839. Fts5Data *pLeaf = pIter->pLeaf;
  180840. int iOff;
  180841. int bNewTerm = 0;
  180842. int nKeep = 0;
  180843. u8 *a;
  180844. int n;
  180845. assert( pbNewTerm==0 || *pbNewTerm==0 );
  180846. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  180847. /* Search for the end of the position list within the current page. */
  180848. a = pLeaf->p;
  180849. n = pLeaf->szLeaf;
  180850. ASSERT_SZLEAF_OK(pLeaf);
  180851. iOff = pIter->iLeafOffset + pIter->nPos;
  180852. if( iOff<n ){
  180853. /* The next entry is on the current page. */
  180854. assert_nc( iOff<=pIter->iEndofDoclist );
  180855. if( iOff>=pIter->iEndofDoclist ){
  180856. bNewTerm = 1;
  180857. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  180858. iOff += fts5GetVarint32(&a[iOff], nKeep);
  180859. }
  180860. }else{
  180861. u64 iDelta;
  180862. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  180863. pIter->iRowid += iDelta;
  180864. assert_nc( iDelta>0 );
  180865. }
  180866. pIter->iLeafOffset = iOff;
  180867. }else if( pIter->pSeg==0 ){
  180868. const u8 *pList = 0;
  180869. const char *zTerm = 0;
  180870. int nList = 0;
  180871. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  180872. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  180873. sqlite3Fts5HashScanNext(p->pHash);
  180874. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  180875. }
  180876. if( pList==0 ){
  180877. fts5DataRelease(pIter->pLeaf);
  180878. pIter->pLeaf = 0;
  180879. }else{
  180880. pIter->pLeaf->p = (u8*)pList;
  180881. pIter->pLeaf->nn = nList;
  180882. pIter->pLeaf->szLeaf = nList;
  180883. pIter->iEndofDoclist = nList+1;
  180884. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  180885. (u8*)zTerm);
  180886. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  180887. *pbNewTerm = 1;
  180888. }
  180889. }else{
  180890. iOff = 0;
  180891. /* Next entry is not on the current page */
  180892. while( iOff==0 ){
  180893. fts5SegIterNextPage(p, pIter);
  180894. pLeaf = pIter->pLeaf;
  180895. if( pLeaf==0 ) break;
  180896. ASSERT_SZLEAF_OK(pLeaf);
  180897. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  180898. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  180899. pIter->iLeafOffset = iOff;
  180900. if( pLeaf->nn>pLeaf->szLeaf ){
  180901. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  180902. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  180903. );
  180904. }
  180905. }
  180906. else if( pLeaf->nn>pLeaf->szLeaf ){
  180907. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  180908. &pLeaf->p[pLeaf->szLeaf], iOff
  180909. );
  180910. pIter->iLeafOffset = iOff;
  180911. pIter->iEndofDoclist = iOff;
  180912. bNewTerm = 1;
  180913. }
  180914. assert_nc( iOff<pLeaf->szLeaf );
  180915. if( iOff>pLeaf->szLeaf ){
  180916. p->rc = FTS5_CORRUPT;
  180917. return;
  180918. }
  180919. }
  180920. }
  180921. /* Check if the iterator is now at EOF. If so, return early. */
  180922. if( pIter->pLeaf ){
  180923. if( bNewTerm ){
  180924. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  180925. fts5DataRelease(pIter->pLeaf);
  180926. pIter->pLeaf = 0;
  180927. }else{
  180928. fts5SegIterLoadTerm(p, pIter, nKeep);
  180929. fts5SegIterLoadNPos(p, pIter);
  180930. if( pbNewTerm ) *pbNewTerm = 1;
  180931. }
  180932. }else{
  180933. /* The following could be done by calling fts5SegIterLoadNPos(). But
  180934. ** this block is particularly performance critical, so equivalent
  180935. ** code is inlined.
  180936. **
  180937. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  180938. ** detail=none mode. Not ideal.
  180939. */
  180940. int nSz;
  180941. assert( p->rc==SQLITE_OK );
  180942. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  180943. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  180944. pIter->bDel = (nSz & 0x0001);
  180945. pIter->nPos = nSz>>1;
  180946. assert_nc( pIter->nPos>=0 );
  180947. }
  180948. }
  180949. }
  180950. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  180951. #define fts5IndexSkipVarint(a, iOff) { \
  180952. int iEnd = iOff+9; \
  180953. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  180954. }
  180955. /*
  180956. ** Iterator pIter currently points to the first rowid in a doclist. This
  180957. ** function sets the iterator up so that iterates in reverse order through
  180958. ** the doclist.
  180959. */
  180960. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  180961. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  180962. Fts5Data *pLast = 0;
  180963. int pgnoLast = 0;
  180964. if( pDlidx ){
  180965. int iSegid = pIter->pSeg->iSegid;
  180966. pgnoLast = fts5DlidxIterPgno(pDlidx);
  180967. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  180968. }else{
  180969. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  180970. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  180971. ** position-list content for the current rowid. Back it up so that it
  180972. ** points to the start of the position-list size field. */
  180973. int iPoslist;
  180974. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  180975. iPoslist = pIter->iTermLeafOffset;
  180976. }else{
  180977. iPoslist = 4;
  180978. }
  180979. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  180980. pIter->iLeafOffset = iPoslist;
  180981. /* If this condition is true then the largest rowid for the current
  180982. ** term may not be stored on the current page. So search forward to
  180983. ** see where said rowid really is. */
  180984. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  180985. int pgno;
  180986. Fts5StructureSegment *pSeg = pIter->pSeg;
  180987. /* The last rowid in the doclist may not be on the current page. Search
  180988. ** forward to find the page containing the last rowid. */
  180989. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  180990. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  180991. Fts5Data *pNew = fts5DataRead(p, iAbs);
  180992. if( pNew ){
  180993. int iRowid, bTermless;
  180994. iRowid = fts5LeafFirstRowidOff(pNew);
  180995. bTermless = fts5LeafIsTermless(pNew);
  180996. if( iRowid ){
  180997. SWAPVAL(Fts5Data*, pNew, pLast);
  180998. pgnoLast = pgno;
  180999. }
  181000. fts5DataRelease(pNew);
  181001. if( bTermless==0 ) break;
  181002. }
  181003. }
  181004. }
  181005. }
  181006. /* If pLast is NULL at this point, then the last rowid for this doclist
  181007. ** lies on the page currently indicated by the iterator. In this case
  181008. ** pIter->iLeafOffset is already set to point to the position-list size
  181009. ** field associated with the first relevant rowid on the page.
  181010. **
  181011. ** Or, if pLast is non-NULL, then it is the page that contains the last
  181012. ** rowid. In this case configure the iterator so that it points to the
  181013. ** first rowid on this page.
  181014. */
  181015. if( pLast ){
  181016. int iOff;
  181017. fts5DataRelease(pIter->pLeaf);
  181018. pIter->pLeaf = pLast;
  181019. pIter->iLeafPgno = pgnoLast;
  181020. iOff = fts5LeafFirstRowidOff(pLast);
  181021. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  181022. pIter->iLeafOffset = iOff;
  181023. if( fts5LeafIsTermless(pLast) ){
  181024. pIter->iEndofDoclist = pLast->nn+1;
  181025. }else{
  181026. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  181027. }
  181028. }
  181029. fts5SegIterReverseInitPage(p, pIter);
  181030. }
  181031. /*
  181032. ** Iterator pIter currently points to the first rowid of a doclist.
  181033. ** There is a doclist-index associated with the final term on the current
  181034. ** page. If the current term is the last term on the page, load the
  181035. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  181036. */
  181037. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  181038. int iSeg = pIter->pSeg->iSegid;
  181039. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  181040. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  181041. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  181042. assert( pIter->pDlidx==0 );
  181043. /* Check if the current doclist ends on this page. If it does, return
  181044. ** early without loading the doclist-index (as it belongs to a different
  181045. ** term. */
  181046. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  181047. && pIter->iEndofDoclist<pLeaf->szLeaf
  181048. ){
  181049. return;
  181050. }
  181051. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  181052. }
  181053. /*
  181054. ** The iterator object passed as the second argument currently contains
  181055. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  181056. ** function searches the leaf page for a term matching (pTerm/nTerm).
  181057. **
  181058. ** If the specified term is found on the page, then the iterator is left
  181059. ** pointing to it. If argument bGe is zero and the term is not found,
  181060. ** the iterator is left pointing at EOF.
  181061. **
  181062. ** If bGe is non-zero and the specified term is not found, then the
  181063. ** iterator is left pointing to the smallest term in the segment that
  181064. ** is larger than the specified term, even if this term is not on the
  181065. ** current page.
  181066. */
  181067. static void fts5LeafSeek(
  181068. Fts5Index *p, /* Leave any error code here */
  181069. int bGe, /* True for a >= search */
  181070. Fts5SegIter *pIter, /* Iterator to seek */
  181071. const u8 *pTerm, int nTerm /* Term to search for */
  181072. ){
  181073. int iOff;
  181074. const u8 *a = pIter->pLeaf->p;
  181075. int szLeaf = pIter->pLeaf->szLeaf;
  181076. int n = pIter->pLeaf->nn;
  181077. int nMatch = 0;
  181078. int nKeep = 0;
  181079. int nNew = 0;
  181080. int iTermOff;
  181081. int iPgidx; /* Current offset in pgidx */
  181082. int bEndOfPage = 0;
  181083. assert( p->rc==SQLITE_OK );
  181084. iPgidx = szLeaf;
  181085. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  181086. iOff = iTermOff;
  181087. if( iOff>n ){
  181088. p->rc = FTS5_CORRUPT;
  181089. return;
  181090. }
  181091. while( 1 ){
  181092. /* Figure out how many new bytes are in this term */
  181093. fts5FastGetVarint32(a, iOff, nNew);
  181094. if( nKeep<nMatch ){
  181095. goto search_failed;
  181096. }
  181097. assert( nKeep>=nMatch );
  181098. if( nKeep==nMatch ){
  181099. int nCmp;
  181100. int i;
  181101. nCmp = MIN(nNew, nTerm-nMatch);
  181102. for(i=0; i<nCmp; i++){
  181103. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  181104. }
  181105. nMatch += i;
  181106. if( nTerm==nMatch ){
  181107. if( i==nNew ){
  181108. goto search_success;
  181109. }else{
  181110. goto search_failed;
  181111. }
  181112. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  181113. goto search_failed;
  181114. }
  181115. }
  181116. if( iPgidx>=n ){
  181117. bEndOfPage = 1;
  181118. break;
  181119. }
  181120. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  181121. iTermOff += nKeep;
  181122. iOff = iTermOff;
  181123. if( iOff>=n ){
  181124. p->rc = FTS5_CORRUPT;
  181125. return;
  181126. }
  181127. /* Read the nKeep field of the next term. */
  181128. fts5FastGetVarint32(a, iOff, nKeep);
  181129. }
  181130. search_failed:
  181131. if( bGe==0 ){
  181132. fts5DataRelease(pIter->pLeaf);
  181133. pIter->pLeaf = 0;
  181134. return;
  181135. }else if( bEndOfPage ){
  181136. do {
  181137. fts5SegIterNextPage(p, pIter);
  181138. if( pIter->pLeaf==0 ) return;
  181139. a = pIter->pLeaf->p;
  181140. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  181141. iPgidx = pIter->pLeaf->szLeaf;
  181142. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  181143. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  181144. p->rc = FTS5_CORRUPT;
  181145. }else{
  181146. nKeep = 0;
  181147. iTermOff = iOff;
  181148. n = pIter->pLeaf->nn;
  181149. iOff += fts5GetVarint32(&a[iOff], nNew);
  181150. break;
  181151. }
  181152. }
  181153. }while( 1 );
  181154. }
  181155. search_success:
  181156. pIter->iLeafOffset = iOff + nNew;
  181157. pIter->iTermLeafOffset = pIter->iLeafOffset;
  181158. pIter->iTermLeafPgno = pIter->iLeafPgno;
  181159. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  181160. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  181161. if( iPgidx>=n ){
  181162. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  181163. }else{
  181164. int nExtra;
  181165. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  181166. pIter->iEndofDoclist = iTermOff + nExtra;
  181167. }
  181168. pIter->iPgidxOff = iPgidx;
  181169. fts5SegIterLoadRowid(p, pIter);
  181170. fts5SegIterLoadNPos(p, pIter);
  181171. }
  181172. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  181173. if( p->pIdxSelect==0 ){
  181174. Fts5Config *pConfig = p->pConfig;
  181175. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  181176. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  181177. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  181178. pConfig->zDb, pConfig->zName
  181179. ));
  181180. }
  181181. return p->pIdxSelect;
  181182. }
  181183. /*
  181184. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  181185. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  181186. **
  181187. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  181188. ** an error has already occurred when this function is called, it is a no-op.
  181189. */
  181190. static void fts5SegIterSeekInit(
  181191. Fts5Index *p, /* FTS5 backend */
  181192. const u8 *pTerm, int nTerm, /* Term to seek to */
  181193. int flags, /* Mask of FTS5INDEX_XXX flags */
  181194. Fts5StructureSegment *pSeg, /* Description of segment */
  181195. Fts5SegIter *pIter /* Object to populate */
  181196. ){
  181197. int iPg = 1;
  181198. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  181199. int bDlidx = 0; /* True if there is a doclist-index */
  181200. sqlite3_stmt *pIdxSelect = 0;
  181201. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  181202. assert( pTerm && nTerm );
  181203. memset(pIter, 0, sizeof(*pIter));
  181204. pIter->pSeg = pSeg;
  181205. /* This block sets stack variable iPg to the leaf page number that may
  181206. ** contain term (pTerm/nTerm), if it is present in the segment. */
  181207. pIdxSelect = fts5IdxSelectStmt(p);
  181208. if( p->rc ) return;
  181209. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  181210. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  181211. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  181212. i64 val = sqlite3_column_int(pIdxSelect, 0);
  181213. iPg = (int)(val>>1);
  181214. bDlidx = (val & 0x0001);
  181215. }
  181216. p->rc = sqlite3_reset(pIdxSelect);
  181217. if( iPg<pSeg->pgnoFirst ){
  181218. iPg = pSeg->pgnoFirst;
  181219. bDlidx = 0;
  181220. }
  181221. pIter->iLeafPgno = iPg - 1;
  181222. fts5SegIterNextPage(p, pIter);
  181223. if( pIter->pLeaf ){
  181224. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  181225. }
  181226. if( p->rc==SQLITE_OK && bGe==0 ){
  181227. pIter->flags |= FTS5_SEGITER_ONETERM;
  181228. if( pIter->pLeaf ){
  181229. if( flags & FTS5INDEX_QUERY_DESC ){
  181230. pIter->flags |= FTS5_SEGITER_REVERSE;
  181231. }
  181232. if( bDlidx ){
  181233. fts5SegIterLoadDlidx(p, pIter);
  181234. }
  181235. if( flags & FTS5INDEX_QUERY_DESC ){
  181236. fts5SegIterReverse(p, pIter);
  181237. }
  181238. }
  181239. }
  181240. fts5SegIterSetNext(p, pIter);
  181241. /* Either:
  181242. **
  181243. ** 1) an error has occurred, or
  181244. ** 2) the iterator points to EOF, or
  181245. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  181246. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  181247. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  181248. */
  181249. assert( p->rc!=SQLITE_OK /* 1 */
  181250. || pIter->pLeaf==0 /* 2 */
  181251. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  181252. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  181253. );
  181254. }
  181255. /*
  181256. ** Initialize the object pIter to point to term pTerm/nTerm within the
  181257. ** in-memory hash table. If there is no such term in the hash-table, the
  181258. ** iterator is set to EOF.
  181259. **
  181260. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  181261. ** an error has already occurred when this function is called, it is a no-op.
  181262. */
  181263. static void fts5SegIterHashInit(
  181264. Fts5Index *p, /* FTS5 backend */
  181265. const u8 *pTerm, int nTerm, /* Term to seek to */
  181266. int flags, /* Mask of FTS5INDEX_XXX flags */
  181267. Fts5SegIter *pIter /* Object to populate */
  181268. ){
  181269. const u8 *pList = 0;
  181270. int nList = 0;
  181271. const u8 *z = 0;
  181272. int n = 0;
  181273. assert( p->pHash );
  181274. assert( p->rc==SQLITE_OK );
  181275. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  181276. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  181277. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  181278. n = (z ? (int)strlen((const char*)z) : 0);
  181279. }else{
  181280. pIter->flags |= FTS5_SEGITER_ONETERM;
  181281. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  181282. z = pTerm;
  181283. n = nTerm;
  181284. }
  181285. if( pList ){
  181286. Fts5Data *pLeaf;
  181287. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  181288. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  181289. if( pLeaf==0 ) return;
  181290. pLeaf->p = (u8*)pList;
  181291. pLeaf->nn = pLeaf->szLeaf = nList;
  181292. pIter->pLeaf = pLeaf;
  181293. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  181294. pIter->iEndofDoclist = pLeaf->nn;
  181295. if( flags & FTS5INDEX_QUERY_DESC ){
  181296. pIter->flags |= FTS5_SEGITER_REVERSE;
  181297. fts5SegIterReverseInitPage(p, pIter);
  181298. }else{
  181299. fts5SegIterLoadNPos(p, pIter);
  181300. }
  181301. }
  181302. fts5SegIterSetNext(p, pIter);
  181303. }
  181304. /*
  181305. ** Zero the iterator passed as the only argument.
  181306. */
  181307. static void fts5SegIterClear(Fts5SegIter *pIter){
  181308. fts5BufferFree(&pIter->term);
  181309. fts5DataRelease(pIter->pLeaf);
  181310. fts5DataRelease(pIter->pNextLeaf);
  181311. fts5DlidxIterFree(pIter->pDlidx);
  181312. sqlite3_free(pIter->aRowidOffset);
  181313. memset(pIter, 0, sizeof(Fts5SegIter));
  181314. }
  181315. #ifdef SQLITE_DEBUG
  181316. /*
  181317. ** This function is used as part of the big assert() procedure implemented by
  181318. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  181319. ** in *pRes is the correct result of comparing the current positions of the
  181320. ** two iterators.
  181321. */
  181322. static void fts5AssertComparisonResult(
  181323. Fts5Iter *pIter,
  181324. Fts5SegIter *p1,
  181325. Fts5SegIter *p2,
  181326. Fts5CResult *pRes
  181327. ){
  181328. int i1 = p1 - pIter->aSeg;
  181329. int i2 = p2 - pIter->aSeg;
  181330. if( p1->pLeaf || p2->pLeaf ){
  181331. if( p1->pLeaf==0 ){
  181332. assert( pRes->iFirst==i2 );
  181333. }else if( p2->pLeaf==0 ){
  181334. assert( pRes->iFirst==i1 );
  181335. }else{
  181336. int nMin = MIN(p1->term.n, p2->term.n);
  181337. int res = memcmp(p1->term.p, p2->term.p, nMin);
  181338. if( res==0 ) res = p1->term.n - p2->term.n;
  181339. if( res==0 ){
  181340. assert( pRes->bTermEq==1 );
  181341. assert( p1->iRowid!=p2->iRowid );
  181342. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  181343. }else{
  181344. assert( pRes->bTermEq==0 );
  181345. }
  181346. if( res<0 ){
  181347. assert( pRes->iFirst==i1 );
  181348. }else{
  181349. assert( pRes->iFirst==i2 );
  181350. }
  181351. }
  181352. }
  181353. }
  181354. /*
  181355. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  181356. ** is compiled. In that case, this function is essentially an assert()
  181357. ** statement used to verify that the contents of the pIter->aFirst[] array
  181358. ** are correct.
  181359. */
  181360. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  181361. if( p->rc==SQLITE_OK ){
  181362. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  181363. int i;
  181364. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  181365. /* Check that pIter->iSwitchRowid is set correctly. */
  181366. for(i=0; i<pIter->nSeg; i++){
  181367. Fts5SegIter *p1 = &pIter->aSeg[i];
  181368. assert( p1==pFirst
  181369. || p1->pLeaf==0
  181370. || fts5BufferCompare(&pFirst->term, &p1->term)
  181371. || p1->iRowid==pIter->iSwitchRowid
  181372. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  181373. );
  181374. }
  181375. for(i=0; i<pIter->nSeg; i+=2){
  181376. Fts5SegIter *p1 = &pIter->aSeg[i];
  181377. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  181378. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  181379. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  181380. }
  181381. for(i=1; i<(pIter->nSeg / 2); i+=2){
  181382. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  181383. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  181384. Fts5CResult *pRes = &pIter->aFirst[i];
  181385. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  181386. }
  181387. }
  181388. }
  181389. #else
  181390. # define fts5AssertMultiIterSetup(x,y)
  181391. #endif
  181392. /*
  181393. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  181394. **
  181395. ** If the returned value is non-zero, then it is the index of an entry
  181396. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  181397. ** to a key that is a duplicate of another, higher priority,
  181398. ** segment-iterator in the pSeg->aSeg[] array.
  181399. */
  181400. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  181401. int i1; /* Index of left-hand Fts5SegIter */
  181402. int i2; /* Index of right-hand Fts5SegIter */
  181403. int iRes;
  181404. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  181405. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  181406. Fts5CResult *pRes = &pIter->aFirst[iOut];
  181407. assert( iOut<pIter->nSeg && iOut>0 );
  181408. assert( pIter->bRev==0 || pIter->bRev==1 );
  181409. if( iOut>=(pIter->nSeg/2) ){
  181410. i1 = (iOut - pIter->nSeg/2) * 2;
  181411. i2 = i1 + 1;
  181412. }else{
  181413. i1 = pIter->aFirst[iOut*2].iFirst;
  181414. i2 = pIter->aFirst[iOut*2+1].iFirst;
  181415. }
  181416. p1 = &pIter->aSeg[i1];
  181417. p2 = &pIter->aSeg[i2];
  181418. pRes->bTermEq = 0;
  181419. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  181420. iRes = i2;
  181421. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  181422. iRes = i1;
  181423. }else{
  181424. int res = fts5BufferCompare(&p1->term, &p2->term);
  181425. if( res==0 ){
  181426. assert( i2>i1 );
  181427. assert( i2!=0 );
  181428. pRes->bTermEq = 1;
  181429. if( p1->iRowid==p2->iRowid ){
  181430. p1->bDel = p2->bDel;
  181431. return i2;
  181432. }
  181433. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  181434. }
  181435. assert( res!=0 );
  181436. if( res<0 ){
  181437. iRes = i1;
  181438. }else{
  181439. iRes = i2;
  181440. }
  181441. }
  181442. pRes->iFirst = (u16)iRes;
  181443. return 0;
  181444. }
  181445. /*
  181446. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  181447. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  181448. */
  181449. static void fts5SegIterGotoPage(
  181450. Fts5Index *p, /* FTS5 backend object */
  181451. Fts5SegIter *pIter, /* Iterator to advance */
  181452. int iLeafPgno
  181453. ){
  181454. assert( iLeafPgno>pIter->iLeafPgno );
  181455. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  181456. p->rc = FTS5_CORRUPT;
  181457. }else{
  181458. fts5DataRelease(pIter->pNextLeaf);
  181459. pIter->pNextLeaf = 0;
  181460. pIter->iLeafPgno = iLeafPgno-1;
  181461. fts5SegIterNextPage(p, pIter);
  181462. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  181463. if( p->rc==SQLITE_OK ){
  181464. int iOff;
  181465. u8 *a = pIter->pLeaf->p;
  181466. int n = pIter->pLeaf->szLeaf;
  181467. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  181468. if( iOff<4 || iOff>=n ){
  181469. p->rc = FTS5_CORRUPT;
  181470. }else{
  181471. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  181472. pIter->iLeafOffset = iOff;
  181473. fts5SegIterLoadNPos(p, pIter);
  181474. }
  181475. }
  181476. }
  181477. }
  181478. /*
  181479. ** Advance the iterator passed as the second argument until it is at or
  181480. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  181481. ** always advanced at least once.
  181482. */
  181483. static void fts5SegIterNextFrom(
  181484. Fts5Index *p, /* FTS5 backend object */
  181485. Fts5SegIter *pIter, /* Iterator to advance */
  181486. i64 iMatch /* Advance iterator at least this far */
  181487. ){
  181488. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  181489. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  181490. int iLeafPgno = pIter->iLeafPgno;
  181491. int bMove = 1;
  181492. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  181493. assert( pIter->pDlidx );
  181494. assert( pIter->pLeaf );
  181495. if( bRev==0 ){
  181496. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  181497. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  181498. fts5DlidxIterNext(p, pDlidx);
  181499. }
  181500. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  181501. if( iLeafPgno>pIter->iLeafPgno ){
  181502. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  181503. bMove = 0;
  181504. }
  181505. }else{
  181506. assert( pIter->pNextLeaf==0 );
  181507. assert( iMatch<pIter->iRowid );
  181508. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  181509. fts5DlidxIterPrev(p, pDlidx);
  181510. }
  181511. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  181512. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  181513. if( iLeafPgno<pIter->iLeafPgno ){
  181514. pIter->iLeafPgno = iLeafPgno+1;
  181515. fts5SegIterReverseNewPage(p, pIter);
  181516. bMove = 0;
  181517. }
  181518. }
  181519. do{
  181520. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  181521. if( pIter->pLeaf==0 ) break;
  181522. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  181523. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  181524. bMove = 1;
  181525. }while( p->rc==SQLITE_OK );
  181526. }
  181527. /*
  181528. ** Free the iterator object passed as the second argument.
  181529. */
  181530. static void fts5MultiIterFree(Fts5Iter *pIter){
  181531. if( pIter ){
  181532. int i;
  181533. for(i=0; i<pIter->nSeg; i++){
  181534. fts5SegIterClear(&pIter->aSeg[i]);
  181535. }
  181536. fts5StructureRelease(pIter->pStruct);
  181537. fts5BufferFree(&pIter->poslist);
  181538. sqlite3_free(pIter);
  181539. }
  181540. }
  181541. static void fts5MultiIterAdvanced(
  181542. Fts5Index *p, /* FTS5 backend to iterate within */
  181543. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  181544. int iChanged, /* Index of sub-iterator just advanced */
  181545. int iMinset /* Minimum entry in aFirst[] to set */
  181546. ){
  181547. int i;
  181548. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  181549. int iEq;
  181550. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  181551. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  181552. assert( p->rc==SQLITE_OK );
  181553. pSeg->xNext(p, pSeg, 0);
  181554. i = pIter->nSeg + iEq;
  181555. }
  181556. }
  181557. }
  181558. /*
  181559. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  181560. ** points to the same term though - just a different rowid. This function
  181561. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  181562. ** If it does so successfully, 0 is returned. Otherwise 1.
  181563. **
  181564. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  181565. ** on the iterator instead. That function does the same as this one, except
  181566. ** that it deals with more complicated cases as well.
  181567. */
  181568. static int fts5MultiIterAdvanceRowid(
  181569. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  181570. int iChanged, /* Index of sub-iterator just advanced */
  181571. Fts5SegIter **ppFirst
  181572. ){
  181573. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  181574. if( pNew->iRowid==pIter->iSwitchRowid
  181575. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  181576. ){
  181577. int i;
  181578. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  181579. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  181580. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  181581. Fts5CResult *pRes = &pIter->aFirst[i];
  181582. assert( pNew->pLeaf );
  181583. assert( pRes->bTermEq==0 || pOther->pLeaf );
  181584. if( pRes->bTermEq ){
  181585. if( pNew->iRowid==pOther->iRowid ){
  181586. return 1;
  181587. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  181588. pIter->iSwitchRowid = pOther->iRowid;
  181589. pNew = pOther;
  181590. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  181591. pIter->iSwitchRowid = pOther->iRowid;
  181592. }
  181593. }
  181594. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  181595. if( i==1 ) break;
  181596. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  181597. }
  181598. }
  181599. *ppFirst = pNew;
  181600. return 0;
  181601. }
  181602. /*
  181603. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  181604. */
  181605. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  181606. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  181607. pIter->base.bEof = pSeg->pLeaf==0;
  181608. pIter->iSwitchRowid = pSeg->iRowid;
  181609. }
  181610. /*
  181611. ** Move the iterator to the next entry.
  181612. **
  181613. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  181614. ** considered an error if the iterator reaches EOF, or if it is already at
  181615. ** EOF when this function is called.
  181616. */
  181617. static void fts5MultiIterNext(
  181618. Fts5Index *p,
  181619. Fts5Iter *pIter,
  181620. int bFrom, /* True if argument iFrom is valid */
  181621. i64 iFrom /* Advance at least as far as this */
  181622. ){
  181623. int bUseFrom = bFrom;
  181624. assert( pIter->base.bEof==0 );
  181625. while( p->rc==SQLITE_OK ){
  181626. int iFirst = pIter->aFirst[1].iFirst;
  181627. int bNewTerm = 0;
  181628. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  181629. assert( p->rc==SQLITE_OK );
  181630. if( bUseFrom && pSeg->pDlidx ){
  181631. fts5SegIterNextFrom(p, pSeg, iFrom);
  181632. }else{
  181633. pSeg->xNext(p, pSeg, &bNewTerm);
  181634. }
  181635. if( pSeg->pLeaf==0 || bNewTerm
  181636. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  181637. ){
  181638. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  181639. fts5MultiIterSetEof(pIter);
  181640. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  181641. if( pSeg->pLeaf==0 ) return;
  181642. }
  181643. fts5AssertMultiIterSetup(p, pIter);
  181644. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  181645. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  181646. pIter->xSetOutputs(pIter, pSeg);
  181647. return;
  181648. }
  181649. bUseFrom = 0;
  181650. }
  181651. }
  181652. static void fts5MultiIterNext2(
  181653. Fts5Index *p,
  181654. Fts5Iter *pIter,
  181655. int *pbNewTerm /* OUT: True if *might* be new term */
  181656. ){
  181657. assert( pIter->bSkipEmpty );
  181658. if( p->rc==SQLITE_OK ){
  181659. *pbNewTerm = 0;
  181660. do{
  181661. int iFirst = pIter->aFirst[1].iFirst;
  181662. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  181663. int bNewTerm = 0;
  181664. assert( p->rc==SQLITE_OK );
  181665. pSeg->xNext(p, pSeg, &bNewTerm);
  181666. if( pSeg->pLeaf==0 || bNewTerm
  181667. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  181668. ){
  181669. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  181670. fts5MultiIterSetEof(pIter);
  181671. *pbNewTerm = 1;
  181672. }
  181673. fts5AssertMultiIterSetup(p, pIter);
  181674. }while( fts5MultiIterIsEmpty(p, pIter) );
  181675. }
  181676. }
  181677. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  181678. UNUSED_PARAM2(pUnused1, pUnused2);
  181679. }
  181680. static Fts5Iter *fts5MultiIterAlloc(
  181681. Fts5Index *p, /* FTS5 backend to iterate within */
  181682. int nSeg
  181683. ){
  181684. Fts5Iter *pNew;
  181685. int nSlot; /* Power of two >= nSeg */
  181686. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  181687. pNew = fts5IdxMalloc(p,
  181688. sizeof(Fts5Iter) + /* pNew */
  181689. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  181690. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  181691. );
  181692. if( pNew ){
  181693. pNew->nSeg = nSlot;
  181694. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  181695. pNew->pIndex = p;
  181696. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  181697. }
  181698. return pNew;
  181699. }
  181700. static void fts5PoslistCallback(
  181701. Fts5Index *pUnused,
  181702. void *pContext,
  181703. const u8 *pChunk, int nChunk
  181704. ){
  181705. UNUSED_PARAM(pUnused);
  181706. assert_nc( nChunk>=0 );
  181707. if( nChunk>0 ){
  181708. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  181709. }
  181710. }
  181711. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  181712. struct PoslistCallbackCtx {
  181713. Fts5Buffer *pBuf; /* Append to this buffer */
  181714. Fts5Colset *pColset; /* Restrict matches to this column */
  181715. int eState; /* See above */
  181716. };
  181717. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  181718. struct PoslistOffsetsCtx {
  181719. Fts5Buffer *pBuf; /* Append to this buffer */
  181720. Fts5Colset *pColset; /* Restrict matches to this column */
  181721. int iRead;
  181722. int iWrite;
  181723. };
  181724. /*
  181725. ** TODO: Make this more efficient!
  181726. */
  181727. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  181728. int i;
  181729. for(i=0; i<pColset->nCol; i++){
  181730. if( pColset->aiCol[i]==iCol ) return 1;
  181731. }
  181732. return 0;
  181733. }
  181734. static void fts5PoslistOffsetsCallback(
  181735. Fts5Index *pUnused,
  181736. void *pContext,
  181737. const u8 *pChunk, int nChunk
  181738. ){
  181739. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  181740. UNUSED_PARAM(pUnused);
  181741. assert_nc( nChunk>=0 );
  181742. if( nChunk>0 ){
  181743. int i = 0;
  181744. while( i<nChunk ){
  181745. int iVal;
  181746. i += fts5GetVarint32(&pChunk[i], iVal);
  181747. iVal += pCtx->iRead - 2;
  181748. pCtx->iRead = iVal;
  181749. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  181750. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  181751. pCtx->iWrite = iVal;
  181752. }
  181753. }
  181754. }
  181755. }
  181756. static void fts5PoslistFilterCallback(
  181757. Fts5Index *pUnused,
  181758. void *pContext,
  181759. const u8 *pChunk, int nChunk
  181760. ){
  181761. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  181762. UNUSED_PARAM(pUnused);
  181763. assert_nc( nChunk>=0 );
  181764. if( nChunk>0 ){
  181765. /* Search through to find the first varint with value 1. This is the
  181766. ** start of the next columns hits. */
  181767. int i = 0;
  181768. int iStart = 0;
  181769. if( pCtx->eState==2 ){
  181770. int iCol;
  181771. fts5FastGetVarint32(pChunk, i, iCol);
  181772. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  181773. pCtx->eState = 1;
  181774. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  181775. }else{
  181776. pCtx->eState = 0;
  181777. }
  181778. }
  181779. do {
  181780. while( i<nChunk && pChunk[i]!=0x01 ){
  181781. while( pChunk[i] & 0x80 ) i++;
  181782. i++;
  181783. }
  181784. if( pCtx->eState ){
  181785. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  181786. }
  181787. if( i<nChunk ){
  181788. int iCol;
  181789. iStart = i;
  181790. i++;
  181791. if( i>=nChunk ){
  181792. pCtx->eState = 2;
  181793. }else{
  181794. fts5FastGetVarint32(pChunk, i, iCol);
  181795. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  181796. if( pCtx->eState ){
  181797. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  181798. iStart = i;
  181799. }
  181800. }
  181801. }
  181802. }while( i<nChunk );
  181803. }
  181804. }
  181805. static void fts5ChunkIterate(
  181806. Fts5Index *p, /* Index object */
  181807. Fts5SegIter *pSeg, /* Poslist of this iterator */
  181808. void *pCtx, /* Context pointer for xChunk callback */
  181809. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  181810. ){
  181811. int nRem = pSeg->nPos; /* Number of bytes still to come */
  181812. Fts5Data *pData = 0;
  181813. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  181814. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  181815. int pgno = pSeg->iLeafPgno;
  181816. int pgnoSave = 0;
  181817. /* This function does notmwork with detail=none databases. */
  181818. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  181819. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  181820. pgnoSave = pgno+1;
  181821. }
  181822. while( 1 ){
  181823. xChunk(p, pCtx, pChunk, nChunk);
  181824. nRem -= nChunk;
  181825. fts5DataRelease(pData);
  181826. if( nRem<=0 ){
  181827. break;
  181828. }else{
  181829. pgno++;
  181830. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  181831. if( pData==0 ) break;
  181832. pChunk = &pData->p[4];
  181833. nChunk = MIN(nRem, pData->szLeaf - 4);
  181834. if( pgno==pgnoSave ){
  181835. assert( pSeg->pNextLeaf==0 );
  181836. pSeg->pNextLeaf = pData;
  181837. pData = 0;
  181838. }
  181839. }
  181840. }
  181841. }
  181842. /*
  181843. ** Iterator pIter currently points to a valid entry (not EOF). This
  181844. ** function appends the position list data for the current entry to
  181845. ** buffer pBuf. It does not make a copy of the position-list size
  181846. ** field.
  181847. */
  181848. static void fts5SegiterPoslist(
  181849. Fts5Index *p,
  181850. Fts5SegIter *pSeg,
  181851. Fts5Colset *pColset,
  181852. Fts5Buffer *pBuf
  181853. ){
  181854. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  181855. if( pColset==0 ){
  181856. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  181857. }else{
  181858. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  181859. PoslistCallbackCtx sCtx;
  181860. sCtx.pBuf = pBuf;
  181861. sCtx.pColset = pColset;
  181862. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  181863. assert( sCtx.eState==0 || sCtx.eState==1 );
  181864. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  181865. }else{
  181866. PoslistOffsetsCtx sCtx;
  181867. memset(&sCtx, 0, sizeof(sCtx));
  181868. sCtx.pBuf = pBuf;
  181869. sCtx.pColset = pColset;
  181870. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  181871. }
  181872. }
  181873. }
  181874. }
  181875. /*
  181876. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  181877. ** the position list contains entries for column iCol, then (*pa) is set
  181878. ** to point to the sub-position-list for that column and the number of
  181879. ** bytes in it returned. Or, if the argument position list does not
  181880. ** contain any entries for column iCol, return 0.
  181881. */
  181882. static int fts5IndexExtractCol(
  181883. const u8 **pa, /* IN/OUT: Pointer to poslist */
  181884. int n, /* IN: Size of poslist in bytes */
  181885. int iCol /* Column to extract from poslist */
  181886. ){
  181887. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  181888. const u8 *p = *pa;
  181889. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  181890. while( iCol>iCurrent ){
  181891. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  181892. ** not part of a varint. Note that it is not possible for a negative
  181893. ** or extremely large varint to occur within an uncorrupted position
  181894. ** list. So the last byte of each varint may be assumed to have a clear
  181895. ** 0x80 bit. */
  181896. while( *p!=0x01 ){
  181897. while( *p++ & 0x80 );
  181898. if( p>=pEnd ) return 0;
  181899. }
  181900. *pa = p++;
  181901. iCurrent = *p++;
  181902. if( iCurrent & 0x80 ){
  181903. p--;
  181904. p += fts5GetVarint32(p, iCurrent);
  181905. }
  181906. }
  181907. if( iCol!=iCurrent ) return 0;
  181908. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  181909. ** not part of a varint */
  181910. while( p<pEnd && *p!=0x01 ){
  181911. while( *p++ & 0x80 );
  181912. }
  181913. return p - (*pa);
  181914. }
  181915. static void fts5IndexExtractColset(
  181916. int *pRc,
  181917. Fts5Colset *pColset, /* Colset to filter on */
  181918. const u8 *pPos, int nPos, /* Position list */
  181919. Fts5Buffer *pBuf /* Output buffer */
  181920. ){
  181921. if( *pRc==SQLITE_OK ){
  181922. int i;
  181923. fts5BufferZero(pBuf);
  181924. for(i=0; i<pColset->nCol; i++){
  181925. const u8 *pSub = pPos;
  181926. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  181927. if( nSub ){
  181928. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  181929. }
  181930. }
  181931. }
  181932. }
  181933. /*
  181934. ** xSetOutputs callback used by detail=none tables.
  181935. */
  181936. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  181937. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  181938. pIter->base.iRowid = pSeg->iRowid;
  181939. pIter->base.nData = pSeg->nPos;
  181940. }
  181941. /*
  181942. ** xSetOutputs callback used by detail=full and detail=col tables when no
  181943. ** column filters are specified.
  181944. */
  181945. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  181946. pIter->base.iRowid = pSeg->iRowid;
  181947. pIter->base.nData = pSeg->nPos;
  181948. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  181949. assert( pIter->pColset==0 );
  181950. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  181951. /* All data is stored on the current page. Populate the output
  181952. ** variables to point into the body of the page object. */
  181953. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  181954. }else{
  181955. /* The data is distributed over two or more pages. Copy it into the
  181956. ** Fts5Iter.poslist buffer and then set the output pointer to point
  181957. ** to this buffer. */
  181958. fts5BufferZero(&pIter->poslist);
  181959. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  181960. pIter->base.pData = pIter->poslist.p;
  181961. }
  181962. }
  181963. /*
  181964. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  181965. ** against no columns at all).
  181966. */
  181967. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  181968. UNUSED_PARAM(pSeg);
  181969. pIter->base.nData = 0;
  181970. }
  181971. /*
  181972. ** xSetOutputs callback used by detail=col when there is a column filter
  181973. ** and there are 100 or more columns. Also called as a fallback from
  181974. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  181975. */
  181976. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  181977. fts5BufferZero(&pIter->poslist);
  181978. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  181979. pIter->base.iRowid = pSeg->iRowid;
  181980. pIter->base.pData = pIter->poslist.p;
  181981. pIter->base.nData = pIter->poslist.n;
  181982. }
  181983. /*
  181984. ** xSetOutputs callback used when:
  181985. **
  181986. ** * detail=col,
  181987. ** * there is a column filter, and
  181988. ** * the table contains 100 or fewer columns.
  181989. **
  181990. ** The last point is to ensure all column numbers are stored as
  181991. ** single-byte varints.
  181992. */
  181993. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  181994. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  181995. assert( pIter->pColset );
  181996. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  181997. fts5IterSetOutputs_Col(pIter, pSeg);
  181998. }else{
  181999. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  182000. u8 *pEnd = (u8*)&a[pSeg->nPos];
  182001. int iPrev = 0;
  182002. int *aiCol = pIter->pColset->aiCol;
  182003. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  182004. u8 *aOut = pIter->poslist.p;
  182005. int iPrevOut = 0;
  182006. pIter->base.iRowid = pSeg->iRowid;
  182007. while( a<pEnd ){
  182008. iPrev += (int)a++[0] - 2;
  182009. while( *aiCol<iPrev ){
  182010. aiCol++;
  182011. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  182012. }
  182013. if( *aiCol==iPrev ){
  182014. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  182015. iPrevOut = iPrev;
  182016. }
  182017. }
  182018. setoutputs_col_out:
  182019. pIter->base.pData = pIter->poslist.p;
  182020. pIter->base.nData = aOut - pIter->poslist.p;
  182021. }
  182022. }
  182023. /*
  182024. ** xSetOutputs callback used by detail=full when there is a column filter.
  182025. */
  182026. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  182027. Fts5Colset *pColset = pIter->pColset;
  182028. pIter->base.iRowid = pSeg->iRowid;
  182029. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  182030. assert( pColset );
  182031. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  182032. /* All data is stored on the current page. Populate the output
  182033. ** variables to point into the body of the page object. */
  182034. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  182035. if( pColset->nCol==1 ){
  182036. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  182037. pIter->base.pData = a;
  182038. }else{
  182039. int *pRc = &pIter->pIndex->rc;
  182040. fts5BufferZero(&pIter->poslist);
  182041. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  182042. pIter->base.pData = pIter->poslist.p;
  182043. pIter->base.nData = pIter->poslist.n;
  182044. }
  182045. }else{
  182046. /* The data is distributed over two or more pages. Copy it into the
  182047. ** Fts5Iter.poslist buffer and then set the output pointer to point
  182048. ** to this buffer. */
  182049. fts5BufferZero(&pIter->poslist);
  182050. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  182051. pIter->base.pData = pIter->poslist.p;
  182052. pIter->base.nData = pIter->poslist.n;
  182053. }
  182054. }
  182055. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  182056. if( *pRc==SQLITE_OK ){
  182057. Fts5Config *pConfig = pIter->pIndex->pConfig;
  182058. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  182059. pIter->xSetOutputs = fts5IterSetOutputs_None;
  182060. }
  182061. else if( pIter->pColset==0 ){
  182062. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  182063. }
  182064. else if( pIter->pColset->nCol==0 ){
  182065. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  182066. }
  182067. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  182068. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  182069. }
  182070. else{
  182071. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  182072. if( pConfig->nCol<=100 ){
  182073. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  182074. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  182075. }else{
  182076. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  182077. }
  182078. }
  182079. }
  182080. }
  182081. /*
  182082. ** Allocate a new Fts5Iter object.
  182083. **
  182084. ** The new object will be used to iterate through data in structure pStruct.
  182085. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  182086. ** is zero or greater, data from the first nSegment segments on level iLevel
  182087. ** is merged.
  182088. **
  182089. ** The iterator initially points to the first term/rowid entry in the
  182090. ** iterated data.
  182091. */
  182092. static void fts5MultiIterNew(
  182093. Fts5Index *p, /* FTS5 backend to iterate within */
  182094. Fts5Structure *pStruct, /* Structure of specific index */
  182095. int flags, /* FTS5INDEX_QUERY_XXX flags */
  182096. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  182097. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  182098. int iLevel, /* Level to iterate (-1 for all) */
  182099. int nSegment, /* Number of segments to merge (iLevel>=0) */
  182100. Fts5Iter **ppOut /* New object */
  182101. ){
  182102. int nSeg = 0; /* Number of segment-iters in use */
  182103. int iIter = 0; /* */
  182104. int iSeg; /* Used to iterate through segments */
  182105. Fts5StructureLevel *pLvl;
  182106. Fts5Iter *pNew;
  182107. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  182108. /* Allocate space for the new multi-seg-iterator. */
  182109. if( p->rc==SQLITE_OK ){
  182110. if( iLevel<0 ){
  182111. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  182112. nSeg = pStruct->nSegment;
  182113. nSeg += (p->pHash ? 1 : 0);
  182114. }else{
  182115. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  182116. }
  182117. }
  182118. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  182119. if( pNew==0 ) return;
  182120. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  182121. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  182122. pNew->pStruct = pStruct;
  182123. pNew->pColset = pColset;
  182124. fts5StructureRef(pStruct);
  182125. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  182126. fts5IterSetOutputCb(&p->rc, pNew);
  182127. }
  182128. /* Initialize each of the component segment iterators. */
  182129. if( p->rc==SQLITE_OK ){
  182130. if( iLevel<0 ){
  182131. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  182132. if( p->pHash ){
  182133. /* Add a segment iterator for the current contents of the hash table. */
  182134. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  182135. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  182136. }
  182137. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  182138. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  182139. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  182140. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  182141. if( pTerm==0 ){
  182142. fts5SegIterInit(p, pSeg, pIter);
  182143. }else{
  182144. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  182145. }
  182146. }
  182147. }
  182148. }else{
  182149. pLvl = &pStruct->aLevel[iLevel];
  182150. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  182151. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  182152. }
  182153. }
  182154. assert( iIter==nSeg );
  182155. }
  182156. /* If the above was successful, each component iterators now points
  182157. ** to the first entry in its segment. In this case initialize the
  182158. ** aFirst[] array. Or, if an error has occurred, free the iterator
  182159. ** object and set the output variable to NULL. */
  182160. if( p->rc==SQLITE_OK ){
  182161. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  182162. int iEq;
  182163. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  182164. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  182165. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  182166. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  182167. }
  182168. }
  182169. fts5MultiIterSetEof(pNew);
  182170. fts5AssertMultiIterSetup(p, pNew);
  182171. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  182172. fts5MultiIterNext(p, pNew, 0, 0);
  182173. }else if( pNew->base.bEof==0 ){
  182174. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  182175. pNew->xSetOutputs(pNew, pSeg);
  182176. }
  182177. }else{
  182178. fts5MultiIterFree(pNew);
  182179. *ppOut = 0;
  182180. }
  182181. }
  182182. /*
  182183. ** Create an Fts5Iter that iterates through the doclist provided
  182184. ** as the second argument.
  182185. */
  182186. static void fts5MultiIterNew2(
  182187. Fts5Index *p, /* FTS5 backend to iterate within */
  182188. Fts5Data *pData, /* Doclist to iterate through */
  182189. int bDesc, /* True for descending rowid order */
  182190. Fts5Iter **ppOut /* New object */
  182191. ){
  182192. Fts5Iter *pNew;
  182193. pNew = fts5MultiIterAlloc(p, 2);
  182194. if( pNew ){
  182195. Fts5SegIter *pIter = &pNew->aSeg[1];
  182196. pIter->flags = FTS5_SEGITER_ONETERM;
  182197. if( pData->szLeaf>0 ){
  182198. pIter->pLeaf = pData;
  182199. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  182200. pIter->iEndofDoclist = pData->nn;
  182201. pNew->aFirst[1].iFirst = 1;
  182202. if( bDesc ){
  182203. pNew->bRev = 1;
  182204. pIter->flags |= FTS5_SEGITER_REVERSE;
  182205. fts5SegIterReverseInitPage(p, pIter);
  182206. }else{
  182207. fts5SegIterLoadNPos(p, pIter);
  182208. }
  182209. pData = 0;
  182210. }else{
  182211. pNew->base.bEof = 1;
  182212. }
  182213. fts5SegIterSetNext(p, pIter);
  182214. *ppOut = pNew;
  182215. }
  182216. fts5DataRelease(pData);
  182217. }
  182218. /*
  182219. ** Return true if the iterator is at EOF or if an error has occurred.
  182220. ** False otherwise.
  182221. */
  182222. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  182223. assert( p->rc
  182224. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  182225. );
  182226. return (p->rc || pIter->base.bEof);
  182227. }
  182228. /*
  182229. ** Return the rowid of the entry that the iterator currently points
  182230. ** to. If the iterator points to EOF when this function is called the
  182231. ** results are undefined.
  182232. */
  182233. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  182234. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  182235. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  182236. }
  182237. /*
  182238. ** Move the iterator to the next entry at or following iMatch.
  182239. */
  182240. static void fts5MultiIterNextFrom(
  182241. Fts5Index *p,
  182242. Fts5Iter *pIter,
  182243. i64 iMatch
  182244. ){
  182245. while( 1 ){
  182246. i64 iRowid;
  182247. fts5MultiIterNext(p, pIter, 1, iMatch);
  182248. if( fts5MultiIterEof(p, pIter) ) break;
  182249. iRowid = fts5MultiIterRowid(pIter);
  182250. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  182251. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  182252. }
  182253. }
  182254. /*
  182255. ** Return a pointer to a buffer containing the term associated with the
  182256. ** entry that the iterator currently points to.
  182257. */
  182258. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  182259. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  182260. *pn = p->term.n;
  182261. return p->term.p;
  182262. }
  182263. /*
  182264. ** Allocate a new segment-id for the structure pStruct. The new segment
  182265. ** id must be between 1 and 65335 inclusive, and must not be used by
  182266. ** any currently existing segment. If a free segment id cannot be found,
  182267. ** SQLITE_FULL is returned.
  182268. **
  182269. ** If an error has already occurred, this function is a no-op. 0 is
  182270. ** returned in this case.
  182271. */
  182272. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  182273. int iSegid = 0;
  182274. if( p->rc==SQLITE_OK ){
  182275. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  182276. p->rc = SQLITE_FULL;
  182277. }else{
  182278. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  182279. ** array is 63 elements, or 252 bytes, in size. */
  182280. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  182281. int iLvl, iSeg;
  182282. int i;
  182283. u32 mask;
  182284. memset(aUsed, 0, sizeof(aUsed));
  182285. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  182286. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  182287. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  182288. if( iId<=FTS5_MAX_SEGMENT ){
  182289. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  182290. }
  182291. }
  182292. }
  182293. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  182294. mask = aUsed[i];
  182295. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  182296. iSegid += 1 + i*32;
  182297. #ifdef SQLITE_DEBUG
  182298. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  182299. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  182300. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  182301. }
  182302. }
  182303. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  182304. {
  182305. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  182306. if( p->rc==SQLITE_OK ){
  182307. u8 aBlob[2] = {0xff, 0xff};
  182308. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  182309. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  182310. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  182311. p->rc = sqlite3_reset(pIdxSelect);
  182312. }
  182313. }
  182314. #endif
  182315. }
  182316. }
  182317. return iSegid;
  182318. }
  182319. /*
  182320. ** Discard all data currently cached in the hash-tables.
  182321. */
  182322. static void fts5IndexDiscardData(Fts5Index *p){
  182323. assert( p->pHash || p->nPendingData==0 );
  182324. if( p->pHash ){
  182325. sqlite3Fts5HashClear(p->pHash);
  182326. p->nPendingData = 0;
  182327. }
  182328. }
  182329. /*
  182330. ** Return the size of the prefix, in bytes, that buffer
  182331. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  182332. **
  182333. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  182334. ** than buffer (pOld/nOld).
  182335. */
  182336. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  182337. int i;
  182338. for(i=0; i<nOld; i++){
  182339. if( pOld[i]!=pNew[i] ) break;
  182340. }
  182341. return i;
  182342. }
  182343. static void fts5WriteDlidxClear(
  182344. Fts5Index *p,
  182345. Fts5SegWriter *pWriter,
  182346. int bFlush /* If true, write dlidx to disk */
  182347. ){
  182348. int i;
  182349. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  182350. for(i=0; i<pWriter->nDlidx; i++){
  182351. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  182352. if( pDlidx->buf.n==0 ) break;
  182353. if( bFlush ){
  182354. assert( pDlidx->pgno!=0 );
  182355. fts5DataWrite(p,
  182356. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  182357. pDlidx->buf.p, pDlidx->buf.n
  182358. );
  182359. }
  182360. sqlite3Fts5BufferZero(&pDlidx->buf);
  182361. pDlidx->bPrevValid = 0;
  182362. }
  182363. }
  182364. /*
  182365. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  182366. ** Any new array elements are zeroed before returning.
  182367. */
  182368. static int fts5WriteDlidxGrow(
  182369. Fts5Index *p,
  182370. Fts5SegWriter *pWriter,
  182371. int nLvl
  182372. ){
  182373. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  182374. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  182375. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  182376. );
  182377. if( aDlidx==0 ){
  182378. p->rc = SQLITE_NOMEM;
  182379. }else{
  182380. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  182381. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  182382. pWriter->aDlidx = aDlidx;
  182383. pWriter->nDlidx = nLvl;
  182384. }
  182385. }
  182386. return p->rc;
  182387. }
  182388. /*
  182389. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  182390. ** enough, flush it to disk and return 1. Otherwise discard it and return
  182391. ** zero.
  182392. */
  182393. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  182394. int bFlag = 0;
  182395. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  182396. ** to the database, also write the doclist-index to disk. */
  182397. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  182398. bFlag = 1;
  182399. }
  182400. fts5WriteDlidxClear(p, pWriter, bFlag);
  182401. pWriter->nEmpty = 0;
  182402. return bFlag;
  182403. }
  182404. /*
  182405. ** This function is called whenever processing of the doclist for the
  182406. ** last term on leaf page (pWriter->iBtPage) is completed.
  182407. **
  182408. ** The doclist-index for that term is currently stored in-memory within the
  182409. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  182410. ** writes it out to disk. Or, if it is too small to bother with, discards
  182411. ** it.
  182412. **
  182413. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  182414. */
  182415. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  182416. int bFlag;
  182417. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  182418. if( pWriter->iBtPage==0 ) return;
  182419. bFlag = fts5WriteFlushDlidx(p, pWriter);
  182420. if( p->rc==SQLITE_OK ){
  182421. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  182422. /* The following was already done in fts5WriteInit(): */
  182423. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  182424. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  182425. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  182426. sqlite3_step(p->pIdxWriter);
  182427. p->rc = sqlite3_reset(p->pIdxWriter);
  182428. }
  182429. pWriter->iBtPage = 0;
  182430. }
  182431. /*
  182432. ** This is called once for each leaf page except the first that contains
  182433. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  182434. ** is larger than all terms written to earlier leaves, and equal to or
  182435. ** smaller than the first term on the new leaf.
  182436. **
  182437. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  182438. ** has already occurred when this function is called, it is a no-op.
  182439. */
  182440. static void fts5WriteBtreeTerm(
  182441. Fts5Index *p, /* FTS5 backend object */
  182442. Fts5SegWriter *pWriter, /* Writer object */
  182443. int nTerm, const u8 *pTerm /* First term on new page */
  182444. ){
  182445. fts5WriteFlushBtree(p, pWriter);
  182446. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  182447. pWriter->iBtPage = pWriter->writer.pgno;
  182448. }
  182449. /*
  182450. ** This function is called when flushing a leaf page that contains no
  182451. ** terms at all to disk.
  182452. */
  182453. static void fts5WriteBtreeNoTerm(
  182454. Fts5Index *p, /* FTS5 backend object */
  182455. Fts5SegWriter *pWriter /* Writer object */
  182456. ){
  182457. /* If there were no rowids on the leaf page either and the doclist-index
  182458. ** has already been started, append an 0x00 byte to it. */
  182459. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  182460. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  182461. assert( pDlidx->bPrevValid );
  182462. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  182463. }
  182464. /* Increment the "number of sequential leaves without a term" counter. */
  182465. pWriter->nEmpty++;
  182466. }
  182467. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  182468. i64 iRowid;
  182469. int iOff;
  182470. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  182471. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  182472. return iRowid;
  182473. }
  182474. /*
  182475. ** Rowid iRowid has just been appended to the current leaf page. It is the
  182476. ** first on the page. This function appends an appropriate entry to the current
  182477. ** doclist-index.
  182478. */
  182479. static void fts5WriteDlidxAppend(
  182480. Fts5Index *p,
  182481. Fts5SegWriter *pWriter,
  182482. i64 iRowid
  182483. ){
  182484. int i;
  182485. int bDone = 0;
  182486. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  182487. i64 iVal;
  182488. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  182489. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  182490. /* The current doclist-index page is full. Write it to disk and push
  182491. ** a copy of iRowid (which will become the first rowid on the next
  182492. ** doclist-index leaf page) up into the next level of the b-tree
  182493. ** hierarchy. If the node being flushed is currently the root node,
  182494. ** also push its first rowid upwards. */
  182495. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  182496. fts5DataWrite(p,
  182497. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  182498. pDlidx->buf.p, pDlidx->buf.n
  182499. );
  182500. fts5WriteDlidxGrow(p, pWriter, i+2);
  182501. pDlidx = &pWriter->aDlidx[i];
  182502. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  182503. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  182504. /* This was the root node. Push its first rowid up to the new root. */
  182505. pDlidx[1].pgno = pDlidx->pgno;
  182506. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  182507. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  182508. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  182509. pDlidx[1].bPrevValid = 1;
  182510. pDlidx[1].iPrev = iFirst;
  182511. }
  182512. sqlite3Fts5BufferZero(&pDlidx->buf);
  182513. pDlidx->bPrevValid = 0;
  182514. pDlidx->pgno++;
  182515. }else{
  182516. bDone = 1;
  182517. }
  182518. if( pDlidx->bPrevValid ){
  182519. iVal = iRowid - pDlidx->iPrev;
  182520. }else{
  182521. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  182522. assert( pDlidx->buf.n==0 );
  182523. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  182524. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  182525. iVal = iRowid;
  182526. }
  182527. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  182528. pDlidx->bPrevValid = 1;
  182529. pDlidx->iPrev = iRowid;
  182530. }
  182531. }
  182532. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  182533. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  182534. Fts5PageWriter *pPage = &pWriter->writer;
  182535. i64 iRowid;
  182536. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  182537. /* Set the szLeaf header field. */
  182538. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  182539. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  182540. if( pWriter->bFirstTermInPage ){
  182541. /* No term was written to this page. */
  182542. assert( pPage->pgidx.n==0 );
  182543. fts5WriteBtreeNoTerm(p, pWriter);
  182544. }else{
  182545. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  182546. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  182547. }
  182548. /* Write the page out to disk */
  182549. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  182550. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  182551. /* Initialize the next page. */
  182552. fts5BufferZero(&pPage->buf);
  182553. fts5BufferZero(&pPage->pgidx);
  182554. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  182555. pPage->iPrevPgidx = 0;
  182556. pPage->pgno++;
  182557. /* Increase the leaves written counter */
  182558. pWriter->nLeafWritten++;
  182559. /* The new leaf holds no terms or rowids */
  182560. pWriter->bFirstTermInPage = 1;
  182561. pWriter->bFirstRowidInPage = 1;
  182562. }
  182563. /*
  182564. ** Append term pTerm/nTerm to the segment being written by the writer passed
  182565. ** as the second argument.
  182566. **
  182567. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  182568. ** already occurred, this function is a no-op.
  182569. */
  182570. static void fts5WriteAppendTerm(
  182571. Fts5Index *p,
  182572. Fts5SegWriter *pWriter,
  182573. int nTerm, const u8 *pTerm
  182574. ){
  182575. int nPrefix; /* Bytes of prefix compression for term */
  182576. Fts5PageWriter *pPage = &pWriter->writer;
  182577. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  182578. assert( p->rc==SQLITE_OK );
  182579. assert( pPage->buf.n>=4 );
  182580. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  182581. /* If the current leaf page is full, flush it to disk. */
  182582. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  182583. if( pPage->buf.n>4 ){
  182584. fts5WriteFlushLeaf(p, pWriter);
  182585. }
  182586. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  182587. }
  182588. /* TODO1: Updating pgidx here. */
  182589. pPgidx->n += sqlite3Fts5PutVarint(
  182590. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  182591. );
  182592. pPage->iPrevPgidx = pPage->buf.n;
  182593. #if 0
  182594. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  182595. pPgidx->n += 2;
  182596. #endif
  182597. if( pWriter->bFirstTermInPage ){
  182598. nPrefix = 0;
  182599. if( pPage->pgno!=1 ){
  182600. /* This is the first term on a leaf that is not the leftmost leaf in
  182601. ** the segment b-tree. In this case it is necessary to add a term to
  182602. ** the b-tree hierarchy that is (a) larger than the largest term
  182603. ** already written to the segment and (b) smaller than or equal to
  182604. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  182605. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  182606. ** previous term.
  182607. **
  182608. ** Usually, the previous term is available in pPage->term. The exception
  182609. ** is if this is the first term written in an incremental-merge step.
  182610. ** In this case the previous term is not available, so just write a
  182611. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  182612. ** inefficient, but still correct. */
  182613. int n = nTerm;
  182614. if( pPage->term.n ){
  182615. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  182616. }
  182617. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  182618. pPage = &pWriter->writer;
  182619. }
  182620. }else{
  182621. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  182622. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  182623. }
  182624. /* Append the number of bytes of new data, then the term data itself
  182625. ** to the page. */
  182626. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  182627. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  182628. /* Update the Fts5PageWriter.term field. */
  182629. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  182630. pWriter->bFirstTermInPage = 0;
  182631. pWriter->bFirstRowidInPage = 0;
  182632. pWriter->bFirstRowidInDoclist = 1;
  182633. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  182634. pWriter->aDlidx[0].pgno = pPage->pgno;
  182635. }
  182636. /*
  182637. ** Append a rowid and position-list size field to the writers output.
  182638. */
  182639. static void fts5WriteAppendRowid(
  182640. Fts5Index *p,
  182641. Fts5SegWriter *pWriter,
  182642. i64 iRowid
  182643. ){
  182644. if( p->rc==SQLITE_OK ){
  182645. Fts5PageWriter *pPage = &pWriter->writer;
  182646. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  182647. fts5WriteFlushLeaf(p, pWriter);
  182648. }
  182649. /* If this is to be the first rowid written to the page, set the
  182650. ** rowid-pointer in the page-header. Also append a value to the dlidx
  182651. ** buffer, in case a doclist-index is required. */
  182652. if( pWriter->bFirstRowidInPage ){
  182653. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  182654. fts5WriteDlidxAppend(p, pWriter, iRowid);
  182655. }
  182656. /* Write the rowid. */
  182657. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  182658. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  182659. }else{
  182660. assert( p->rc || iRowid>pWriter->iPrevRowid );
  182661. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  182662. }
  182663. pWriter->iPrevRowid = iRowid;
  182664. pWriter->bFirstRowidInDoclist = 0;
  182665. pWriter->bFirstRowidInPage = 0;
  182666. }
  182667. }
  182668. static void fts5WriteAppendPoslistData(
  182669. Fts5Index *p,
  182670. Fts5SegWriter *pWriter,
  182671. const u8 *aData,
  182672. int nData
  182673. ){
  182674. Fts5PageWriter *pPage = &pWriter->writer;
  182675. const u8 *a = aData;
  182676. int n = nData;
  182677. assert( p->pConfig->pgsz>0 );
  182678. while( p->rc==SQLITE_OK
  182679. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  182680. ){
  182681. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  182682. int nCopy = 0;
  182683. while( nCopy<nReq ){
  182684. i64 dummy;
  182685. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  182686. }
  182687. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  182688. a += nCopy;
  182689. n -= nCopy;
  182690. fts5WriteFlushLeaf(p, pWriter);
  182691. }
  182692. if( n>0 ){
  182693. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  182694. }
  182695. }
  182696. /*
  182697. ** Flush any data cached by the writer object to the database. Free any
  182698. ** allocations associated with the writer.
  182699. */
  182700. static void fts5WriteFinish(
  182701. Fts5Index *p,
  182702. Fts5SegWriter *pWriter, /* Writer object */
  182703. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  182704. ){
  182705. int i;
  182706. Fts5PageWriter *pLeaf = &pWriter->writer;
  182707. if( p->rc==SQLITE_OK ){
  182708. assert( pLeaf->pgno>=1 );
  182709. if( pLeaf->buf.n>4 ){
  182710. fts5WriteFlushLeaf(p, pWriter);
  182711. }
  182712. *pnLeaf = pLeaf->pgno-1;
  182713. if( pLeaf->pgno>1 ){
  182714. fts5WriteFlushBtree(p, pWriter);
  182715. }
  182716. }
  182717. fts5BufferFree(&pLeaf->term);
  182718. fts5BufferFree(&pLeaf->buf);
  182719. fts5BufferFree(&pLeaf->pgidx);
  182720. fts5BufferFree(&pWriter->btterm);
  182721. for(i=0; i<pWriter->nDlidx; i++){
  182722. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  182723. }
  182724. sqlite3_free(pWriter->aDlidx);
  182725. }
  182726. static void fts5WriteInit(
  182727. Fts5Index *p,
  182728. Fts5SegWriter *pWriter,
  182729. int iSegid
  182730. ){
  182731. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  182732. memset(pWriter, 0, sizeof(Fts5SegWriter));
  182733. pWriter->iSegid = iSegid;
  182734. fts5WriteDlidxGrow(p, pWriter, 1);
  182735. pWriter->writer.pgno = 1;
  182736. pWriter->bFirstTermInPage = 1;
  182737. pWriter->iBtPage = 1;
  182738. assert( pWriter->writer.buf.n==0 );
  182739. assert( pWriter->writer.pgidx.n==0 );
  182740. /* Grow the two buffers to pgsz + padding bytes in size. */
  182741. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  182742. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  182743. if( p->pIdxWriter==0 ){
  182744. Fts5Config *pConfig = p->pConfig;
  182745. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  182746. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  182747. pConfig->zDb, pConfig->zName
  182748. ));
  182749. }
  182750. if( p->rc==SQLITE_OK ){
  182751. /* Initialize the 4-byte leaf-page header to 0x00. */
  182752. memset(pWriter->writer.buf.p, 0, 4);
  182753. pWriter->writer.buf.n = 4;
  182754. /* Bind the current output segment id to the index-writer. This is an
  182755. ** optimization over binding the same value over and over as rows are
  182756. ** inserted into %_idx by the current writer. */
  182757. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  182758. }
  182759. }
  182760. /*
  182761. ** Iterator pIter was used to iterate through the input segments of on an
  182762. ** incremental merge operation. This function is called if the incremental
  182763. ** merge step has finished but the input has not been completely exhausted.
  182764. */
  182765. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  182766. int i;
  182767. Fts5Buffer buf;
  182768. memset(&buf, 0, sizeof(Fts5Buffer));
  182769. for(i=0; i<pIter->nSeg; i++){
  182770. Fts5SegIter *pSeg = &pIter->aSeg[i];
  182771. if( pSeg->pSeg==0 ){
  182772. /* no-op */
  182773. }else if( pSeg->pLeaf==0 ){
  182774. /* All keys from this input segment have been transfered to the output.
  182775. ** Set both the first and last page-numbers to 0 to indicate that the
  182776. ** segment is now empty. */
  182777. pSeg->pSeg->pgnoLast = 0;
  182778. pSeg->pSeg->pgnoFirst = 0;
  182779. }else{
  182780. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  182781. i64 iLeafRowid;
  182782. Fts5Data *pData;
  182783. int iId = pSeg->pSeg->iSegid;
  182784. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  182785. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  182786. pData = fts5DataRead(p, iLeafRowid);
  182787. if( pData ){
  182788. fts5BufferZero(&buf);
  182789. fts5BufferGrow(&p->rc, &buf, pData->nn);
  182790. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  182791. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  182792. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  182793. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  182794. if( p->rc==SQLITE_OK ){
  182795. /* Set the szLeaf field */
  182796. fts5PutU16(&buf.p[2], (u16)buf.n);
  182797. }
  182798. /* Set up the new page-index array */
  182799. fts5BufferAppendVarint(&p->rc, &buf, 4);
  182800. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  182801. && pSeg->iEndofDoclist<pData->szLeaf
  182802. ){
  182803. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  182804. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  182805. fts5BufferAppendBlob(&p->rc, &buf,
  182806. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  182807. );
  182808. }
  182809. fts5DataRelease(pData);
  182810. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  182811. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  182812. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  182813. }
  182814. }
  182815. }
  182816. fts5BufferFree(&buf);
  182817. }
  182818. static void fts5MergeChunkCallback(
  182819. Fts5Index *p,
  182820. void *pCtx,
  182821. const u8 *pChunk, int nChunk
  182822. ){
  182823. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  182824. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  182825. }
  182826. /*
  182827. **
  182828. */
  182829. static void fts5IndexMergeLevel(
  182830. Fts5Index *p, /* FTS5 backend object */
  182831. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  182832. int iLvl, /* Level to read input from */
  182833. int *pnRem /* Write up to this many output leaves */
  182834. ){
  182835. Fts5Structure *pStruct = *ppStruct;
  182836. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  182837. Fts5StructureLevel *pLvlOut;
  182838. Fts5Iter *pIter = 0; /* Iterator to read input data */
  182839. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  182840. int nInput; /* Number of input segments */
  182841. Fts5SegWriter writer; /* Writer object */
  182842. Fts5StructureSegment *pSeg; /* Output segment */
  182843. Fts5Buffer term;
  182844. int bOldest; /* True if the output segment is the oldest */
  182845. int eDetail = p->pConfig->eDetail;
  182846. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  182847. int bTermWritten = 0; /* True if current term already output */
  182848. assert( iLvl<pStruct->nLevel );
  182849. assert( pLvl->nMerge<=pLvl->nSeg );
  182850. memset(&writer, 0, sizeof(Fts5SegWriter));
  182851. memset(&term, 0, sizeof(Fts5Buffer));
  182852. if( pLvl->nMerge ){
  182853. pLvlOut = &pStruct->aLevel[iLvl+1];
  182854. assert( pLvlOut->nSeg>0 );
  182855. nInput = pLvl->nMerge;
  182856. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  182857. fts5WriteInit(p, &writer, pSeg->iSegid);
  182858. writer.writer.pgno = pSeg->pgnoLast+1;
  182859. writer.iBtPage = 0;
  182860. }else{
  182861. int iSegid = fts5AllocateSegid(p, pStruct);
  182862. /* Extend the Fts5Structure object as required to ensure the output
  182863. ** segment exists. */
  182864. if( iLvl==pStruct->nLevel-1 ){
  182865. fts5StructureAddLevel(&p->rc, ppStruct);
  182866. pStruct = *ppStruct;
  182867. }
  182868. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  182869. if( p->rc ) return;
  182870. pLvl = &pStruct->aLevel[iLvl];
  182871. pLvlOut = &pStruct->aLevel[iLvl+1];
  182872. fts5WriteInit(p, &writer, iSegid);
  182873. /* Add the new segment to the output level */
  182874. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  182875. pLvlOut->nSeg++;
  182876. pSeg->pgnoFirst = 1;
  182877. pSeg->iSegid = iSegid;
  182878. pStruct->nSegment++;
  182879. /* Read input from all segments in the input level */
  182880. nInput = pLvl->nSeg;
  182881. }
  182882. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  182883. assert( iLvl>=0 );
  182884. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  182885. fts5MultiIterEof(p, pIter)==0;
  182886. fts5MultiIterNext(p, pIter, 0, 0)
  182887. ){
  182888. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  182889. int nPos; /* position-list size field value */
  182890. int nTerm;
  182891. const u8 *pTerm;
  182892. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  182893. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  182894. if( pnRem && writer.nLeafWritten>nRem ){
  182895. break;
  182896. }
  182897. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  182898. bTermWritten =0;
  182899. }
  182900. /* Check for key annihilation. */
  182901. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  182902. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  182903. /* This is a new term. Append a term to the output segment. */
  182904. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  182905. bTermWritten = 1;
  182906. }
  182907. /* Append the rowid to the output */
  182908. /* WRITEPOSLISTSIZE */
  182909. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  182910. if( eDetail==FTS5_DETAIL_NONE ){
  182911. if( pSegIter->bDel ){
  182912. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  182913. if( pSegIter->nPos>0 ){
  182914. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  182915. }
  182916. }
  182917. }else{
  182918. /* Append the position-list data to the output */
  182919. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  182920. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  182921. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  182922. }
  182923. }
  182924. /* Flush the last leaf page to disk. Set the output segment b-tree height
  182925. ** and last leaf page number at the same time. */
  182926. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  182927. if( fts5MultiIterEof(p, pIter) ){
  182928. int i;
  182929. /* Remove the redundant segments from the %_data table */
  182930. for(i=0; i<nInput; i++){
  182931. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  182932. }
  182933. /* Remove the redundant segments from the input level */
  182934. if( pLvl->nSeg!=nInput ){
  182935. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  182936. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  182937. }
  182938. pStruct->nSegment -= nInput;
  182939. pLvl->nSeg -= nInput;
  182940. pLvl->nMerge = 0;
  182941. if( pSeg->pgnoLast==0 ){
  182942. pLvlOut->nSeg--;
  182943. pStruct->nSegment--;
  182944. }
  182945. }else{
  182946. assert( pSeg->pgnoLast>0 );
  182947. fts5TrimSegments(p, pIter);
  182948. pLvl->nMerge = nInput;
  182949. }
  182950. fts5MultiIterFree(pIter);
  182951. fts5BufferFree(&term);
  182952. if( pnRem ) *pnRem -= writer.nLeafWritten;
  182953. }
  182954. /*
  182955. ** Do up to nPg pages of automerge work on the index.
  182956. **
  182957. ** Return true if any changes were actually made, or false otherwise.
  182958. */
  182959. static int fts5IndexMerge(
  182960. Fts5Index *p, /* FTS5 backend object */
  182961. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  182962. int nPg, /* Pages of work to do */
  182963. int nMin /* Minimum number of segments to merge */
  182964. ){
  182965. int nRem = nPg;
  182966. int bRet = 0;
  182967. Fts5Structure *pStruct = *ppStruct;
  182968. while( nRem>0 && p->rc==SQLITE_OK ){
  182969. int iLvl; /* To iterate through levels */
  182970. int iBestLvl = 0; /* Level offering the most input segments */
  182971. int nBest = 0; /* Number of input segments on best level */
  182972. /* Set iBestLvl to the level to read input segments from. */
  182973. assert( pStruct->nLevel>0 );
  182974. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  182975. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  182976. if( pLvl->nMerge ){
  182977. if( pLvl->nMerge>nBest ){
  182978. iBestLvl = iLvl;
  182979. nBest = pLvl->nMerge;
  182980. }
  182981. break;
  182982. }
  182983. if( pLvl->nSeg>nBest ){
  182984. nBest = pLvl->nSeg;
  182985. iBestLvl = iLvl;
  182986. }
  182987. }
  182988. /* If nBest is still 0, then the index must be empty. */
  182989. #ifdef SQLITE_DEBUG
  182990. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  182991. assert( pStruct->aLevel[iLvl].nSeg==0 );
  182992. }
  182993. #endif
  182994. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  182995. break;
  182996. }
  182997. bRet = 1;
  182998. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  182999. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  183000. fts5StructurePromote(p, iBestLvl+1, pStruct);
  183001. }
  183002. }
  183003. *ppStruct = pStruct;
  183004. return bRet;
  183005. }
  183006. /*
  183007. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  183008. ** segment. This function updates the write-counter accordingly and, if
  183009. ** necessary, performs incremental merge work.
  183010. **
  183011. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  183012. ** already occurred, this function is a no-op.
  183013. */
  183014. static void fts5IndexAutomerge(
  183015. Fts5Index *p, /* FTS5 backend object */
  183016. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  183017. int nLeaf /* Number of output leaves just written */
  183018. ){
  183019. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  183020. Fts5Structure *pStruct = *ppStruct;
  183021. u64 nWrite; /* Initial value of write-counter */
  183022. int nWork; /* Number of work-quanta to perform */
  183023. int nRem; /* Number of leaf pages left to write */
  183024. /* Update the write-counter. While doing so, set nWork. */
  183025. nWrite = pStruct->nWriteCounter;
  183026. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  183027. pStruct->nWriteCounter += nLeaf;
  183028. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  183029. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  183030. }
  183031. }
  183032. static void fts5IndexCrisismerge(
  183033. Fts5Index *p, /* FTS5 backend object */
  183034. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  183035. ){
  183036. const int nCrisis = p->pConfig->nCrisisMerge;
  183037. Fts5Structure *pStruct = *ppStruct;
  183038. int iLvl = 0;
  183039. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  183040. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  183041. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  183042. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  183043. fts5StructurePromote(p, iLvl+1, pStruct);
  183044. iLvl++;
  183045. }
  183046. *ppStruct = pStruct;
  183047. }
  183048. static int fts5IndexReturn(Fts5Index *p){
  183049. int rc = p->rc;
  183050. p->rc = SQLITE_OK;
  183051. return rc;
  183052. }
  183053. typedef struct Fts5FlushCtx Fts5FlushCtx;
  183054. struct Fts5FlushCtx {
  183055. Fts5Index *pIdx;
  183056. Fts5SegWriter writer;
  183057. };
  183058. /*
  183059. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  183060. ** in a 32-bit integer. Return the size of the largest prefix of this
  183061. ** list nMax bytes or less in size.
  183062. */
  183063. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  183064. int ret;
  183065. u32 dummy;
  183066. ret = fts5GetVarint32(aBuf, dummy);
  183067. if( ret<nMax ){
  183068. while( 1 ){
  183069. int i = fts5GetVarint32(&aBuf[ret], dummy);
  183070. if( (ret + i) > nMax ) break;
  183071. ret += i;
  183072. }
  183073. }
  183074. return ret;
  183075. }
  183076. /*
  183077. ** Flush the contents of in-memory hash table iHash to a new level-0
  183078. ** segment on disk. Also update the corresponding structure record.
  183079. **
  183080. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  183081. ** already occurred, this function is a no-op.
  183082. */
  183083. static void fts5FlushOneHash(Fts5Index *p){
  183084. Fts5Hash *pHash = p->pHash;
  183085. Fts5Structure *pStruct;
  183086. int iSegid;
  183087. int pgnoLast = 0; /* Last leaf page number in segment */
  183088. /* Obtain a reference to the index structure and allocate a new segment-id
  183089. ** for the new level-0 segment. */
  183090. pStruct = fts5StructureRead(p);
  183091. iSegid = fts5AllocateSegid(p, pStruct);
  183092. fts5StructureInvalidate(p);
  183093. if( iSegid ){
  183094. const int pgsz = p->pConfig->pgsz;
  183095. int eDetail = p->pConfig->eDetail;
  183096. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  183097. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  183098. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  183099. Fts5SegWriter writer;
  183100. fts5WriteInit(p, &writer, iSegid);
  183101. pBuf = &writer.writer.buf;
  183102. pPgidx = &writer.writer.pgidx;
  183103. /* fts5WriteInit() should have initialized the buffers to (most likely)
  183104. ** the maximum space required. */
  183105. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  183106. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  183107. /* Begin scanning through hash table entries. This loop runs once for each
  183108. ** term/doclist currently stored within the hash table. */
  183109. if( p->rc==SQLITE_OK ){
  183110. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  183111. }
  183112. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  183113. const char *zTerm; /* Buffer containing term */
  183114. const u8 *pDoclist; /* Pointer to doclist for this term */
  183115. int nDoclist; /* Size of doclist in bytes */
  183116. /* Write the term for this entry to disk. */
  183117. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  183118. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  183119. assert( writer.bFirstRowidInPage==0 );
  183120. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  183121. /* The entire doclist will fit on the current leaf. */
  183122. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  183123. }else{
  183124. i64 iRowid = 0;
  183125. i64 iDelta = 0;
  183126. int iOff = 0;
  183127. /* The entire doclist will not fit on this leaf. The following
  183128. ** loop iterates through the poslists that make up the current
  183129. ** doclist. */
  183130. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  183131. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  183132. iRowid += iDelta;
  183133. if( writer.bFirstRowidInPage ){
  183134. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  183135. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  183136. writer.bFirstRowidInPage = 0;
  183137. fts5WriteDlidxAppend(p, &writer, iRowid);
  183138. }else{
  183139. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  183140. }
  183141. assert( pBuf->n<=pBuf->nSpace );
  183142. if( eDetail==FTS5_DETAIL_NONE ){
  183143. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  183144. pBuf->p[pBuf->n++] = 0;
  183145. iOff++;
  183146. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  183147. pBuf->p[pBuf->n++] = 0;
  183148. iOff++;
  183149. }
  183150. }
  183151. if( (pBuf->n + pPgidx->n)>=pgsz ){
  183152. fts5WriteFlushLeaf(p, &writer);
  183153. }
  183154. }else{
  183155. int bDummy;
  183156. int nPos;
  183157. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  183158. nCopy += nPos;
  183159. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  183160. /* The entire poslist will fit on the current leaf. So copy
  183161. ** it in one go. */
  183162. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  183163. }else{
  183164. /* The entire poslist will not fit on this leaf. So it needs
  183165. ** to be broken into sections. The only qualification being
  183166. ** that each varint must be stored contiguously. */
  183167. const u8 *pPoslist = &pDoclist[iOff];
  183168. int iPos = 0;
  183169. while( p->rc==SQLITE_OK ){
  183170. int nSpace = pgsz - pBuf->n - pPgidx->n;
  183171. int n = 0;
  183172. if( (nCopy - iPos)<=nSpace ){
  183173. n = nCopy - iPos;
  183174. }else{
  183175. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  183176. }
  183177. assert( n>0 );
  183178. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  183179. iPos += n;
  183180. if( (pBuf->n + pPgidx->n)>=pgsz ){
  183181. fts5WriteFlushLeaf(p, &writer);
  183182. }
  183183. if( iPos>=nCopy ) break;
  183184. }
  183185. }
  183186. iOff += nCopy;
  183187. }
  183188. }
  183189. }
  183190. /* TODO2: Doclist terminator written here. */
  183191. /* pBuf->p[pBuf->n++] = '\0'; */
  183192. assert( pBuf->n<=pBuf->nSpace );
  183193. sqlite3Fts5HashScanNext(pHash);
  183194. }
  183195. sqlite3Fts5HashClear(pHash);
  183196. fts5WriteFinish(p, &writer, &pgnoLast);
  183197. /* Update the Fts5Structure. It is written back to the database by the
  183198. ** fts5StructureRelease() call below. */
  183199. if( pStruct->nLevel==0 ){
  183200. fts5StructureAddLevel(&p->rc, &pStruct);
  183201. }
  183202. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  183203. if( p->rc==SQLITE_OK ){
  183204. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  183205. pSeg->iSegid = iSegid;
  183206. pSeg->pgnoFirst = 1;
  183207. pSeg->pgnoLast = pgnoLast;
  183208. pStruct->nSegment++;
  183209. }
  183210. fts5StructurePromote(p, 0, pStruct);
  183211. }
  183212. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  183213. fts5IndexCrisismerge(p, &pStruct);
  183214. fts5StructureWrite(p, pStruct);
  183215. fts5StructureRelease(pStruct);
  183216. }
  183217. /*
  183218. ** Flush any data stored in the in-memory hash tables to the database.
  183219. */
  183220. static void fts5IndexFlush(Fts5Index *p){
  183221. /* Unless it is empty, flush the hash table to disk */
  183222. if( p->nPendingData ){
  183223. assert( p->pHash );
  183224. p->nPendingData = 0;
  183225. fts5FlushOneHash(p);
  183226. }
  183227. }
  183228. static Fts5Structure *fts5IndexOptimizeStruct(
  183229. Fts5Index *p,
  183230. Fts5Structure *pStruct
  183231. ){
  183232. Fts5Structure *pNew = 0;
  183233. int nByte = sizeof(Fts5Structure);
  183234. int nSeg = pStruct->nSegment;
  183235. int i;
  183236. /* Figure out if this structure requires optimization. A structure does
  183237. ** not require optimization if either:
  183238. **
  183239. ** + it consists of fewer than two segments, or
  183240. ** + all segments are on the same level, or
  183241. ** + all segments except one are currently inputs to a merge operation.
  183242. **
  183243. ** In the first case, return NULL. In the second, increment the ref-count
  183244. ** on *pStruct and return a copy of the pointer to it.
  183245. */
  183246. if( nSeg<2 ) return 0;
  183247. for(i=0; i<pStruct->nLevel; i++){
  183248. int nThis = pStruct->aLevel[i].nSeg;
  183249. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  183250. fts5StructureRef(pStruct);
  183251. return pStruct;
  183252. }
  183253. assert( pStruct->aLevel[i].nMerge<=nThis );
  183254. }
  183255. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  183256. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  183257. if( pNew ){
  183258. Fts5StructureLevel *pLvl;
  183259. nByte = nSeg * sizeof(Fts5StructureSegment);
  183260. pNew->nLevel = pStruct->nLevel+1;
  183261. pNew->nRef = 1;
  183262. pNew->nWriteCounter = pStruct->nWriteCounter;
  183263. pLvl = &pNew->aLevel[pStruct->nLevel];
  183264. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  183265. if( pLvl->aSeg ){
  183266. int iLvl, iSeg;
  183267. int iSegOut = 0;
  183268. /* Iterate through all segments, from oldest to newest. Add them to
  183269. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  183270. ** segment in the data structure. */
  183271. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  183272. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  183273. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  183274. iSegOut++;
  183275. }
  183276. }
  183277. pNew->nSegment = pLvl->nSeg = nSeg;
  183278. }else{
  183279. sqlite3_free(pNew);
  183280. pNew = 0;
  183281. }
  183282. }
  183283. return pNew;
  183284. }
  183285. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  183286. Fts5Structure *pStruct;
  183287. Fts5Structure *pNew = 0;
  183288. assert( p->rc==SQLITE_OK );
  183289. fts5IndexFlush(p);
  183290. pStruct = fts5StructureRead(p);
  183291. fts5StructureInvalidate(p);
  183292. if( pStruct ){
  183293. pNew = fts5IndexOptimizeStruct(p, pStruct);
  183294. }
  183295. fts5StructureRelease(pStruct);
  183296. assert( pNew==0 || pNew->nSegment>0 );
  183297. if( pNew ){
  183298. int iLvl;
  183299. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  183300. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  183301. int nRem = FTS5_OPT_WORK_UNIT;
  183302. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  183303. }
  183304. fts5StructureWrite(p, pNew);
  183305. fts5StructureRelease(pNew);
  183306. }
  183307. return fts5IndexReturn(p);
  183308. }
  183309. /*
  183310. ** This is called to implement the special "VALUES('merge', $nMerge)"
  183311. ** INSERT command.
  183312. */
  183313. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  183314. Fts5Structure *pStruct = fts5StructureRead(p);
  183315. if( pStruct ){
  183316. int nMin = p->pConfig->nUsermerge;
  183317. fts5StructureInvalidate(p);
  183318. if( nMerge<0 ){
  183319. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  183320. fts5StructureRelease(pStruct);
  183321. pStruct = pNew;
  183322. nMin = 2;
  183323. nMerge = nMerge*-1;
  183324. }
  183325. if( pStruct && pStruct->nLevel ){
  183326. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  183327. fts5StructureWrite(p, pStruct);
  183328. }
  183329. }
  183330. fts5StructureRelease(pStruct);
  183331. }
  183332. return fts5IndexReturn(p);
  183333. }
  183334. static void fts5AppendRowid(
  183335. Fts5Index *p,
  183336. i64 iDelta,
  183337. Fts5Iter *pUnused,
  183338. Fts5Buffer *pBuf
  183339. ){
  183340. UNUSED_PARAM(pUnused);
  183341. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  183342. }
  183343. static void fts5AppendPoslist(
  183344. Fts5Index *p,
  183345. i64 iDelta,
  183346. Fts5Iter *pMulti,
  183347. Fts5Buffer *pBuf
  183348. ){
  183349. int nData = pMulti->base.nData;
  183350. assert( nData>0 );
  183351. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  183352. fts5BufferSafeAppendVarint(pBuf, iDelta);
  183353. fts5BufferSafeAppendVarint(pBuf, nData*2);
  183354. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  183355. }
  183356. }
  183357. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  183358. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  183359. assert( pIter->aPoslist );
  183360. if( p>=pIter->aEof ){
  183361. pIter->aPoslist = 0;
  183362. }else{
  183363. i64 iDelta;
  183364. p += fts5GetVarint(p, (u64*)&iDelta);
  183365. pIter->iRowid += iDelta;
  183366. /* Read position list size */
  183367. if( p[0] & 0x80 ){
  183368. int nPos;
  183369. pIter->nSize = fts5GetVarint32(p, nPos);
  183370. pIter->nPoslist = (nPos>>1);
  183371. }else{
  183372. pIter->nPoslist = ((int)(p[0])) >> 1;
  183373. pIter->nSize = 1;
  183374. }
  183375. pIter->aPoslist = p;
  183376. }
  183377. }
  183378. static void fts5DoclistIterInit(
  183379. Fts5Buffer *pBuf,
  183380. Fts5DoclistIter *pIter
  183381. ){
  183382. memset(pIter, 0, sizeof(*pIter));
  183383. pIter->aPoslist = pBuf->p;
  183384. pIter->aEof = &pBuf->p[pBuf->n];
  183385. fts5DoclistIterNext(pIter);
  183386. }
  183387. #if 0
  183388. /*
  183389. ** Append a doclist to buffer pBuf.
  183390. **
  183391. ** This function assumes that space within the buffer has already been
  183392. ** allocated.
  183393. */
  183394. static void fts5MergeAppendDocid(
  183395. Fts5Buffer *pBuf, /* Buffer to write to */
  183396. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  183397. i64 iRowid /* Rowid to append */
  183398. ){
  183399. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  183400. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  183401. *piLastRowid = iRowid;
  183402. }
  183403. #endif
  183404. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  183405. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  183406. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  183407. (iLastRowid) = (iRowid); \
  183408. }
  183409. /*
  183410. ** Swap the contents of buffer *p1 with that of *p2.
  183411. */
  183412. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  183413. Fts5Buffer tmp = *p1;
  183414. *p1 = *p2;
  183415. *p2 = tmp;
  183416. }
  183417. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  183418. int i = *piOff;
  183419. if( i>=pBuf->n ){
  183420. *piOff = -1;
  183421. }else{
  183422. u64 iVal;
  183423. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  183424. *piRowid += iVal;
  183425. }
  183426. }
  183427. /*
  183428. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  183429. ** In this case the buffers consist of a delta-encoded list of rowids only.
  183430. */
  183431. static void fts5MergeRowidLists(
  183432. Fts5Index *p, /* FTS5 backend object */
  183433. Fts5Buffer *p1, /* First list to merge */
  183434. Fts5Buffer *p2 /* Second list to merge */
  183435. ){
  183436. int i1 = 0;
  183437. int i2 = 0;
  183438. i64 iRowid1 = 0;
  183439. i64 iRowid2 = 0;
  183440. i64 iOut = 0;
  183441. Fts5Buffer out;
  183442. memset(&out, 0, sizeof(out));
  183443. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  183444. if( p->rc ) return;
  183445. fts5NextRowid(p1, &i1, &iRowid1);
  183446. fts5NextRowid(p2, &i2, &iRowid2);
  183447. while( i1>=0 || i2>=0 ){
  183448. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  183449. assert( iOut==0 || iRowid1>iOut );
  183450. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  183451. iOut = iRowid1;
  183452. fts5NextRowid(p1, &i1, &iRowid1);
  183453. }else{
  183454. assert( iOut==0 || iRowid2>iOut );
  183455. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  183456. iOut = iRowid2;
  183457. if( i1>=0 && iRowid1==iRowid2 ){
  183458. fts5NextRowid(p1, &i1, &iRowid1);
  183459. }
  183460. fts5NextRowid(p2, &i2, &iRowid2);
  183461. }
  183462. }
  183463. fts5BufferSwap(&out, p1);
  183464. fts5BufferFree(&out);
  183465. }
  183466. /*
  183467. ** Buffers p1 and p2 contain doclists. This function merges the content
  183468. ** of the two doclists together and sets buffer p1 to the result before
  183469. ** returning.
  183470. **
  183471. ** If an error occurs, an error code is left in p->rc. If an error has
  183472. ** already occurred, this function is a no-op.
  183473. */
  183474. static void fts5MergePrefixLists(
  183475. Fts5Index *p, /* FTS5 backend object */
  183476. Fts5Buffer *p1, /* First list to merge */
  183477. Fts5Buffer *p2 /* Second list to merge */
  183478. ){
  183479. if( p2->n ){
  183480. i64 iLastRowid = 0;
  183481. Fts5DoclistIter i1;
  183482. Fts5DoclistIter i2;
  183483. Fts5Buffer out = {0, 0, 0};
  183484. Fts5Buffer tmp = {0, 0, 0};
  183485. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
  183486. fts5DoclistIterInit(p1, &i1);
  183487. fts5DoclistIterInit(p2, &i2);
  183488. while( 1 ){
  183489. if( i1.iRowid<i2.iRowid ){
  183490. /* Copy entry from i1 */
  183491. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  183492. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  183493. fts5DoclistIterNext(&i1);
  183494. if( i1.aPoslist==0 ) break;
  183495. }
  183496. else if( i2.iRowid!=i1.iRowid ){
  183497. /* Copy entry from i2 */
  183498. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  183499. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  183500. fts5DoclistIterNext(&i2);
  183501. if( i2.aPoslist==0 ) break;
  183502. }
  183503. else{
  183504. /* Merge the two position lists. */
  183505. i64 iPos1 = 0;
  183506. i64 iPos2 = 0;
  183507. int iOff1 = 0;
  183508. int iOff2 = 0;
  183509. u8 *a1 = &i1.aPoslist[i1.nSize];
  183510. u8 *a2 = &i2.aPoslist[i2.nSize];
  183511. i64 iPrev = 0;
  183512. Fts5PoslistWriter writer;
  183513. memset(&writer, 0, sizeof(writer));
  183514. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  183515. fts5BufferZero(&tmp);
  183516. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  183517. if( p->rc ) break;
  183518. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  183519. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  183520. assert( iPos1>=0 && iPos2>=0 );
  183521. if( iPos1<iPos2 ){
  183522. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  183523. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  183524. }else{
  183525. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  183526. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  183527. }
  183528. if( iPos1>=0 && iPos2>=0 ){
  183529. while( 1 ){
  183530. if( iPos1<iPos2 ){
  183531. if( iPos1!=iPrev ){
  183532. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  183533. }
  183534. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  183535. if( iPos1<0 ) break;
  183536. }else{
  183537. assert( iPos2!=iPrev );
  183538. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  183539. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  183540. if( iPos2<0 ) break;
  183541. }
  183542. }
  183543. }
  183544. if( iPos1>=0 ){
  183545. if( iPos1!=iPrev ){
  183546. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  183547. }
  183548. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  183549. }else{
  183550. assert( iPos2>=0 && iPos2!=iPrev );
  183551. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  183552. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  183553. }
  183554. /* WRITEPOSLISTSIZE */
  183555. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  183556. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  183557. fts5DoclistIterNext(&i1);
  183558. fts5DoclistIterNext(&i2);
  183559. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  183560. }
  183561. }
  183562. if( i1.aPoslist ){
  183563. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  183564. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  183565. }
  183566. else if( i2.aPoslist ){
  183567. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  183568. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  183569. }
  183570. fts5BufferSet(&p->rc, p1, out.n, out.p);
  183571. fts5BufferFree(&tmp);
  183572. fts5BufferFree(&out);
  183573. }
  183574. }
  183575. static void fts5SetupPrefixIter(
  183576. Fts5Index *p, /* Index to read from */
  183577. int bDesc, /* True for "ORDER BY rowid DESC" */
  183578. const u8 *pToken, /* Buffer containing prefix to match */
  183579. int nToken, /* Size of buffer pToken in bytes */
  183580. Fts5Colset *pColset, /* Restrict matches to these columns */
  183581. Fts5Iter **ppIter /* OUT: New iterator */
  183582. ){
  183583. Fts5Structure *pStruct;
  183584. Fts5Buffer *aBuf;
  183585. const int nBuf = 32;
  183586. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  183587. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  183588. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  183589. xMerge = fts5MergeRowidLists;
  183590. xAppend = fts5AppendRowid;
  183591. }else{
  183592. xMerge = fts5MergePrefixLists;
  183593. xAppend = fts5AppendPoslist;
  183594. }
  183595. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  183596. pStruct = fts5StructureRead(p);
  183597. if( aBuf && pStruct ){
  183598. const int flags = FTS5INDEX_QUERY_SCAN
  183599. | FTS5INDEX_QUERY_SKIPEMPTY
  183600. | FTS5INDEX_QUERY_NOOUTPUT;
  183601. int i;
  183602. i64 iLastRowid = 0;
  183603. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  183604. Fts5Data *pData;
  183605. Fts5Buffer doclist;
  183606. int bNewTerm = 1;
  183607. memset(&doclist, 0, sizeof(doclist));
  183608. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  183609. fts5IterSetOutputCb(&p->rc, p1);
  183610. for( /* no-op */ ;
  183611. fts5MultiIterEof(p, p1)==0;
  183612. fts5MultiIterNext2(p, p1, &bNewTerm)
  183613. ){
  183614. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  183615. int nTerm = pSeg->term.n;
  183616. const u8 *pTerm = pSeg->term.p;
  183617. p1->xSetOutputs(p1, pSeg);
  183618. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  183619. if( bNewTerm ){
  183620. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  183621. }
  183622. if( p1->base.nData==0 ) continue;
  183623. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  183624. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  183625. assert( i<nBuf );
  183626. if( aBuf[i].n==0 ){
  183627. fts5BufferSwap(&doclist, &aBuf[i]);
  183628. fts5BufferZero(&doclist);
  183629. }else{
  183630. xMerge(p, &doclist, &aBuf[i]);
  183631. fts5BufferZero(&aBuf[i]);
  183632. }
  183633. }
  183634. iLastRowid = 0;
  183635. }
  183636. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  183637. iLastRowid = p1->base.iRowid;
  183638. }
  183639. for(i=0; i<nBuf; i++){
  183640. if( p->rc==SQLITE_OK ){
  183641. xMerge(p, &doclist, &aBuf[i]);
  183642. }
  183643. fts5BufferFree(&aBuf[i]);
  183644. }
  183645. fts5MultiIterFree(p1);
  183646. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  183647. if( pData ){
  183648. pData->p = (u8*)&pData[1];
  183649. pData->nn = pData->szLeaf = doclist.n;
  183650. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  183651. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  183652. }
  183653. fts5BufferFree(&doclist);
  183654. }
  183655. fts5StructureRelease(pStruct);
  183656. sqlite3_free(aBuf);
  183657. }
  183658. /*
  183659. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  183660. ** to the document with rowid iRowid.
  183661. */
  183662. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  183663. assert( p->rc==SQLITE_OK );
  183664. /* Allocate the hash table if it has not already been allocated */
  183665. if( p->pHash==0 ){
  183666. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  183667. }
  183668. /* Flush the hash table to disk if required */
  183669. if( iRowid<p->iWriteRowid
  183670. || (iRowid==p->iWriteRowid && p->bDelete==0)
  183671. || (p->nPendingData > p->pConfig->nHashSize)
  183672. ){
  183673. fts5IndexFlush(p);
  183674. }
  183675. p->iWriteRowid = iRowid;
  183676. p->bDelete = bDelete;
  183677. return fts5IndexReturn(p);
  183678. }
  183679. /*
  183680. ** Commit data to disk.
  183681. */
  183682. static int sqlite3Fts5IndexSync(Fts5Index *p){
  183683. assert( p->rc==SQLITE_OK );
  183684. fts5IndexFlush(p);
  183685. fts5CloseReader(p);
  183686. return fts5IndexReturn(p);
  183687. }
  183688. /*
  183689. ** Discard any data stored in the in-memory hash tables. Do not write it
  183690. ** to the database. Additionally, assume that the contents of the %_data
  183691. ** table may have changed on disk. So any in-memory caches of %_data
  183692. ** records must be invalidated.
  183693. */
  183694. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  183695. fts5CloseReader(p);
  183696. fts5IndexDiscardData(p);
  183697. fts5StructureInvalidate(p);
  183698. /* assert( p->rc==SQLITE_OK ); */
  183699. return SQLITE_OK;
  183700. }
  183701. /*
  183702. ** The %_data table is completely empty when this function is called. This
  183703. ** function populates it with the initial structure objects for each index,
  183704. ** and the initial version of the "averages" record (a zero-byte blob).
  183705. */
  183706. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  183707. Fts5Structure s;
  183708. fts5StructureInvalidate(p);
  183709. memset(&s, 0, sizeof(Fts5Structure));
  183710. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  183711. fts5StructureWrite(p, &s);
  183712. return fts5IndexReturn(p);
  183713. }
  183714. /*
  183715. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  183716. ** and initialize the underlying %_data table.
  183717. **
  183718. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  183719. ** Otherwise, set *pp to NULL and return an SQLite error code.
  183720. */
  183721. static int sqlite3Fts5IndexOpen(
  183722. Fts5Config *pConfig,
  183723. int bCreate,
  183724. Fts5Index **pp,
  183725. char **pzErr
  183726. ){
  183727. int rc = SQLITE_OK;
  183728. Fts5Index *p; /* New object */
  183729. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  183730. if( rc==SQLITE_OK ){
  183731. p->pConfig = pConfig;
  183732. p->nWorkUnit = FTS5_WORK_UNIT;
  183733. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  183734. if( p->zDataTbl && bCreate ){
  183735. rc = sqlite3Fts5CreateTable(
  183736. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  183737. );
  183738. if( rc==SQLITE_OK ){
  183739. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  183740. "segid, term, pgno, PRIMARY KEY(segid, term)",
  183741. 1, pzErr
  183742. );
  183743. }
  183744. if( rc==SQLITE_OK ){
  183745. rc = sqlite3Fts5IndexReinit(p);
  183746. }
  183747. }
  183748. }
  183749. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  183750. if( rc ){
  183751. sqlite3Fts5IndexClose(p);
  183752. *pp = 0;
  183753. }
  183754. return rc;
  183755. }
  183756. /*
  183757. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  183758. */
  183759. static int sqlite3Fts5IndexClose(Fts5Index *p){
  183760. int rc = SQLITE_OK;
  183761. if( p ){
  183762. assert( p->pReader==0 );
  183763. fts5StructureInvalidate(p);
  183764. sqlite3_finalize(p->pWriter);
  183765. sqlite3_finalize(p->pDeleter);
  183766. sqlite3_finalize(p->pIdxWriter);
  183767. sqlite3_finalize(p->pIdxDeleter);
  183768. sqlite3_finalize(p->pIdxSelect);
  183769. sqlite3_finalize(p->pDataVersion);
  183770. sqlite3Fts5HashFree(p->pHash);
  183771. sqlite3_free(p->zDataTbl);
  183772. sqlite3_free(p);
  183773. }
  183774. return rc;
  183775. }
  183776. /*
  183777. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  183778. ** size. Return the number of bytes in the nChar character prefix of the
  183779. ** buffer, or 0 if there are less than nChar characters in total.
  183780. */
  183781. static int sqlite3Fts5IndexCharlenToBytelen(
  183782. const char *p,
  183783. int nByte,
  183784. int nChar
  183785. ){
  183786. int n = 0;
  183787. int i;
  183788. for(i=0; i<nChar; i++){
  183789. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  183790. if( (unsigned char)p[n++]>=0xc0 ){
  183791. while( (p[n] & 0xc0)==0x80 ) n++;
  183792. }
  183793. }
  183794. return n;
  183795. }
  183796. /*
  183797. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  183798. ** unicode characters in the string.
  183799. */
  183800. static int fts5IndexCharlen(const char *pIn, int nIn){
  183801. int nChar = 0;
  183802. int i = 0;
  183803. while( i<nIn ){
  183804. if( (unsigned char)pIn[i++]>=0xc0 ){
  183805. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  183806. }
  183807. nChar++;
  183808. }
  183809. return nChar;
  183810. }
  183811. /*
  183812. ** Insert or remove data to or from the index. Each time a document is
  183813. ** added to or removed from the index, this function is called one or more
  183814. ** times.
  183815. **
  183816. ** For an insert, it must be called once for each token in the new document.
  183817. ** If the operation is a delete, it must be called (at least) once for each
  183818. ** unique token in the document with an iCol value less than zero. The iPos
  183819. ** argument is ignored for a delete.
  183820. */
  183821. static int sqlite3Fts5IndexWrite(
  183822. Fts5Index *p, /* Index to write to */
  183823. int iCol, /* Column token appears in (-ve -> delete) */
  183824. int iPos, /* Position of token within column */
  183825. const char *pToken, int nToken /* Token to add or remove to or from index */
  183826. ){
  183827. int i; /* Used to iterate through indexes */
  183828. int rc = SQLITE_OK; /* Return code */
  183829. Fts5Config *pConfig = p->pConfig;
  183830. assert( p->rc==SQLITE_OK );
  183831. assert( (iCol<0)==p->bDelete );
  183832. /* Add the entry to the main terms index. */
  183833. rc = sqlite3Fts5HashWrite(
  183834. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  183835. );
  183836. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  183837. const int nChar = pConfig->aPrefix[i];
  183838. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  183839. if( nByte ){
  183840. rc = sqlite3Fts5HashWrite(p->pHash,
  183841. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  183842. nByte
  183843. );
  183844. }
  183845. }
  183846. return rc;
  183847. }
  183848. /*
  183849. ** Open a new iterator to iterate though all rowid that match the
  183850. ** specified token or token prefix.
  183851. */
  183852. static int sqlite3Fts5IndexQuery(
  183853. Fts5Index *p, /* FTS index to query */
  183854. const char *pToken, int nToken, /* Token (or prefix) to query for */
  183855. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  183856. Fts5Colset *pColset, /* Match these columns only */
  183857. Fts5IndexIter **ppIter /* OUT: New iterator object */
  183858. ){
  183859. Fts5Config *pConfig = p->pConfig;
  183860. Fts5Iter *pRet = 0;
  183861. Fts5Buffer buf = {0, 0, 0};
  183862. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  183863. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  183864. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  183865. int iIdx = 0; /* Index to search */
  183866. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  183867. /* Figure out which index to search and set iIdx accordingly. If this
  183868. ** is a prefix query for which there is no prefix index, set iIdx to
  183869. ** greater than pConfig->nPrefix to indicate that the query will be
  183870. ** satisfied by scanning multiple terms in the main index.
  183871. **
  183872. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  183873. ** prefix-query. Instead of using a prefix-index (if one exists),
  183874. ** evaluate the prefix query using the main FTS index. This is used
  183875. ** for internal sanity checking by the integrity-check in debug
  183876. ** mode only. */
  183877. #ifdef SQLITE_DEBUG
  183878. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  183879. assert( flags & FTS5INDEX_QUERY_PREFIX );
  183880. iIdx = 1+pConfig->nPrefix;
  183881. }else
  183882. #endif
  183883. if( flags & FTS5INDEX_QUERY_PREFIX ){
  183884. int nChar = fts5IndexCharlen(pToken, nToken);
  183885. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  183886. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  183887. }
  183888. }
  183889. if( iIdx<=pConfig->nPrefix ){
  183890. /* Straight index lookup */
  183891. Fts5Structure *pStruct = fts5StructureRead(p);
  183892. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  183893. if( pStruct ){
  183894. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  183895. pColset, buf.p, nToken+1, -1, 0, &pRet
  183896. );
  183897. fts5StructureRelease(pStruct);
  183898. }
  183899. }else{
  183900. /* Scan multiple terms in the main index */
  183901. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  183902. buf.p[0] = FTS5_MAIN_PREFIX;
  183903. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  183904. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  183905. fts5IterSetOutputCb(&p->rc, pRet);
  183906. if( p->rc==SQLITE_OK ){
  183907. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  183908. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  183909. }
  183910. }
  183911. if( p->rc ){
  183912. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  183913. pRet = 0;
  183914. fts5CloseReader(p);
  183915. }
  183916. *ppIter = &pRet->base;
  183917. sqlite3Fts5BufferFree(&buf);
  183918. }
  183919. return fts5IndexReturn(p);
  183920. }
  183921. /*
  183922. ** Return true if the iterator passed as the only argument is at EOF.
  183923. */
  183924. /*
  183925. ** Move to the next matching rowid.
  183926. */
  183927. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  183928. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  183929. assert( pIter->pIndex->rc==SQLITE_OK );
  183930. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  183931. return fts5IndexReturn(pIter->pIndex);
  183932. }
  183933. /*
  183934. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  183935. */
  183936. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  183937. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  183938. Fts5Index *p = pIter->pIndex;
  183939. assert( pIter->pIndex->rc==SQLITE_OK );
  183940. fts5MultiIterNext(p, pIter, 0, 0);
  183941. if( p->rc==SQLITE_OK ){
  183942. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  183943. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  183944. fts5DataRelease(pSeg->pLeaf);
  183945. pSeg->pLeaf = 0;
  183946. pIter->base.bEof = 1;
  183947. }
  183948. }
  183949. return fts5IndexReturn(pIter->pIndex);
  183950. }
  183951. /*
  183952. ** Move to the next matching rowid that occurs at or after iMatch. The
  183953. ** definition of "at or after" depends on whether this iterator iterates
  183954. ** in ascending or descending rowid order.
  183955. */
  183956. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  183957. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  183958. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  183959. return fts5IndexReturn(pIter->pIndex);
  183960. }
  183961. /*
  183962. ** Return the current term.
  183963. */
  183964. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  183965. int n;
  183966. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  183967. *pn = n-1;
  183968. return &z[1];
  183969. }
  183970. /*
  183971. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  183972. */
  183973. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  183974. if( pIndexIter ){
  183975. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  183976. Fts5Index *pIndex = pIter->pIndex;
  183977. fts5MultiIterFree(pIter);
  183978. fts5CloseReader(pIndex);
  183979. }
  183980. }
  183981. /*
  183982. ** Read and decode the "averages" record from the database.
  183983. **
  183984. ** Parameter anSize must point to an array of size nCol, where nCol is
  183985. ** the number of user defined columns in the FTS table.
  183986. */
  183987. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  183988. int nCol = p->pConfig->nCol;
  183989. Fts5Data *pData;
  183990. *pnRow = 0;
  183991. memset(anSize, 0, sizeof(i64) * nCol);
  183992. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  183993. if( p->rc==SQLITE_OK && pData->nn ){
  183994. int i = 0;
  183995. int iCol;
  183996. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  183997. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  183998. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  183999. }
  184000. }
  184001. fts5DataRelease(pData);
  184002. return fts5IndexReturn(p);
  184003. }
  184004. /*
  184005. ** Replace the current "averages" record with the contents of the buffer
  184006. ** supplied as the second argument.
  184007. */
  184008. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  184009. assert( p->rc==SQLITE_OK );
  184010. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  184011. return fts5IndexReturn(p);
  184012. }
  184013. /*
  184014. ** Return the total number of blocks this module has read from the %_data
  184015. ** table since it was created.
  184016. */
  184017. static int sqlite3Fts5IndexReads(Fts5Index *p){
  184018. return p->nRead;
  184019. }
  184020. /*
  184021. ** Set the 32-bit cookie value stored at the start of all structure
  184022. ** records to the value passed as the second argument.
  184023. **
  184024. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  184025. ** occurs.
  184026. */
  184027. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  184028. int rc; /* Return code */
  184029. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  184030. u8 aCookie[4]; /* Binary representation of iNew */
  184031. sqlite3_blob *pBlob = 0;
  184032. assert( p->rc==SQLITE_OK );
  184033. sqlite3Fts5Put32(aCookie, iNew);
  184034. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  184035. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  184036. );
  184037. if( rc==SQLITE_OK ){
  184038. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  184039. rc = sqlite3_blob_close(pBlob);
  184040. }
  184041. return rc;
  184042. }
  184043. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  184044. Fts5Structure *pStruct;
  184045. pStruct = fts5StructureRead(p);
  184046. fts5StructureRelease(pStruct);
  184047. return fts5IndexReturn(p);
  184048. }
  184049. /*************************************************************************
  184050. **************************************************************************
  184051. ** Below this point is the implementation of the integrity-check
  184052. ** functionality.
  184053. */
  184054. /*
  184055. ** Return a simple checksum value based on the arguments.
  184056. */
  184057. static u64 sqlite3Fts5IndexEntryCksum(
  184058. i64 iRowid,
  184059. int iCol,
  184060. int iPos,
  184061. int iIdx,
  184062. const char *pTerm,
  184063. int nTerm
  184064. ){
  184065. int i;
  184066. u64 ret = iRowid;
  184067. ret += (ret<<3) + iCol;
  184068. ret += (ret<<3) + iPos;
  184069. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  184070. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  184071. return ret;
  184072. }
  184073. #ifdef SQLITE_DEBUG
  184074. /*
  184075. ** This function is purely an internal test. It does not contribute to
  184076. ** FTS functionality, or even the integrity-check, in any way.
  184077. **
  184078. ** Instead, it tests that the same set of pgno/rowid combinations are
  184079. ** visited regardless of whether the doclist-index identified by parameters
  184080. ** iSegid/iLeaf is iterated in forwards or reverse order.
  184081. */
  184082. static void fts5TestDlidxReverse(
  184083. Fts5Index *p,
  184084. int iSegid, /* Segment id to load from */
  184085. int iLeaf /* Load doclist-index for this leaf */
  184086. ){
  184087. Fts5DlidxIter *pDlidx = 0;
  184088. u64 cksum1 = 13;
  184089. u64 cksum2 = 13;
  184090. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  184091. fts5DlidxIterEof(p, pDlidx)==0;
  184092. fts5DlidxIterNext(p, pDlidx)
  184093. ){
  184094. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  184095. int pgno = fts5DlidxIterPgno(pDlidx);
  184096. assert( pgno>iLeaf );
  184097. cksum1 += iRowid + ((i64)pgno<<32);
  184098. }
  184099. fts5DlidxIterFree(pDlidx);
  184100. pDlidx = 0;
  184101. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  184102. fts5DlidxIterEof(p, pDlidx)==0;
  184103. fts5DlidxIterPrev(p, pDlidx)
  184104. ){
  184105. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  184106. int pgno = fts5DlidxIterPgno(pDlidx);
  184107. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  184108. cksum2 += iRowid + ((i64)pgno<<32);
  184109. }
  184110. fts5DlidxIterFree(pDlidx);
  184111. pDlidx = 0;
  184112. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  184113. }
  184114. static int fts5QueryCksum(
  184115. Fts5Index *p, /* Fts5 index object */
  184116. int iIdx,
  184117. const char *z, /* Index key to query for */
  184118. int n, /* Size of index key in bytes */
  184119. int flags, /* Flags for Fts5IndexQuery */
  184120. u64 *pCksum /* IN/OUT: Checksum value */
  184121. ){
  184122. int eDetail = p->pConfig->eDetail;
  184123. u64 cksum = *pCksum;
  184124. Fts5IndexIter *pIter = 0;
  184125. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  184126. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  184127. i64 rowid = pIter->iRowid;
  184128. if( eDetail==FTS5_DETAIL_NONE ){
  184129. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  184130. }else{
  184131. Fts5PoslistReader sReader;
  184132. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  184133. sReader.bEof==0;
  184134. sqlite3Fts5PoslistReaderNext(&sReader)
  184135. ){
  184136. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  184137. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  184138. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  184139. }
  184140. }
  184141. if( rc==SQLITE_OK ){
  184142. rc = sqlite3Fts5IterNext(pIter);
  184143. }
  184144. }
  184145. sqlite3Fts5IterClose(pIter);
  184146. *pCksum = cksum;
  184147. return rc;
  184148. }
  184149. /*
  184150. ** This function is also purely an internal test. It does not contribute to
  184151. ** FTS functionality, or even the integrity-check, in any way.
  184152. */
  184153. static void fts5TestTerm(
  184154. Fts5Index *p,
  184155. Fts5Buffer *pPrev, /* Previous term */
  184156. const char *z, int n, /* Possibly new term to test */
  184157. u64 expected,
  184158. u64 *pCksum
  184159. ){
  184160. int rc = p->rc;
  184161. if( pPrev->n==0 ){
  184162. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  184163. }else
  184164. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  184165. u64 cksum3 = *pCksum;
  184166. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  184167. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  184168. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  184169. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  184170. u64 ck1 = 0;
  184171. u64 ck2 = 0;
  184172. /* Check that the results returned for ASC and DESC queries are
  184173. ** the same. If not, call this corruption. */
  184174. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  184175. if( rc==SQLITE_OK ){
  184176. int f = flags|FTS5INDEX_QUERY_DESC;
  184177. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  184178. }
  184179. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  184180. /* If this is a prefix query, check that the results returned if the
  184181. ** the index is disabled are the same. In both ASC and DESC order.
  184182. **
  184183. ** This check may only be performed if the hash table is empty. This
  184184. ** is because the hash table only supports a single scan query at
  184185. ** a time, and the multi-iter loop from which this function is called
  184186. ** is already performing such a scan. */
  184187. if( p->nPendingData==0 ){
  184188. if( iIdx>0 && rc==SQLITE_OK ){
  184189. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  184190. ck2 = 0;
  184191. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  184192. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  184193. }
  184194. if( iIdx>0 && rc==SQLITE_OK ){
  184195. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  184196. ck2 = 0;
  184197. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  184198. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  184199. }
  184200. }
  184201. cksum3 ^= ck1;
  184202. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  184203. if( rc==SQLITE_OK && cksum3!=expected ){
  184204. rc = FTS5_CORRUPT;
  184205. }
  184206. *pCksum = cksum3;
  184207. }
  184208. p->rc = rc;
  184209. }
  184210. #else
  184211. # define fts5TestDlidxReverse(x,y,z)
  184212. # define fts5TestTerm(u,v,w,x,y,z)
  184213. #endif
  184214. /*
  184215. ** Check that:
  184216. **
  184217. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  184218. ** contain zero terms.
  184219. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  184220. ** contain zero rowids.
  184221. */
  184222. static void fts5IndexIntegrityCheckEmpty(
  184223. Fts5Index *p,
  184224. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  184225. int iFirst,
  184226. int iNoRowid,
  184227. int iLast
  184228. ){
  184229. int i;
  184230. /* Now check that the iter.nEmpty leaves following the current leaf
  184231. ** (a) exist and (b) contain no terms. */
  184232. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  184233. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  184234. if( pLeaf ){
  184235. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  184236. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  184237. }
  184238. fts5DataRelease(pLeaf);
  184239. }
  184240. }
  184241. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  184242. int iTermOff = 0;
  184243. int ii;
  184244. Fts5Buffer buf1 = {0,0,0};
  184245. Fts5Buffer buf2 = {0,0,0};
  184246. ii = pLeaf->szLeaf;
  184247. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  184248. int res;
  184249. int iOff;
  184250. int nIncr;
  184251. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  184252. iTermOff += nIncr;
  184253. iOff = iTermOff;
  184254. if( iOff>=pLeaf->szLeaf ){
  184255. p->rc = FTS5_CORRUPT;
  184256. }else if( iTermOff==nIncr ){
  184257. int nByte;
  184258. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  184259. if( (iOff+nByte)>pLeaf->szLeaf ){
  184260. p->rc = FTS5_CORRUPT;
  184261. }else{
  184262. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  184263. }
  184264. }else{
  184265. int nKeep, nByte;
  184266. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  184267. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  184268. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  184269. p->rc = FTS5_CORRUPT;
  184270. }else{
  184271. buf1.n = nKeep;
  184272. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  184273. }
  184274. if( p->rc==SQLITE_OK ){
  184275. res = fts5BufferCompare(&buf1, &buf2);
  184276. if( res<=0 ) p->rc = FTS5_CORRUPT;
  184277. }
  184278. }
  184279. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  184280. }
  184281. fts5BufferFree(&buf1);
  184282. fts5BufferFree(&buf2);
  184283. }
  184284. static void fts5IndexIntegrityCheckSegment(
  184285. Fts5Index *p, /* FTS5 backend object */
  184286. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  184287. ){
  184288. Fts5Config *pConfig = p->pConfig;
  184289. sqlite3_stmt *pStmt = 0;
  184290. int rc2;
  184291. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  184292. int iDlidxPrevLeaf = pSeg->pgnoLast;
  184293. if( pSeg->pgnoFirst==0 ) return;
  184294. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  184295. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  184296. pConfig->zDb, pConfig->zName, pSeg->iSegid
  184297. ));
  184298. /* Iterate through the b-tree hierarchy. */
  184299. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  184300. i64 iRow; /* Rowid for this leaf */
  184301. Fts5Data *pLeaf; /* Data for this leaf */
  184302. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  184303. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  184304. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  184305. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  184306. /* If the leaf in question has already been trimmed from the segment,
  184307. ** ignore this b-tree entry. Otherwise, load it into memory. */
  184308. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  184309. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  184310. pLeaf = fts5LeafRead(p, iRow);
  184311. if( pLeaf==0 ) break;
  184312. /* Check that the leaf contains at least one term, and that it is equal
  184313. ** to or larger than the split-key in zIdxTerm. Also check that if there
  184314. ** is also a rowid pointer within the leaf page header, it points to a
  184315. ** location before the term. */
  184316. if( pLeaf->nn<=pLeaf->szLeaf ){
  184317. p->rc = FTS5_CORRUPT;
  184318. }else{
  184319. int iOff; /* Offset of first term on leaf */
  184320. int iRowidOff; /* Offset of first rowid on leaf */
  184321. int nTerm; /* Size of term on leaf in bytes */
  184322. int res; /* Comparison of term and split-key */
  184323. iOff = fts5LeafFirstTermOff(pLeaf);
  184324. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  184325. if( iRowidOff>=iOff ){
  184326. p->rc = FTS5_CORRUPT;
  184327. }else{
  184328. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  184329. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  184330. if( res==0 ) res = nTerm - nIdxTerm;
  184331. if( res<0 ) p->rc = FTS5_CORRUPT;
  184332. }
  184333. fts5IntegrityCheckPgidx(p, pLeaf);
  184334. }
  184335. fts5DataRelease(pLeaf);
  184336. if( p->rc ) break;
  184337. /* Now check that the iter.nEmpty leaves following the current leaf
  184338. ** (a) exist and (b) contain no terms. */
  184339. fts5IndexIntegrityCheckEmpty(
  184340. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  184341. );
  184342. if( p->rc ) break;
  184343. /* If there is a doclist-index, check that it looks right. */
  184344. if( bIdxDlidx ){
  184345. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  184346. int iPrevLeaf = iIdxLeaf;
  184347. int iSegid = pSeg->iSegid;
  184348. int iPg = 0;
  184349. i64 iKey;
  184350. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  184351. fts5DlidxIterEof(p, pDlidx)==0;
  184352. fts5DlidxIterNext(p, pDlidx)
  184353. ){
  184354. /* Check any rowid-less pages that occur before the current leaf. */
  184355. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  184356. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  184357. pLeaf = fts5DataRead(p, iKey);
  184358. if( pLeaf ){
  184359. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  184360. fts5DataRelease(pLeaf);
  184361. }
  184362. }
  184363. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  184364. /* Check that the leaf page indicated by the iterator really does
  184365. ** contain the rowid suggested by the same. */
  184366. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  184367. pLeaf = fts5DataRead(p, iKey);
  184368. if( pLeaf ){
  184369. i64 iRowid;
  184370. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  184371. ASSERT_SZLEAF_OK(pLeaf);
  184372. if( iRowidOff>=pLeaf->szLeaf ){
  184373. p->rc = FTS5_CORRUPT;
  184374. }else{
  184375. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  184376. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  184377. }
  184378. fts5DataRelease(pLeaf);
  184379. }
  184380. }
  184381. iDlidxPrevLeaf = iPg;
  184382. fts5DlidxIterFree(pDlidx);
  184383. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  184384. }else{
  184385. iDlidxPrevLeaf = pSeg->pgnoLast;
  184386. /* TODO: Check there is no doclist index */
  184387. }
  184388. iIdxPrevLeaf = iIdxLeaf;
  184389. }
  184390. rc2 = sqlite3_finalize(pStmt);
  184391. if( p->rc==SQLITE_OK ) p->rc = rc2;
  184392. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  184393. #if 0
  184394. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  184395. p->rc = FTS5_CORRUPT;
  184396. }
  184397. #endif
  184398. }
  184399. /*
  184400. ** Run internal checks to ensure that the FTS index (a) is internally
  184401. ** consistent and (b) contains entries for which the XOR of the checksums
  184402. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  184403. **
  184404. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  184405. ** checksum does not match. Return SQLITE_OK if all checks pass without
  184406. ** error, or some other SQLite error code if another error (e.g. OOM)
  184407. ** occurs.
  184408. */
  184409. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  184410. int eDetail = p->pConfig->eDetail;
  184411. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  184412. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  184413. Fts5Iter *pIter; /* Used to iterate through entire index */
  184414. Fts5Structure *pStruct; /* Index structure */
  184415. #ifdef SQLITE_DEBUG
  184416. /* Used by extra internal tests only run if NDEBUG is not defined */
  184417. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  184418. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  184419. #endif
  184420. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  184421. /* Load the FTS index structure */
  184422. pStruct = fts5StructureRead(p);
  184423. /* Check that the internal nodes of each segment match the leaves */
  184424. if( pStruct ){
  184425. int iLvl, iSeg;
  184426. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  184427. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  184428. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  184429. fts5IndexIntegrityCheckSegment(p, pSeg);
  184430. }
  184431. }
  184432. }
  184433. /* The cksum argument passed to this function is a checksum calculated
  184434. ** based on all expected entries in the FTS index (including prefix index
  184435. ** entries). This block checks that a checksum calculated based on the
  184436. ** actual contents of FTS index is identical.
  184437. **
  184438. ** Two versions of the same checksum are calculated. The first (stack
  184439. ** variable cksum2) based on entries extracted from the full-text index
  184440. ** while doing a linear scan of each individual index in turn.
  184441. **
  184442. ** As each term visited by the linear scans, a separate query for the
  184443. ** same term is performed. cksum3 is calculated based on the entries
  184444. ** extracted by these queries.
  184445. */
  184446. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  184447. fts5MultiIterEof(p, pIter)==0;
  184448. fts5MultiIterNext(p, pIter, 0, 0)
  184449. ){
  184450. int n; /* Size of term in bytes */
  184451. i64 iPos = 0; /* Position read from poslist */
  184452. int iOff = 0; /* Offset within poslist */
  184453. i64 iRowid = fts5MultiIterRowid(pIter);
  184454. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  184455. /* If this is a new term, query for it. Update cksum3 with the results. */
  184456. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  184457. if( eDetail==FTS5_DETAIL_NONE ){
  184458. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  184459. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  184460. }
  184461. }else{
  184462. poslist.n = 0;
  184463. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  184464. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  184465. int iCol = FTS5_POS2COLUMN(iPos);
  184466. int iTokOff = FTS5_POS2OFFSET(iPos);
  184467. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  184468. }
  184469. }
  184470. }
  184471. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  184472. fts5MultiIterFree(pIter);
  184473. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  184474. fts5StructureRelease(pStruct);
  184475. #ifdef SQLITE_DEBUG
  184476. fts5BufferFree(&term);
  184477. #endif
  184478. fts5BufferFree(&poslist);
  184479. return fts5IndexReturn(p);
  184480. }
  184481. /*************************************************************************
  184482. **************************************************************************
  184483. ** Below this point is the implementation of the fts5_decode() scalar
  184484. ** function only.
  184485. */
  184486. /*
  184487. ** Decode a segment-data rowid from the %_data table. This function is
  184488. ** the opposite of macro FTS5_SEGMENT_ROWID().
  184489. */
  184490. static void fts5DecodeRowid(
  184491. i64 iRowid, /* Rowid from %_data table */
  184492. int *piSegid, /* OUT: Segment id */
  184493. int *pbDlidx, /* OUT: Dlidx flag */
  184494. int *piHeight, /* OUT: Height */
  184495. int *piPgno /* OUT: Page number */
  184496. ){
  184497. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  184498. iRowid >>= FTS5_DATA_PAGE_B;
  184499. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  184500. iRowid >>= FTS5_DATA_HEIGHT_B;
  184501. *pbDlidx = (int)(iRowid & 0x0001);
  184502. iRowid >>= FTS5_DATA_DLI_B;
  184503. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  184504. }
  184505. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  184506. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  184507. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  184508. if( iSegid==0 ){
  184509. if( iKey==FTS5_AVERAGES_ROWID ){
  184510. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  184511. }else{
  184512. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  184513. }
  184514. }
  184515. else{
  184516. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  184517. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  184518. );
  184519. }
  184520. }
  184521. static void fts5DebugStructure(
  184522. int *pRc, /* IN/OUT: error code */
  184523. Fts5Buffer *pBuf,
  184524. Fts5Structure *p
  184525. ){
  184526. int iLvl, iSeg; /* Iterate through levels, segments */
  184527. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  184528. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  184529. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  184530. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  184531. );
  184532. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  184533. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  184534. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  184535. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  184536. );
  184537. }
  184538. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  184539. }
  184540. }
  184541. /*
  184542. ** This is part of the fts5_decode() debugging aid.
  184543. **
  184544. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  184545. ** function appends a human-readable representation of the same object
  184546. ** to the buffer passed as the second argument.
  184547. */
  184548. static void fts5DecodeStructure(
  184549. int *pRc, /* IN/OUT: error code */
  184550. Fts5Buffer *pBuf,
  184551. const u8 *pBlob, int nBlob
  184552. ){
  184553. int rc; /* Return code */
  184554. Fts5Structure *p = 0; /* Decoded structure object */
  184555. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  184556. if( rc!=SQLITE_OK ){
  184557. *pRc = rc;
  184558. return;
  184559. }
  184560. fts5DebugStructure(pRc, pBuf, p);
  184561. fts5StructureRelease(p);
  184562. }
  184563. /*
  184564. ** This is part of the fts5_decode() debugging aid.
  184565. **
  184566. ** Arguments pBlob/nBlob contain an "averages" record. This function
  184567. ** appends a human-readable representation of record to the buffer passed
  184568. ** as the second argument.
  184569. */
  184570. static void fts5DecodeAverages(
  184571. int *pRc, /* IN/OUT: error code */
  184572. Fts5Buffer *pBuf,
  184573. const u8 *pBlob, int nBlob
  184574. ){
  184575. int i = 0;
  184576. const char *zSpace = "";
  184577. while( i<nBlob ){
  184578. u64 iVal;
  184579. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  184580. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  184581. zSpace = " ";
  184582. }
  184583. }
  184584. /*
  184585. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  184586. ** each varint and append its string representation to buffer pBuf. Return
  184587. ** after either the input buffer is exhausted or a 0 value is read.
  184588. **
  184589. ** The return value is the number of bytes read from the input buffer.
  184590. */
  184591. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  184592. int iOff = 0;
  184593. while( iOff<n ){
  184594. int iVal;
  184595. iOff += fts5GetVarint32(&a[iOff], iVal);
  184596. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  184597. }
  184598. return iOff;
  184599. }
  184600. /*
  184601. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  184602. ** may or may not finish within the buffer. This function appends a text
  184603. ** representation of the part of the doclist that is present to buffer
  184604. ** pBuf.
  184605. **
  184606. ** The return value is the number of bytes read from the input buffer.
  184607. */
  184608. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  184609. i64 iDocid = 0;
  184610. int iOff = 0;
  184611. if( n>0 ){
  184612. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  184613. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  184614. }
  184615. while( iOff<n ){
  184616. int nPos;
  184617. int bDel;
  184618. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  184619. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  184620. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  184621. if( iOff<n ){
  184622. i64 iDelta;
  184623. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  184624. iDocid += iDelta;
  184625. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  184626. }
  184627. }
  184628. return iOff;
  184629. }
  184630. /*
  184631. ** This function is part of the fts5_decode() debugging function. It is
  184632. ** only ever used with detail=none tables.
  184633. **
  184634. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  184635. ** tables. This function appends a human-readable version of that list to
  184636. ** buffer pBuf.
  184637. **
  184638. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  184639. ** no-op. If an OOM or other error occurs within this function, *pRc is
  184640. ** set to an SQLite error code before returning. The final state of buffer
  184641. ** pBuf is undefined in this case.
  184642. */
  184643. static void fts5DecodeRowidList(
  184644. int *pRc, /* IN/OUT: Error code */
  184645. Fts5Buffer *pBuf, /* Buffer to append text to */
  184646. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  184647. ){
  184648. int i = 0;
  184649. i64 iRowid = 0;
  184650. while( i<nData ){
  184651. const char *zApp = "";
  184652. u64 iVal;
  184653. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  184654. iRowid += iVal;
  184655. if( i<nData && pData[i]==0x00 ){
  184656. i++;
  184657. if( i<nData && pData[i]==0x00 ){
  184658. i++;
  184659. zApp = "+";
  184660. }else{
  184661. zApp = "*";
  184662. }
  184663. }
  184664. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  184665. }
  184666. }
  184667. /*
  184668. ** The implementation of user-defined scalar function fts5_decode().
  184669. */
  184670. static void fts5DecodeFunction(
  184671. sqlite3_context *pCtx, /* Function call context */
  184672. int nArg, /* Number of args (always 2) */
  184673. sqlite3_value **apVal /* Function arguments */
  184674. ){
  184675. i64 iRowid; /* Rowid for record being decoded */
  184676. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  184677. const u8 *aBlob; int n; /* Record to decode */
  184678. u8 *a = 0;
  184679. Fts5Buffer s; /* Build up text to return here */
  184680. int rc = SQLITE_OK; /* Return code */
  184681. int nSpace = 0;
  184682. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  184683. assert( nArg==2 );
  184684. UNUSED_PARAM(nArg);
  184685. memset(&s, 0, sizeof(Fts5Buffer));
  184686. iRowid = sqlite3_value_int64(apVal[0]);
  184687. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  184688. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  184689. ** buffer overreads even if the record is corrupt. */
  184690. n = sqlite3_value_bytes(apVal[1]);
  184691. aBlob = sqlite3_value_blob(apVal[1]);
  184692. nSpace = n + FTS5_DATA_ZERO_PADDING;
  184693. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  184694. if( a==0 ) goto decode_out;
  184695. memcpy(a, aBlob, n);
  184696. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  184697. fts5DebugRowid(&rc, &s, iRowid);
  184698. if( bDlidx ){
  184699. Fts5Data dlidx;
  184700. Fts5DlidxLvl lvl;
  184701. dlidx.p = a;
  184702. dlidx.nn = n;
  184703. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  184704. lvl.pData = &dlidx;
  184705. lvl.iLeafPgno = iPgno;
  184706. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  184707. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  184708. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  184709. );
  184710. }
  184711. }else if( iSegid==0 ){
  184712. if( iRowid==FTS5_AVERAGES_ROWID ){
  184713. fts5DecodeAverages(&rc, &s, a, n);
  184714. }else{
  184715. fts5DecodeStructure(&rc, &s, a, n);
  184716. }
  184717. }else if( eDetailNone ){
  184718. Fts5Buffer term; /* Current term read from page */
  184719. int szLeaf;
  184720. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  184721. int iTermOff;
  184722. int nKeep = 0;
  184723. int iOff;
  184724. memset(&term, 0, sizeof(Fts5Buffer));
  184725. /* Decode any entries that occur before the first term. */
  184726. if( szLeaf<n ){
  184727. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  184728. }else{
  184729. iTermOff = szLeaf;
  184730. }
  184731. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  184732. iOff = iTermOff;
  184733. while( iOff<szLeaf ){
  184734. int nAppend;
  184735. /* Read the term data for the next term*/
  184736. iOff += fts5GetVarint32(&a[iOff], nAppend);
  184737. term.n = nKeep;
  184738. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  184739. sqlite3Fts5BufferAppendPrintf(
  184740. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  184741. );
  184742. iOff += nAppend;
  184743. /* Figure out where the doclist for this term ends */
  184744. if( iPgidxOff<n ){
  184745. int nIncr;
  184746. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  184747. iTermOff += nIncr;
  184748. }else{
  184749. iTermOff = szLeaf;
  184750. }
  184751. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  184752. iOff = iTermOff;
  184753. if( iOff<szLeaf ){
  184754. iOff += fts5GetVarint32(&a[iOff], nKeep);
  184755. }
  184756. }
  184757. fts5BufferFree(&term);
  184758. }else{
  184759. Fts5Buffer term; /* Current term read from page */
  184760. int szLeaf; /* Offset of pgidx in a[] */
  184761. int iPgidxOff;
  184762. int iPgidxPrev = 0; /* Previous value read from pgidx */
  184763. int iTermOff = 0;
  184764. int iRowidOff = 0;
  184765. int iOff;
  184766. int nDoclist;
  184767. memset(&term, 0, sizeof(Fts5Buffer));
  184768. if( n<4 ){
  184769. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  184770. goto decode_out;
  184771. }else{
  184772. iRowidOff = fts5GetU16(&a[0]);
  184773. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  184774. if( iPgidxOff<n ){
  184775. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  184776. }
  184777. }
  184778. /* Decode the position list tail at the start of the page */
  184779. if( iRowidOff!=0 ){
  184780. iOff = iRowidOff;
  184781. }else if( iTermOff!=0 ){
  184782. iOff = iTermOff;
  184783. }else{
  184784. iOff = szLeaf;
  184785. }
  184786. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  184787. /* Decode any more doclist data that appears on the page before the
  184788. ** first term. */
  184789. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  184790. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  184791. while( iPgidxOff<n ){
  184792. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  184793. int nByte; /* Bytes of data */
  184794. int iEnd;
  184795. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  184796. iPgidxPrev += nByte;
  184797. iOff = iPgidxPrev;
  184798. if( iPgidxOff<n ){
  184799. fts5GetVarint32(&a[iPgidxOff], nByte);
  184800. iEnd = iPgidxPrev + nByte;
  184801. }else{
  184802. iEnd = szLeaf;
  184803. }
  184804. if( bFirst==0 ){
  184805. iOff += fts5GetVarint32(&a[iOff], nByte);
  184806. term.n = nByte;
  184807. }
  184808. iOff += fts5GetVarint32(&a[iOff], nByte);
  184809. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  184810. iOff += nByte;
  184811. sqlite3Fts5BufferAppendPrintf(
  184812. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  184813. );
  184814. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  184815. }
  184816. fts5BufferFree(&term);
  184817. }
  184818. decode_out:
  184819. sqlite3_free(a);
  184820. if( rc==SQLITE_OK ){
  184821. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  184822. }else{
  184823. sqlite3_result_error_code(pCtx, rc);
  184824. }
  184825. fts5BufferFree(&s);
  184826. }
  184827. /*
  184828. ** The implementation of user-defined scalar function fts5_rowid().
  184829. */
  184830. static void fts5RowidFunction(
  184831. sqlite3_context *pCtx, /* Function call context */
  184832. int nArg, /* Number of args (always 2) */
  184833. sqlite3_value **apVal /* Function arguments */
  184834. ){
  184835. const char *zArg;
  184836. if( nArg==0 ){
  184837. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  184838. }else{
  184839. zArg = (const char*)sqlite3_value_text(apVal[0]);
  184840. if( 0==sqlite3_stricmp(zArg, "segment") ){
  184841. i64 iRowid;
  184842. int segid, pgno;
  184843. if( nArg!=3 ){
  184844. sqlite3_result_error(pCtx,
  184845. "should be: fts5_rowid('segment', segid, pgno))", -1
  184846. );
  184847. }else{
  184848. segid = sqlite3_value_int(apVal[1]);
  184849. pgno = sqlite3_value_int(apVal[2]);
  184850. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  184851. sqlite3_result_int64(pCtx, iRowid);
  184852. }
  184853. }else{
  184854. sqlite3_result_error(pCtx,
  184855. "first arg to fts5_rowid() must be 'segment'" , -1
  184856. );
  184857. }
  184858. }
  184859. }
  184860. /*
  184861. ** This is called as part of registering the FTS5 module with database
  184862. ** connection db. It registers several user-defined scalar functions useful
  184863. ** with FTS5.
  184864. **
  184865. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  184866. ** SQLite error code is returned instead.
  184867. */
  184868. static int sqlite3Fts5IndexInit(sqlite3 *db){
  184869. int rc = sqlite3_create_function(
  184870. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  184871. );
  184872. if( rc==SQLITE_OK ){
  184873. rc = sqlite3_create_function(
  184874. db, "fts5_decode_none", 2,
  184875. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  184876. );
  184877. }
  184878. if( rc==SQLITE_OK ){
  184879. rc = sqlite3_create_function(
  184880. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  184881. );
  184882. }
  184883. return rc;
  184884. }
  184885. static int sqlite3Fts5IndexReset(Fts5Index *p){
  184886. assert( p->pStruct==0 || p->iStructVersion!=0 );
  184887. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  184888. fts5StructureInvalidate(p);
  184889. }
  184890. return fts5IndexReturn(p);
  184891. }
  184892. /*
  184893. ** 2014 Jun 09
  184894. **
  184895. ** The author disclaims copyright to this source code. In place of
  184896. ** a legal notice, here is a blessing:
  184897. **
  184898. ** May you do good and not evil.
  184899. ** May you find forgiveness for yourself and forgive others.
  184900. ** May you share freely, never taking more than you give.
  184901. **
  184902. ******************************************************************************
  184903. **
  184904. ** This is an SQLite module implementing full-text search.
  184905. */
  184906. /* #include "fts5Int.h" */
  184907. /*
  184908. ** This variable is set to false when running tests for which the on disk
  184909. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  184910. ** assert() conditions in the fts5 code are activated - conditions that are
  184911. ** only true if it is guaranteed that the fts5 database is not corrupt.
  184912. */
  184913. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  184914. typedef struct Fts5Auxdata Fts5Auxdata;
  184915. typedef struct Fts5Auxiliary Fts5Auxiliary;
  184916. typedef struct Fts5Cursor Fts5Cursor;
  184917. typedef struct Fts5Sorter Fts5Sorter;
  184918. typedef struct Fts5Table Fts5Table;
  184919. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  184920. /*
  184921. ** NOTES ON TRANSACTIONS:
  184922. **
  184923. ** SQLite invokes the following virtual table methods as transactions are
  184924. ** opened and closed by the user:
  184925. **
  184926. ** xBegin(): Start of a new transaction.
  184927. ** xSync(): Initial part of two-phase commit.
  184928. ** xCommit(): Final part of two-phase commit.
  184929. ** xRollback(): Rollback the transaction.
  184930. **
  184931. ** Anything that is required as part of a commit that may fail is performed
  184932. ** in the xSync() callback. Current versions of SQLite ignore any errors
  184933. ** returned by xCommit().
  184934. **
  184935. ** And as sub-transactions are opened/closed:
  184936. **
  184937. ** xSavepoint(int S): Open savepoint S.
  184938. ** xRelease(int S): Commit and close savepoint S.
  184939. ** xRollbackTo(int S): Rollback to start of savepoint S.
  184940. **
  184941. ** During a write-transaction the fts5_index.c module may cache some data
  184942. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  184943. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  184944. ** is called.
  184945. **
  184946. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  184947. ** structure is used to record the current transaction state. This information
  184948. ** is not required, but it is used in the assert() statements executed by
  184949. ** function fts5CheckTransactionState() (see below).
  184950. */
  184951. struct Fts5TransactionState {
  184952. int eState; /* 0==closed, 1==open, 2==synced */
  184953. int iSavepoint; /* Number of open savepoints (0 -> none) */
  184954. };
  184955. /*
  184956. ** A single object of this type is allocated when the FTS5 module is
  184957. ** registered with a database handle. It is used to store pointers to
  184958. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  184959. */
  184960. struct Fts5Global {
  184961. fts5_api api; /* User visible part of object (see fts5.h) */
  184962. sqlite3 *db; /* Associated database connection */
  184963. i64 iNextId; /* Used to allocate unique cursor ids */
  184964. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  184965. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  184966. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  184967. Fts5Cursor *pCsr; /* First in list of all open cursors */
  184968. };
  184969. /*
  184970. ** Each auxiliary function registered with the FTS5 module is represented
  184971. ** by an object of the following type. All such objects are stored as part
  184972. ** of the Fts5Global.pAux list.
  184973. */
  184974. struct Fts5Auxiliary {
  184975. Fts5Global *pGlobal; /* Global context for this function */
  184976. char *zFunc; /* Function name (nul-terminated) */
  184977. void *pUserData; /* User-data pointer */
  184978. fts5_extension_function xFunc; /* Callback function */
  184979. void (*xDestroy)(void*); /* Destructor function */
  184980. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  184981. };
  184982. /*
  184983. ** Each tokenizer module registered with the FTS5 module is represented
  184984. ** by an object of the following type. All such objects are stored as part
  184985. ** of the Fts5Global.pTok list.
  184986. */
  184987. struct Fts5TokenizerModule {
  184988. char *zName; /* Name of tokenizer */
  184989. void *pUserData; /* User pointer passed to xCreate() */
  184990. fts5_tokenizer x; /* Tokenizer functions */
  184991. void (*xDestroy)(void*); /* Destructor function */
  184992. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  184993. };
  184994. /*
  184995. ** Virtual-table object.
  184996. */
  184997. struct Fts5Table {
  184998. sqlite3_vtab base; /* Base class used by SQLite core */
  184999. Fts5Config *pConfig; /* Virtual table configuration */
  185000. Fts5Index *pIndex; /* Full-text index */
  185001. Fts5Storage *pStorage; /* Document store */
  185002. Fts5Global *pGlobal; /* Global (connection wide) data */
  185003. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  185004. #ifdef SQLITE_DEBUG
  185005. struct Fts5TransactionState ts;
  185006. #endif
  185007. };
  185008. struct Fts5MatchPhrase {
  185009. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  185010. int nTerm; /* Size of phrase in terms */
  185011. };
  185012. /*
  185013. ** pStmt:
  185014. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  185015. **
  185016. ** aIdx[]:
  185017. ** There is one entry in the aIdx[] array for each phrase in the query,
  185018. ** the value of which is the offset within aPoslist[] following the last
  185019. ** byte of the position list for the corresponding phrase.
  185020. */
  185021. struct Fts5Sorter {
  185022. sqlite3_stmt *pStmt;
  185023. i64 iRowid; /* Current rowid */
  185024. const u8 *aPoslist; /* Position lists for current row */
  185025. int nIdx; /* Number of entries in aIdx[] */
  185026. int aIdx[1]; /* Offsets into aPoslist for current row */
  185027. };
  185028. /*
  185029. ** Virtual-table cursor object.
  185030. **
  185031. ** iSpecial:
  185032. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  185033. ** then this variable contains the result of the query.
  185034. **
  185035. ** iFirstRowid, iLastRowid:
  185036. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  185037. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  185038. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  185039. ** WHERE clause in the user's query might have been:
  185040. **
  185041. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  185042. **
  185043. ** If the cursor iterates in descending order of rowid, iFirstRowid
  185044. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  185045. ** the lower.
  185046. */
  185047. struct Fts5Cursor {
  185048. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  185049. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  185050. int *aColumnSize; /* Values for xColumnSize() */
  185051. i64 iCsrId; /* Cursor id */
  185052. /* Zero from this point onwards on cursor reset */
  185053. int ePlan; /* FTS5_PLAN_XXX value */
  185054. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  185055. i64 iFirstRowid; /* Return no rowids earlier than this */
  185056. i64 iLastRowid; /* Return no rowids later than this */
  185057. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  185058. Fts5Expr *pExpr; /* Expression for MATCH queries */
  185059. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  185060. int csrflags; /* Mask of cursor flags (see below) */
  185061. i64 iSpecial; /* Result of special query */
  185062. /* "rank" function. Populated on demand from vtab.xColumn(). */
  185063. char *zRank; /* Custom rank function */
  185064. char *zRankArgs; /* Custom rank function args */
  185065. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  185066. int nRankArg; /* Number of trailing arguments for rank() */
  185067. sqlite3_value **apRankArg; /* Array of trailing arguments */
  185068. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  185069. /* Auxiliary data storage */
  185070. Fts5Auxiliary *pAux; /* Currently executing extension function */
  185071. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  185072. /* Cache used by auxiliary functions xInst() and xInstCount() */
  185073. Fts5PoslistReader *aInstIter; /* One for each phrase */
  185074. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  185075. int nInstCount; /* Number of phrase instances */
  185076. int *aInst; /* 3 integers per phrase instance */
  185077. };
  185078. /*
  185079. ** Bits that make up the "idxNum" parameter passed indirectly by
  185080. ** xBestIndex() to xFilter().
  185081. */
  185082. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  185083. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  185084. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  185085. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  185086. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  185087. #define FTS5_BI_ORDER_RANK 0x0020
  185088. #define FTS5_BI_ORDER_ROWID 0x0040
  185089. #define FTS5_BI_ORDER_DESC 0x0080
  185090. /*
  185091. ** Values for Fts5Cursor.csrflags
  185092. */
  185093. #define FTS5CSR_EOF 0x01
  185094. #define FTS5CSR_REQUIRE_CONTENT 0x02
  185095. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  185096. #define FTS5CSR_REQUIRE_INST 0x08
  185097. #define FTS5CSR_FREE_ZRANK 0x10
  185098. #define FTS5CSR_REQUIRE_RESEEK 0x20
  185099. #define FTS5CSR_REQUIRE_POSLIST 0x40
  185100. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  185101. #define BitFlagTest(x,y) (((x) & (y))!=0)
  185102. /*
  185103. ** Macros to Set(), Clear() and Test() cursor flags.
  185104. */
  185105. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  185106. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  185107. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  185108. struct Fts5Auxdata {
  185109. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  185110. void *pPtr; /* Pointer value */
  185111. void(*xDelete)(void*); /* Destructor */
  185112. Fts5Auxdata *pNext; /* Next object in linked list */
  185113. };
  185114. #ifdef SQLITE_DEBUG
  185115. #define FTS5_BEGIN 1
  185116. #define FTS5_SYNC 2
  185117. #define FTS5_COMMIT 3
  185118. #define FTS5_ROLLBACK 4
  185119. #define FTS5_SAVEPOINT 5
  185120. #define FTS5_RELEASE 6
  185121. #define FTS5_ROLLBACKTO 7
  185122. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  185123. switch( op ){
  185124. case FTS5_BEGIN:
  185125. assert( p->ts.eState==0 );
  185126. p->ts.eState = 1;
  185127. p->ts.iSavepoint = -1;
  185128. break;
  185129. case FTS5_SYNC:
  185130. assert( p->ts.eState==1 );
  185131. p->ts.eState = 2;
  185132. break;
  185133. case FTS5_COMMIT:
  185134. assert( p->ts.eState==2 );
  185135. p->ts.eState = 0;
  185136. break;
  185137. case FTS5_ROLLBACK:
  185138. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  185139. p->ts.eState = 0;
  185140. break;
  185141. case FTS5_SAVEPOINT:
  185142. assert( p->ts.eState==1 );
  185143. assert( iSavepoint>=0 );
  185144. assert( iSavepoint>p->ts.iSavepoint );
  185145. p->ts.iSavepoint = iSavepoint;
  185146. break;
  185147. case FTS5_RELEASE:
  185148. assert( p->ts.eState==1 );
  185149. assert( iSavepoint>=0 );
  185150. assert( iSavepoint<=p->ts.iSavepoint );
  185151. p->ts.iSavepoint = iSavepoint-1;
  185152. break;
  185153. case FTS5_ROLLBACKTO:
  185154. assert( p->ts.eState==1 );
  185155. assert( iSavepoint>=0 );
  185156. assert( iSavepoint<=p->ts.iSavepoint );
  185157. p->ts.iSavepoint = iSavepoint;
  185158. break;
  185159. }
  185160. }
  185161. #else
  185162. # define fts5CheckTransactionState(x,y,z)
  185163. #endif
  185164. /*
  185165. ** Return true if pTab is a contentless table.
  185166. */
  185167. static int fts5IsContentless(Fts5Table *pTab){
  185168. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  185169. }
  185170. /*
  185171. ** Delete a virtual table handle allocated by fts5InitVtab().
  185172. */
  185173. static void fts5FreeVtab(Fts5Table *pTab){
  185174. if( pTab ){
  185175. sqlite3Fts5IndexClose(pTab->pIndex);
  185176. sqlite3Fts5StorageClose(pTab->pStorage);
  185177. sqlite3Fts5ConfigFree(pTab->pConfig);
  185178. sqlite3_free(pTab);
  185179. }
  185180. }
  185181. /*
  185182. ** The xDisconnect() virtual table method.
  185183. */
  185184. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  185185. fts5FreeVtab((Fts5Table*)pVtab);
  185186. return SQLITE_OK;
  185187. }
  185188. /*
  185189. ** The xDestroy() virtual table method.
  185190. */
  185191. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  185192. Fts5Table *pTab = (Fts5Table*)pVtab;
  185193. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  185194. if( rc==SQLITE_OK ){
  185195. fts5FreeVtab((Fts5Table*)pVtab);
  185196. }
  185197. return rc;
  185198. }
  185199. /*
  185200. ** This function is the implementation of both the xConnect and xCreate
  185201. ** methods of the FTS3 virtual table.
  185202. **
  185203. ** The argv[] array contains the following:
  185204. **
  185205. ** argv[0] -> module name ("fts5")
  185206. ** argv[1] -> database name
  185207. ** argv[2] -> table name
  185208. ** argv[...] -> "column name" and other module argument fields.
  185209. */
  185210. static int fts5InitVtab(
  185211. int bCreate, /* True for xCreate, false for xConnect */
  185212. sqlite3 *db, /* The SQLite database connection */
  185213. void *pAux, /* Hash table containing tokenizers */
  185214. int argc, /* Number of elements in argv array */
  185215. const char * const *argv, /* xCreate/xConnect argument array */
  185216. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  185217. char **pzErr /* Write any error message here */
  185218. ){
  185219. Fts5Global *pGlobal = (Fts5Global*)pAux;
  185220. const char **azConfig = (const char**)argv;
  185221. int rc = SQLITE_OK; /* Return code */
  185222. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  185223. Fts5Table *pTab = 0; /* New virtual table object */
  185224. /* Allocate the new vtab object and parse the configuration */
  185225. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  185226. if( rc==SQLITE_OK ){
  185227. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  185228. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  185229. }
  185230. if( rc==SQLITE_OK ){
  185231. pTab->pConfig = pConfig;
  185232. pTab->pGlobal = pGlobal;
  185233. }
  185234. /* Open the index sub-system */
  185235. if( rc==SQLITE_OK ){
  185236. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  185237. }
  185238. /* Open the storage sub-system */
  185239. if( rc==SQLITE_OK ){
  185240. rc = sqlite3Fts5StorageOpen(
  185241. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  185242. );
  185243. }
  185244. /* Call sqlite3_declare_vtab() */
  185245. if( rc==SQLITE_OK ){
  185246. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  185247. }
  185248. /* Load the initial configuration */
  185249. if( rc==SQLITE_OK ){
  185250. assert( pConfig->pzErrmsg==0 );
  185251. pConfig->pzErrmsg = pzErr;
  185252. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  185253. sqlite3Fts5IndexRollback(pTab->pIndex);
  185254. pConfig->pzErrmsg = 0;
  185255. }
  185256. if( rc!=SQLITE_OK ){
  185257. fts5FreeVtab(pTab);
  185258. pTab = 0;
  185259. }else if( bCreate ){
  185260. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  185261. }
  185262. *ppVTab = (sqlite3_vtab*)pTab;
  185263. return rc;
  185264. }
  185265. /*
  185266. ** The xConnect() and xCreate() methods for the virtual table. All the
  185267. ** work is done in function fts5InitVtab().
  185268. */
  185269. static int fts5ConnectMethod(
  185270. sqlite3 *db, /* Database connection */
  185271. void *pAux, /* Pointer to tokenizer hash table */
  185272. int argc, /* Number of elements in argv array */
  185273. const char * const *argv, /* xCreate/xConnect argument array */
  185274. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  185275. char **pzErr /* OUT: sqlite3_malloc'd error message */
  185276. ){
  185277. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  185278. }
  185279. static int fts5CreateMethod(
  185280. sqlite3 *db, /* Database connection */
  185281. void *pAux, /* Pointer to tokenizer hash table */
  185282. int argc, /* Number of elements in argv array */
  185283. const char * const *argv, /* xCreate/xConnect argument array */
  185284. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  185285. char **pzErr /* OUT: sqlite3_malloc'd error message */
  185286. ){
  185287. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  185288. }
  185289. /*
  185290. ** The different query plans.
  185291. */
  185292. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  185293. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  185294. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  185295. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  185296. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  185297. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  185298. /*
  185299. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  185300. ** extension is currently being used by a version of SQLite too old to
  185301. ** support index-info flags. In that case this function is a no-op.
  185302. */
  185303. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  185304. #if SQLITE_VERSION_NUMBER>=3008012
  185305. #ifndef SQLITE_CORE
  185306. if( sqlite3_libversion_number()>=3008012 )
  185307. #endif
  185308. {
  185309. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  185310. }
  185311. #endif
  185312. }
  185313. /*
  185314. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  185315. ** WHERE constraint, it searches for the following:
  185316. **
  185317. ** 1. A MATCH constraint against the special column.
  185318. ** 2. A MATCH constraint against the "rank" column.
  185319. ** 3. An == constraint against the rowid column.
  185320. ** 4. A < or <= constraint against the rowid column.
  185321. ** 5. A > or >= constraint against the rowid column.
  185322. **
  185323. ** Within the ORDER BY, either:
  185324. **
  185325. ** 5. ORDER BY rank [ASC|DESC]
  185326. ** 6. ORDER BY rowid [ASC|DESC]
  185327. **
  185328. ** Costs are assigned as follows:
  185329. **
  185330. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  185331. ** cost is unconditionally set to 1e50 (a really big number).
  185332. **
  185333. ** a) If a MATCH operator is present, the cost depends on the other
  185334. ** constraints also present. As follows:
  185335. **
  185336. ** * No other constraints: cost=1000.0
  185337. ** * One rowid range constraint: cost=750.0
  185338. ** * Both rowid range constraints: cost=500.0
  185339. ** * An == rowid constraint: cost=100.0
  185340. **
  185341. ** b) Otherwise, if there is no MATCH:
  185342. **
  185343. ** * No other constraints: cost=1000000.0
  185344. ** * One rowid range constraint: cost=750000.0
  185345. ** * Both rowid range constraints: cost=250000.0
  185346. ** * An == rowid constraint: cost=10.0
  185347. **
  185348. ** Costs are not modified by the ORDER BY clause.
  185349. */
  185350. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  185351. Fts5Table *pTab = (Fts5Table*)pVTab;
  185352. Fts5Config *pConfig = pTab->pConfig;
  185353. const int nCol = pConfig->nCol;
  185354. int idxFlags = 0; /* Parameter passed through to xFilter() */
  185355. int bHasMatch;
  185356. int iNext;
  185357. int i;
  185358. struct Constraint {
  185359. int op; /* Mask against sqlite3_index_constraint.op */
  185360. int fts5op; /* FTS5 mask for idxFlags */
  185361. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  185362. int omit; /* True to omit this if found */
  185363. int iConsIndex; /* Index in pInfo->aConstraint[] */
  185364. } aConstraint[] = {
  185365. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  185366. FTS5_BI_MATCH, 1, 1, -1},
  185367. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  185368. FTS5_BI_RANK, 2, 1, -1},
  185369. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  185370. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  185371. FTS5_BI_ROWID_LE, 0, 0, -1},
  185372. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  185373. FTS5_BI_ROWID_GE, 0, 0, -1},
  185374. };
  185375. int aColMap[3];
  185376. aColMap[0] = -1;
  185377. aColMap[1] = nCol;
  185378. aColMap[2] = nCol+1;
  185379. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  185380. for(i=0; i<pInfo->nConstraint; i++){
  185381. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  185382. int iCol = p->iColumn;
  185383. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  185384. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  185385. ){
  185386. /* A MATCH operator or equivalent */
  185387. if( p->usable ){
  185388. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  185389. aConstraint[0].iConsIndex = i;
  185390. }else{
  185391. /* As there exists an unusable MATCH constraint this is an
  185392. ** unusable plan. Set a prohibitively high cost. */
  185393. pInfo->estimatedCost = 1e50;
  185394. return SQLITE_OK;
  185395. }
  185396. }else{
  185397. int j;
  185398. for(j=1; j<ArraySize(aConstraint); j++){
  185399. struct Constraint *pC = &aConstraint[j];
  185400. if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
  185401. pC->iConsIndex = i;
  185402. idxFlags |= pC->fts5op;
  185403. }
  185404. }
  185405. }
  185406. }
  185407. /* Set idxFlags flags for the ORDER BY clause */
  185408. if( pInfo->nOrderBy==1 ){
  185409. int iSort = pInfo->aOrderBy[0].iColumn;
  185410. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  185411. idxFlags |= FTS5_BI_ORDER_RANK;
  185412. }else if( iSort==-1 ){
  185413. idxFlags |= FTS5_BI_ORDER_ROWID;
  185414. }
  185415. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  185416. pInfo->orderByConsumed = 1;
  185417. if( pInfo->aOrderBy[0].desc ){
  185418. idxFlags |= FTS5_BI_ORDER_DESC;
  185419. }
  185420. }
  185421. }
  185422. /* Calculate the estimated cost based on the flags set in idxFlags. */
  185423. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  185424. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  185425. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  185426. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  185427. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  185428. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  185429. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  185430. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  185431. }else{
  185432. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  185433. }
  185434. /* Assign argvIndex values to each constraint in use. */
  185435. iNext = 1;
  185436. for(i=0; i<ArraySize(aConstraint); i++){
  185437. struct Constraint *pC = &aConstraint[i];
  185438. if( pC->iConsIndex>=0 ){
  185439. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  185440. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  185441. }
  185442. }
  185443. pInfo->idxNum = idxFlags;
  185444. return SQLITE_OK;
  185445. }
  185446. static int fts5NewTransaction(Fts5Table *pTab){
  185447. Fts5Cursor *pCsr;
  185448. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  185449. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  185450. }
  185451. return sqlite3Fts5StorageReset(pTab->pStorage);
  185452. }
  185453. /*
  185454. ** Implementation of xOpen method.
  185455. */
  185456. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  185457. Fts5Table *pTab = (Fts5Table*)pVTab;
  185458. Fts5Config *pConfig = pTab->pConfig;
  185459. Fts5Cursor *pCsr = 0; /* New cursor object */
  185460. int nByte; /* Bytes of space to allocate */
  185461. int rc; /* Return code */
  185462. rc = fts5NewTransaction(pTab);
  185463. if( rc==SQLITE_OK ){
  185464. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  185465. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  185466. if( pCsr ){
  185467. Fts5Global *pGlobal = pTab->pGlobal;
  185468. memset(pCsr, 0, nByte);
  185469. pCsr->aColumnSize = (int*)&pCsr[1];
  185470. pCsr->pNext = pGlobal->pCsr;
  185471. pGlobal->pCsr = pCsr;
  185472. pCsr->iCsrId = ++pGlobal->iNextId;
  185473. }else{
  185474. rc = SQLITE_NOMEM;
  185475. }
  185476. }
  185477. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  185478. return rc;
  185479. }
  185480. static int fts5StmtType(Fts5Cursor *pCsr){
  185481. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  185482. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  185483. }
  185484. return FTS5_STMT_LOOKUP;
  185485. }
  185486. /*
  185487. ** This function is called after the cursor passed as the only argument
  185488. ** is moved to point at a different row. It clears all cached data
  185489. ** specific to the previous row stored by the cursor object.
  185490. */
  185491. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  185492. CsrFlagSet(pCsr,
  185493. FTS5CSR_REQUIRE_CONTENT
  185494. | FTS5CSR_REQUIRE_DOCSIZE
  185495. | FTS5CSR_REQUIRE_INST
  185496. | FTS5CSR_REQUIRE_POSLIST
  185497. );
  185498. }
  185499. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  185500. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  185501. Fts5Auxdata *pData;
  185502. Fts5Auxdata *pNext;
  185503. sqlite3_free(pCsr->aInstIter);
  185504. sqlite3_free(pCsr->aInst);
  185505. if( pCsr->pStmt ){
  185506. int eStmt = fts5StmtType(pCsr);
  185507. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  185508. }
  185509. if( pCsr->pSorter ){
  185510. Fts5Sorter *pSorter = pCsr->pSorter;
  185511. sqlite3_finalize(pSorter->pStmt);
  185512. sqlite3_free(pSorter);
  185513. }
  185514. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  185515. sqlite3Fts5ExprFree(pCsr->pExpr);
  185516. }
  185517. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  185518. pNext = pData->pNext;
  185519. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  185520. sqlite3_free(pData);
  185521. }
  185522. sqlite3_finalize(pCsr->pRankArgStmt);
  185523. sqlite3_free(pCsr->apRankArg);
  185524. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  185525. sqlite3_free(pCsr->zRank);
  185526. sqlite3_free(pCsr->zRankArgs);
  185527. }
  185528. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  185529. }
  185530. /*
  185531. ** Close the cursor. For additional information see the documentation
  185532. ** on the xClose method of the virtual table interface.
  185533. */
  185534. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  185535. if( pCursor ){
  185536. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  185537. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  185538. Fts5Cursor **pp;
  185539. fts5FreeCursorComponents(pCsr);
  185540. /* Remove the cursor from the Fts5Global.pCsr list */
  185541. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  185542. *pp = pCsr->pNext;
  185543. sqlite3_free(pCsr);
  185544. }
  185545. return SQLITE_OK;
  185546. }
  185547. static int fts5SorterNext(Fts5Cursor *pCsr){
  185548. Fts5Sorter *pSorter = pCsr->pSorter;
  185549. int rc;
  185550. rc = sqlite3_step(pSorter->pStmt);
  185551. if( rc==SQLITE_DONE ){
  185552. rc = SQLITE_OK;
  185553. CsrFlagSet(pCsr, FTS5CSR_EOF);
  185554. }else if( rc==SQLITE_ROW ){
  185555. const u8 *a;
  185556. const u8 *aBlob;
  185557. int nBlob;
  185558. int i;
  185559. int iOff = 0;
  185560. rc = SQLITE_OK;
  185561. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  185562. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  185563. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  185564. /* nBlob==0 in detail=none mode. */
  185565. if( nBlob>0 ){
  185566. for(i=0; i<(pSorter->nIdx-1); i++){
  185567. int iVal;
  185568. a += fts5GetVarint32(a, iVal);
  185569. iOff += iVal;
  185570. pSorter->aIdx[i] = iOff;
  185571. }
  185572. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  185573. pSorter->aPoslist = a;
  185574. }
  185575. fts5CsrNewrow(pCsr);
  185576. }
  185577. return rc;
  185578. }
  185579. /*
  185580. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  185581. ** open on table pTab.
  185582. */
  185583. static void fts5TripCursors(Fts5Table *pTab){
  185584. Fts5Cursor *pCsr;
  185585. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  185586. if( pCsr->ePlan==FTS5_PLAN_MATCH
  185587. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  185588. ){
  185589. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  185590. }
  185591. }
  185592. }
  185593. /*
  185594. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  185595. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  185596. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  185597. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  185598. **
  185599. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  185600. ** to 1 before returning. Otherwise, leave it unchanged.
  185601. **
  185602. ** Return SQLITE_OK if successful or if no reseek was required, or an
  185603. ** error code if an error occurred.
  185604. */
  185605. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  185606. int rc = SQLITE_OK;
  185607. assert( *pbSkip==0 );
  185608. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  185609. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  185610. int bDesc = pCsr->bDesc;
  185611. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  185612. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  185613. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  185614. *pbSkip = 1;
  185615. }
  185616. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  185617. fts5CsrNewrow(pCsr);
  185618. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  185619. CsrFlagSet(pCsr, FTS5CSR_EOF);
  185620. *pbSkip = 1;
  185621. }
  185622. }
  185623. return rc;
  185624. }
  185625. /*
  185626. ** Advance the cursor to the next row in the table that matches the
  185627. ** search criteria.
  185628. **
  185629. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  185630. ** even if we reach end-of-file. The fts5EofMethod() will be called
  185631. ** subsequently to determine whether or not an EOF was hit.
  185632. */
  185633. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  185634. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  185635. int rc;
  185636. assert( (pCsr->ePlan<3)==
  185637. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  185638. );
  185639. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  185640. if( pCsr->ePlan<3 ){
  185641. int bSkip = 0;
  185642. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  185643. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  185644. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  185645. fts5CsrNewrow(pCsr);
  185646. }else{
  185647. switch( pCsr->ePlan ){
  185648. case FTS5_PLAN_SPECIAL: {
  185649. CsrFlagSet(pCsr, FTS5CSR_EOF);
  185650. rc = SQLITE_OK;
  185651. break;
  185652. }
  185653. case FTS5_PLAN_SORTED_MATCH: {
  185654. rc = fts5SorterNext(pCsr);
  185655. break;
  185656. }
  185657. default:
  185658. rc = sqlite3_step(pCsr->pStmt);
  185659. if( rc!=SQLITE_ROW ){
  185660. CsrFlagSet(pCsr, FTS5CSR_EOF);
  185661. rc = sqlite3_reset(pCsr->pStmt);
  185662. }else{
  185663. rc = SQLITE_OK;
  185664. }
  185665. break;
  185666. }
  185667. }
  185668. return rc;
  185669. }
  185670. static int fts5PrepareStatement(
  185671. sqlite3_stmt **ppStmt,
  185672. Fts5Config *pConfig,
  185673. const char *zFmt,
  185674. ...
  185675. ){
  185676. sqlite3_stmt *pRet = 0;
  185677. int rc;
  185678. char *zSql;
  185679. va_list ap;
  185680. va_start(ap, zFmt);
  185681. zSql = sqlite3_vmprintf(zFmt, ap);
  185682. if( zSql==0 ){
  185683. rc = SQLITE_NOMEM;
  185684. }else{
  185685. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  185686. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  185687. if( rc!=SQLITE_OK ){
  185688. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  185689. }
  185690. sqlite3_free(zSql);
  185691. }
  185692. va_end(ap);
  185693. *ppStmt = pRet;
  185694. return rc;
  185695. }
  185696. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  185697. Fts5Config *pConfig = pTab->pConfig;
  185698. Fts5Sorter *pSorter;
  185699. int nPhrase;
  185700. int nByte;
  185701. int rc;
  185702. const char *zRank = pCsr->zRank;
  185703. const char *zRankArgs = pCsr->zRankArgs;
  185704. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  185705. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  185706. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  185707. if( pSorter==0 ) return SQLITE_NOMEM;
  185708. memset(pSorter, 0, nByte);
  185709. pSorter->nIdx = nPhrase;
  185710. /* TODO: It would be better to have some system for reusing statement
  185711. ** handles here, rather than preparing a new one for each query. But that
  185712. ** is not possible as SQLite reference counts the virtual table objects.
  185713. ** And since the statement required here reads from this very virtual
  185714. ** table, saving it creates a circular reference.
  185715. **
  185716. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  185717. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  185718. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  185719. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  185720. (zRankArgs ? ", " : ""),
  185721. (zRankArgs ? zRankArgs : ""),
  185722. bDesc ? "DESC" : "ASC"
  185723. );
  185724. pCsr->pSorter = pSorter;
  185725. if( rc==SQLITE_OK ){
  185726. assert( pTab->pSortCsr==0 );
  185727. pTab->pSortCsr = pCsr;
  185728. rc = fts5SorterNext(pCsr);
  185729. pTab->pSortCsr = 0;
  185730. }
  185731. if( rc!=SQLITE_OK ){
  185732. sqlite3_finalize(pSorter->pStmt);
  185733. sqlite3_free(pSorter);
  185734. pCsr->pSorter = 0;
  185735. }
  185736. return rc;
  185737. }
  185738. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  185739. int rc;
  185740. Fts5Expr *pExpr = pCsr->pExpr;
  185741. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  185742. if( sqlite3Fts5ExprEof(pExpr) ){
  185743. CsrFlagSet(pCsr, FTS5CSR_EOF);
  185744. }
  185745. fts5CsrNewrow(pCsr);
  185746. return rc;
  185747. }
  185748. /*
  185749. ** Process a "special" query. A special query is identified as one with a
  185750. ** MATCH expression that begins with a '*' character. The remainder of
  185751. ** the text passed to the MATCH operator are used as the special query
  185752. ** parameters.
  185753. */
  185754. static int fts5SpecialMatch(
  185755. Fts5Table *pTab,
  185756. Fts5Cursor *pCsr,
  185757. const char *zQuery
  185758. ){
  185759. int rc = SQLITE_OK; /* Return code */
  185760. const char *z = zQuery; /* Special query text */
  185761. int n; /* Number of bytes in text at z */
  185762. while( z[0]==' ' ) z++;
  185763. for(n=0; z[n] && z[n]!=' '; n++);
  185764. assert( pTab->base.zErrMsg==0 );
  185765. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  185766. if( 0==sqlite3_strnicmp("reads", z, n) ){
  185767. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  185768. }
  185769. else if( 0==sqlite3_strnicmp("id", z, n) ){
  185770. pCsr->iSpecial = pCsr->iCsrId;
  185771. }
  185772. else{
  185773. /* An unrecognized directive. Return an error message. */
  185774. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  185775. rc = SQLITE_ERROR;
  185776. }
  185777. return rc;
  185778. }
  185779. /*
  185780. ** Search for an auxiliary function named zName that can be used with table
  185781. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  185782. ** structure. Otherwise, if no such function exists, return NULL.
  185783. */
  185784. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  185785. Fts5Auxiliary *pAux;
  185786. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  185787. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  185788. }
  185789. /* No function of the specified name was found. Return 0. */
  185790. return 0;
  185791. }
  185792. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  185793. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  185794. Fts5Config *pConfig = pTab->pConfig;
  185795. int rc = SQLITE_OK;
  185796. Fts5Auxiliary *pAux = 0;
  185797. const char *zRank = pCsr->zRank;
  185798. const char *zRankArgs = pCsr->zRankArgs;
  185799. if( zRankArgs ){
  185800. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  185801. if( zSql ){
  185802. sqlite3_stmt *pStmt = 0;
  185803. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  185804. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  185805. sqlite3_free(zSql);
  185806. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  185807. if( rc==SQLITE_OK ){
  185808. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  185809. int nByte;
  185810. pCsr->nRankArg = sqlite3_column_count(pStmt);
  185811. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  185812. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  185813. if( rc==SQLITE_OK ){
  185814. int i;
  185815. for(i=0; i<pCsr->nRankArg; i++){
  185816. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  185817. }
  185818. }
  185819. pCsr->pRankArgStmt = pStmt;
  185820. }else{
  185821. rc = sqlite3_finalize(pStmt);
  185822. assert( rc!=SQLITE_OK );
  185823. }
  185824. }
  185825. }
  185826. }
  185827. if( rc==SQLITE_OK ){
  185828. pAux = fts5FindAuxiliary(pTab, zRank);
  185829. if( pAux==0 ){
  185830. assert( pTab->base.zErrMsg==0 );
  185831. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  185832. rc = SQLITE_ERROR;
  185833. }
  185834. }
  185835. pCsr->pRank = pAux;
  185836. return rc;
  185837. }
  185838. static int fts5CursorParseRank(
  185839. Fts5Config *pConfig,
  185840. Fts5Cursor *pCsr,
  185841. sqlite3_value *pRank
  185842. ){
  185843. int rc = SQLITE_OK;
  185844. if( pRank ){
  185845. const char *z = (const char*)sqlite3_value_text(pRank);
  185846. char *zRank = 0;
  185847. char *zRankArgs = 0;
  185848. if( z==0 ){
  185849. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  185850. }else{
  185851. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  185852. }
  185853. if( rc==SQLITE_OK ){
  185854. pCsr->zRank = zRank;
  185855. pCsr->zRankArgs = zRankArgs;
  185856. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  185857. }else if( rc==SQLITE_ERROR ){
  185858. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  185859. "parse error in rank function: %s", z
  185860. );
  185861. }
  185862. }else{
  185863. if( pConfig->zRank ){
  185864. pCsr->zRank = (char*)pConfig->zRank;
  185865. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  185866. }else{
  185867. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  185868. pCsr->zRankArgs = 0;
  185869. }
  185870. }
  185871. return rc;
  185872. }
  185873. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  185874. if( pVal ){
  185875. int eType = sqlite3_value_numeric_type(pVal);
  185876. if( eType==SQLITE_INTEGER ){
  185877. return sqlite3_value_int64(pVal);
  185878. }
  185879. }
  185880. return iDefault;
  185881. }
  185882. /*
  185883. ** This is the xFilter interface for the virtual table. See
  185884. ** the virtual table xFilter method documentation for additional
  185885. ** information.
  185886. **
  185887. ** There are three possible query strategies:
  185888. **
  185889. ** 1. Full-text search using a MATCH operator.
  185890. ** 2. A by-rowid lookup.
  185891. ** 3. A full-table scan.
  185892. */
  185893. static int fts5FilterMethod(
  185894. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  185895. int idxNum, /* Strategy index */
  185896. const char *zUnused, /* Unused */
  185897. int nVal, /* Number of elements in apVal */
  185898. sqlite3_value **apVal /* Arguments for the indexing scheme */
  185899. ){
  185900. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  185901. Fts5Config *pConfig = pTab->pConfig;
  185902. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  185903. int rc = SQLITE_OK; /* Error code */
  185904. int iVal = 0; /* Counter for apVal[] */
  185905. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  185906. int bOrderByRank; /* True if ORDER BY rank */
  185907. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  185908. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  185909. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  185910. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  185911. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  185912. int iCol; /* Column on LHS of MATCH operator */
  185913. char **pzErrmsg = pConfig->pzErrmsg;
  185914. UNUSED_PARAM(zUnused);
  185915. UNUSED_PARAM(nVal);
  185916. if( pCsr->ePlan ){
  185917. fts5FreeCursorComponents(pCsr);
  185918. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  185919. }
  185920. assert( pCsr->pStmt==0 );
  185921. assert( pCsr->pExpr==0 );
  185922. assert( pCsr->csrflags==0 );
  185923. assert( pCsr->pRank==0 );
  185924. assert( pCsr->zRank==0 );
  185925. assert( pCsr->zRankArgs==0 );
  185926. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  185927. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  185928. /* Decode the arguments passed through to this function.
  185929. **
  185930. ** Note: The following set of if(...) statements must be in the same
  185931. ** order as the corresponding entries in the struct at the top of
  185932. ** fts5BestIndexMethod(). */
  185933. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  185934. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  185935. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  185936. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  185937. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  185938. iCol = (idxNum>>16);
  185939. assert( iCol>=0 && iCol<=pConfig->nCol );
  185940. assert( iVal==nVal );
  185941. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  185942. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  185943. /* Set the cursor upper and lower rowid limits. Only some strategies
  185944. ** actually use them. This is ok, as the xBestIndex() method leaves the
  185945. ** sqlite3_index_constraint.omit flag clear for range constraints
  185946. ** on the rowid field. */
  185947. if( pRowidEq ){
  185948. pRowidLe = pRowidGe = pRowidEq;
  185949. }
  185950. if( bDesc ){
  185951. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  185952. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  185953. }else{
  185954. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  185955. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  185956. }
  185957. if( pTab->pSortCsr ){
  185958. /* If pSortCsr is non-NULL, then this call is being made as part of
  185959. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  185960. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  185961. ** return results to the user for this query. The current cursor
  185962. ** (pCursor) is used to execute the query issued by function
  185963. ** fts5CursorFirstSorted() above. */
  185964. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  185965. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  185966. assert( pCsr->iLastRowid==LARGEST_INT64 );
  185967. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  185968. pCsr->ePlan = FTS5_PLAN_SOURCE;
  185969. pCsr->pExpr = pTab->pSortCsr->pExpr;
  185970. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  185971. }else if( pMatch ){
  185972. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  185973. if( zExpr==0 ) zExpr = "";
  185974. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  185975. if( rc==SQLITE_OK ){
  185976. if( zExpr[0]=='*' ){
  185977. /* The user has issued a query of the form "MATCH '*...'". This
  185978. ** indicates that the MATCH expression is not a full text query,
  185979. ** but a request for an internal parameter. */
  185980. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  185981. }else{
  185982. char **pzErr = &pTab->base.zErrMsg;
  185983. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  185984. if( rc==SQLITE_OK ){
  185985. if( bOrderByRank ){
  185986. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  185987. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  185988. }else{
  185989. pCsr->ePlan = FTS5_PLAN_MATCH;
  185990. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  185991. }
  185992. }
  185993. }
  185994. }
  185995. }else if( pConfig->zContent==0 ){
  185996. *pConfig->pzErrmsg = sqlite3_mprintf(
  185997. "%s: table does not support scanning", pConfig->zName
  185998. );
  185999. rc = SQLITE_ERROR;
  186000. }else{
  186001. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  186002. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  186003. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  186004. rc = sqlite3Fts5StorageStmt(
  186005. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  186006. );
  186007. if( rc==SQLITE_OK ){
  186008. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  186009. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  186010. }else{
  186011. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  186012. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  186013. }
  186014. rc = fts5NextMethod(pCursor);
  186015. }
  186016. }
  186017. pConfig->pzErrmsg = pzErrmsg;
  186018. return rc;
  186019. }
  186020. /*
  186021. ** This is the xEof method of the virtual table. SQLite calls this
  186022. ** routine to find out if it has reached the end of a result set.
  186023. */
  186024. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  186025. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  186026. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  186027. }
  186028. /*
  186029. ** Return the rowid that the cursor currently points to.
  186030. */
  186031. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  186032. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  186033. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  186034. || pCsr->ePlan==FTS5_PLAN_SOURCE
  186035. );
  186036. if( pCsr->pSorter ){
  186037. return pCsr->pSorter->iRowid;
  186038. }else{
  186039. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  186040. }
  186041. }
  186042. /*
  186043. ** This is the xRowid method. The SQLite core calls this routine to
  186044. ** retrieve the rowid for the current row of the result set. fts5
  186045. ** exposes %_content.rowid as the rowid for the virtual table. The
  186046. ** rowid should be written to *pRowid.
  186047. */
  186048. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  186049. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  186050. int ePlan = pCsr->ePlan;
  186051. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  186052. switch( ePlan ){
  186053. case FTS5_PLAN_SPECIAL:
  186054. *pRowid = 0;
  186055. break;
  186056. case FTS5_PLAN_SOURCE:
  186057. case FTS5_PLAN_MATCH:
  186058. case FTS5_PLAN_SORTED_MATCH:
  186059. *pRowid = fts5CursorRowid(pCsr);
  186060. break;
  186061. default:
  186062. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  186063. break;
  186064. }
  186065. return SQLITE_OK;
  186066. }
  186067. /*
  186068. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  186069. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  186070. **
  186071. ** If argument bErrormsg is true and an error occurs, an error message may
  186072. ** be left in sqlite3_vtab.zErrMsg.
  186073. */
  186074. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  186075. int rc = SQLITE_OK;
  186076. /* If the cursor does not yet have a statement handle, obtain one now. */
  186077. if( pCsr->pStmt==0 ){
  186078. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186079. int eStmt = fts5StmtType(pCsr);
  186080. rc = sqlite3Fts5StorageStmt(
  186081. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  186082. );
  186083. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  186084. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  186085. }
  186086. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  186087. assert( pCsr->pExpr );
  186088. sqlite3_reset(pCsr->pStmt);
  186089. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  186090. rc = sqlite3_step(pCsr->pStmt);
  186091. if( rc==SQLITE_ROW ){
  186092. rc = SQLITE_OK;
  186093. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  186094. }else{
  186095. rc = sqlite3_reset(pCsr->pStmt);
  186096. if( rc==SQLITE_OK ){
  186097. rc = FTS5_CORRUPT;
  186098. }
  186099. }
  186100. }
  186101. return rc;
  186102. }
  186103. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  186104. va_list ap; /* ... printf arguments */
  186105. va_start(ap, zFormat);
  186106. assert( p->base.zErrMsg==0 );
  186107. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  186108. va_end(ap);
  186109. }
  186110. /*
  186111. ** This function is called to handle an FTS INSERT command. In other words,
  186112. ** an INSERT statement of the form:
  186113. **
  186114. ** INSERT INTO fts(fts) VALUES($pCmd)
  186115. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  186116. **
  186117. ** Argument pVal is the value assigned to column "fts" by the INSERT
  186118. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  186119. ** error code if an error occurs.
  186120. **
  186121. ** The commands implemented by this function are documented in the "Special
  186122. ** INSERT Directives" section of the documentation. It should be updated if
  186123. ** more commands are added to this function.
  186124. */
  186125. static int fts5SpecialInsert(
  186126. Fts5Table *pTab, /* Fts5 table object */
  186127. const char *zCmd, /* Text inserted into table-name column */
  186128. sqlite3_value *pVal /* Value inserted into rank column */
  186129. ){
  186130. Fts5Config *pConfig = pTab->pConfig;
  186131. int rc = SQLITE_OK;
  186132. int bError = 0;
  186133. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  186134. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  186135. fts5SetVtabError(pTab,
  186136. "'delete-all' may only be used with a "
  186137. "contentless or external content fts5 table"
  186138. );
  186139. rc = SQLITE_ERROR;
  186140. }else{
  186141. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  186142. }
  186143. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  186144. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  186145. fts5SetVtabError(pTab,
  186146. "'rebuild' may not be used with a contentless fts5 table"
  186147. );
  186148. rc = SQLITE_ERROR;
  186149. }else{
  186150. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  186151. }
  186152. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  186153. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  186154. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  186155. int nMerge = sqlite3_value_int(pVal);
  186156. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  186157. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  186158. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  186159. #ifdef SQLITE_DEBUG
  186160. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  186161. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  186162. #endif
  186163. }else{
  186164. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  186165. if( rc==SQLITE_OK ){
  186166. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  186167. }
  186168. if( rc==SQLITE_OK ){
  186169. if( bError ){
  186170. rc = SQLITE_ERROR;
  186171. }else{
  186172. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  186173. }
  186174. }
  186175. }
  186176. return rc;
  186177. }
  186178. static int fts5SpecialDelete(
  186179. Fts5Table *pTab,
  186180. sqlite3_value **apVal
  186181. ){
  186182. int rc = SQLITE_OK;
  186183. int eType1 = sqlite3_value_type(apVal[1]);
  186184. if( eType1==SQLITE_INTEGER ){
  186185. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  186186. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  186187. }
  186188. return rc;
  186189. }
  186190. static void fts5StorageInsert(
  186191. int *pRc,
  186192. Fts5Table *pTab,
  186193. sqlite3_value **apVal,
  186194. i64 *piRowid
  186195. ){
  186196. int rc = *pRc;
  186197. if( rc==SQLITE_OK ){
  186198. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  186199. }
  186200. if( rc==SQLITE_OK ){
  186201. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  186202. }
  186203. *pRc = rc;
  186204. }
  186205. /*
  186206. ** This function is the implementation of the xUpdate callback used by
  186207. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  186208. ** inserted, updated or deleted.
  186209. **
  186210. ** A delete specifies a single argument - the rowid of the row to remove.
  186211. **
  186212. ** Update and insert operations pass:
  186213. **
  186214. ** 1. The "old" rowid, or NULL.
  186215. ** 2. The "new" rowid.
  186216. ** 3. Values for each of the nCol matchable columns.
  186217. ** 4. Values for the two hidden columns (<tablename> and "rank").
  186218. */
  186219. static int fts5UpdateMethod(
  186220. sqlite3_vtab *pVtab, /* Virtual table handle */
  186221. int nArg, /* Size of argument array */
  186222. sqlite3_value **apVal, /* Array of arguments */
  186223. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  186224. ){
  186225. Fts5Table *pTab = (Fts5Table*)pVtab;
  186226. Fts5Config *pConfig = pTab->pConfig;
  186227. int eType0; /* value_type() of apVal[0] */
  186228. int rc = SQLITE_OK; /* Return code */
  186229. /* A transaction must be open when this is called. */
  186230. assert( pTab->ts.eState==1 );
  186231. assert( pVtab->zErrMsg==0 );
  186232. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  186233. assert( nArg==1
  186234. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  186235. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  186236. );
  186237. assert( pTab->pConfig->pzErrmsg==0 );
  186238. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  186239. /* Put any active cursors into REQUIRE_SEEK state. */
  186240. fts5TripCursors(pTab);
  186241. eType0 = sqlite3_value_type(apVal[0]);
  186242. if( eType0==SQLITE_NULL
  186243. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  186244. ){
  186245. /* A "special" INSERT op. These are handled separately. */
  186246. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  186247. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  186248. && 0==sqlite3_stricmp("delete", z)
  186249. ){
  186250. rc = fts5SpecialDelete(pTab, apVal);
  186251. }else{
  186252. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  186253. }
  186254. }else{
  186255. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  186256. ** any conflict on the rowid value must be detected before any
  186257. ** modifications are made to the database file. There are 4 cases:
  186258. **
  186259. ** 1) DELETE
  186260. ** 2) UPDATE (rowid not modified)
  186261. ** 3) UPDATE (rowid modified)
  186262. ** 4) INSERT
  186263. **
  186264. ** Cases 3 and 4 may violate the rowid constraint.
  186265. */
  186266. int eConflict = SQLITE_ABORT;
  186267. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  186268. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  186269. }
  186270. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  186271. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  186272. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  186273. ** This is not suported. */
  186274. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  186275. pTab->base.zErrMsg = sqlite3_mprintf(
  186276. "cannot %s contentless fts5 table: %s",
  186277. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  186278. );
  186279. rc = SQLITE_ERROR;
  186280. }
  186281. /* DELETE */
  186282. else if( nArg==1 ){
  186283. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  186284. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  186285. }
  186286. /* INSERT */
  186287. else if( eType0!=SQLITE_INTEGER ){
  186288. /* If this is a REPLACE, first remove the current entry (if any) */
  186289. if( eConflict==SQLITE_REPLACE
  186290. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  186291. ){
  186292. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  186293. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  186294. }
  186295. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  186296. }
  186297. /* UPDATE */
  186298. else{
  186299. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  186300. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  186301. if( iOld!=iNew ){
  186302. if( eConflict==SQLITE_REPLACE ){
  186303. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  186304. if( rc==SQLITE_OK ){
  186305. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  186306. }
  186307. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  186308. }else{
  186309. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  186310. if( rc==SQLITE_OK ){
  186311. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  186312. }
  186313. if( rc==SQLITE_OK ){
  186314. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  186315. }
  186316. }
  186317. }else{
  186318. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  186319. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  186320. }
  186321. }
  186322. }
  186323. pTab->pConfig->pzErrmsg = 0;
  186324. return rc;
  186325. }
  186326. /*
  186327. ** Implementation of xSync() method.
  186328. */
  186329. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  186330. int rc;
  186331. Fts5Table *pTab = (Fts5Table*)pVtab;
  186332. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  186333. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  186334. fts5TripCursors(pTab);
  186335. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  186336. pTab->pConfig->pzErrmsg = 0;
  186337. return rc;
  186338. }
  186339. /*
  186340. ** Implementation of xBegin() method.
  186341. */
  186342. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  186343. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  186344. fts5NewTransaction((Fts5Table*)pVtab);
  186345. return SQLITE_OK;
  186346. }
  186347. /*
  186348. ** Implementation of xCommit() method. This is a no-op. The contents of
  186349. ** the pending-terms hash-table have already been flushed into the database
  186350. ** by fts5SyncMethod().
  186351. */
  186352. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  186353. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  186354. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  186355. return SQLITE_OK;
  186356. }
  186357. /*
  186358. ** Implementation of xRollback(). Discard the contents of the pending-terms
  186359. ** hash-table. Any changes made to the database are reverted by SQLite.
  186360. */
  186361. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  186362. int rc;
  186363. Fts5Table *pTab = (Fts5Table*)pVtab;
  186364. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  186365. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  186366. return rc;
  186367. }
  186368. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  186369. static void *fts5ApiUserData(Fts5Context *pCtx){
  186370. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186371. return pCsr->pAux->pUserData;
  186372. }
  186373. static int fts5ApiColumnCount(Fts5Context *pCtx){
  186374. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186375. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  186376. }
  186377. static int fts5ApiColumnTotalSize(
  186378. Fts5Context *pCtx,
  186379. int iCol,
  186380. sqlite3_int64 *pnToken
  186381. ){
  186382. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186383. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186384. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  186385. }
  186386. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  186387. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186388. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186389. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  186390. }
  186391. static int fts5ApiTokenize(
  186392. Fts5Context *pCtx,
  186393. const char *pText, int nText,
  186394. void *pUserData,
  186395. int (*xToken)(void*, int, const char*, int, int, int)
  186396. ){
  186397. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186398. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186399. return sqlite3Fts5Tokenize(
  186400. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  186401. );
  186402. }
  186403. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  186404. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186405. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  186406. }
  186407. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  186408. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186409. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  186410. }
  186411. static int fts5ApiColumnText(
  186412. Fts5Context *pCtx,
  186413. int iCol,
  186414. const char **pz,
  186415. int *pn
  186416. ){
  186417. int rc = SQLITE_OK;
  186418. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186419. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  186420. *pz = 0;
  186421. *pn = 0;
  186422. }else{
  186423. rc = fts5SeekCursor(pCsr, 0);
  186424. if( rc==SQLITE_OK ){
  186425. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  186426. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  186427. }
  186428. }
  186429. return rc;
  186430. }
  186431. static int fts5CsrPoslist(
  186432. Fts5Cursor *pCsr,
  186433. int iPhrase,
  186434. const u8 **pa,
  186435. int *pn
  186436. ){
  186437. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  186438. int rc = SQLITE_OK;
  186439. int bLive = (pCsr->pSorter==0);
  186440. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  186441. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  186442. Fts5PoslistPopulator *aPopulator;
  186443. int i;
  186444. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  186445. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  186446. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  186447. int n; const char *z;
  186448. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  186449. if( rc==SQLITE_OK ){
  186450. rc = sqlite3Fts5ExprPopulatePoslists(
  186451. pConfig, pCsr->pExpr, aPopulator, i, z, n
  186452. );
  186453. }
  186454. }
  186455. sqlite3_free(aPopulator);
  186456. if( pCsr->pSorter ){
  186457. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  186458. }
  186459. }
  186460. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  186461. }
  186462. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  186463. Fts5Sorter *pSorter = pCsr->pSorter;
  186464. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  186465. *pn = pSorter->aIdx[iPhrase] - i1;
  186466. *pa = &pSorter->aPoslist[i1];
  186467. }else{
  186468. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  186469. }
  186470. return rc;
  186471. }
  186472. /*
  186473. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  186474. ** correctly for the current view. Return SQLITE_OK if successful, or an
  186475. ** SQLite error code otherwise.
  186476. */
  186477. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  186478. int rc = SQLITE_OK;
  186479. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  186480. int nIter; /* Number of iterators/phrases */
  186481. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  186482. if( pCsr->aInstIter==0 ){
  186483. int nByte = sizeof(Fts5PoslistReader) * nIter;
  186484. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  186485. }
  186486. aIter = pCsr->aInstIter;
  186487. if( aIter ){
  186488. int nInst = 0; /* Number instances seen so far */
  186489. int i;
  186490. /* Initialize all iterators */
  186491. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  186492. const u8 *a;
  186493. int n;
  186494. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  186495. if( rc==SQLITE_OK ){
  186496. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  186497. }
  186498. }
  186499. if( rc==SQLITE_OK ){
  186500. while( 1 ){
  186501. int *aInst;
  186502. int iBest = -1;
  186503. for(i=0; i<nIter; i++){
  186504. if( (aIter[i].bEof==0)
  186505. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  186506. ){
  186507. iBest = i;
  186508. }
  186509. }
  186510. if( iBest<0 ) break;
  186511. nInst++;
  186512. if( nInst>=pCsr->nInstAlloc ){
  186513. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  186514. aInst = (int*)sqlite3_realloc(
  186515. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  186516. );
  186517. if( aInst ){
  186518. pCsr->aInst = aInst;
  186519. }else{
  186520. rc = SQLITE_NOMEM;
  186521. break;
  186522. }
  186523. }
  186524. aInst = &pCsr->aInst[3 * (nInst-1)];
  186525. aInst[0] = iBest;
  186526. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  186527. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  186528. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  186529. }
  186530. }
  186531. pCsr->nInstCount = nInst;
  186532. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  186533. }
  186534. return rc;
  186535. }
  186536. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  186537. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186538. int rc = SQLITE_OK;
  186539. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  186540. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  186541. *pnInst = pCsr->nInstCount;
  186542. }
  186543. return rc;
  186544. }
  186545. static int fts5ApiInst(
  186546. Fts5Context *pCtx,
  186547. int iIdx,
  186548. int *piPhrase,
  186549. int *piCol,
  186550. int *piOff
  186551. ){
  186552. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186553. int rc = SQLITE_OK;
  186554. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  186555. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  186556. ){
  186557. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  186558. rc = SQLITE_RANGE;
  186559. #if 0
  186560. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  186561. *piPhrase = pCsr->aInst[iIdx*3];
  186562. *piCol = pCsr->aInst[iIdx*3 + 2];
  186563. *piOff = -1;
  186564. #endif
  186565. }else{
  186566. *piPhrase = pCsr->aInst[iIdx*3];
  186567. *piCol = pCsr->aInst[iIdx*3 + 1];
  186568. *piOff = pCsr->aInst[iIdx*3 + 2];
  186569. }
  186570. }
  186571. return rc;
  186572. }
  186573. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  186574. return fts5CursorRowid((Fts5Cursor*)pCtx);
  186575. }
  186576. static int fts5ColumnSizeCb(
  186577. void *pContext, /* Pointer to int */
  186578. int tflags,
  186579. const char *pUnused, /* Buffer containing token */
  186580. int nUnused, /* Size of token in bytes */
  186581. int iUnused1, /* Start offset of token */
  186582. int iUnused2 /* End offset of token */
  186583. ){
  186584. int *pCnt = (int*)pContext;
  186585. UNUSED_PARAM2(pUnused, nUnused);
  186586. UNUSED_PARAM2(iUnused1, iUnused2);
  186587. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  186588. (*pCnt)++;
  186589. }
  186590. return SQLITE_OK;
  186591. }
  186592. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  186593. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186594. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186595. Fts5Config *pConfig = pTab->pConfig;
  186596. int rc = SQLITE_OK;
  186597. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  186598. if( pConfig->bColumnsize ){
  186599. i64 iRowid = fts5CursorRowid(pCsr);
  186600. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  186601. }else if( pConfig->zContent==0 ){
  186602. int i;
  186603. for(i=0; i<pConfig->nCol; i++){
  186604. if( pConfig->abUnindexed[i]==0 ){
  186605. pCsr->aColumnSize[i] = -1;
  186606. }
  186607. }
  186608. }else{
  186609. int i;
  186610. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  186611. if( pConfig->abUnindexed[i]==0 ){
  186612. const char *z; int n;
  186613. void *p = (void*)(&pCsr->aColumnSize[i]);
  186614. pCsr->aColumnSize[i] = 0;
  186615. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  186616. if( rc==SQLITE_OK ){
  186617. rc = sqlite3Fts5Tokenize(
  186618. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  186619. );
  186620. }
  186621. }
  186622. }
  186623. }
  186624. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  186625. }
  186626. if( iCol<0 ){
  186627. int i;
  186628. *pnToken = 0;
  186629. for(i=0; i<pConfig->nCol; i++){
  186630. *pnToken += pCsr->aColumnSize[i];
  186631. }
  186632. }else if( iCol<pConfig->nCol ){
  186633. *pnToken = pCsr->aColumnSize[iCol];
  186634. }else{
  186635. *pnToken = 0;
  186636. rc = SQLITE_RANGE;
  186637. }
  186638. return rc;
  186639. }
  186640. /*
  186641. ** Implementation of the xSetAuxdata() method.
  186642. */
  186643. static int fts5ApiSetAuxdata(
  186644. Fts5Context *pCtx, /* Fts5 context */
  186645. void *pPtr, /* Pointer to save as auxdata */
  186646. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  186647. ){
  186648. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186649. Fts5Auxdata *pData;
  186650. /* Search through the cursors list of Fts5Auxdata objects for one that
  186651. ** corresponds to the currently executing auxiliary function. */
  186652. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  186653. if( pData->pAux==pCsr->pAux ) break;
  186654. }
  186655. if( pData ){
  186656. if( pData->xDelete ){
  186657. pData->xDelete(pData->pPtr);
  186658. }
  186659. }else{
  186660. int rc = SQLITE_OK;
  186661. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  186662. if( pData==0 ){
  186663. if( xDelete ) xDelete(pPtr);
  186664. return rc;
  186665. }
  186666. pData->pAux = pCsr->pAux;
  186667. pData->pNext = pCsr->pAuxdata;
  186668. pCsr->pAuxdata = pData;
  186669. }
  186670. pData->xDelete = xDelete;
  186671. pData->pPtr = pPtr;
  186672. return SQLITE_OK;
  186673. }
  186674. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  186675. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186676. Fts5Auxdata *pData;
  186677. void *pRet = 0;
  186678. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  186679. if( pData->pAux==pCsr->pAux ) break;
  186680. }
  186681. if( pData ){
  186682. pRet = pData->pPtr;
  186683. if( bClear ){
  186684. pData->pPtr = 0;
  186685. pData->xDelete = 0;
  186686. }
  186687. }
  186688. return pRet;
  186689. }
  186690. static void fts5ApiPhraseNext(
  186691. Fts5Context *pUnused,
  186692. Fts5PhraseIter *pIter,
  186693. int *piCol, int *piOff
  186694. ){
  186695. UNUSED_PARAM(pUnused);
  186696. if( pIter->a>=pIter->b ){
  186697. *piCol = -1;
  186698. *piOff = -1;
  186699. }else{
  186700. int iVal;
  186701. pIter->a += fts5GetVarint32(pIter->a, iVal);
  186702. if( iVal==1 ){
  186703. pIter->a += fts5GetVarint32(pIter->a, iVal);
  186704. *piCol = iVal;
  186705. *piOff = 0;
  186706. pIter->a += fts5GetVarint32(pIter->a, iVal);
  186707. }
  186708. *piOff += (iVal-2);
  186709. }
  186710. }
  186711. static int fts5ApiPhraseFirst(
  186712. Fts5Context *pCtx,
  186713. int iPhrase,
  186714. Fts5PhraseIter *pIter,
  186715. int *piCol, int *piOff
  186716. ){
  186717. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186718. int n;
  186719. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  186720. if( rc==SQLITE_OK ){
  186721. pIter->b = &pIter->a[n];
  186722. *piCol = 0;
  186723. *piOff = 0;
  186724. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  186725. }
  186726. return rc;
  186727. }
  186728. static void fts5ApiPhraseNextColumn(
  186729. Fts5Context *pCtx,
  186730. Fts5PhraseIter *pIter,
  186731. int *piCol
  186732. ){
  186733. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186734. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  186735. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186736. if( pIter->a>=pIter->b ){
  186737. *piCol = -1;
  186738. }else{
  186739. int iIncr;
  186740. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  186741. *piCol += (iIncr-2);
  186742. }
  186743. }else{
  186744. while( 1 ){
  186745. int dummy;
  186746. if( pIter->a>=pIter->b ){
  186747. *piCol = -1;
  186748. return;
  186749. }
  186750. if( pIter->a[0]==0x01 ) break;
  186751. pIter->a += fts5GetVarint32(pIter->a, dummy);
  186752. }
  186753. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  186754. }
  186755. }
  186756. static int fts5ApiPhraseFirstColumn(
  186757. Fts5Context *pCtx,
  186758. int iPhrase,
  186759. Fts5PhraseIter *pIter,
  186760. int *piCol
  186761. ){
  186762. int rc = SQLITE_OK;
  186763. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186764. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  186765. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186766. Fts5Sorter *pSorter = pCsr->pSorter;
  186767. int n;
  186768. if( pSorter ){
  186769. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  186770. n = pSorter->aIdx[iPhrase] - i1;
  186771. pIter->a = &pSorter->aPoslist[i1];
  186772. }else{
  186773. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  186774. }
  186775. if( rc==SQLITE_OK ){
  186776. pIter->b = &pIter->a[n];
  186777. *piCol = 0;
  186778. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  186779. }
  186780. }else{
  186781. int n;
  186782. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  186783. if( rc==SQLITE_OK ){
  186784. pIter->b = &pIter->a[n];
  186785. if( n<=0 ){
  186786. *piCol = -1;
  186787. }else if( pIter->a[0]==0x01 ){
  186788. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  186789. }else{
  186790. *piCol = 0;
  186791. }
  186792. }
  186793. }
  186794. return rc;
  186795. }
  186796. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  186797. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  186798. );
  186799. static const Fts5ExtensionApi sFts5Api = {
  186800. 2, /* iVersion */
  186801. fts5ApiUserData,
  186802. fts5ApiColumnCount,
  186803. fts5ApiRowCount,
  186804. fts5ApiColumnTotalSize,
  186805. fts5ApiTokenize,
  186806. fts5ApiPhraseCount,
  186807. fts5ApiPhraseSize,
  186808. fts5ApiInstCount,
  186809. fts5ApiInst,
  186810. fts5ApiRowid,
  186811. fts5ApiColumnText,
  186812. fts5ApiColumnSize,
  186813. fts5ApiQueryPhrase,
  186814. fts5ApiSetAuxdata,
  186815. fts5ApiGetAuxdata,
  186816. fts5ApiPhraseFirst,
  186817. fts5ApiPhraseNext,
  186818. fts5ApiPhraseFirstColumn,
  186819. fts5ApiPhraseNextColumn,
  186820. };
  186821. /*
  186822. ** Implementation of API function xQueryPhrase().
  186823. */
  186824. static int fts5ApiQueryPhrase(
  186825. Fts5Context *pCtx,
  186826. int iPhrase,
  186827. void *pUserData,
  186828. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  186829. ){
  186830. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  186831. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  186832. int rc;
  186833. Fts5Cursor *pNew = 0;
  186834. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  186835. if( rc==SQLITE_OK ){
  186836. pNew->ePlan = FTS5_PLAN_MATCH;
  186837. pNew->iFirstRowid = SMALLEST_INT64;
  186838. pNew->iLastRowid = LARGEST_INT64;
  186839. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  186840. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  186841. }
  186842. if( rc==SQLITE_OK ){
  186843. for(rc = fts5CursorFirst(pTab, pNew, 0);
  186844. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  186845. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  186846. ){
  186847. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  186848. if( rc!=SQLITE_OK ){
  186849. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  186850. break;
  186851. }
  186852. }
  186853. }
  186854. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  186855. return rc;
  186856. }
  186857. static void fts5ApiInvoke(
  186858. Fts5Auxiliary *pAux,
  186859. Fts5Cursor *pCsr,
  186860. sqlite3_context *context,
  186861. int argc,
  186862. sqlite3_value **argv
  186863. ){
  186864. assert( pCsr->pAux==0 );
  186865. pCsr->pAux = pAux;
  186866. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  186867. pCsr->pAux = 0;
  186868. }
  186869. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  186870. Fts5Cursor *pCsr;
  186871. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  186872. if( pCsr->iCsrId==iCsrId ) break;
  186873. }
  186874. return pCsr;
  186875. }
  186876. static void fts5ApiCallback(
  186877. sqlite3_context *context,
  186878. int argc,
  186879. sqlite3_value **argv
  186880. ){
  186881. Fts5Auxiliary *pAux;
  186882. Fts5Cursor *pCsr;
  186883. i64 iCsrId;
  186884. assert( argc>=1 );
  186885. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  186886. iCsrId = sqlite3_value_int64(argv[0]);
  186887. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  186888. if( pCsr==0 ){
  186889. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  186890. sqlite3_result_error(context, zErr, -1);
  186891. sqlite3_free(zErr);
  186892. }else{
  186893. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  186894. }
  186895. }
  186896. /*
  186897. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  186898. ** object. Or NULL If the cursor id does not exist.
  186899. **
  186900. ** If successful, set *ppConfig to point to the associated config object
  186901. ** before returning.
  186902. */
  186903. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  186904. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  186905. i64 iCsrId, /* Id of cursor to find */
  186906. Fts5Config **ppConfig /* OUT: Configuration object */
  186907. ){
  186908. Fts5Cursor *pCsr;
  186909. Fts5Table *pTab;
  186910. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  186911. pTab = (Fts5Table*)pCsr->base.pVtab;
  186912. *ppConfig = pTab->pConfig;
  186913. return pTab->pIndex;
  186914. }
  186915. /*
  186916. ** Return a "position-list blob" corresponding to the current position of
  186917. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  186918. ** the current position-list for each phrase in the query associated with
  186919. ** cursor pCsr.
  186920. **
  186921. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  186922. ** the number of phrases in the query. Following the varints are the
  186923. ** concatenated position lists for each phrase, in order.
  186924. **
  186925. ** The first varint (if it exists) contains the size of the position list
  186926. ** for phrase 0. The second (same disclaimer) contains the size of position
  186927. ** list 1. And so on. There is no size field for the final position list,
  186928. ** as it can be derived from the total size of the blob.
  186929. */
  186930. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  186931. int i;
  186932. int rc = SQLITE_OK;
  186933. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  186934. Fts5Buffer val;
  186935. memset(&val, 0, sizeof(Fts5Buffer));
  186936. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  186937. case FTS5_DETAIL_FULL:
  186938. /* Append the varints */
  186939. for(i=0; i<(nPhrase-1); i++){
  186940. const u8 *dummy;
  186941. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  186942. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  186943. }
  186944. /* Append the position lists */
  186945. for(i=0; i<nPhrase; i++){
  186946. const u8 *pPoslist;
  186947. int nPoslist;
  186948. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  186949. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  186950. }
  186951. break;
  186952. case FTS5_DETAIL_COLUMNS:
  186953. /* Append the varints */
  186954. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  186955. const u8 *dummy;
  186956. int nByte;
  186957. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  186958. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  186959. }
  186960. /* Append the position lists */
  186961. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  186962. const u8 *pPoslist;
  186963. int nPoslist;
  186964. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  186965. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  186966. }
  186967. break;
  186968. default:
  186969. break;
  186970. }
  186971. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  186972. return rc;
  186973. }
  186974. /*
  186975. ** This is the xColumn method, called by SQLite to request a value from
  186976. ** the row that the supplied cursor currently points to.
  186977. */
  186978. static int fts5ColumnMethod(
  186979. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  186980. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  186981. int iCol /* Index of column to read value from */
  186982. ){
  186983. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  186984. Fts5Config *pConfig = pTab->pConfig;
  186985. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  186986. int rc = SQLITE_OK;
  186987. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  186988. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  186989. if( iCol==pConfig->nCol ){
  186990. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  186991. }
  186992. }else
  186993. if( iCol==pConfig->nCol ){
  186994. /* User is requesting the value of the special column with the same name
  186995. ** as the table. Return the cursor integer id number. This value is only
  186996. ** useful in that it may be passed as the first argument to an FTS5
  186997. ** auxiliary function. */
  186998. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  186999. }else if( iCol==pConfig->nCol+1 ){
  187000. /* The value of the "rank" column. */
  187001. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  187002. fts5PoslistBlob(pCtx, pCsr);
  187003. }else if(
  187004. pCsr->ePlan==FTS5_PLAN_MATCH
  187005. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  187006. ){
  187007. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  187008. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  187009. }
  187010. }
  187011. }else if( !fts5IsContentless(pTab) ){
  187012. rc = fts5SeekCursor(pCsr, 1);
  187013. if( rc==SQLITE_OK ){
  187014. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  187015. }
  187016. }
  187017. return rc;
  187018. }
  187019. /*
  187020. ** This routine implements the xFindFunction method for the FTS3
  187021. ** virtual table.
  187022. */
  187023. static int fts5FindFunctionMethod(
  187024. sqlite3_vtab *pVtab, /* Virtual table handle */
  187025. int nUnused, /* Number of SQL function arguments */
  187026. const char *zName, /* Name of SQL function */
  187027. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  187028. void **ppArg /* OUT: User data for *pxFunc */
  187029. ){
  187030. Fts5Table *pTab = (Fts5Table*)pVtab;
  187031. Fts5Auxiliary *pAux;
  187032. UNUSED_PARAM(nUnused);
  187033. pAux = fts5FindAuxiliary(pTab, zName);
  187034. if( pAux ){
  187035. *pxFunc = fts5ApiCallback;
  187036. *ppArg = (void*)pAux;
  187037. return 1;
  187038. }
  187039. /* No function of the specified name was found. Return 0. */
  187040. return 0;
  187041. }
  187042. /*
  187043. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  187044. */
  187045. static int fts5RenameMethod(
  187046. sqlite3_vtab *pVtab, /* Virtual table handle */
  187047. const char *zName /* New name of table */
  187048. ){
  187049. Fts5Table *pTab = (Fts5Table*)pVtab;
  187050. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  187051. }
  187052. /*
  187053. ** The xSavepoint() method.
  187054. **
  187055. ** Flush the contents of the pending-terms table to disk.
  187056. */
  187057. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  187058. Fts5Table *pTab = (Fts5Table*)pVtab;
  187059. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  187060. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  187061. fts5TripCursors(pTab);
  187062. return sqlite3Fts5StorageSync(pTab->pStorage);
  187063. }
  187064. /*
  187065. ** The xRelease() method.
  187066. **
  187067. ** This is a no-op.
  187068. */
  187069. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  187070. Fts5Table *pTab = (Fts5Table*)pVtab;
  187071. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  187072. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  187073. fts5TripCursors(pTab);
  187074. return sqlite3Fts5StorageSync(pTab->pStorage);
  187075. }
  187076. /*
  187077. ** The xRollbackTo() method.
  187078. **
  187079. ** Discard the contents of the pending terms table.
  187080. */
  187081. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  187082. Fts5Table *pTab = (Fts5Table*)pVtab;
  187083. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  187084. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  187085. fts5TripCursors(pTab);
  187086. return sqlite3Fts5StorageRollback(pTab->pStorage);
  187087. }
  187088. /*
  187089. ** Register a new auxiliary function with global context pGlobal.
  187090. */
  187091. static int fts5CreateAux(
  187092. fts5_api *pApi, /* Global context (one per db handle) */
  187093. const char *zName, /* Name of new function */
  187094. void *pUserData, /* User data for aux. function */
  187095. fts5_extension_function xFunc, /* Aux. function implementation */
  187096. void(*xDestroy)(void*) /* Destructor for pUserData */
  187097. ){
  187098. Fts5Global *pGlobal = (Fts5Global*)pApi;
  187099. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  187100. if( rc==SQLITE_OK ){
  187101. Fts5Auxiliary *pAux;
  187102. int nName; /* Size of zName in bytes, including \0 */
  187103. int nByte; /* Bytes of space to allocate */
  187104. nName = (int)strlen(zName) + 1;
  187105. nByte = sizeof(Fts5Auxiliary) + nName;
  187106. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  187107. if( pAux ){
  187108. memset(pAux, 0, nByte);
  187109. pAux->zFunc = (char*)&pAux[1];
  187110. memcpy(pAux->zFunc, zName, nName);
  187111. pAux->pGlobal = pGlobal;
  187112. pAux->pUserData = pUserData;
  187113. pAux->xFunc = xFunc;
  187114. pAux->xDestroy = xDestroy;
  187115. pAux->pNext = pGlobal->pAux;
  187116. pGlobal->pAux = pAux;
  187117. }else{
  187118. rc = SQLITE_NOMEM;
  187119. }
  187120. }
  187121. return rc;
  187122. }
  187123. /*
  187124. ** Register a new tokenizer. This is the implementation of the
  187125. ** fts5_api.xCreateTokenizer() method.
  187126. */
  187127. static int fts5CreateTokenizer(
  187128. fts5_api *pApi, /* Global context (one per db handle) */
  187129. const char *zName, /* Name of new function */
  187130. void *pUserData, /* User data for aux. function */
  187131. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  187132. void(*xDestroy)(void*) /* Destructor for pUserData */
  187133. ){
  187134. Fts5Global *pGlobal = (Fts5Global*)pApi;
  187135. Fts5TokenizerModule *pNew;
  187136. int nName; /* Size of zName and its \0 terminator */
  187137. int nByte; /* Bytes of space to allocate */
  187138. int rc = SQLITE_OK;
  187139. nName = (int)strlen(zName) + 1;
  187140. nByte = sizeof(Fts5TokenizerModule) + nName;
  187141. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  187142. if( pNew ){
  187143. memset(pNew, 0, nByte);
  187144. pNew->zName = (char*)&pNew[1];
  187145. memcpy(pNew->zName, zName, nName);
  187146. pNew->pUserData = pUserData;
  187147. pNew->x = *pTokenizer;
  187148. pNew->xDestroy = xDestroy;
  187149. pNew->pNext = pGlobal->pTok;
  187150. pGlobal->pTok = pNew;
  187151. if( pNew->pNext==0 ){
  187152. pGlobal->pDfltTok = pNew;
  187153. }
  187154. }else{
  187155. rc = SQLITE_NOMEM;
  187156. }
  187157. return rc;
  187158. }
  187159. static Fts5TokenizerModule *fts5LocateTokenizer(
  187160. Fts5Global *pGlobal,
  187161. const char *zName
  187162. ){
  187163. Fts5TokenizerModule *pMod = 0;
  187164. if( zName==0 ){
  187165. pMod = pGlobal->pDfltTok;
  187166. }else{
  187167. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  187168. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  187169. }
  187170. }
  187171. return pMod;
  187172. }
  187173. /*
  187174. ** Find a tokenizer. This is the implementation of the
  187175. ** fts5_api.xFindTokenizer() method.
  187176. */
  187177. static int fts5FindTokenizer(
  187178. fts5_api *pApi, /* Global context (one per db handle) */
  187179. const char *zName, /* Name of new function */
  187180. void **ppUserData,
  187181. fts5_tokenizer *pTokenizer /* Populate this object */
  187182. ){
  187183. int rc = SQLITE_OK;
  187184. Fts5TokenizerModule *pMod;
  187185. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  187186. if( pMod ){
  187187. *pTokenizer = pMod->x;
  187188. *ppUserData = pMod->pUserData;
  187189. }else{
  187190. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  187191. rc = SQLITE_ERROR;
  187192. }
  187193. return rc;
  187194. }
  187195. static int sqlite3Fts5GetTokenizer(
  187196. Fts5Global *pGlobal,
  187197. const char **azArg,
  187198. int nArg,
  187199. Fts5Tokenizer **ppTok,
  187200. fts5_tokenizer **ppTokApi,
  187201. char **pzErr
  187202. ){
  187203. Fts5TokenizerModule *pMod;
  187204. int rc = SQLITE_OK;
  187205. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  187206. if( pMod==0 ){
  187207. assert( nArg>0 );
  187208. rc = SQLITE_ERROR;
  187209. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  187210. }else{
  187211. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  187212. *ppTokApi = &pMod->x;
  187213. if( rc!=SQLITE_OK && pzErr ){
  187214. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  187215. }
  187216. }
  187217. if( rc!=SQLITE_OK ){
  187218. *ppTokApi = 0;
  187219. *ppTok = 0;
  187220. }
  187221. return rc;
  187222. }
  187223. static void fts5ModuleDestroy(void *pCtx){
  187224. Fts5TokenizerModule *pTok, *pNextTok;
  187225. Fts5Auxiliary *pAux, *pNextAux;
  187226. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  187227. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  187228. pNextAux = pAux->pNext;
  187229. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  187230. sqlite3_free(pAux);
  187231. }
  187232. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  187233. pNextTok = pTok->pNext;
  187234. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  187235. sqlite3_free(pTok);
  187236. }
  187237. sqlite3_free(pGlobal);
  187238. }
  187239. static void fts5Fts5Func(
  187240. sqlite3_context *pCtx, /* Function call context */
  187241. int nArg, /* Number of args */
  187242. sqlite3_value **apArg /* Function arguments */
  187243. ){
  187244. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  187245. fts5_api **ppApi;
  187246. UNUSED_PARAM(nArg);
  187247. assert( nArg==1 );
  187248. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  187249. if( ppApi ) *ppApi = &pGlobal->api;
  187250. }
  187251. /*
  187252. ** Implementation of fts5_source_id() function.
  187253. */
  187254. static void fts5SourceIdFunc(
  187255. sqlite3_context *pCtx, /* Function call context */
  187256. int nArg, /* Number of args */
  187257. sqlite3_value **apUnused /* Function arguments */
  187258. ){
  187259. assert( nArg==0 );
  187260. UNUSED_PARAM2(nArg, apUnused);
  187261. sqlite3_result_text(pCtx, "fts5: 2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827", -1, SQLITE_TRANSIENT);
  187262. }
  187263. static int fts5Init(sqlite3 *db){
  187264. static const sqlite3_module fts5Mod = {
  187265. /* iVersion */ 2,
  187266. /* xCreate */ fts5CreateMethod,
  187267. /* xConnect */ fts5ConnectMethod,
  187268. /* xBestIndex */ fts5BestIndexMethod,
  187269. /* xDisconnect */ fts5DisconnectMethod,
  187270. /* xDestroy */ fts5DestroyMethod,
  187271. /* xOpen */ fts5OpenMethod,
  187272. /* xClose */ fts5CloseMethod,
  187273. /* xFilter */ fts5FilterMethod,
  187274. /* xNext */ fts5NextMethod,
  187275. /* xEof */ fts5EofMethod,
  187276. /* xColumn */ fts5ColumnMethod,
  187277. /* xRowid */ fts5RowidMethod,
  187278. /* xUpdate */ fts5UpdateMethod,
  187279. /* xBegin */ fts5BeginMethod,
  187280. /* xSync */ fts5SyncMethod,
  187281. /* xCommit */ fts5CommitMethod,
  187282. /* xRollback */ fts5RollbackMethod,
  187283. /* xFindFunction */ fts5FindFunctionMethod,
  187284. /* xRename */ fts5RenameMethod,
  187285. /* xSavepoint */ fts5SavepointMethod,
  187286. /* xRelease */ fts5ReleaseMethod,
  187287. /* xRollbackTo */ fts5RollbackToMethod,
  187288. };
  187289. int rc;
  187290. Fts5Global *pGlobal = 0;
  187291. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  187292. if( pGlobal==0 ){
  187293. rc = SQLITE_NOMEM;
  187294. }else{
  187295. void *p = (void*)pGlobal;
  187296. memset(pGlobal, 0, sizeof(Fts5Global));
  187297. pGlobal->db = db;
  187298. pGlobal->api.iVersion = 2;
  187299. pGlobal->api.xCreateFunction = fts5CreateAux;
  187300. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  187301. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  187302. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  187303. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  187304. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  187305. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  187306. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  187307. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  187308. if( rc==SQLITE_OK ){
  187309. rc = sqlite3_create_function(
  187310. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  187311. );
  187312. }
  187313. if( rc==SQLITE_OK ){
  187314. rc = sqlite3_create_function(
  187315. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  187316. );
  187317. }
  187318. }
  187319. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  187320. ** fts5_test_mi.c is compiled and linked into the executable. And call
  187321. ** its entry point to enable the matchinfo() demo. */
  187322. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  187323. if( rc==SQLITE_OK ){
  187324. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  187325. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  187326. }
  187327. #endif
  187328. return rc;
  187329. }
  187330. /*
  187331. ** The following functions are used to register the module with SQLite. If
  187332. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  187333. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  187334. **
  187335. ** Or, if this module is being built as a loadable extension,
  187336. ** sqlite3Fts5Init() is omitted and the two standard entry points
  187337. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  187338. */
  187339. #ifndef SQLITE_CORE
  187340. #ifdef _WIN32
  187341. __declspec(dllexport)
  187342. #endif
  187343. SQLITE_API int sqlite3_fts_init(
  187344. sqlite3 *db,
  187345. char **pzErrMsg,
  187346. const sqlite3_api_routines *pApi
  187347. ){
  187348. SQLITE_EXTENSION_INIT2(pApi);
  187349. (void)pzErrMsg; /* Unused parameter */
  187350. return fts5Init(db);
  187351. }
  187352. #ifdef _WIN32
  187353. __declspec(dllexport)
  187354. #endif
  187355. SQLITE_API int sqlite3_fts5_init(
  187356. sqlite3 *db,
  187357. char **pzErrMsg,
  187358. const sqlite3_api_routines *pApi
  187359. ){
  187360. SQLITE_EXTENSION_INIT2(pApi);
  187361. (void)pzErrMsg; /* Unused parameter */
  187362. return fts5Init(db);
  187363. }
  187364. #else
  187365. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  187366. return fts5Init(db);
  187367. }
  187368. #endif
  187369. /*
  187370. ** 2014 May 31
  187371. **
  187372. ** The author disclaims copyright to this source code. In place of
  187373. ** a legal notice, here is a blessing:
  187374. **
  187375. ** May you do good and not evil.
  187376. ** May you find forgiveness for yourself and forgive others.
  187377. ** May you share freely, never taking more than you give.
  187378. **
  187379. ******************************************************************************
  187380. **
  187381. */
  187382. /* #include "fts5Int.h" */
  187383. struct Fts5Storage {
  187384. Fts5Config *pConfig;
  187385. Fts5Index *pIndex;
  187386. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  187387. i64 nTotalRow; /* Total number of rows in FTS table */
  187388. i64 *aTotalSize; /* Total sizes of each column */
  187389. sqlite3_stmt *aStmt[11];
  187390. };
  187391. #if FTS5_STMT_SCAN_ASC!=0
  187392. # error "FTS5_STMT_SCAN_ASC mismatch"
  187393. #endif
  187394. #if FTS5_STMT_SCAN_DESC!=1
  187395. # error "FTS5_STMT_SCAN_DESC mismatch"
  187396. #endif
  187397. #if FTS5_STMT_LOOKUP!=2
  187398. # error "FTS5_STMT_LOOKUP mismatch"
  187399. #endif
  187400. #define FTS5_STMT_INSERT_CONTENT 3
  187401. #define FTS5_STMT_REPLACE_CONTENT 4
  187402. #define FTS5_STMT_DELETE_CONTENT 5
  187403. #define FTS5_STMT_REPLACE_DOCSIZE 6
  187404. #define FTS5_STMT_DELETE_DOCSIZE 7
  187405. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  187406. #define FTS5_STMT_REPLACE_CONFIG 9
  187407. #define FTS5_STMT_SCAN 10
  187408. /*
  187409. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  187410. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  187411. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  187412. ** occurs.
  187413. */
  187414. static int fts5StorageGetStmt(
  187415. Fts5Storage *p, /* Storage handle */
  187416. int eStmt, /* FTS5_STMT_XXX constant */
  187417. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  187418. char **pzErrMsg /* OUT: Error message (if any) */
  187419. ){
  187420. int rc = SQLITE_OK;
  187421. /* If there is no %_docsize table, there should be no requests for
  187422. ** statements to operate on it. */
  187423. assert( p->pConfig->bColumnsize || (
  187424. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  187425. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  187426. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  187427. ));
  187428. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  187429. if( p->aStmt[eStmt]==0 ){
  187430. const char *azStmt[] = {
  187431. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  187432. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  187433. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  187434. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  187435. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  187436. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  187437. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  187438. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  187439. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  187440. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  187441. "SELECT %s FROM %s AS T", /* SCAN */
  187442. };
  187443. Fts5Config *pC = p->pConfig;
  187444. char *zSql = 0;
  187445. switch( eStmt ){
  187446. case FTS5_STMT_SCAN:
  187447. zSql = sqlite3_mprintf(azStmt[eStmt],
  187448. pC->zContentExprlist, pC->zContent
  187449. );
  187450. break;
  187451. case FTS5_STMT_SCAN_ASC:
  187452. case FTS5_STMT_SCAN_DESC:
  187453. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  187454. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  187455. pC->zContentRowid
  187456. );
  187457. break;
  187458. case FTS5_STMT_LOOKUP:
  187459. zSql = sqlite3_mprintf(azStmt[eStmt],
  187460. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  187461. );
  187462. break;
  187463. case FTS5_STMT_INSERT_CONTENT:
  187464. case FTS5_STMT_REPLACE_CONTENT: {
  187465. int nCol = pC->nCol + 1;
  187466. char *zBind;
  187467. int i;
  187468. zBind = sqlite3_malloc(1 + nCol*2);
  187469. if( zBind ){
  187470. for(i=0; i<nCol; i++){
  187471. zBind[i*2] = '?';
  187472. zBind[i*2 + 1] = ',';
  187473. }
  187474. zBind[i*2-1] = '\0';
  187475. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  187476. sqlite3_free(zBind);
  187477. }
  187478. break;
  187479. }
  187480. default:
  187481. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  187482. break;
  187483. }
  187484. if( zSql==0 ){
  187485. rc = SQLITE_NOMEM;
  187486. }else{
  187487. rc = sqlite3_prepare_v3(pC->db, zSql, -1,
  187488. SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
  187489. sqlite3_free(zSql);
  187490. if( rc!=SQLITE_OK && pzErrMsg ){
  187491. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  187492. }
  187493. }
  187494. }
  187495. *ppStmt = p->aStmt[eStmt];
  187496. sqlite3_reset(*ppStmt);
  187497. return rc;
  187498. }
  187499. static int fts5ExecPrintf(
  187500. sqlite3 *db,
  187501. char **pzErr,
  187502. const char *zFormat,
  187503. ...
  187504. ){
  187505. int rc;
  187506. va_list ap; /* ... printf arguments */
  187507. char *zSql;
  187508. va_start(ap, zFormat);
  187509. zSql = sqlite3_vmprintf(zFormat, ap);
  187510. if( zSql==0 ){
  187511. rc = SQLITE_NOMEM;
  187512. }else{
  187513. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  187514. sqlite3_free(zSql);
  187515. }
  187516. va_end(ap);
  187517. return rc;
  187518. }
  187519. /*
  187520. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  187521. ** code otherwise.
  187522. */
  187523. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  187524. int rc = fts5ExecPrintf(pConfig->db, 0,
  187525. "DROP TABLE IF EXISTS %Q.'%q_data';"
  187526. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  187527. "DROP TABLE IF EXISTS %Q.'%q_config';",
  187528. pConfig->zDb, pConfig->zName,
  187529. pConfig->zDb, pConfig->zName,
  187530. pConfig->zDb, pConfig->zName
  187531. );
  187532. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  187533. rc = fts5ExecPrintf(pConfig->db, 0,
  187534. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  187535. pConfig->zDb, pConfig->zName
  187536. );
  187537. }
  187538. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  187539. rc = fts5ExecPrintf(pConfig->db, 0,
  187540. "DROP TABLE IF EXISTS %Q.'%q_content';",
  187541. pConfig->zDb, pConfig->zName
  187542. );
  187543. }
  187544. return rc;
  187545. }
  187546. static void fts5StorageRenameOne(
  187547. Fts5Config *pConfig, /* Current FTS5 configuration */
  187548. int *pRc, /* IN/OUT: Error code */
  187549. const char *zTail, /* Tail of table name e.g. "data", "config" */
  187550. const char *zName /* New name of FTS5 table */
  187551. ){
  187552. if( *pRc==SQLITE_OK ){
  187553. *pRc = fts5ExecPrintf(pConfig->db, 0,
  187554. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  187555. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  187556. );
  187557. }
  187558. }
  187559. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  187560. Fts5Config *pConfig = pStorage->pConfig;
  187561. int rc = sqlite3Fts5StorageSync(pStorage);
  187562. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  187563. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  187564. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  187565. if( pConfig->bColumnsize ){
  187566. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  187567. }
  187568. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  187569. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  187570. }
  187571. return rc;
  187572. }
  187573. /*
  187574. ** Create the shadow table named zPost, with definition zDefn. Return
  187575. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  187576. */
  187577. static int sqlite3Fts5CreateTable(
  187578. Fts5Config *pConfig, /* FTS5 configuration */
  187579. const char *zPost, /* Shadow table to create (e.g. "content") */
  187580. const char *zDefn, /* Columns etc. for shadow table */
  187581. int bWithout, /* True for without rowid */
  187582. char **pzErr /* OUT: Error message */
  187583. ){
  187584. int rc;
  187585. char *zErr = 0;
  187586. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  187587. pConfig->zDb, pConfig->zName, zPost, zDefn,
  187588. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  187589. bWithout?" WITHOUT ROWID":
  187590. #endif
  187591. ""
  187592. );
  187593. if( zErr ){
  187594. *pzErr = sqlite3_mprintf(
  187595. "fts5: error creating shadow table %q_%s: %s",
  187596. pConfig->zName, zPost, zErr
  187597. );
  187598. sqlite3_free(zErr);
  187599. }
  187600. return rc;
  187601. }
  187602. /*
  187603. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  187604. ** and initialize the underlying tables
  187605. **
  187606. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  187607. ** Otherwise, set *pp to NULL and return an SQLite error code.
  187608. */
  187609. static int sqlite3Fts5StorageOpen(
  187610. Fts5Config *pConfig,
  187611. Fts5Index *pIndex,
  187612. int bCreate,
  187613. Fts5Storage **pp,
  187614. char **pzErr /* OUT: Error message */
  187615. ){
  187616. int rc = SQLITE_OK;
  187617. Fts5Storage *p; /* New object */
  187618. int nByte; /* Bytes of space to allocate */
  187619. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  187620. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  187621. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  187622. if( !p ) return SQLITE_NOMEM;
  187623. memset(p, 0, nByte);
  187624. p->aTotalSize = (i64*)&p[1];
  187625. p->pConfig = pConfig;
  187626. p->pIndex = pIndex;
  187627. if( bCreate ){
  187628. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  187629. int nDefn = 32 + pConfig->nCol*10;
  187630. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  187631. if( zDefn==0 ){
  187632. rc = SQLITE_NOMEM;
  187633. }else{
  187634. int i;
  187635. int iOff;
  187636. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  187637. iOff = (int)strlen(zDefn);
  187638. for(i=0; i<pConfig->nCol; i++){
  187639. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  187640. iOff += (int)strlen(&zDefn[iOff]);
  187641. }
  187642. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  187643. }
  187644. sqlite3_free(zDefn);
  187645. }
  187646. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  187647. rc = sqlite3Fts5CreateTable(
  187648. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  187649. );
  187650. }
  187651. if( rc==SQLITE_OK ){
  187652. rc = sqlite3Fts5CreateTable(
  187653. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  187654. );
  187655. }
  187656. if( rc==SQLITE_OK ){
  187657. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  187658. }
  187659. }
  187660. if( rc ){
  187661. sqlite3Fts5StorageClose(p);
  187662. *pp = 0;
  187663. }
  187664. return rc;
  187665. }
  187666. /*
  187667. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  187668. */
  187669. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  187670. int rc = SQLITE_OK;
  187671. if( p ){
  187672. int i;
  187673. /* Finalize all SQL statements */
  187674. for(i=0; i<ArraySize(p->aStmt); i++){
  187675. sqlite3_finalize(p->aStmt[i]);
  187676. }
  187677. sqlite3_free(p);
  187678. }
  187679. return rc;
  187680. }
  187681. typedef struct Fts5InsertCtx Fts5InsertCtx;
  187682. struct Fts5InsertCtx {
  187683. Fts5Storage *pStorage;
  187684. int iCol;
  187685. int szCol; /* Size of column value in tokens */
  187686. };
  187687. /*
  187688. ** Tokenization callback used when inserting tokens into the FTS index.
  187689. */
  187690. static int fts5StorageInsertCallback(
  187691. void *pContext, /* Pointer to Fts5InsertCtx object */
  187692. int tflags,
  187693. const char *pToken, /* Buffer containing token */
  187694. int nToken, /* Size of token in bytes */
  187695. int iUnused1, /* Start offset of token */
  187696. int iUnused2 /* End offset of token */
  187697. ){
  187698. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  187699. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  187700. UNUSED_PARAM2(iUnused1, iUnused2);
  187701. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  187702. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  187703. pCtx->szCol++;
  187704. }
  187705. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  187706. }
  187707. /*
  187708. ** If a row with rowid iDel is present in the %_content table, add the
  187709. ** delete-markers to the FTS index necessary to delete it. Do not actually
  187710. ** remove the %_content row at this time though.
  187711. */
  187712. static int fts5StorageDeleteFromIndex(
  187713. Fts5Storage *p,
  187714. i64 iDel,
  187715. sqlite3_value **apVal
  187716. ){
  187717. Fts5Config *pConfig = p->pConfig;
  187718. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  187719. int rc; /* Return code */
  187720. int rc2; /* sqlite3_reset() return code */
  187721. int iCol;
  187722. Fts5InsertCtx ctx;
  187723. if( apVal==0 ){
  187724. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  187725. if( rc!=SQLITE_OK ) return rc;
  187726. sqlite3_bind_int64(pSeek, 1, iDel);
  187727. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  187728. return sqlite3_reset(pSeek);
  187729. }
  187730. }
  187731. ctx.pStorage = p;
  187732. ctx.iCol = -1;
  187733. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  187734. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  187735. if( pConfig->abUnindexed[iCol-1]==0 ){
  187736. const char *zText;
  187737. int nText;
  187738. if( pSeek ){
  187739. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  187740. nText = sqlite3_column_bytes(pSeek, iCol);
  187741. }else{
  187742. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  187743. nText = sqlite3_value_bytes(apVal[iCol-1]);
  187744. }
  187745. ctx.szCol = 0;
  187746. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  187747. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  187748. );
  187749. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  187750. }
  187751. }
  187752. p->nTotalRow--;
  187753. rc2 = sqlite3_reset(pSeek);
  187754. if( rc==SQLITE_OK ) rc = rc2;
  187755. return rc;
  187756. }
  187757. /*
  187758. ** Insert a record into the %_docsize table. Specifically, do:
  187759. **
  187760. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  187761. **
  187762. ** If there is no %_docsize table (as happens if the columnsize=0 option
  187763. ** is specified when the FTS5 table is created), this function is a no-op.
  187764. */
  187765. static int fts5StorageInsertDocsize(
  187766. Fts5Storage *p, /* Storage module to write to */
  187767. i64 iRowid, /* id value */
  187768. Fts5Buffer *pBuf /* sz value */
  187769. ){
  187770. int rc = SQLITE_OK;
  187771. if( p->pConfig->bColumnsize ){
  187772. sqlite3_stmt *pReplace = 0;
  187773. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  187774. if( rc==SQLITE_OK ){
  187775. sqlite3_bind_int64(pReplace, 1, iRowid);
  187776. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  187777. sqlite3_step(pReplace);
  187778. rc = sqlite3_reset(pReplace);
  187779. }
  187780. }
  187781. return rc;
  187782. }
  187783. /*
  187784. ** Load the contents of the "averages" record from disk into the
  187785. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  187786. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  187787. ** that the contents of aTotalSize[] and nTotalRow are valid until
  187788. ** further notice.
  187789. **
  187790. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  187791. ** occurs.
  187792. */
  187793. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  187794. int rc = SQLITE_OK;
  187795. if( p->bTotalsValid==0 ){
  187796. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  187797. p->bTotalsValid = bCache;
  187798. }
  187799. return rc;
  187800. }
  187801. /*
  187802. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  187803. ** variables in the "averages" record on disk.
  187804. **
  187805. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  187806. ** occurs.
  187807. */
  187808. static int fts5StorageSaveTotals(Fts5Storage *p){
  187809. int nCol = p->pConfig->nCol;
  187810. int i;
  187811. Fts5Buffer buf;
  187812. int rc = SQLITE_OK;
  187813. memset(&buf, 0, sizeof(buf));
  187814. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  187815. for(i=0; i<nCol; i++){
  187816. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  187817. }
  187818. if( rc==SQLITE_OK ){
  187819. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  187820. }
  187821. sqlite3_free(buf.p);
  187822. return rc;
  187823. }
  187824. /*
  187825. ** Remove a row from the FTS table.
  187826. */
  187827. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  187828. Fts5Config *pConfig = p->pConfig;
  187829. int rc;
  187830. sqlite3_stmt *pDel = 0;
  187831. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  187832. rc = fts5StorageLoadTotals(p, 1);
  187833. /* Delete the index records */
  187834. if( rc==SQLITE_OK ){
  187835. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  187836. }
  187837. /* Delete the %_docsize record */
  187838. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  187839. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  187840. if( rc==SQLITE_OK ){
  187841. sqlite3_bind_int64(pDel, 1, iDel);
  187842. sqlite3_step(pDel);
  187843. rc = sqlite3_reset(pDel);
  187844. }
  187845. }
  187846. /* Delete the %_content record */
  187847. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  187848. if( rc==SQLITE_OK ){
  187849. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  187850. }
  187851. if( rc==SQLITE_OK ){
  187852. sqlite3_bind_int64(pDel, 1, iDel);
  187853. sqlite3_step(pDel);
  187854. rc = sqlite3_reset(pDel);
  187855. }
  187856. }
  187857. return rc;
  187858. }
  187859. /*
  187860. ** Delete all entries in the FTS5 index.
  187861. */
  187862. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  187863. Fts5Config *pConfig = p->pConfig;
  187864. int rc;
  187865. /* Delete the contents of the %_data and %_docsize tables. */
  187866. rc = fts5ExecPrintf(pConfig->db, 0,
  187867. "DELETE FROM %Q.'%q_data';"
  187868. "DELETE FROM %Q.'%q_idx';",
  187869. pConfig->zDb, pConfig->zName,
  187870. pConfig->zDb, pConfig->zName
  187871. );
  187872. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  187873. rc = fts5ExecPrintf(pConfig->db, 0,
  187874. "DELETE FROM %Q.'%q_docsize';",
  187875. pConfig->zDb, pConfig->zName
  187876. );
  187877. }
  187878. /* Reinitialize the %_data table. This call creates the initial structure
  187879. ** and averages records. */
  187880. if( rc==SQLITE_OK ){
  187881. rc = sqlite3Fts5IndexReinit(p->pIndex);
  187882. }
  187883. if( rc==SQLITE_OK ){
  187884. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  187885. }
  187886. return rc;
  187887. }
  187888. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  187889. Fts5Buffer buf = {0,0,0};
  187890. Fts5Config *pConfig = p->pConfig;
  187891. sqlite3_stmt *pScan = 0;
  187892. Fts5InsertCtx ctx;
  187893. int rc;
  187894. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  187895. ctx.pStorage = p;
  187896. rc = sqlite3Fts5StorageDeleteAll(p);
  187897. if( rc==SQLITE_OK ){
  187898. rc = fts5StorageLoadTotals(p, 1);
  187899. }
  187900. if( rc==SQLITE_OK ){
  187901. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  187902. }
  187903. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  187904. i64 iRowid = sqlite3_column_int64(pScan, 0);
  187905. sqlite3Fts5BufferZero(&buf);
  187906. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  187907. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  187908. ctx.szCol = 0;
  187909. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  187910. rc = sqlite3Fts5Tokenize(pConfig,
  187911. FTS5_TOKENIZE_DOCUMENT,
  187912. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  187913. sqlite3_column_bytes(pScan, ctx.iCol+1),
  187914. (void*)&ctx,
  187915. fts5StorageInsertCallback
  187916. );
  187917. }
  187918. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  187919. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  187920. }
  187921. p->nTotalRow++;
  187922. if( rc==SQLITE_OK ){
  187923. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  187924. }
  187925. }
  187926. sqlite3_free(buf.p);
  187927. /* Write the averages record */
  187928. if( rc==SQLITE_OK ){
  187929. rc = fts5StorageSaveTotals(p);
  187930. }
  187931. return rc;
  187932. }
  187933. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  187934. return sqlite3Fts5IndexOptimize(p->pIndex);
  187935. }
  187936. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  187937. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  187938. }
  187939. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  187940. return sqlite3Fts5IndexReset(p->pIndex);
  187941. }
  187942. /*
  187943. ** Allocate a new rowid. This is used for "external content" tables when
  187944. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  187945. ** by inserting a dummy row into the %_docsize table. The dummy will be
  187946. ** overwritten later.
  187947. **
  187948. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  187949. ** this case the user is required to provide a rowid explicitly.
  187950. */
  187951. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  187952. int rc = SQLITE_MISMATCH;
  187953. if( p->pConfig->bColumnsize ){
  187954. sqlite3_stmt *pReplace = 0;
  187955. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  187956. if( rc==SQLITE_OK ){
  187957. sqlite3_bind_null(pReplace, 1);
  187958. sqlite3_bind_null(pReplace, 2);
  187959. sqlite3_step(pReplace);
  187960. rc = sqlite3_reset(pReplace);
  187961. }
  187962. if( rc==SQLITE_OK ){
  187963. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  187964. }
  187965. }
  187966. return rc;
  187967. }
  187968. /*
  187969. ** Insert a new row into the FTS content table.
  187970. */
  187971. static int sqlite3Fts5StorageContentInsert(
  187972. Fts5Storage *p,
  187973. sqlite3_value **apVal,
  187974. i64 *piRowid
  187975. ){
  187976. Fts5Config *pConfig = p->pConfig;
  187977. int rc = SQLITE_OK;
  187978. /* Insert the new row into the %_content table. */
  187979. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  187980. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  187981. *piRowid = sqlite3_value_int64(apVal[1]);
  187982. }else{
  187983. rc = fts5StorageNewRowid(p, piRowid);
  187984. }
  187985. }else{
  187986. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  187987. int i; /* Counter variable */
  187988. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  187989. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  187990. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  187991. }
  187992. if( rc==SQLITE_OK ){
  187993. sqlite3_step(pInsert);
  187994. rc = sqlite3_reset(pInsert);
  187995. }
  187996. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  187997. }
  187998. return rc;
  187999. }
  188000. /*
  188001. ** Insert new entries into the FTS index and %_docsize table.
  188002. */
  188003. static int sqlite3Fts5StorageIndexInsert(
  188004. Fts5Storage *p,
  188005. sqlite3_value **apVal,
  188006. i64 iRowid
  188007. ){
  188008. Fts5Config *pConfig = p->pConfig;
  188009. int rc = SQLITE_OK; /* Return code */
  188010. Fts5InsertCtx ctx; /* Tokenization callback context object */
  188011. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  188012. memset(&buf, 0, sizeof(Fts5Buffer));
  188013. ctx.pStorage = p;
  188014. rc = fts5StorageLoadTotals(p, 1);
  188015. if( rc==SQLITE_OK ){
  188016. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  188017. }
  188018. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  188019. ctx.szCol = 0;
  188020. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  188021. rc = sqlite3Fts5Tokenize(pConfig,
  188022. FTS5_TOKENIZE_DOCUMENT,
  188023. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  188024. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  188025. (void*)&ctx,
  188026. fts5StorageInsertCallback
  188027. );
  188028. }
  188029. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  188030. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  188031. }
  188032. p->nTotalRow++;
  188033. /* Write the %_docsize record */
  188034. if( rc==SQLITE_OK ){
  188035. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  188036. }
  188037. sqlite3_free(buf.p);
  188038. return rc;
  188039. }
  188040. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  188041. Fts5Config *pConfig = p->pConfig;
  188042. char *zSql;
  188043. int rc;
  188044. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  188045. pConfig->zDb, pConfig->zName, zSuffix
  188046. );
  188047. if( zSql==0 ){
  188048. rc = SQLITE_NOMEM;
  188049. }else{
  188050. sqlite3_stmt *pCnt = 0;
  188051. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  188052. if( rc==SQLITE_OK ){
  188053. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  188054. *pnRow = sqlite3_column_int64(pCnt, 0);
  188055. }
  188056. rc = sqlite3_finalize(pCnt);
  188057. }
  188058. }
  188059. sqlite3_free(zSql);
  188060. return rc;
  188061. }
  188062. /*
  188063. ** Context object used by sqlite3Fts5StorageIntegrity().
  188064. */
  188065. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  188066. struct Fts5IntegrityCtx {
  188067. i64 iRowid;
  188068. int iCol;
  188069. int szCol;
  188070. u64 cksum;
  188071. Fts5Termset *pTermset;
  188072. Fts5Config *pConfig;
  188073. };
  188074. /*
  188075. ** Tokenization callback used by integrity check.
  188076. */
  188077. static int fts5StorageIntegrityCallback(
  188078. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  188079. int tflags,
  188080. const char *pToken, /* Buffer containing token */
  188081. int nToken, /* Size of token in bytes */
  188082. int iUnused1, /* Start offset of token */
  188083. int iUnused2 /* End offset of token */
  188084. ){
  188085. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  188086. Fts5Termset *pTermset = pCtx->pTermset;
  188087. int bPresent;
  188088. int ii;
  188089. int rc = SQLITE_OK;
  188090. int iPos;
  188091. int iCol;
  188092. UNUSED_PARAM2(iUnused1, iUnused2);
  188093. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  188094. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  188095. pCtx->szCol++;
  188096. }
  188097. switch( pCtx->pConfig->eDetail ){
  188098. case FTS5_DETAIL_FULL:
  188099. iPos = pCtx->szCol-1;
  188100. iCol = pCtx->iCol;
  188101. break;
  188102. case FTS5_DETAIL_COLUMNS:
  188103. iPos = pCtx->iCol;
  188104. iCol = 0;
  188105. break;
  188106. default:
  188107. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  188108. iPos = 0;
  188109. iCol = 0;
  188110. break;
  188111. }
  188112. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  188113. if( rc==SQLITE_OK && bPresent==0 ){
  188114. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  188115. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  188116. );
  188117. }
  188118. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  188119. const int nChar = pCtx->pConfig->aPrefix[ii];
  188120. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  188121. if( nByte ){
  188122. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  188123. if( bPresent==0 ){
  188124. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  188125. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  188126. );
  188127. }
  188128. }
  188129. }
  188130. return rc;
  188131. }
  188132. /*
  188133. ** Check that the contents of the FTS index match that of the %_content
  188134. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  188135. ** some other SQLite error code if an error occurs while attempting to
  188136. ** determine this.
  188137. */
  188138. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  188139. Fts5Config *pConfig = p->pConfig;
  188140. int rc; /* Return code */
  188141. int *aColSize; /* Array of size pConfig->nCol */
  188142. i64 *aTotalSize; /* Array of size pConfig->nCol */
  188143. Fts5IntegrityCtx ctx;
  188144. sqlite3_stmt *pScan;
  188145. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  188146. ctx.pConfig = p->pConfig;
  188147. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  188148. if( !aTotalSize ) return SQLITE_NOMEM;
  188149. aColSize = (int*)&aTotalSize[pConfig->nCol];
  188150. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  188151. /* Generate the expected index checksum based on the contents of the
  188152. ** %_content table. This block stores the checksum in ctx.cksum. */
  188153. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  188154. if( rc==SQLITE_OK ){
  188155. int rc2;
  188156. while( SQLITE_ROW==sqlite3_step(pScan) ){
  188157. int i;
  188158. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  188159. ctx.szCol = 0;
  188160. if( pConfig->bColumnsize ){
  188161. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  188162. }
  188163. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  188164. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  188165. }
  188166. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  188167. if( pConfig->abUnindexed[i] ) continue;
  188168. ctx.iCol = i;
  188169. ctx.szCol = 0;
  188170. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  188171. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  188172. }
  188173. if( rc==SQLITE_OK ){
  188174. rc = sqlite3Fts5Tokenize(pConfig,
  188175. FTS5_TOKENIZE_DOCUMENT,
  188176. (const char*)sqlite3_column_text(pScan, i+1),
  188177. sqlite3_column_bytes(pScan, i+1),
  188178. (void*)&ctx,
  188179. fts5StorageIntegrityCallback
  188180. );
  188181. }
  188182. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  188183. rc = FTS5_CORRUPT;
  188184. }
  188185. aTotalSize[i] += ctx.szCol;
  188186. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  188187. sqlite3Fts5TermsetFree(ctx.pTermset);
  188188. ctx.pTermset = 0;
  188189. }
  188190. }
  188191. sqlite3Fts5TermsetFree(ctx.pTermset);
  188192. ctx.pTermset = 0;
  188193. if( rc!=SQLITE_OK ) break;
  188194. }
  188195. rc2 = sqlite3_reset(pScan);
  188196. if( rc==SQLITE_OK ) rc = rc2;
  188197. }
  188198. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  188199. if( rc==SQLITE_OK ){
  188200. int i;
  188201. rc = fts5StorageLoadTotals(p, 0);
  188202. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  188203. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  188204. }
  188205. }
  188206. /* Check that the %_docsize and %_content tables contain the expected
  188207. ** number of rows. */
  188208. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  188209. i64 nRow = 0;
  188210. rc = fts5StorageCount(p, "content", &nRow);
  188211. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  188212. }
  188213. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  188214. i64 nRow = 0;
  188215. rc = fts5StorageCount(p, "docsize", &nRow);
  188216. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  188217. }
  188218. /* Pass the expected checksum down to the FTS index module. It will
  188219. ** verify, amongst other things, that it matches the checksum generated by
  188220. ** inspecting the index itself. */
  188221. if( rc==SQLITE_OK ){
  188222. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  188223. }
  188224. sqlite3_free(aTotalSize);
  188225. return rc;
  188226. }
  188227. /*
  188228. ** Obtain an SQLite statement handle that may be used to read data from the
  188229. ** %_content table.
  188230. */
  188231. static int sqlite3Fts5StorageStmt(
  188232. Fts5Storage *p,
  188233. int eStmt,
  188234. sqlite3_stmt **pp,
  188235. char **pzErrMsg
  188236. ){
  188237. int rc;
  188238. assert( eStmt==FTS5_STMT_SCAN_ASC
  188239. || eStmt==FTS5_STMT_SCAN_DESC
  188240. || eStmt==FTS5_STMT_LOOKUP
  188241. );
  188242. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  188243. if( rc==SQLITE_OK ){
  188244. assert( p->aStmt[eStmt]==*pp );
  188245. p->aStmt[eStmt] = 0;
  188246. }
  188247. return rc;
  188248. }
  188249. /*
  188250. ** Release an SQLite statement handle obtained via an earlier call to
  188251. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  188252. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  188253. */
  188254. static void sqlite3Fts5StorageStmtRelease(
  188255. Fts5Storage *p,
  188256. int eStmt,
  188257. sqlite3_stmt *pStmt
  188258. ){
  188259. assert( eStmt==FTS5_STMT_SCAN_ASC
  188260. || eStmt==FTS5_STMT_SCAN_DESC
  188261. || eStmt==FTS5_STMT_LOOKUP
  188262. );
  188263. if( p->aStmt[eStmt]==0 ){
  188264. sqlite3_reset(pStmt);
  188265. p->aStmt[eStmt] = pStmt;
  188266. }else{
  188267. sqlite3_finalize(pStmt);
  188268. }
  188269. }
  188270. static int fts5StorageDecodeSizeArray(
  188271. int *aCol, int nCol, /* Array to populate */
  188272. const u8 *aBlob, int nBlob /* Record to read varints from */
  188273. ){
  188274. int i;
  188275. int iOff = 0;
  188276. for(i=0; i<nCol; i++){
  188277. if( iOff>=nBlob ) return 1;
  188278. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  188279. }
  188280. return (iOff!=nBlob);
  188281. }
  188282. /*
  188283. ** Argument aCol points to an array of integers containing one entry for
  188284. ** each table column. This function reads the %_docsize record for the
  188285. ** specified rowid and populates aCol[] with the results.
  188286. **
  188287. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  188288. ** otherwise.
  188289. */
  188290. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  188291. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  188292. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  188293. int rc; /* Return Code */
  188294. assert( p->pConfig->bColumnsize );
  188295. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  188296. if( rc==SQLITE_OK ){
  188297. int bCorrupt = 1;
  188298. sqlite3_bind_int64(pLookup, 1, iRowid);
  188299. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  188300. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  188301. int nBlob = sqlite3_column_bytes(pLookup, 0);
  188302. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  188303. bCorrupt = 0;
  188304. }
  188305. }
  188306. rc = sqlite3_reset(pLookup);
  188307. if( bCorrupt && rc==SQLITE_OK ){
  188308. rc = FTS5_CORRUPT;
  188309. }
  188310. }
  188311. return rc;
  188312. }
  188313. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  188314. int rc = fts5StorageLoadTotals(p, 0);
  188315. if( rc==SQLITE_OK ){
  188316. *pnToken = 0;
  188317. if( iCol<0 ){
  188318. int i;
  188319. for(i=0; i<p->pConfig->nCol; i++){
  188320. *pnToken += p->aTotalSize[i];
  188321. }
  188322. }else if( iCol<p->pConfig->nCol ){
  188323. *pnToken = p->aTotalSize[iCol];
  188324. }else{
  188325. rc = SQLITE_RANGE;
  188326. }
  188327. }
  188328. return rc;
  188329. }
  188330. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  188331. int rc = fts5StorageLoadTotals(p, 0);
  188332. if( rc==SQLITE_OK ){
  188333. *pnRow = p->nTotalRow;
  188334. }
  188335. return rc;
  188336. }
  188337. /*
  188338. ** Flush any data currently held in-memory to disk.
  188339. */
  188340. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  188341. int rc = SQLITE_OK;
  188342. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  188343. if( p->bTotalsValid ){
  188344. rc = fts5StorageSaveTotals(p);
  188345. p->bTotalsValid = 0;
  188346. }
  188347. if( rc==SQLITE_OK ){
  188348. rc = sqlite3Fts5IndexSync(p->pIndex);
  188349. }
  188350. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  188351. return rc;
  188352. }
  188353. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  188354. p->bTotalsValid = 0;
  188355. return sqlite3Fts5IndexRollback(p->pIndex);
  188356. }
  188357. static int sqlite3Fts5StorageConfigValue(
  188358. Fts5Storage *p,
  188359. const char *z,
  188360. sqlite3_value *pVal,
  188361. int iVal
  188362. ){
  188363. sqlite3_stmt *pReplace = 0;
  188364. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  188365. if( rc==SQLITE_OK ){
  188366. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  188367. if( pVal ){
  188368. sqlite3_bind_value(pReplace, 2, pVal);
  188369. }else{
  188370. sqlite3_bind_int(pReplace, 2, iVal);
  188371. }
  188372. sqlite3_step(pReplace);
  188373. rc = sqlite3_reset(pReplace);
  188374. }
  188375. if( rc==SQLITE_OK && pVal ){
  188376. int iNew = p->pConfig->iCookie + 1;
  188377. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  188378. if( rc==SQLITE_OK ){
  188379. p->pConfig->iCookie = iNew;
  188380. }
  188381. }
  188382. return rc;
  188383. }
  188384. /*
  188385. ** 2014 May 31
  188386. **
  188387. ** The author disclaims copyright to this source code. In place of
  188388. ** a legal notice, here is a blessing:
  188389. **
  188390. ** May you do good and not evil.
  188391. ** May you find forgiveness for yourself and forgive others.
  188392. ** May you share freely, never taking more than you give.
  188393. **
  188394. ******************************************************************************
  188395. */
  188396. /* #include "fts5Int.h" */
  188397. /**************************************************************************
  188398. ** Start of ascii tokenizer implementation.
  188399. */
  188400. /*
  188401. ** For tokenizers with no "unicode" modifier, the set of token characters
  188402. ** is the same as the set of ASCII range alphanumeric characters.
  188403. */
  188404. static unsigned char aAsciiTokenChar[128] = {
  188405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  188406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  188407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  188408. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  188409. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  188410. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  188411. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  188412. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  188413. };
  188414. typedef struct AsciiTokenizer AsciiTokenizer;
  188415. struct AsciiTokenizer {
  188416. unsigned char aTokenChar[128];
  188417. };
  188418. static void fts5AsciiAddExceptions(
  188419. AsciiTokenizer *p,
  188420. const char *zArg,
  188421. int bTokenChars
  188422. ){
  188423. int i;
  188424. for(i=0; zArg[i]; i++){
  188425. if( (zArg[i] & 0x80)==0 ){
  188426. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  188427. }
  188428. }
  188429. }
  188430. /*
  188431. ** Delete a "ascii" tokenizer.
  188432. */
  188433. static void fts5AsciiDelete(Fts5Tokenizer *p){
  188434. sqlite3_free(p);
  188435. }
  188436. /*
  188437. ** Create an "ascii" tokenizer.
  188438. */
  188439. static int fts5AsciiCreate(
  188440. void *pUnused,
  188441. const char **azArg, int nArg,
  188442. Fts5Tokenizer **ppOut
  188443. ){
  188444. int rc = SQLITE_OK;
  188445. AsciiTokenizer *p = 0;
  188446. UNUSED_PARAM(pUnused);
  188447. if( nArg%2 ){
  188448. rc = SQLITE_ERROR;
  188449. }else{
  188450. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  188451. if( p==0 ){
  188452. rc = SQLITE_NOMEM;
  188453. }else{
  188454. int i;
  188455. memset(p, 0, sizeof(AsciiTokenizer));
  188456. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  188457. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  188458. const char *zArg = azArg[i+1];
  188459. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  188460. fts5AsciiAddExceptions(p, zArg, 1);
  188461. }else
  188462. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  188463. fts5AsciiAddExceptions(p, zArg, 0);
  188464. }else{
  188465. rc = SQLITE_ERROR;
  188466. }
  188467. }
  188468. if( rc!=SQLITE_OK ){
  188469. fts5AsciiDelete((Fts5Tokenizer*)p);
  188470. p = 0;
  188471. }
  188472. }
  188473. }
  188474. *ppOut = (Fts5Tokenizer*)p;
  188475. return rc;
  188476. }
  188477. static void asciiFold(char *aOut, const char *aIn, int nByte){
  188478. int i;
  188479. for(i=0; i<nByte; i++){
  188480. char c = aIn[i];
  188481. if( c>='A' && c<='Z' ) c += 32;
  188482. aOut[i] = c;
  188483. }
  188484. }
  188485. /*
  188486. ** Tokenize some text using the ascii tokenizer.
  188487. */
  188488. static int fts5AsciiTokenize(
  188489. Fts5Tokenizer *pTokenizer,
  188490. void *pCtx,
  188491. int iUnused,
  188492. const char *pText, int nText,
  188493. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  188494. ){
  188495. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  188496. int rc = SQLITE_OK;
  188497. int ie;
  188498. int is = 0;
  188499. char aFold[64];
  188500. int nFold = sizeof(aFold);
  188501. char *pFold = aFold;
  188502. unsigned char *a = p->aTokenChar;
  188503. UNUSED_PARAM(iUnused);
  188504. while( is<nText && rc==SQLITE_OK ){
  188505. int nByte;
  188506. /* Skip any leading divider characters. */
  188507. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  188508. is++;
  188509. }
  188510. if( is==nText ) break;
  188511. /* Count the token characters */
  188512. ie = is+1;
  188513. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  188514. ie++;
  188515. }
  188516. /* Fold to lower case */
  188517. nByte = ie-is;
  188518. if( nByte>nFold ){
  188519. if( pFold!=aFold ) sqlite3_free(pFold);
  188520. pFold = sqlite3_malloc(nByte*2);
  188521. if( pFold==0 ){
  188522. rc = SQLITE_NOMEM;
  188523. break;
  188524. }
  188525. nFold = nByte*2;
  188526. }
  188527. asciiFold(pFold, &pText[is], nByte);
  188528. /* Invoke the token callback */
  188529. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  188530. is = ie+1;
  188531. }
  188532. if( pFold!=aFold ) sqlite3_free(pFold);
  188533. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  188534. return rc;
  188535. }
  188536. /**************************************************************************
  188537. ** Start of unicode61 tokenizer implementation.
  188538. */
  188539. /*
  188540. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  188541. ** from the sqlite3 source file utf.c. If this file is compiled as part
  188542. ** of the amalgamation, they are not required.
  188543. */
  188544. #ifndef SQLITE_AMALGAMATION
  188545. static const unsigned char sqlite3Utf8Trans1[] = {
  188546. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  188547. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  188548. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  188549. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  188550. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  188551. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  188552. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  188553. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  188554. };
  188555. #define READ_UTF8(zIn, zTerm, c) \
  188556. c = *(zIn++); \
  188557. if( c>=0xc0 ){ \
  188558. c = sqlite3Utf8Trans1[c-0xc0]; \
  188559. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  188560. c = (c<<6) + (0x3f & *(zIn++)); \
  188561. } \
  188562. if( c<0x80 \
  188563. || (c&0xFFFFF800)==0xD800 \
  188564. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  188565. }
  188566. #define WRITE_UTF8(zOut, c) { \
  188567. if( c<0x00080 ){ \
  188568. *zOut++ = (unsigned char)(c&0xFF); \
  188569. } \
  188570. else if( c<0x00800 ){ \
  188571. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  188572. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  188573. } \
  188574. else if( c<0x10000 ){ \
  188575. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  188576. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  188577. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  188578. }else{ \
  188579. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  188580. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  188581. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  188582. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  188583. } \
  188584. }
  188585. #endif /* ifndef SQLITE_AMALGAMATION */
  188586. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  188587. struct Unicode61Tokenizer {
  188588. unsigned char aTokenChar[128]; /* ASCII range token characters */
  188589. char *aFold; /* Buffer to fold text into */
  188590. int nFold; /* Size of aFold[] in bytes */
  188591. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  188592. int nException;
  188593. int *aiException;
  188594. };
  188595. static int fts5UnicodeAddExceptions(
  188596. Unicode61Tokenizer *p, /* Tokenizer object */
  188597. const char *z, /* Characters to treat as exceptions */
  188598. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  188599. ){
  188600. int rc = SQLITE_OK;
  188601. int n = (int)strlen(z);
  188602. int *aNew;
  188603. if( n>0 ){
  188604. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  188605. if( aNew ){
  188606. int nNew = p->nException;
  188607. const unsigned char *zCsr = (const unsigned char*)z;
  188608. const unsigned char *zTerm = (const unsigned char*)&z[n];
  188609. while( zCsr<zTerm ){
  188610. int iCode;
  188611. int bToken;
  188612. READ_UTF8(zCsr, zTerm, iCode);
  188613. if( iCode<128 ){
  188614. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  188615. }else{
  188616. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  188617. assert( (bToken==0 || bToken==1) );
  188618. assert( (bTokenChars==0 || bTokenChars==1) );
  188619. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  188620. int i;
  188621. for(i=0; i<nNew; i++){
  188622. if( aNew[i]>iCode ) break;
  188623. }
  188624. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  188625. aNew[i] = iCode;
  188626. nNew++;
  188627. }
  188628. }
  188629. }
  188630. p->aiException = aNew;
  188631. p->nException = nNew;
  188632. }else{
  188633. rc = SQLITE_NOMEM;
  188634. }
  188635. }
  188636. return rc;
  188637. }
  188638. /*
  188639. ** Return true if the p->aiException[] array contains the value iCode.
  188640. */
  188641. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  188642. if( p->nException>0 ){
  188643. int *a = p->aiException;
  188644. int iLo = 0;
  188645. int iHi = p->nException-1;
  188646. while( iHi>=iLo ){
  188647. int iTest = (iHi + iLo) / 2;
  188648. if( iCode==a[iTest] ){
  188649. return 1;
  188650. }else if( iCode>a[iTest] ){
  188651. iLo = iTest+1;
  188652. }else{
  188653. iHi = iTest-1;
  188654. }
  188655. }
  188656. }
  188657. return 0;
  188658. }
  188659. /*
  188660. ** Delete a "unicode61" tokenizer.
  188661. */
  188662. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  188663. if( pTok ){
  188664. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  188665. sqlite3_free(p->aiException);
  188666. sqlite3_free(p->aFold);
  188667. sqlite3_free(p);
  188668. }
  188669. return;
  188670. }
  188671. /*
  188672. ** Create a "unicode61" tokenizer.
  188673. */
  188674. static int fts5UnicodeCreate(
  188675. void *pUnused,
  188676. const char **azArg, int nArg,
  188677. Fts5Tokenizer **ppOut
  188678. ){
  188679. int rc = SQLITE_OK; /* Return code */
  188680. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  188681. UNUSED_PARAM(pUnused);
  188682. if( nArg%2 ){
  188683. rc = SQLITE_ERROR;
  188684. }else{
  188685. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  188686. if( p ){
  188687. int i;
  188688. memset(p, 0, sizeof(Unicode61Tokenizer));
  188689. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  188690. p->bRemoveDiacritic = 1;
  188691. p->nFold = 64;
  188692. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  188693. if( p->aFold==0 ){
  188694. rc = SQLITE_NOMEM;
  188695. }
  188696. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  188697. const char *zArg = azArg[i+1];
  188698. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  188699. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  188700. rc = SQLITE_ERROR;
  188701. }
  188702. p->bRemoveDiacritic = (zArg[0]=='1');
  188703. }else
  188704. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  188705. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  188706. }else
  188707. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  188708. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  188709. }else{
  188710. rc = SQLITE_ERROR;
  188711. }
  188712. }
  188713. }else{
  188714. rc = SQLITE_NOMEM;
  188715. }
  188716. if( rc!=SQLITE_OK ){
  188717. fts5UnicodeDelete((Fts5Tokenizer*)p);
  188718. p = 0;
  188719. }
  188720. *ppOut = (Fts5Tokenizer*)p;
  188721. }
  188722. return rc;
  188723. }
  188724. /*
  188725. ** Return true if, for the purposes of tokenizing with the tokenizer
  188726. ** passed as the first argument, codepoint iCode is considered a token
  188727. ** character (not a separator).
  188728. */
  188729. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  188730. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  188731. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  188732. }
  188733. static int fts5UnicodeTokenize(
  188734. Fts5Tokenizer *pTokenizer,
  188735. void *pCtx,
  188736. int iUnused,
  188737. const char *pText, int nText,
  188738. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  188739. ){
  188740. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  188741. int rc = SQLITE_OK;
  188742. unsigned char *a = p->aTokenChar;
  188743. unsigned char *zTerm = (unsigned char*)&pText[nText];
  188744. unsigned char *zCsr = (unsigned char *)pText;
  188745. /* Output buffer */
  188746. char *aFold = p->aFold;
  188747. int nFold = p->nFold;
  188748. const char *pEnd = &aFold[nFold-6];
  188749. UNUSED_PARAM(iUnused);
  188750. /* Each iteration of this loop gobbles up a contiguous run of separators,
  188751. ** then the next token. */
  188752. while( rc==SQLITE_OK ){
  188753. int iCode; /* non-ASCII codepoint read from input */
  188754. char *zOut = aFold;
  188755. int is;
  188756. int ie;
  188757. /* Skip any separator characters. */
  188758. while( 1 ){
  188759. if( zCsr>=zTerm ) goto tokenize_done;
  188760. if( *zCsr & 0x80 ) {
  188761. /* A character outside of the ascii range. Skip past it if it is
  188762. ** a separator character. Or break out of the loop if it is not. */
  188763. is = zCsr - (unsigned char*)pText;
  188764. READ_UTF8(zCsr, zTerm, iCode);
  188765. if( fts5UnicodeIsAlnum(p, iCode) ){
  188766. goto non_ascii_tokenchar;
  188767. }
  188768. }else{
  188769. if( a[*zCsr] ){
  188770. is = zCsr - (unsigned char*)pText;
  188771. goto ascii_tokenchar;
  188772. }
  188773. zCsr++;
  188774. }
  188775. }
  188776. /* Run through the tokenchars. Fold them into the output buffer along
  188777. ** the way. */
  188778. while( zCsr<zTerm ){
  188779. /* Grow the output buffer so that there is sufficient space to fit the
  188780. ** largest possible utf-8 character. */
  188781. if( zOut>pEnd ){
  188782. aFold = sqlite3_malloc(nFold*2);
  188783. if( aFold==0 ){
  188784. rc = SQLITE_NOMEM;
  188785. goto tokenize_done;
  188786. }
  188787. zOut = &aFold[zOut - p->aFold];
  188788. memcpy(aFold, p->aFold, nFold);
  188789. sqlite3_free(p->aFold);
  188790. p->aFold = aFold;
  188791. p->nFold = nFold = nFold*2;
  188792. pEnd = &aFold[nFold-6];
  188793. }
  188794. if( *zCsr & 0x80 ){
  188795. /* An non-ascii-range character. Fold it into the output buffer if
  188796. ** it is a token character, or break out of the loop if it is not. */
  188797. READ_UTF8(zCsr, zTerm, iCode);
  188798. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  188799. non_ascii_tokenchar:
  188800. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  188801. if( iCode ) WRITE_UTF8(zOut, iCode);
  188802. }else{
  188803. break;
  188804. }
  188805. }else if( a[*zCsr]==0 ){
  188806. /* An ascii-range separator character. End of token. */
  188807. break;
  188808. }else{
  188809. ascii_tokenchar:
  188810. if( *zCsr>='A' && *zCsr<='Z' ){
  188811. *zOut++ = *zCsr + 32;
  188812. }else{
  188813. *zOut++ = *zCsr;
  188814. }
  188815. zCsr++;
  188816. }
  188817. ie = zCsr - (unsigned char*)pText;
  188818. }
  188819. /* Invoke the token callback */
  188820. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  188821. }
  188822. tokenize_done:
  188823. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  188824. return rc;
  188825. }
  188826. /**************************************************************************
  188827. ** Start of porter stemmer implementation.
  188828. */
  188829. /* Any tokens larger than this (in bytes) are passed through without
  188830. ** stemming. */
  188831. #define FTS5_PORTER_MAX_TOKEN 64
  188832. typedef struct PorterTokenizer PorterTokenizer;
  188833. struct PorterTokenizer {
  188834. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  188835. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  188836. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  188837. };
  188838. /*
  188839. ** Delete a "porter" tokenizer.
  188840. */
  188841. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  188842. if( pTok ){
  188843. PorterTokenizer *p = (PorterTokenizer*)pTok;
  188844. if( p->pTokenizer ){
  188845. p->tokenizer.xDelete(p->pTokenizer);
  188846. }
  188847. sqlite3_free(p);
  188848. }
  188849. }
  188850. /*
  188851. ** Create a "porter" tokenizer.
  188852. */
  188853. static int fts5PorterCreate(
  188854. void *pCtx,
  188855. const char **azArg, int nArg,
  188856. Fts5Tokenizer **ppOut
  188857. ){
  188858. fts5_api *pApi = (fts5_api*)pCtx;
  188859. int rc = SQLITE_OK;
  188860. PorterTokenizer *pRet;
  188861. void *pUserdata = 0;
  188862. const char *zBase = "unicode61";
  188863. if( nArg>0 ){
  188864. zBase = azArg[0];
  188865. }
  188866. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  188867. if( pRet ){
  188868. memset(pRet, 0, sizeof(PorterTokenizer));
  188869. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  188870. }else{
  188871. rc = SQLITE_NOMEM;
  188872. }
  188873. if( rc==SQLITE_OK ){
  188874. int nArg2 = (nArg>0 ? nArg-1 : 0);
  188875. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  188876. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  188877. }
  188878. if( rc!=SQLITE_OK ){
  188879. fts5PorterDelete((Fts5Tokenizer*)pRet);
  188880. pRet = 0;
  188881. }
  188882. *ppOut = (Fts5Tokenizer*)pRet;
  188883. return rc;
  188884. }
  188885. typedef struct PorterContext PorterContext;
  188886. struct PorterContext {
  188887. void *pCtx;
  188888. int (*xToken)(void*, int, const char*, int, int, int);
  188889. char *aBuf;
  188890. };
  188891. typedef struct PorterRule PorterRule;
  188892. struct PorterRule {
  188893. const char *zSuffix;
  188894. int nSuffix;
  188895. int (*xCond)(char *zStem, int nStem);
  188896. const char *zOutput;
  188897. int nOutput;
  188898. };
  188899. #if 0
  188900. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  188901. int ret = -1;
  188902. int nBuf = *pnBuf;
  188903. PorterRule *p;
  188904. for(p=aRule; p->zSuffix; p++){
  188905. assert( strlen(p->zSuffix)==p->nSuffix );
  188906. assert( strlen(p->zOutput)==p->nOutput );
  188907. if( nBuf<p->nSuffix ) continue;
  188908. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  188909. }
  188910. if( p->zSuffix ){
  188911. int nStem = nBuf - p->nSuffix;
  188912. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  188913. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  188914. *pnBuf = nStem + p->nOutput;
  188915. ret = p - aRule;
  188916. }
  188917. }
  188918. return ret;
  188919. }
  188920. #endif
  188921. static int fts5PorterIsVowel(char c, int bYIsVowel){
  188922. return (
  188923. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  188924. );
  188925. }
  188926. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  188927. int i;
  188928. int bCons = bPrevCons;
  188929. /* Scan for a vowel */
  188930. for(i=0; i<nStem; i++){
  188931. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  188932. }
  188933. /* Scan for a consonent */
  188934. for(i++; i<nStem; i++){
  188935. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  188936. }
  188937. return 0;
  188938. }
  188939. /* porter rule condition: (m > 0) */
  188940. static int fts5Porter_MGt0(char *zStem, int nStem){
  188941. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  188942. }
  188943. /* porter rule condition: (m > 1) */
  188944. static int fts5Porter_MGt1(char *zStem, int nStem){
  188945. int n;
  188946. n = fts5PorterGobbleVC(zStem, nStem, 0);
  188947. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  188948. return 1;
  188949. }
  188950. return 0;
  188951. }
  188952. /* porter rule condition: (m = 1) */
  188953. static int fts5Porter_MEq1(char *zStem, int nStem){
  188954. int n;
  188955. n = fts5PorterGobbleVC(zStem, nStem, 0);
  188956. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  188957. return 1;
  188958. }
  188959. return 0;
  188960. }
  188961. /* porter rule condition: (*o) */
  188962. static int fts5Porter_Ostar(char *zStem, int nStem){
  188963. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  188964. return 0;
  188965. }else{
  188966. int i;
  188967. int mask = 0;
  188968. int bCons = 0;
  188969. for(i=0; i<nStem; i++){
  188970. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  188971. assert( bCons==0 || bCons==1 );
  188972. mask = (mask << 1) + bCons;
  188973. }
  188974. return ((mask & 0x0007)==0x0005);
  188975. }
  188976. }
  188977. /* porter rule condition: (m > 1 and (*S or *T)) */
  188978. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  188979. assert( nStem>0 );
  188980. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  188981. && fts5Porter_MGt1(zStem, nStem);
  188982. }
  188983. /* porter rule condition: (*v*) */
  188984. static int fts5Porter_Vowel(char *zStem, int nStem){
  188985. int i;
  188986. for(i=0; i<nStem; i++){
  188987. if( fts5PorterIsVowel(zStem[i], i>0) ){
  188988. return 1;
  188989. }
  188990. }
  188991. return 0;
  188992. }
  188993. /**************************************************************************
  188994. ***************************************************************************
  188995. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  188996. */
  188997. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  188998. int ret = 0;
  188999. int nBuf = *pnBuf;
  189000. switch( aBuf[nBuf-2] ){
  189001. case 'a':
  189002. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  189003. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  189004. *pnBuf = nBuf - 2;
  189005. }
  189006. }
  189007. break;
  189008. case 'c':
  189009. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  189010. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  189011. *pnBuf = nBuf - 4;
  189012. }
  189013. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  189014. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  189015. *pnBuf = nBuf - 4;
  189016. }
  189017. }
  189018. break;
  189019. case 'e':
  189020. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  189021. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  189022. *pnBuf = nBuf - 2;
  189023. }
  189024. }
  189025. break;
  189026. case 'i':
  189027. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  189028. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  189029. *pnBuf = nBuf - 2;
  189030. }
  189031. }
  189032. break;
  189033. case 'l':
  189034. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  189035. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  189036. *pnBuf = nBuf - 4;
  189037. }
  189038. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  189039. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  189040. *pnBuf = nBuf - 4;
  189041. }
  189042. }
  189043. break;
  189044. case 'n':
  189045. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  189046. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189047. *pnBuf = nBuf - 3;
  189048. }
  189049. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  189050. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  189051. *pnBuf = nBuf - 5;
  189052. }
  189053. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  189054. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  189055. *pnBuf = nBuf - 4;
  189056. }
  189057. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  189058. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189059. *pnBuf = nBuf - 3;
  189060. }
  189061. }
  189062. break;
  189063. case 'o':
  189064. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  189065. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  189066. *pnBuf = nBuf - 3;
  189067. }
  189068. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  189069. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  189070. *pnBuf = nBuf - 2;
  189071. }
  189072. }
  189073. break;
  189074. case 's':
  189075. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  189076. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189077. *pnBuf = nBuf - 3;
  189078. }
  189079. }
  189080. break;
  189081. case 't':
  189082. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  189083. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189084. *pnBuf = nBuf - 3;
  189085. }
  189086. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  189087. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189088. *pnBuf = nBuf - 3;
  189089. }
  189090. }
  189091. break;
  189092. case 'u':
  189093. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  189094. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189095. *pnBuf = nBuf - 3;
  189096. }
  189097. }
  189098. break;
  189099. case 'v':
  189100. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  189101. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189102. *pnBuf = nBuf - 3;
  189103. }
  189104. }
  189105. break;
  189106. case 'z':
  189107. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  189108. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  189109. *pnBuf = nBuf - 3;
  189110. }
  189111. }
  189112. break;
  189113. }
  189114. return ret;
  189115. }
  189116. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  189117. int ret = 0;
  189118. int nBuf = *pnBuf;
  189119. switch( aBuf[nBuf-2] ){
  189120. case 'a':
  189121. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  189122. memcpy(&aBuf[nBuf-2], "ate", 3);
  189123. *pnBuf = nBuf - 2 + 3;
  189124. ret = 1;
  189125. }
  189126. break;
  189127. case 'b':
  189128. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  189129. memcpy(&aBuf[nBuf-2], "ble", 3);
  189130. *pnBuf = nBuf - 2 + 3;
  189131. ret = 1;
  189132. }
  189133. break;
  189134. case 'i':
  189135. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  189136. memcpy(&aBuf[nBuf-2], "ize", 3);
  189137. *pnBuf = nBuf - 2 + 3;
  189138. ret = 1;
  189139. }
  189140. break;
  189141. }
  189142. return ret;
  189143. }
  189144. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  189145. int ret = 0;
  189146. int nBuf = *pnBuf;
  189147. switch( aBuf[nBuf-2] ){
  189148. case 'a':
  189149. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  189150. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  189151. memcpy(&aBuf[nBuf-7], "ate", 3);
  189152. *pnBuf = nBuf - 7 + 3;
  189153. }
  189154. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  189155. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  189156. memcpy(&aBuf[nBuf-6], "tion", 4);
  189157. *pnBuf = nBuf - 6 + 4;
  189158. }
  189159. }
  189160. break;
  189161. case 'c':
  189162. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  189163. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189164. memcpy(&aBuf[nBuf-4], "ence", 4);
  189165. *pnBuf = nBuf - 4 + 4;
  189166. }
  189167. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  189168. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189169. memcpy(&aBuf[nBuf-4], "ance", 4);
  189170. *pnBuf = nBuf - 4 + 4;
  189171. }
  189172. }
  189173. break;
  189174. case 'e':
  189175. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  189176. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189177. memcpy(&aBuf[nBuf-4], "ize", 3);
  189178. *pnBuf = nBuf - 4 + 3;
  189179. }
  189180. }
  189181. break;
  189182. case 'g':
  189183. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  189184. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189185. memcpy(&aBuf[nBuf-4], "log", 3);
  189186. *pnBuf = nBuf - 4 + 3;
  189187. }
  189188. }
  189189. break;
  189190. case 'l':
  189191. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  189192. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  189193. memcpy(&aBuf[nBuf-3], "ble", 3);
  189194. *pnBuf = nBuf - 3 + 3;
  189195. }
  189196. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  189197. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189198. memcpy(&aBuf[nBuf-4], "al", 2);
  189199. *pnBuf = nBuf - 4 + 2;
  189200. }
  189201. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  189202. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189203. memcpy(&aBuf[nBuf-5], "ent", 3);
  189204. *pnBuf = nBuf - 5 + 3;
  189205. }
  189206. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  189207. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  189208. memcpy(&aBuf[nBuf-3], "e", 1);
  189209. *pnBuf = nBuf - 3 + 1;
  189210. }
  189211. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  189212. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189213. memcpy(&aBuf[nBuf-5], "ous", 3);
  189214. *pnBuf = nBuf - 5 + 3;
  189215. }
  189216. }
  189217. break;
  189218. case 'o':
  189219. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  189220. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  189221. memcpy(&aBuf[nBuf-7], "ize", 3);
  189222. *pnBuf = nBuf - 7 + 3;
  189223. }
  189224. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  189225. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189226. memcpy(&aBuf[nBuf-5], "ate", 3);
  189227. *pnBuf = nBuf - 5 + 3;
  189228. }
  189229. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  189230. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189231. memcpy(&aBuf[nBuf-4], "ate", 3);
  189232. *pnBuf = nBuf - 4 + 3;
  189233. }
  189234. }
  189235. break;
  189236. case 's':
  189237. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  189238. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189239. memcpy(&aBuf[nBuf-5], "al", 2);
  189240. *pnBuf = nBuf - 5 + 2;
  189241. }
  189242. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  189243. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  189244. memcpy(&aBuf[nBuf-7], "ive", 3);
  189245. *pnBuf = nBuf - 7 + 3;
  189246. }
  189247. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  189248. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  189249. memcpy(&aBuf[nBuf-7], "ful", 3);
  189250. *pnBuf = nBuf - 7 + 3;
  189251. }
  189252. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  189253. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  189254. memcpy(&aBuf[nBuf-7], "ous", 3);
  189255. *pnBuf = nBuf - 7 + 3;
  189256. }
  189257. }
  189258. break;
  189259. case 't':
  189260. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  189261. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189262. memcpy(&aBuf[nBuf-5], "al", 2);
  189263. *pnBuf = nBuf - 5 + 2;
  189264. }
  189265. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  189266. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189267. memcpy(&aBuf[nBuf-5], "ive", 3);
  189268. *pnBuf = nBuf - 5 + 3;
  189269. }
  189270. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  189271. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  189272. memcpy(&aBuf[nBuf-6], "ble", 3);
  189273. *pnBuf = nBuf - 6 + 3;
  189274. }
  189275. }
  189276. break;
  189277. }
  189278. return ret;
  189279. }
  189280. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  189281. int ret = 0;
  189282. int nBuf = *pnBuf;
  189283. switch( aBuf[nBuf-2] ){
  189284. case 'a':
  189285. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  189286. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189287. memcpy(&aBuf[nBuf-4], "ic", 2);
  189288. *pnBuf = nBuf - 4 + 2;
  189289. }
  189290. }
  189291. break;
  189292. case 's':
  189293. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  189294. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  189295. *pnBuf = nBuf - 4;
  189296. }
  189297. }
  189298. break;
  189299. case 't':
  189300. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  189301. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189302. memcpy(&aBuf[nBuf-5], "ic", 2);
  189303. *pnBuf = nBuf - 5 + 2;
  189304. }
  189305. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  189306. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189307. memcpy(&aBuf[nBuf-5], "ic", 2);
  189308. *pnBuf = nBuf - 5 + 2;
  189309. }
  189310. }
  189311. break;
  189312. case 'u':
  189313. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  189314. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  189315. *pnBuf = nBuf - 3;
  189316. }
  189317. }
  189318. break;
  189319. case 'v':
  189320. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  189321. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189322. *pnBuf = nBuf - 5;
  189323. }
  189324. }
  189325. break;
  189326. case 'z':
  189327. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  189328. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  189329. memcpy(&aBuf[nBuf-5], "al", 2);
  189330. *pnBuf = nBuf - 5 + 2;
  189331. }
  189332. }
  189333. break;
  189334. }
  189335. return ret;
  189336. }
  189337. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  189338. int ret = 0;
  189339. int nBuf = *pnBuf;
  189340. switch( aBuf[nBuf-2] ){
  189341. case 'e':
  189342. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  189343. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  189344. memcpy(&aBuf[nBuf-3], "ee", 2);
  189345. *pnBuf = nBuf - 3 + 2;
  189346. }
  189347. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  189348. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  189349. *pnBuf = nBuf - 2;
  189350. ret = 1;
  189351. }
  189352. }
  189353. break;
  189354. case 'n':
  189355. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  189356. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  189357. *pnBuf = nBuf - 3;
  189358. ret = 1;
  189359. }
  189360. }
  189361. break;
  189362. }
  189363. return ret;
  189364. }
  189365. /*
  189366. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  189367. ***************************************************************************
  189368. **************************************************************************/
  189369. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  189370. int nBuf = *pnBuf;
  189371. if( aBuf[nBuf-1]=='s' ){
  189372. if( aBuf[nBuf-2]=='e' ){
  189373. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  189374. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  189375. ){
  189376. *pnBuf = nBuf-2;
  189377. }else{
  189378. *pnBuf = nBuf-1;
  189379. }
  189380. }
  189381. else if( aBuf[nBuf-2]!='s' ){
  189382. *pnBuf = nBuf-1;
  189383. }
  189384. }
  189385. }
  189386. static int fts5PorterCb(
  189387. void *pCtx,
  189388. int tflags,
  189389. const char *pToken,
  189390. int nToken,
  189391. int iStart,
  189392. int iEnd
  189393. ){
  189394. PorterContext *p = (PorterContext*)pCtx;
  189395. char *aBuf;
  189396. int nBuf;
  189397. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  189398. aBuf = p->aBuf;
  189399. nBuf = nToken;
  189400. memcpy(aBuf, pToken, nBuf);
  189401. /* Step 1. */
  189402. fts5PorterStep1A(aBuf, &nBuf);
  189403. if( fts5PorterStep1B(aBuf, &nBuf) ){
  189404. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  189405. char c = aBuf[nBuf-1];
  189406. if( fts5PorterIsVowel(c, 0)==0
  189407. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  189408. ){
  189409. nBuf--;
  189410. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  189411. aBuf[nBuf++] = 'e';
  189412. }
  189413. }
  189414. }
  189415. /* Step 1C. */
  189416. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  189417. aBuf[nBuf-1] = 'i';
  189418. }
  189419. /* Steps 2 through 4. */
  189420. fts5PorterStep2(aBuf, &nBuf);
  189421. fts5PorterStep3(aBuf, &nBuf);
  189422. fts5PorterStep4(aBuf, &nBuf);
  189423. /* Step 5a. */
  189424. assert( nBuf>0 );
  189425. if( aBuf[nBuf-1]=='e' ){
  189426. if( fts5Porter_MGt1(aBuf, nBuf-1)
  189427. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  189428. ){
  189429. nBuf--;
  189430. }
  189431. }
  189432. /* Step 5b. */
  189433. if( nBuf>1 && aBuf[nBuf-1]=='l'
  189434. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  189435. ){
  189436. nBuf--;
  189437. }
  189438. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  189439. pass_through:
  189440. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  189441. }
  189442. /*
  189443. ** Tokenize using the porter tokenizer.
  189444. */
  189445. static int fts5PorterTokenize(
  189446. Fts5Tokenizer *pTokenizer,
  189447. void *pCtx,
  189448. int flags,
  189449. const char *pText, int nText,
  189450. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  189451. ){
  189452. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  189453. PorterContext sCtx;
  189454. sCtx.xToken = xToken;
  189455. sCtx.pCtx = pCtx;
  189456. sCtx.aBuf = p->aBuf;
  189457. return p->tokenizer.xTokenize(
  189458. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  189459. );
  189460. }
  189461. /*
  189462. ** Register all built-in tokenizers with FTS5.
  189463. */
  189464. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  189465. struct BuiltinTokenizer {
  189466. const char *zName;
  189467. fts5_tokenizer x;
  189468. } aBuiltin[] = {
  189469. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  189470. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  189471. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  189472. };
  189473. int rc = SQLITE_OK; /* Return code */
  189474. int i; /* To iterate through builtin functions */
  189475. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  189476. rc = pApi->xCreateTokenizer(pApi,
  189477. aBuiltin[i].zName,
  189478. (void*)pApi,
  189479. &aBuiltin[i].x,
  189480. 0
  189481. );
  189482. }
  189483. return rc;
  189484. }
  189485. /*
  189486. ** 2012 May 25
  189487. **
  189488. ** The author disclaims copyright to this source code. In place of
  189489. ** a legal notice, here is a blessing:
  189490. **
  189491. ** May you do good and not evil.
  189492. ** May you find forgiveness for yourself and forgive others.
  189493. ** May you share freely, never taking more than you give.
  189494. **
  189495. ******************************************************************************
  189496. */
  189497. /*
  189498. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  189499. */
  189500. /* #include <assert.h> */
  189501. /*
  189502. ** Return true if the argument corresponds to a unicode codepoint
  189503. ** classified as either a letter or a number. Otherwise false.
  189504. **
  189505. ** The results are undefined if the value passed to this function
  189506. ** is less than zero.
  189507. */
  189508. static int sqlite3Fts5UnicodeIsalnum(int c){
  189509. /* Each unsigned integer in the following array corresponds to a contiguous
  189510. ** range of unicode codepoints that are not either letters or numbers (i.e.
  189511. ** codepoints for which this function should return 0).
  189512. **
  189513. ** The most significant 22 bits in each 32-bit value contain the first
  189514. ** codepoint in the range. The least significant 10 bits are used to store
  189515. ** the size of the range (always at least 1). In other words, the value
  189516. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  189517. ** C. It is not possible to represent a range larger than 1023 codepoints
  189518. ** using this format.
  189519. */
  189520. static const unsigned int aEntry[] = {
  189521. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  189522. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  189523. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  189524. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  189525. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  189526. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  189527. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  189528. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  189529. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  189530. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  189531. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  189532. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  189533. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  189534. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  189535. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  189536. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  189537. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  189538. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  189539. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  189540. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  189541. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  189542. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  189543. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  189544. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  189545. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  189546. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  189547. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  189548. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  189549. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  189550. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  189551. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  189552. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  189553. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  189554. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  189555. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  189556. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  189557. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  189558. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  189559. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  189560. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  189561. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  189562. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  189563. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  189564. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  189565. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  189566. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  189567. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  189568. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  189569. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  189570. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  189571. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  189572. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  189573. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  189574. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  189575. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  189576. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  189577. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  189578. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  189579. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  189580. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  189581. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  189582. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  189583. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  189584. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  189585. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  189586. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  189587. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  189588. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  189589. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  189590. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  189591. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  189592. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  189593. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  189594. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  189595. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  189596. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  189597. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  189598. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  189599. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  189600. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  189601. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  189602. 0x380400F0,
  189603. };
  189604. static const unsigned int aAscii[4] = {
  189605. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  189606. };
  189607. if( (unsigned int)c<128 ){
  189608. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  189609. }else if( (unsigned int)c<(1<<22) ){
  189610. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  189611. int iRes = 0;
  189612. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  189613. int iLo = 0;
  189614. while( iHi>=iLo ){
  189615. int iTest = (iHi + iLo) / 2;
  189616. if( key >= aEntry[iTest] ){
  189617. iRes = iTest;
  189618. iLo = iTest+1;
  189619. }else{
  189620. iHi = iTest-1;
  189621. }
  189622. }
  189623. assert( aEntry[0]<key );
  189624. assert( key>=aEntry[iRes] );
  189625. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  189626. }
  189627. return 1;
  189628. }
  189629. /*
  189630. ** If the argument is a codepoint corresponding to a lowercase letter
  189631. ** in the ASCII range with a diacritic added, return the codepoint
  189632. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  189633. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  189634. ** E"). The resuls of passing a codepoint that corresponds to an
  189635. ** uppercase letter are undefined.
  189636. */
  189637. static int fts5_remove_diacritic(int c){
  189638. unsigned short aDia[] = {
  189639. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  189640. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  189641. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  189642. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  189643. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  189644. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  189645. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  189646. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  189647. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  189648. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  189649. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  189650. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  189651. 62924, 63050, 63082, 63274, 63390,
  189652. };
  189653. char aChar[] = {
  189654. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  189655. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  189656. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  189657. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  189658. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  189659. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  189660. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  189661. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  189662. 'e', 'i', 'o', 'u', 'y',
  189663. };
  189664. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  189665. int iRes = 0;
  189666. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  189667. int iLo = 0;
  189668. while( iHi>=iLo ){
  189669. int iTest = (iHi + iLo) / 2;
  189670. if( key >= aDia[iTest] ){
  189671. iRes = iTest;
  189672. iLo = iTest+1;
  189673. }else{
  189674. iHi = iTest-1;
  189675. }
  189676. }
  189677. assert( key>=aDia[iRes] );
  189678. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  189679. }
  189680. /*
  189681. ** Return true if the argument interpreted as a unicode codepoint
  189682. ** is a diacritical modifier character.
  189683. */
  189684. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  189685. unsigned int mask0 = 0x08029FDF;
  189686. unsigned int mask1 = 0x000361F8;
  189687. if( c<768 || c>817 ) return 0;
  189688. return (c < 768+32) ?
  189689. (mask0 & (1 << (c-768))) :
  189690. (mask1 & (1 << (c-768-32)));
  189691. }
  189692. /*
  189693. ** Interpret the argument as a unicode codepoint. If the codepoint
  189694. ** is an upper case character that has a lower case equivalent,
  189695. ** return the codepoint corresponding to the lower case version.
  189696. ** Otherwise, return a copy of the argument.
  189697. **
  189698. ** The results are undefined if the value passed to this function
  189699. ** is less than zero.
  189700. */
  189701. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  189702. /* Each entry in the following array defines a rule for folding a range
  189703. ** of codepoints to lower case. The rule applies to a range of nRange
  189704. ** codepoints starting at codepoint iCode.
  189705. **
  189706. ** If the least significant bit in flags is clear, then the rule applies
  189707. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  189708. ** need to be folded). Or, if it is set, then the rule only applies to
  189709. ** every second codepoint in the range, starting with codepoint C.
  189710. **
  189711. ** The 7 most significant bits in flags are an index into the aiOff[]
  189712. ** array. If a specific codepoint C does require folding, then its lower
  189713. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  189714. **
  189715. ** The contents of this array are generated by parsing the CaseFolding.txt
  189716. ** file distributed as part of the "Unicode Character Database". See
  189717. ** http://www.unicode.org for details.
  189718. */
  189719. static const struct TableEntry {
  189720. unsigned short iCode;
  189721. unsigned char flags;
  189722. unsigned char nRange;
  189723. } aEntry[] = {
  189724. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  189725. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  189726. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  189727. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  189728. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  189729. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  189730. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  189731. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  189732. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  189733. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  189734. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  189735. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  189736. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  189737. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  189738. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  189739. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  189740. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  189741. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  189742. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  189743. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  189744. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  189745. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  189746. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  189747. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  189748. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  189749. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  189750. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  189751. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  189752. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  189753. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  189754. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  189755. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  189756. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  189757. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  189758. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  189759. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  189760. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  189761. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  189762. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  189763. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  189764. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  189765. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  189766. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  189767. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  189768. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  189769. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  189770. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  189771. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  189772. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  189773. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  189774. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  189775. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  189776. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  189777. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  189778. {65313, 14, 26},
  189779. };
  189780. static const unsigned short aiOff[] = {
  189781. 1, 2, 8, 15, 16, 26, 28, 32,
  189782. 37, 38, 40, 48, 63, 64, 69, 71,
  189783. 79, 80, 116, 202, 203, 205, 206, 207,
  189784. 209, 210, 211, 213, 214, 217, 218, 219,
  189785. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  189786. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  189787. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  189788. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  189789. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  189790. 65514, 65521, 65527, 65528, 65529,
  189791. };
  189792. int ret = c;
  189793. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  189794. if( c<128 ){
  189795. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  189796. }else if( c<65536 ){
  189797. const struct TableEntry *p;
  189798. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  189799. int iLo = 0;
  189800. int iRes = -1;
  189801. assert( c>aEntry[0].iCode );
  189802. while( iHi>=iLo ){
  189803. int iTest = (iHi + iLo) / 2;
  189804. int cmp = (c - aEntry[iTest].iCode);
  189805. if( cmp>=0 ){
  189806. iRes = iTest;
  189807. iLo = iTest+1;
  189808. }else{
  189809. iHi = iTest-1;
  189810. }
  189811. }
  189812. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  189813. p = &aEntry[iRes];
  189814. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  189815. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  189816. assert( ret>0 );
  189817. }
  189818. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  189819. }
  189820. else if( c>=66560 && c<66600 ){
  189821. ret = c + 40;
  189822. }
  189823. return ret;
  189824. }
  189825. /*
  189826. ** 2015 May 30
  189827. **
  189828. ** The author disclaims copyright to this source code. In place of
  189829. ** a legal notice, here is a blessing:
  189830. **
  189831. ** May you do good and not evil.
  189832. ** May you find forgiveness for yourself and forgive others.
  189833. ** May you share freely, never taking more than you give.
  189834. **
  189835. ******************************************************************************
  189836. **
  189837. ** Routines for varint serialization and deserialization.
  189838. */
  189839. /* #include "fts5Int.h" */
  189840. /*
  189841. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  189842. ** Except, this version does handle the single byte case that the core
  189843. ** version depends on being handled before its function is called.
  189844. */
  189845. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  189846. u32 a,b;
  189847. /* The 1-byte case. Overwhelmingly the most common. */
  189848. a = *p;
  189849. /* a: p0 (unmasked) */
  189850. if (!(a&0x80))
  189851. {
  189852. /* Values between 0 and 127 */
  189853. *v = a;
  189854. return 1;
  189855. }
  189856. /* The 2-byte case */
  189857. p++;
  189858. b = *p;
  189859. /* b: p1 (unmasked) */
  189860. if (!(b&0x80))
  189861. {
  189862. /* Values between 128 and 16383 */
  189863. a &= 0x7f;
  189864. a = a<<7;
  189865. *v = a | b;
  189866. return 2;
  189867. }
  189868. /* The 3-byte case */
  189869. p++;
  189870. a = a<<14;
  189871. a |= *p;
  189872. /* a: p0<<14 | p2 (unmasked) */
  189873. if (!(a&0x80))
  189874. {
  189875. /* Values between 16384 and 2097151 */
  189876. a &= (0x7f<<14)|(0x7f);
  189877. b &= 0x7f;
  189878. b = b<<7;
  189879. *v = a | b;
  189880. return 3;
  189881. }
  189882. /* A 32-bit varint is used to store size information in btrees.
  189883. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  189884. ** A 3-byte varint is sufficient, for example, to record the size
  189885. ** of a 1048569-byte BLOB or string.
  189886. **
  189887. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  189888. ** rare larger cases can be handled by the slower 64-bit varint
  189889. ** routine.
  189890. */
  189891. {
  189892. u64 v64;
  189893. u8 n;
  189894. p -= 2;
  189895. n = sqlite3Fts5GetVarint(p, &v64);
  189896. *v = (u32)v64;
  189897. assert( n>3 && n<=9 );
  189898. return n;
  189899. }
  189900. }
  189901. /*
  189902. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  189903. ** are defined here rather than simply putting the constant expressions
  189904. ** inline in order to work around bugs in the RVT compiler.
  189905. **
  189906. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  189907. **
  189908. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  189909. */
  189910. #define SLOT_2_0 0x001fc07f
  189911. #define SLOT_4_2_0 0xf01fc07f
  189912. /*
  189913. ** Read a 64-bit variable-length integer from memory starting at p[0].
  189914. ** Return the number of bytes read. The value is stored in *v.
  189915. */
  189916. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  189917. u32 a,b,s;
  189918. a = *p;
  189919. /* a: p0 (unmasked) */
  189920. if (!(a&0x80))
  189921. {
  189922. *v = a;
  189923. return 1;
  189924. }
  189925. p++;
  189926. b = *p;
  189927. /* b: p1 (unmasked) */
  189928. if (!(b&0x80))
  189929. {
  189930. a &= 0x7f;
  189931. a = a<<7;
  189932. a |= b;
  189933. *v = a;
  189934. return 2;
  189935. }
  189936. /* Verify that constants are precomputed correctly */
  189937. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  189938. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  189939. p++;
  189940. a = a<<14;
  189941. a |= *p;
  189942. /* a: p0<<14 | p2 (unmasked) */
  189943. if (!(a&0x80))
  189944. {
  189945. a &= SLOT_2_0;
  189946. b &= 0x7f;
  189947. b = b<<7;
  189948. a |= b;
  189949. *v = a;
  189950. return 3;
  189951. }
  189952. /* CSE1 from below */
  189953. a &= SLOT_2_0;
  189954. p++;
  189955. b = b<<14;
  189956. b |= *p;
  189957. /* b: p1<<14 | p3 (unmasked) */
  189958. if (!(b&0x80))
  189959. {
  189960. b &= SLOT_2_0;
  189961. /* moved CSE1 up */
  189962. /* a &= (0x7f<<14)|(0x7f); */
  189963. a = a<<7;
  189964. a |= b;
  189965. *v = a;
  189966. return 4;
  189967. }
  189968. /* a: p0<<14 | p2 (masked) */
  189969. /* b: p1<<14 | p3 (unmasked) */
  189970. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  189971. /* moved CSE1 up */
  189972. /* a &= (0x7f<<14)|(0x7f); */
  189973. b &= SLOT_2_0;
  189974. s = a;
  189975. /* s: p0<<14 | p2 (masked) */
  189976. p++;
  189977. a = a<<14;
  189978. a |= *p;
  189979. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  189980. if (!(a&0x80))
  189981. {
  189982. /* we can skip these cause they were (effectively) done above in calc'ing s */
  189983. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  189984. /* b &= (0x7f<<14)|(0x7f); */
  189985. b = b<<7;
  189986. a |= b;
  189987. s = s>>18;
  189988. *v = ((u64)s)<<32 | a;
  189989. return 5;
  189990. }
  189991. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  189992. s = s<<7;
  189993. s |= b;
  189994. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  189995. p++;
  189996. b = b<<14;
  189997. b |= *p;
  189998. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  189999. if (!(b&0x80))
  190000. {
  190001. /* we can skip this cause it was (effectively) done above in calc'ing s */
  190002. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  190003. a &= SLOT_2_0;
  190004. a = a<<7;
  190005. a |= b;
  190006. s = s>>18;
  190007. *v = ((u64)s)<<32 | a;
  190008. return 6;
  190009. }
  190010. p++;
  190011. a = a<<14;
  190012. a |= *p;
  190013. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  190014. if (!(a&0x80))
  190015. {
  190016. a &= SLOT_4_2_0;
  190017. b &= SLOT_2_0;
  190018. b = b<<7;
  190019. a |= b;
  190020. s = s>>11;
  190021. *v = ((u64)s)<<32 | a;
  190022. return 7;
  190023. }
  190024. /* CSE2 from below */
  190025. a &= SLOT_2_0;
  190026. p++;
  190027. b = b<<14;
  190028. b |= *p;
  190029. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  190030. if (!(b&0x80))
  190031. {
  190032. b &= SLOT_4_2_0;
  190033. /* moved CSE2 up */
  190034. /* a &= (0x7f<<14)|(0x7f); */
  190035. a = a<<7;
  190036. a |= b;
  190037. s = s>>4;
  190038. *v = ((u64)s)<<32 | a;
  190039. return 8;
  190040. }
  190041. p++;
  190042. a = a<<15;
  190043. a |= *p;
  190044. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  190045. /* moved CSE2 up */
  190046. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  190047. b &= SLOT_2_0;
  190048. b = b<<8;
  190049. a |= b;
  190050. s = s<<4;
  190051. b = p[-4];
  190052. b &= 0x7f;
  190053. b = b>>3;
  190054. s |= b;
  190055. *v = ((u64)s)<<32 | a;
  190056. return 9;
  190057. }
  190058. /*
  190059. ** The variable-length integer encoding is as follows:
  190060. **
  190061. ** KEY:
  190062. ** A = 0xxxxxxx 7 bits of data and one flag bit
  190063. ** B = 1xxxxxxx 7 bits of data and one flag bit
  190064. ** C = xxxxxxxx 8 bits of data
  190065. **
  190066. ** 7 bits - A
  190067. ** 14 bits - BA
  190068. ** 21 bits - BBA
  190069. ** 28 bits - BBBA
  190070. ** 35 bits - BBBBA
  190071. ** 42 bits - BBBBBA
  190072. ** 49 bits - BBBBBBA
  190073. ** 56 bits - BBBBBBBA
  190074. ** 64 bits - BBBBBBBBC
  190075. */
  190076. #ifdef SQLITE_NOINLINE
  190077. # define FTS5_NOINLINE SQLITE_NOINLINE
  190078. #else
  190079. # define FTS5_NOINLINE
  190080. #endif
  190081. /*
  190082. ** Write a 64-bit variable-length integer to memory starting at p[0].
  190083. ** The length of data write will be between 1 and 9 bytes. The number
  190084. ** of bytes written is returned.
  190085. **
  190086. ** A variable-length integer consists of the lower 7 bits of each byte
  190087. ** for all bytes that have the 8th bit set and one byte with the 8th
  190088. ** bit clear. Except, if we get to the 9th byte, it stores the full
  190089. ** 8 bits and is the last byte.
  190090. */
  190091. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  190092. int i, j, n;
  190093. u8 buf[10];
  190094. if( v & (((u64)0xff000000)<<32) ){
  190095. p[8] = (u8)v;
  190096. v >>= 8;
  190097. for(i=7; i>=0; i--){
  190098. p[i] = (u8)((v & 0x7f) | 0x80);
  190099. v >>= 7;
  190100. }
  190101. return 9;
  190102. }
  190103. n = 0;
  190104. do{
  190105. buf[n++] = (u8)((v & 0x7f) | 0x80);
  190106. v >>= 7;
  190107. }while( v!=0 );
  190108. buf[0] &= 0x7f;
  190109. assert( n<=9 );
  190110. for(i=0, j=n-1; j>=0; j--, i++){
  190111. p[i] = buf[j];
  190112. }
  190113. return n;
  190114. }
  190115. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  190116. if( v<=0x7f ){
  190117. p[0] = v&0x7f;
  190118. return 1;
  190119. }
  190120. if( v<=0x3fff ){
  190121. p[0] = ((v>>7)&0x7f)|0x80;
  190122. p[1] = v&0x7f;
  190123. return 2;
  190124. }
  190125. return fts5PutVarint64(p,v);
  190126. }
  190127. static int sqlite3Fts5GetVarintLen(u32 iVal){
  190128. #if 0
  190129. if( iVal<(1 << 7 ) ) return 1;
  190130. #endif
  190131. assert( iVal>=(1 << 7) );
  190132. if( iVal<(1 << 14) ) return 2;
  190133. if( iVal<(1 << 21) ) return 3;
  190134. if( iVal<(1 << 28) ) return 4;
  190135. return 5;
  190136. }
  190137. /*
  190138. ** 2015 May 08
  190139. **
  190140. ** The author disclaims copyright to this source code. In place of
  190141. ** a legal notice, here is a blessing:
  190142. **
  190143. ** May you do good and not evil.
  190144. ** May you find forgiveness for yourself and forgive others.
  190145. ** May you share freely, never taking more than you give.
  190146. **
  190147. ******************************************************************************
  190148. **
  190149. ** This is an SQLite virtual table module implementing direct access to an
  190150. ** existing FTS5 index. The module may create several different types of
  190151. ** tables:
  190152. **
  190153. ** col:
  190154. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  190155. **
  190156. ** One row for each term/column combination. The value of $doc is set to
  190157. ** the number of fts5 rows that contain at least one instance of term
  190158. ** $term within column $col. Field $cnt is set to the total number of
  190159. ** instances of term $term in column $col (in any row of the fts5 table).
  190160. **
  190161. ** row:
  190162. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  190163. **
  190164. ** One row for each term in the database. The value of $doc is set to
  190165. ** the number of fts5 rows that contain at least one instance of term
  190166. ** $term. Field $cnt is set to the total number of instances of term
  190167. ** $term in the database.
  190168. **
  190169. ** instance:
  190170. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  190171. **
  190172. ** One row for each term instance in the database.
  190173. */
  190174. /* #include "fts5Int.h" */
  190175. typedef struct Fts5VocabTable Fts5VocabTable;
  190176. typedef struct Fts5VocabCursor Fts5VocabCursor;
  190177. struct Fts5VocabTable {
  190178. sqlite3_vtab base;
  190179. char *zFts5Tbl; /* Name of fts5 table */
  190180. char *zFts5Db; /* Db containing fts5 table */
  190181. sqlite3 *db; /* Database handle */
  190182. Fts5Global *pGlobal; /* FTS5 global object for this database */
  190183. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  190184. };
  190185. struct Fts5VocabCursor {
  190186. sqlite3_vtab_cursor base;
  190187. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  190188. Fts5Index *pIndex; /* Associated FTS5 index */
  190189. int bEof; /* True if this cursor is at EOF */
  190190. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  190191. int nLeTerm; /* Size of zLeTerm in bytes */
  190192. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  190193. /* These are used by 'col' tables only */
  190194. Fts5Config *pConfig; /* Fts5 table configuration */
  190195. int iCol;
  190196. i64 *aCnt;
  190197. i64 *aDoc;
  190198. /* Output values used by all tables. */
  190199. i64 rowid; /* This table's current rowid value */
  190200. Fts5Buffer term; /* Current value of 'term' column */
  190201. /* Output values Used by 'instance' tables only */
  190202. i64 iInstPos;
  190203. int iInstOff;
  190204. };
  190205. #define FTS5_VOCAB_COL 0
  190206. #define FTS5_VOCAB_ROW 1
  190207. #define FTS5_VOCAB_INSTANCE 2
  190208. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  190209. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  190210. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  190211. /*
  190212. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  190213. */
  190214. #define FTS5_VOCAB_TERM_EQ 0x01
  190215. #define FTS5_VOCAB_TERM_GE 0x02
  190216. #define FTS5_VOCAB_TERM_LE 0x04
  190217. /*
  190218. ** Translate a string containing an fts5vocab table type to an
  190219. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  190220. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  190221. ** and return SQLITE_ERROR.
  190222. */
  190223. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  190224. int rc = SQLITE_OK;
  190225. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  190226. if( rc==SQLITE_OK ){
  190227. sqlite3Fts5Dequote(zCopy);
  190228. if( sqlite3_stricmp(zCopy, "col")==0 ){
  190229. *peType = FTS5_VOCAB_COL;
  190230. }else
  190231. if( sqlite3_stricmp(zCopy, "row")==0 ){
  190232. *peType = FTS5_VOCAB_ROW;
  190233. }else
  190234. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  190235. *peType = FTS5_VOCAB_INSTANCE;
  190236. }else
  190237. {
  190238. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  190239. rc = SQLITE_ERROR;
  190240. }
  190241. sqlite3_free(zCopy);
  190242. }
  190243. return rc;
  190244. }
  190245. /*
  190246. ** The xDisconnect() virtual table method.
  190247. */
  190248. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  190249. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  190250. sqlite3_free(pTab);
  190251. return SQLITE_OK;
  190252. }
  190253. /*
  190254. ** The xDestroy() virtual table method.
  190255. */
  190256. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  190257. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  190258. sqlite3_free(pTab);
  190259. return SQLITE_OK;
  190260. }
  190261. /*
  190262. ** This function is the implementation of both the xConnect and xCreate
  190263. ** methods of the FTS3 virtual table.
  190264. **
  190265. ** The argv[] array contains the following:
  190266. **
  190267. ** argv[0] -> module name ("fts5vocab")
  190268. ** argv[1] -> database name
  190269. ** argv[2] -> table name
  190270. **
  190271. ** then:
  190272. **
  190273. ** argv[3] -> name of fts5 table
  190274. ** argv[4] -> type of fts5vocab table
  190275. **
  190276. ** or, for tables in the TEMP schema only.
  190277. **
  190278. ** argv[3] -> name of fts5 tables database
  190279. ** argv[4] -> name of fts5 table
  190280. ** argv[5] -> type of fts5vocab table
  190281. */
  190282. static int fts5VocabInitVtab(
  190283. sqlite3 *db, /* The SQLite database connection */
  190284. void *pAux, /* Pointer to Fts5Global object */
  190285. int argc, /* Number of elements in argv array */
  190286. const char * const *argv, /* xCreate/xConnect argument array */
  190287. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  190288. char **pzErr /* Write any error message here */
  190289. ){
  190290. const char *azSchema[] = {
  190291. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  190292. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  190293. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  190294. };
  190295. Fts5VocabTable *pRet = 0;
  190296. int rc = SQLITE_OK; /* Return code */
  190297. int bDb;
  190298. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  190299. if( argc!=5 && bDb==0 ){
  190300. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  190301. rc = SQLITE_ERROR;
  190302. }else{
  190303. int nByte; /* Bytes of space to allocate */
  190304. const char *zDb = bDb ? argv[3] : argv[1];
  190305. const char *zTab = bDb ? argv[4] : argv[3];
  190306. const char *zType = bDb ? argv[5] : argv[4];
  190307. int nDb = (int)strlen(zDb)+1;
  190308. int nTab = (int)strlen(zTab)+1;
  190309. int eType = 0;
  190310. rc = fts5VocabTableType(zType, pzErr, &eType);
  190311. if( rc==SQLITE_OK ){
  190312. assert( eType>=0 && eType<ArraySize(azSchema) );
  190313. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  190314. }
  190315. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  190316. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  190317. if( pRet ){
  190318. pRet->pGlobal = (Fts5Global*)pAux;
  190319. pRet->eType = eType;
  190320. pRet->db = db;
  190321. pRet->zFts5Tbl = (char*)&pRet[1];
  190322. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  190323. memcpy(pRet->zFts5Tbl, zTab, nTab);
  190324. memcpy(pRet->zFts5Db, zDb, nDb);
  190325. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  190326. sqlite3Fts5Dequote(pRet->zFts5Db);
  190327. }
  190328. }
  190329. *ppVTab = (sqlite3_vtab*)pRet;
  190330. return rc;
  190331. }
  190332. /*
  190333. ** The xConnect() and xCreate() methods for the virtual table. All the
  190334. ** work is done in function fts5VocabInitVtab().
  190335. */
  190336. static int fts5VocabConnectMethod(
  190337. sqlite3 *db, /* Database connection */
  190338. void *pAux, /* Pointer to tokenizer hash table */
  190339. int argc, /* Number of elements in argv array */
  190340. const char * const *argv, /* xCreate/xConnect argument array */
  190341. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  190342. char **pzErr /* OUT: sqlite3_malloc'd error message */
  190343. ){
  190344. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  190345. }
  190346. static int fts5VocabCreateMethod(
  190347. sqlite3 *db, /* Database connection */
  190348. void *pAux, /* Pointer to tokenizer hash table */
  190349. int argc, /* Number of elements in argv array */
  190350. const char * const *argv, /* xCreate/xConnect argument array */
  190351. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  190352. char **pzErr /* OUT: sqlite3_malloc'd error message */
  190353. ){
  190354. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  190355. }
  190356. /*
  190357. ** Implementation of the xBestIndex method.
  190358. **
  190359. ** Only constraints of the form:
  190360. **
  190361. ** term <= ?
  190362. ** term == ?
  190363. ** term >= ?
  190364. **
  190365. ** are interpreted. Less-than and less-than-or-equal are treated
  190366. ** identically, as are greater-than and greater-than-or-equal.
  190367. */
  190368. static int fts5VocabBestIndexMethod(
  190369. sqlite3_vtab *pUnused,
  190370. sqlite3_index_info *pInfo
  190371. ){
  190372. int i;
  190373. int iTermEq = -1;
  190374. int iTermGe = -1;
  190375. int iTermLe = -1;
  190376. int idxNum = 0;
  190377. int nArg = 0;
  190378. UNUSED_PARAM(pUnused);
  190379. for(i=0; i<pInfo->nConstraint; i++){
  190380. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  190381. if( p->usable==0 ) continue;
  190382. if( p->iColumn==0 ){ /* term column */
  190383. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  190384. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  190385. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  190386. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  190387. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  190388. }
  190389. }
  190390. if( iTermEq>=0 ){
  190391. idxNum |= FTS5_VOCAB_TERM_EQ;
  190392. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  190393. pInfo->estimatedCost = 100;
  190394. }else{
  190395. pInfo->estimatedCost = 1000000;
  190396. if( iTermGe>=0 ){
  190397. idxNum |= FTS5_VOCAB_TERM_GE;
  190398. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  190399. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  190400. }
  190401. if( iTermLe>=0 ){
  190402. idxNum |= FTS5_VOCAB_TERM_LE;
  190403. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  190404. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  190405. }
  190406. }
  190407. /* This virtual table always delivers results in ascending order of
  190408. ** the "term" column (column 0). So if the user has requested this
  190409. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  190410. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  190411. ** are already in sorted order. */
  190412. if( pInfo->nOrderBy==1
  190413. && pInfo->aOrderBy[0].iColumn==0
  190414. && pInfo->aOrderBy[0].desc==0
  190415. ){
  190416. pInfo->orderByConsumed = 1;
  190417. }
  190418. pInfo->idxNum = idxNum;
  190419. return SQLITE_OK;
  190420. }
  190421. /*
  190422. ** Implementation of xOpen method.
  190423. */
  190424. static int fts5VocabOpenMethod(
  190425. sqlite3_vtab *pVTab,
  190426. sqlite3_vtab_cursor **ppCsr
  190427. ){
  190428. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  190429. Fts5Index *pIndex = 0;
  190430. Fts5Config *pConfig = 0;
  190431. Fts5VocabCursor *pCsr = 0;
  190432. int rc = SQLITE_OK;
  190433. sqlite3_stmt *pStmt = 0;
  190434. char *zSql = 0;
  190435. zSql = sqlite3Fts5Mprintf(&rc,
  190436. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  190437. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  190438. );
  190439. if( zSql ){
  190440. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  190441. }
  190442. sqlite3_free(zSql);
  190443. assert( rc==SQLITE_OK || pStmt==0 );
  190444. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  190445. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  190446. i64 iId = sqlite3_column_int64(pStmt, 0);
  190447. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  190448. }
  190449. if( rc==SQLITE_OK && pIndex==0 ){
  190450. rc = sqlite3_finalize(pStmt);
  190451. pStmt = 0;
  190452. if( rc==SQLITE_OK ){
  190453. pVTab->zErrMsg = sqlite3_mprintf(
  190454. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  190455. );
  190456. rc = SQLITE_ERROR;
  190457. }
  190458. }
  190459. if( rc==SQLITE_OK ){
  190460. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  190461. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  190462. }
  190463. if( pCsr ){
  190464. pCsr->pIndex = pIndex;
  190465. pCsr->pStmt = pStmt;
  190466. pCsr->pConfig = pConfig;
  190467. pCsr->aCnt = (i64*)&pCsr[1];
  190468. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  190469. }else{
  190470. sqlite3_finalize(pStmt);
  190471. }
  190472. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  190473. return rc;
  190474. }
  190475. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  190476. pCsr->rowid = 0;
  190477. sqlite3Fts5IterClose(pCsr->pIter);
  190478. pCsr->pIter = 0;
  190479. sqlite3_free(pCsr->zLeTerm);
  190480. pCsr->nLeTerm = -1;
  190481. pCsr->zLeTerm = 0;
  190482. }
  190483. /*
  190484. ** Close the cursor. For additional information see the documentation
  190485. ** on the xClose method of the virtual table interface.
  190486. */
  190487. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  190488. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190489. fts5VocabResetCursor(pCsr);
  190490. sqlite3Fts5BufferFree(&pCsr->term);
  190491. sqlite3_finalize(pCsr->pStmt);
  190492. sqlite3_free(pCsr);
  190493. return SQLITE_OK;
  190494. }
  190495. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  190496. int rc = SQLITE_OK;
  190497. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  190498. pCsr->bEof = 1;
  190499. }else{
  190500. const char *zTerm;
  190501. int nTerm;
  190502. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  190503. if( pCsr->nLeTerm>=0 ){
  190504. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  190505. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  190506. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  190507. pCsr->bEof = 1;
  190508. }
  190509. }
  190510. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  190511. }
  190512. return rc;
  190513. }
  190514. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  190515. int eDetail = pCsr->pConfig->eDetail;
  190516. int rc = SQLITE_OK;
  190517. Fts5IndexIter *pIter = pCsr->pIter;
  190518. i64 *pp = &pCsr->iInstPos;
  190519. int *po = &pCsr->iInstOff;
  190520. while( eDetail==FTS5_DETAIL_NONE
  190521. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  190522. ){
  190523. pCsr->iInstPos = 0;
  190524. pCsr->iInstOff = 0;
  190525. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  190526. if( rc==SQLITE_OK ){
  190527. rc = fts5VocabInstanceNewTerm(pCsr);
  190528. if( eDetail==FTS5_DETAIL_NONE ) break;
  190529. }
  190530. if( rc ){
  190531. pCsr->bEof = 1;
  190532. break;
  190533. }
  190534. }
  190535. return rc;
  190536. }
  190537. /*
  190538. ** Advance the cursor to the next row in the table.
  190539. */
  190540. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  190541. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190542. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  190543. int rc = SQLITE_OK;
  190544. int nCol = pCsr->pConfig->nCol;
  190545. pCsr->rowid++;
  190546. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  190547. return fts5VocabInstanceNext(pCsr);
  190548. }
  190549. if( pTab->eType==FTS5_VOCAB_COL ){
  190550. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  190551. if( pCsr->aDoc[pCsr->iCol] ) break;
  190552. }
  190553. }
  190554. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  190555. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  190556. pCsr->bEof = 1;
  190557. }else{
  190558. const char *zTerm;
  190559. int nTerm;
  190560. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  190561. if( pCsr->nLeTerm>=0 ){
  190562. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  190563. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  190564. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  190565. pCsr->bEof = 1;
  190566. return SQLITE_OK;
  190567. }
  190568. }
  190569. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  190570. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  190571. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  190572. pCsr->iCol = 0;
  190573. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  190574. while( rc==SQLITE_OK ){
  190575. int eDetail = pCsr->pConfig->eDetail;
  190576. const u8 *pPos; int nPos; /* Position list */
  190577. i64 iPos = 0; /* 64-bit position read from poslist */
  190578. int iOff = 0; /* Current offset within position list */
  190579. pPos = pCsr->pIter->pData;
  190580. nPos = pCsr->pIter->nData;
  190581. switch( pTab->eType ){
  190582. case FTS5_VOCAB_ROW:
  190583. if( eDetail==FTS5_DETAIL_FULL ){
  190584. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  190585. pCsr->aCnt[0]++;
  190586. }
  190587. }
  190588. pCsr->aDoc[0]++;
  190589. break;
  190590. case FTS5_VOCAB_COL:
  190591. if( eDetail==FTS5_DETAIL_FULL ){
  190592. int iCol = -1;
  190593. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  190594. int ii = FTS5_POS2COLUMN(iPos);
  190595. pCsr->aCnt[ii]++;
  190596. if( iCol!=ii ){
  190597. if( ii>=nCol ){
  190598. rc = FTS5_CORRUPT;
  190599. break;
  190600. }
  190601. pCsr->aDoc[ii]++;
  190602. iCol = ii;
  190603. }
  190604. }
  190605. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  190606. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  190607. assert_nc( iPos>=0 && iPos<nCol );
  190608. if( iPos>=nCol ){
  190609. rc = FTS5_CORRUPT;
  190610. break;
  190611. }
  190612. pCsr->aDoc[iPos]++;
  190613. }
  190614. }else{
  190615. assert( eDetail==FTS5_DETAIL_NONE );
  190616. pCsr->aDoc[0]++;
  190617. }
  190618. break;
  190619. default:
  190620. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  190621. break;
  190622. }
  190623. if( rc==SQLITE_OK ){
  190624. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  190625. }
  190626. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  190627. if( rc==SQLITE_OK ){
  190628. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  190629. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  190630. break;
  190631. }
  190632. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  190633. }
  190634. }
  190635. }
  190636. }
  190637. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  190638. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  190639. assert( pCsr->iCol<pCsr->pConfig->nCol );
  190640. }
  190641. return rc;
  190642. }
  190643. /*
  190644. ** This is the xFilter implementation for the virtual table.
  190645. */
  190646. static int fts5VocabFilterMethod(
  190647. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  190648. int idxNum, /* Strategy index */
  190649. const char *zUnused, /* Unused */
  190650. int nUnused, /* Number of elements in apVal */
  190651. sqlite3_value **apVal /* Arguments for the indexing scheme */
  190652. ){
  190653. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  190654. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190655. int eType = pTab->eType;
  190656. int rc = SQLITE_OK;
  190657. int iVal = 0;
  190658. int f = FTS5INDEX_QUERY_SCAN;
  190659. const char *zTerm = 0;
  190660. int nTerm = 0;
  190661. sqlite3_value *pEq = 0;
  190662. sqlite3_value *pGe = 0;
  190663. sqlite3_value *pLe = 0;
  190664. UNUSED_PARAM2(zUnused, nUnused);
  190665. fts5VocabResetCursor(pCsr);
  190666. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  190667. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  190668. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  190669. if( pEq ){
  190670. zTerm = (const char *)sqlite3_value_text(pEq);
  190671. nTerm = sqlite3_value_bytes(pEq);
  190672. f = 0;
  190673. }else{
  190674. if( pGe ){
  190675. zTerm = (const char *)sqlite3_value_text(pGe);
  190676. nTerm = sqlite3_value_bytes(pGe);
  190677. }
  190678. if( pLe ){
  190679. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  190680. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  190681. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  190682. if( pCsr->zLeTerm==0 ){
  190683. rc = SQLITE_NOMEM;
  190684. }else{
  190685. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  190686. }
  190687. }
  190688. }
  190689. if( rc==SQLITE_OK ){
  190690. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  190691. }
  190692. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  190693. rc = fts5VocabInstanceNewTerm(pCsr);
  190694. }
  190695. if( rc==SQLITE_OK
  190696. && !pCsr->bEof
  190697. && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
  190698. ){
  190699. rc = fts5VocabNextMethod(pCursor);
  190700. }
  190701. return rc;
  190702. }
  190703. /*
  190704. ** This is the xEof method of the virtual table. SQLite calls this
  190705. ** routine to find out if it has reached the end of a result set.
  190706. */
  190707. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  190708. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190709. return pCsr->bEof;
  190710. }
  190711. static int fts5VocabColumnMethod(
  190712. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  190713. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  190714. int iCol /* Index of column to read value from */
  190715. ){
  190716. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190717. int eDetail = pCsr->pConfig->eDetail;
  190718. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  190719. i64 iVal = 0;
  190720. if( iCol==0 ){
  190721. sqlite3_result_text(
  190722. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  190723. );
  190724. }else if( eType==FTS5_VOCAB_COL ){
  190725. assert( iCol==1 || iCol==2 || iCol==3 );
  190726. if( iCol==1 ){
  190727. if( eDetail!=FTS5_DETAIL_NONE ){
  190728. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  190729. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  190730. }
  190731. }else if( iCol==2 ){
  190732. iVal = pCsr->aDoc[pCsr->iCol];
  190733. }else{
  190734. iVal = pCsr->aCnt[pCsr->iCol];
  190735. }
  190736. }else if( eType==FTS5_VOCAB_ROW ){
  190737. assert( iCol==1 || iCol==2 );
  190738. if( iCol==1 ){
  190739. iVal = pCsr->aDoc[0];
  190740. }else{
  190741. iVal = pCsr->aCnt[0];
  190742. }
  190743. }else{
  190744. assert( eType==FTS5_VOCAB_INSTANCE );
  190745. switch( iCol ){
  190746. case 1:
  190747. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  190748. break;
  190749. case 2: {
  190750. int ii = -1;
  190751. if( eDetail==FTS5_DETAIL_FULL ){
  190752. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  190753. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  190754. ii = (int)pCsr->iInstPos;
  190755. }
  190756. if( ii>=0 && ii<pCsr->pConfig->nCol ){
  190757. const char *z = pCsr->pConfig->azCol[ii];
  190758. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  190759. }
  190760. break;
  190761. }
  190762. default: {
  190763. assert( iCol==3 );
  190764. if( eDetail==FTS5_DETAIL_FULL ){
  190765. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  190766. sqlite3_result_int(pCtx, ii);
  190767. }
  190768. break;
  190769. }
  190770. }
  190771. }
  190772. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  190773. return SQLITE_OK;
  190774. }
  190775. /*
  190776. ** This is the xRowid method. The SQLite core calls this routine to
  190777. ** retrieve the rowid for the current row of the result set. The
  190778. ** rowid should be written to *pRowid.
  190779. */
  190780. static int fts5VocabRowidMethod(
  190781. sqlite3_vtab_cursor *pCursor,
  190782. sqlite_int64 *pRowid
  190783. ){
  190784. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  190785. *pRowid = pCsr->rowid;
  190786. return SQLITE_OK;
  190787. }
  190788. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  190789. static const sqlite3_module fts5Vocab = {
  190790. /* iVersion */ 2,
  190791. /* xCreate */ fts5VocabCreateMethod,
  190792. /* xConnect */ fts5VocabConnectMethod,
  190793. /* xBestIndex */ fts5VocabBestIndexMethod,
  190794. /* xDisconnect */ fts5VocabDisconnectMethod,
  190795. /* xDestroy */ fts5VocabDestroyMethod,
  190796. /* xOpen */ fts5VocabOpenMethod,
  190797. /* xClose */ fts5VocabCloseMethod,
  190798. /* xFilter */ fts5VocabFilterMethod,
  190799. /* xNext */ fts5VocabNextMethod,
  190800. /* xEof */ fts5VocabEofMethod,
  190801. /* xColumn */ fts5VocabColumnMethod,
  190802. /* xRowid */ fts5VocabRowidMethod,
  190803. /* xUpdate */ 0,
  190804. /* xBegin */ 0,
  190805. /* xSync */ 0,
  190806. /* xCommit */ 0,
  190807. /* xRollback */ 0,
  190808. /* xFindFunction */ 0,
  190809. /* xRename */ 0,
  190810. /* xSavepoint */ 0,
  190811. /* xRelease */ 0,
  190812. /* xRollbackTo */ 0,
  190813. };
  190814. void *p = (void*)pGlobal;
  190815. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  190816. }
  190817. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  190818. /************** End of fts5.c ************************************************/
  190819. /************** Begin file stmt.c ********************************************/
  190820. /*
  190821. ** 2017-05-31
  190822. **
  190823. ** The author disclaims copyright to this source code. In place of
  190824. ** a legal notice, here is a blessing:
  190825. **
  190826. ** May you do good and not evil.
  190827. ** May you find forgiveness for yourself and forgive others.
  190828. ** May you share freely, never taking more than you give.
  190829. **
  190830. *************************************************************************
  190831. **
  190832. ** This file demonstrates an eponymous virtual table that returns information
  190833. ** about all prepared statements for the database connection.
  190834. **
  190835. ** Usage example:
  190836. **
  190837. ** .load ./stmt
  190838. ** .mode line
  190839. ** .header on
  190840. ** SELECT * FROM stmt;
  190841. */
  190842. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  190843. #if !defined(SQLITEINT_H)
  190844. /* #include "sqlite3ext.h" */
  190845. #endif
  190846. SQLITE_EXTENSION_INIT1
  190847. /* #include <assert.h> */
  190848. /* #include <string.h> */
  190849. #ifndef SQLITE_OMIT_VIRTUALTABLE
  190850. /* stmt_vtab is a subclass of sqlite3_vtab which will
  190851. ** serve as the underlying representation of a stmt virtual table
  190852. */
  190853. typedef struct stmt_vtab stmt_vtab;
  190854. struct stmt_vtab {
  190855. sqlite3_vtab base; /* Base class - must be first */
  190856. sqlite3 *db; /* Database connection for this stmt vtab */
  190857. };
  190858. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  190859. ** serve as the underlying representation of a cursor that scans
  190860. ** over rows of the result
  190861. */
  190862. typedef struct stmt_cursor stmt_cursor;
  190863. struct stmt_cursor {
  190864. sqlite3_vtab_cursor base; /* Base class - must be first */
  190865. sqlite3 *db; /* Database connection for this cursor */
  190866. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  190867. sqlite3_int64 iRowid; /* The rowid */
  190868. };
  190869. /*
  190870. ** The stmtConnect() method is invoked to create a new
  190871. ** stmt_vtab that describes the stmt virtual table.
  190872. **
  190873. ** Think of this routine as the constructor for stmt_vtab objects.
  190874. **
  190875. ** All this routine needs to do is:
  190876. **
  190877. ** (1) Allocate the stmt_vtab object and initialize all fields.
  190878. **
  190879. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  190880. ** result set of queries against stmt will look like.
  190881. */
  190882. static int stmtConnect(
  190883. sqlite3 *db,
  190884. void *pAux,
  190885. int argc, const char *const*argv,
  190886. sqlite3_vtab **ppVtab,
  190887. char **pzErr
  190888. ){
  190889. stmt_vtab *pNew;
  190890. int rc;
  190891. /* Column numbers */
  190892. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  190893. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  190894. #define STMT_COLUMN_RO 2 /* True if read-only */
  190895. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  190896. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  190897. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  190898. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  190899. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  190900. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  190901. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  190902. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  190903. rc = sqlite3_declare_vtab(db,
  190904. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  190905. "reprep,run,mem)");
  190906. if( rc==SQLITE_OK ){
  190907. pNew = sqlite3_malloc( sizeof(*pNew) );
  190908. *ppVtab = (sqlite3_vtab*)pNew;
  190909. if( pNew==0 ) return SQLITE_NOMEM;
  190910. memset(pNew, 0, sizeof(*pNew));
  190911. pNew->db = db;
  190912. }
  190913. return rc;
  190914. }
  190915. /*
  190916. ** This method is the destructor for stmt_cursor objects.
  190917. */
  190918. static int stmtDisconnect(sqlite3_vtab *pVtab){
  190919. sqlite3_free(pVtab);
  190920. return SQLITE_OK;
  190921. }
  190922. /*
  190923. ** Constructor for a new stmt_cursor object.
  190924. */
  190925. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  190926. stmt_cursor *pCur;
  190927. pCur = sqlite3_malloc( sizeof(*pCur) );
  190928. if( pCur==0 ) return SQLITE_NOMEM;
  190929. memset(pCur, 0, sizeof(*pCur));
  190930. pCur->db = ((stmt_vtab*)p)->db;
  190931. *ppCursor = &pCur->base;
  190932. return SQLITE_OK;
  190933. }
  190934. /*
  190935. ** Destructor for a stmt_cursor.
  190936. */
  190937. static int stmtClose(sqlite3_vtab_cursor *cur){
  190938. sqlite3_free(cur);
  190939. return SQLITE_OK;
  190940. }
  190941. /*
  190942. ** Advance a stmt_cursor to its next row of output.
  190943. */
  190944. static int stmtNext(sqlite3_vtab_cursor *cur){
  190945. stmt_cursor *pCur = (stmt_cursor*)cur;
  190946. pCur->iRowid++;
  190947. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  190948. return SQLITE_OK;
  190949. }
  190950. /*
  190951. ** Return values of columns for the row at which the stmt_cursor
  190952. ** is currently pointing.
  190953. */
  190954. static int stmtColumn(
  190955. sqlite3_vtab_cursor *cur, /* The cursor */
  190956. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  190957. int i /* Which column to return */
  190958. ){
  190959. stmt_cursor *pCur = (stmt_cursor*)cur;
  190960. switch( i ){
  190961. case STMT_COLUMN_SQL: {
  190962. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  190963. break;
  190964. }
  190965. case STMT_COLUMN_NCOL: {
  190966. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  190967. break;
  190968. }
  190969. case STMT_COLUMN_RO: {
  190970. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  190971. break;
  190972. }
  190973. case STMT_COLUMN_BUSY: {
  190974. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  190975. break;
  190976. }
  190977. case STMT_COLUMN_MEM: {
  190978. i = SQLITE_STMTSTATUS_MEMUSED +
  190979. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  190980. /* Fall thru */
  190981. }
  190982. case STMT_COLUMN_NSCAN:
  190983. case STMT_COLUMN_NSORT:
  190984. case STMT_COLUMN_NAIDX:
  190985. case STMT_COLUMN_NSTEP:
  190986. case STMT_COLUMN_REPREP:
  190987. case STMT_COLUMN_RUN: {
  190988. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  190989. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  190990. break;
  190991. }
  190992. }
  190993. return SQLITE_OK;
  190994. }
  190995. /*
  190996. ** Return the rowid for the current row. In this implementation, the
  190997. ** rowid is the same as the output value.
  190998. */
  190999. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  191000. stmt_cursor *pCur = (stmt_cursor*)cur;
  191001. *pRowid = pCur->iRowid;
  191002. return SQLITE_OK;
  191003. }
  191004. /*
  191005. ** Return TRUE if the cursor has been moved off of the last
  191006. ** row of output.
  191007. */
  191008. static int stmtEof(sqlite3_vtab_cursor *cur){
  191009. stmt_cursor *pCur = (stmt_cursor*)cur;
  191010. return pCur->pStmt==0;
  191011. }
  191012. /*
  191013. ** This method is called to "rewind" the stmt_cursor object back
  191014. ** to the first row of output. This method is always called at least
  191015. ** once prior to any call to stmtColumn() or stmtRowid() or
  191016. ** stmtEof().
  191017. */
  191018. static int stmtFilter(
  191019. sqlite3_vtab_cursor *pVtabCursor,
  191020. int idxNum, const char *idxStr,
  191021. int argc, sqlite3_value **argv
  191022. ){
  191023. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  191024. pCur->pStmt = 0;
  191025. pCur->iRowid = 0;
  191026. return stmtNext(pVtabCursor);
  191027. }
  191028. /*
  191029. ** SQLite will invoke this method one or more times while planning a query
  191030. ** that uses the stmt virtual table. This routine needs to create
  191031. ** a query plan for each invocation and compute an estimated cost for that
  191032. ** plan.
  191033. */
  191034. static int stmtBestIndex(
  191035. sqlite3_vtab *tab,
  191036. sqlite3_index_info *pIdxInfo
  191037. ){
  191038. pIdxInfo->estimatedCost = (double)500;
  191039. pIdxInfo->estimatedRows = 500;
  191040. return SQLITE_OK;
  191041. }
  191042. /*
  191043. ** This following structure defines all the methods for the
  191044. ** stmt virtual table.
  191045. */
  191046. static sqlite3_module stmtModule = {
  191047. 0, /* iVersion */
  191048. 0, /* xCreate */
  191049. stmtConnect, /* xConnect */
  191050. stmtBestIndex, /* xBestIndex */
  191051. stmtDisconnect, /* xDisconnect */
  191052. 0, /* xDestroy */
  191053. stmtOpen, /* xOpen - open a cursor */
  191054. stmtClose, /* xClose - close a cursor */
  191055. stmtFilter, /* xFilter - configure scan constraints */
  191056. stmtNext, /* xNext - advance a cursor */
  191057. stmtEof, /* xEof - check for end of scan */
  191058. stmtColumn, /* xColumn - read data */
  191059. stmtRowid, /* xRowid - read data */
  191060. 0, /* xUpdate */
  191061. 0, /* xBegin */
  191062. 0, /* xSync */
  191063. 0, /* xCommit */
  191064. 0, /* xRollback */
  191065. 0, /* xFindMethod */
  191066. 0, /* xRename */
  191067. 0, /* xSavepoint */
  191068. 0, /* xRelease */
  191069. 0, /* xRollbackTo */
  191070. };
  191071. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  191072. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  191073. int rc = SQLITE_OK;
  191074. #ifndef SQLITE_OMIT_VIRTUALTABLE
  191075. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  191076. #endif
  191077. return rc;
  191078. }
  191079. #ifndef SQLITE_CORE
  191080. #ifdef _WIN32
  191081. __declspec(dllexport)
  191082. #endif
  191083. SQLITE_API int sqlite3_stmt_init(
  191084. sqlite3 *db,
  191085. char **pzErrMsg,
  191086. const sqlite3_api_routines *pApi
  191087. ){
  191088. int rc = SQLITE_OK;
  191089. SQLITE_EXTENSION_INIT2(pApi);
  191090. #ifndef SQLITE_OMIT_VIRTUALTABLE
  191091. rc = sqlite3StmtVtabInit(db);
  191092. #endif
  191093. return rc;
  191094. }
  191095. #endif /* SQLITE_CORE */
  191096. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  191097. /************** End of stmt.c ************************************************/
  191098. #if __LINE__!=205346
  191099. #undef SQLITE_SOURCE_ID
  191100. #define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de4alt2"
  191101. #endif
  191102. /* Return the source-id for this library */
  191103. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  191104. /************************** End of sqlite3.c ******************************/
  191105. #else // USE_LIBSQLITE3
  191106. // If users really want to link against the system sqlite3 we
  191107. // need to make this file a noop.
  191108. #endif